Index: 3rdParty_sources/joda-time/org/joda/time/Chronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/Chronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/Chronology.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,859 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import org.joda.time.chrono.BuddhistChronology; +import org.joda.time.chrono.CopticChronology; +import org.joda.time.chrono.GJChronology; +import org.joda.time.chrono.GregorianChronology; +import org.joda.time.chrono.ISOChronology; +import org.joda.time.chrono.JulianChronology; + +/** + * Chronology provides access to the individual date time fields for a + * chronological calendar system. + *

+ * Various chronologies are supported by subclasses including ISO and GregorianJulian. + * This class provides static factory methods to access these chronologies. + * For example, to obtain the current time in the coptic calendar system: + *

+ * DateTime dt = new DateTime(Chronology.getCoptic());
+ * 
+ *

+ * The provided chronology implementations are: + *

+ * Hopefully future releases will contain more chronologies. + *

+ * This class defines a number of fields with names from the ISO8601 standard. + * It does not 'strongly' define these fields however, thus implementations + * are free to interpret the field names as they wish. + * For example, a week could be defined as 10 days and a month as 40 days in a + * special WeirdChronology implementation. Clearly the GJ and ISO + * implementations provided use the field names as you would expect. + * + * @see org.joda.time.chrono.ISOChronology + * @see org.joda.time.chrono.GJChronology + * @see org.joda.time.chrono.GregorianChronology + * @see org.joda.time.chrono.JulianChronology + * @see org.joda.time.chrono.CopticChronology + * @see org.joda.time.chrono.BuddhistChronology + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class Chronology { + + /** + * Gets an instance of the ISOChronology in the default zone. + *

+ * {@link ISOChronology} defines all fields in line with the ISO8601 standard. + * This chronology is the default, and is suitable for all normal datetime processing. + * It is unsuitable for historical datetimes before October 15, 1582 + * as it applies the modern Gregorian calendar rules before that date. + * + * @return the ISO chronology + */ + public static Chronology getISO() { + return ISOChronology.getInstance(); + } + + /** + * Gets an instance of the ISOChronology in the UTC zone. + *

+ * {@link ISOChronology} defines all fields in line with the ISO8601 standard. + * This chronology is the default, and is suitable for all normal datetime processing. + * It is unsuitable for historical datetimes before October 15, 1582 + * as it applies the modern Gregorian calendar rules before that date. + * + * @return the ISO chronology + */ + public static Chronology getISOUTC() { + return ISOChronology.getInstanceUTC(); + } + + /** + * Gets an instance of the ISOChronology in the specified zone. + *

+ * {@link ISOChronology} defines all fields in line with the ISO8601 standard. + * This chronology is the default, and is suitable for all normal datetime processing. + * It is unsuitable for historical datetimes before October 15, 1582 + * as it applies the modern Gregorian calendar rules before that date. + * + * @param zone the zone to use, null means default zone + * @return the ISO chronology + */ + public static Chronology getISO(DateTimeZone zone) { + return ISOChronology.getInstance(zone); + } + + //----------------------------------------------------------------------- + /** + * Gets an instance of the GJChronology in the default zone. + *

+ * {@link GJChronology} defines all fields using standard meanings. + * This chronology is intended to be used as a replacement for GregorianCalendar. + * The Gregorian calendar system is used after October 15, 1582, while the + * Julian calendar system is used before. + *

+ * Unlike GregorianCalendar, this chronology returns a year of -1 + * for 1 BCE, -2 for 2 BCE and so on. Thus there is no year zero. + *

+ * This method uses the standard Julian to Gregorian cutover date of + * October 15th 1582. If you require a cutover on a different date, then use + * the factories on GJChronology itself. + *

+ * When dealing solely with dates in the modern era, from 1600 onwards, + * we recommend using ISOChronology, which is the default. + * + * @return the GJ chronology + */ + public static Chronology getGJ() { + return GJChronology.getInstance(); + } + + /** + * Gets an instance of the GJChronology in the UTC zone. + *

+ * {@link GJChronology} defines all fields using standard meanings. + * This chronology is intended to be used as a replacement for GregorianCalendar. + * The Gregorian calendar system is used after October 15, 1582, while the + * Julian calendar system is used before. + *

+ * Unlike GregorianCalendar, this chronology returns a year of -1 + * for 1 BCE, -2 for 2 BCE and so on. Thus there is no year zero. + *

+ * This method uses the standard Julian to Gregorian cutover date of + * October 15th 1582. If you require a cutover on a different date, then use + * the factories on GJChronology itself. + *

+ * When dealing solely with dates in the modern era, from 1600 onwards, + * we recommend using ISOChronology, which is the default. + * + * @return the GJ chronology + */ + public static Chronology getGJUTC() { + return GJChronology.getInstanceUTC(); + } + + /** + * Gets an instance of the GJChronology in the specified zone. + *

+ * {@link GJChronology} defines all fields using standard meanings. + * This chronology is intended to be used as a replacement for GregorianCalendar. + * The Gregorian calendar system is used after October 15, 1582, while the + * Julian calendar system is used before. + *

+ * Unlike GregorianCalendar, this chronology returns a year of -1 + * for 1 BCE, -2 for 2 BCE and so on. Thus there is no year zero. + *

+ * This method uses the standard Julian to Gregorian cutover date of + * October 15th 1582. If you require a cutover on a different date, then use + * the factories on GJChronology itself. + *

+ * When dealing solely with dates in the modern era, from 1600 onwards, + * we recommend using ISOChronology, which is the default. + * + * @param zone the zone to use, null means default zone + * @return the GJ chronology + */ + public static Chronology getGJ(DateTimeZone zone) { + return GJChronology.getInstance(zone); + } + + //----------------------------------------------------------------------- + /** + * Gets an instance of the GregorianChronology in the default zone. + *

+ * {@link GregorianChronology} defines all fields using standard meanings. + * It uses the Gregorian calendar rules for all time (proleptic) + * thus it is NOT a replacement for GregorianCalendar. + * For that purpose, you should use {@link #getGJ()}. + *

+ * The Gregorian calendar system defines a leap year every four years, + * except that every 100 years is not leap, but every 400 is leap. + *

+ * Technically, this chronology is almost identical to the ISO chronology, + * thus we recommend using ISOChronology instead, which is the default. + * + * @return the Gregorian chronology + */ + public static Chronology getGregorian() { + return GregorianChronology.getInstance(); + } + + /** + * Gets an instance of the GregorianChronology in the UTC zone. + *

+ * {@link GregorianChronology} defines all fields using standard meanings. + * It uses the Gregorian calendar rules for all time (proleptic) + * thus it is NOT a replacement for GregorianCalendar. + * For that purpose, you should use {@link #getGJ()}. + *

+ * The Gregorian calendar system defines a leap year every four years, + * except that every 100 years is not leap, but every 400 is leap. + *

+ * Technically, this chronology is almost identical to the ISO chronology, + * thus we recommend using ISOChronology instead, which is the default. + * + * @return the Gregorian chronology + */ + public static Chronology getGregorianUTC() { + return GregorianChronology.getInstanceUTC(); + } + + /** + * Gets an instance of the GregorianChronology in the specified zone. + *

+ * {@link GregorianChronology} defines all fields using standard meanings. + * It uses the Gregorian calendar rules for all time (proleptic) + * thus it is NOT a replacement for GregorianCalendar. + * For that purpose, you should use {@link #getGJ()}. + *

+ * The Gregorian calendar system defines a leap year every four years, + * except that every 100 years is not leap, but every 400 is leap. + *

+ * Technically, this chronology is almost identical to the ISO chronology, + * thus we recommend using ISOChronology instead, which is the default. + * + * @param zone the zone to use, null means default zone + * @return the Gregorian chronology + */ + public static Chronology getGregorian(DateTimeZone zone) { + return GregorianChronology.getInstance(zone); + } + + //----------------------------------------------------------------------- + /** + * Gets an instance of the JulianChronology in the default zone. + *

+ * {@link JulianChronology} defines all fields using standard meanings. + * It uses the Julian calendar rules for all time (proleptic). + * The Julian calendar system defines a leap year every four years. + * + * @return the Julian chronology + */ + public static Chronology getJulian() { + return JulianChronology.getInstance(); + } + + /** + * Gets an instance of the JulianChronology in the UTC zone. + *

+ * {@link JulianChronology} defines all fields using standard meanings. + * It uses the Julian calendar rules for all time (proleptic). + * The Julian calendar system defines a leap year every four years. + * + * @return the Julian chronology + */ + public static Chronology getJulianUTC() { + return JulianChronology.getInstanceUTC(); + } + + /** + * Gets an instance of the JulianChronology in the specified zone. + *

+ * {@link JulianChronology} defines all fields using standard meanings. + * It uses the Julian calendar rules for all time (proleptic). + * The Julian calendar system defines a leap year every four years. + * + * @param zone the zone to use, null means default zone + * @return the Julian chronology + */ + public static Chronology getJulian(DateTimeZone zone) { + return JulianChronology.getInstance(zone); + } + + //----------------------------------------------------------------------- + /** + * Gets an instance of the BuddhistChronology in the default zone. + *

+ * {@link BuddhistChronology} defines all fields using standard meanings, + * however the year is offset by 543. The chronology cannot be used before + * year 1 in the Buddhist calendar. + * + * @return the Buddhist chronology + */ + public static Chronology getBuddhist() { + return BuddhistChronology.getInstance(); + } + + /** + * Gets an instance of the BuddhistChronology in the UTC zone. + *

+ * {@link BuddhistChronology} defines all fields using standard meanings, + * however the year is offset by 543. The chronology cannot be used before + * year 1 in the Buddhist calendar. + * + * @return the Buddhist chronology + */ + public static Chronology getBuddhistUTC() { + return BuddhistChronology.getInstanceUTC(); + } + + /** + * Gets an instance of the BuddhistChronology in the specified zone. + *

+ * {@link BuddhistChronology} defines all fields using standard meanings, + * however the year is offset by 543. The chronology cannot be used before + * year 1 in the Buddhist calendar. + * + * @param zone the zone to use, null means default zone + * @return the Buddhist chronology + */ + public static Chronology getBuddhist(DateTimeZone zone) { + return BuddhistChronology.getInstance(zone); + } + + //----------------------------------------------------------------------- + /** + * Gets an instance of the CopticChronology in the default zone. + *

+ * {@link CopticChronology} defines fields sensibly for the Coptic calendar system. + * The Coptic calendar system defines every fourth year as leap. + * The year is broken down into 12 months, each 30 days in length. + * An extra period at the end of the year is either 5 or 6 days in length + * and is returned as a 13th month. + * Year 1 in the Coptic calendar began on August 29, 284 CE (Julian). + * The chronology cannot be used before the first Coptic year. + * + * @return the Coptic chronology + */ + public static Chronology getCoptic() { + return CopticChronology.getInstance(); + } + + /** + * Gets an instance of the CopticChronology in the UTC zone. + *

+ * {@link CopticChronology} defines fields sensibly for the Coptic calendar system. + * The Coptic calendar system defines every fourth year as leap. + * The year is broken down into 12 months, each 30 days in length. + * An extra period at the end of the year is either 5 or 6 days in length + * and is returned as a 13th month. + * Year 1 in the Coptic calendar began on August 29, 284 CE (Julian). + * The chronology cannot be used before the first Coptic year. + * + * @return the Coptic chronology + */ + public static Chronology getCopticUTC() { + return CopticChronology.getInstanceUTC(); + } + + /** + * Gets an instance of the CopticChronology in the specified zone. + *

+ * {@link CopticChronology} defines fields sensibly for the Coptic calendar system. + * The Coptic calendar system defines every fourth year as leap. + * The year is broken down into 12 months, each 30 days in length. + * An extra period at the end of the year is either 5 or 6 days in length + * and is returned as a 13th month. + * Year 1 in the Coptic calendar began on August 29, 284 CE (Julian). + * The chronology cannot be used before the first Coptic year. + * + * @param zone the zone to use, null means default zone + * @return the Coptic chronology + */ + public static Chronology getCoptic(DateTimeZone zone) { + return CopticChronology.getInstance(zone); + } + + //----------------------------------------------------------------------- + /** + * Returns the DateTimeZone that this Chronology operates in, or null if + * unspecified. + * + * @return DateTimeZone null if unspecified + */ + public abstract DateTimeZone getZone(); + + /** + * Returns an instance of this Chronology that operates in the UTC time + * zone. Chronologies that do not operate in a time zone or are already + * UTC must return themself. + * + * @return a version of this chronology that ignores time zones + */ + public abstract Chronology withUTC(); + + /** + * Returns an instance of this Chronology that operates in any time zone. + * + * @return a version of this chronology with a specific time zone + * @param zone to use, or default if null + * @see org.joda.time.chrono.ZonedChronology + */ + public abstract Chronology withZone(DateTimeZone zone); + + /** + * Returns a datetime millisecond instant, formed from the given year, + * month, day, and millisecond values. The set of given values must refer + * to a valid datetime, or else an IllegalArgumentException is thrown. + *

+ * The default implementation calls upon separate DateTimeFields to + * determine the result. Subclasses are encouraged to provide a more + * efficient implementation. + * + * @param year year to use + * @param monthOfYear month to use + * @param dayOfMonth day of month to use + * @param millisOfDay millisecond to use + * @return millisecond instant from 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if the values are invalid + */ + public abstract long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay); + + /** + * Returns a datetime millisecond instant, formed from the given year, + * month, day, hour, minute, second, and millisecond values. The set of + * given values must refer to a valid datetime, or else an + * IllegalArgumentException is thrown. + *

+ * The default implementation calls upon separate DateTimeFields to + * determine the result. Subclasses are encouraged to provide a more + * efficient implementation. + * + * @param year year to use + * @param monthOfYear month to use + * @param dayOfMonth day of month to use + * @param hourOfDay hour to use + * @param minuteOfHour minute to use + * @param secondOfMinute second to use + * @param millisOfSecond millisecond to use + * @return millisecond instant from 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if the values are invalid + */ + public abstract long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond); + + /** + * Returns a datetime millisecond instant, from from the given instant, + * hour, minute, second, and millisecond values. The set of given values + * must refer to a valid datetime, or else an IllegalArgumentException is + * thrown. + *

+ * The default implementation calls upon separate DateTimeFields to + * determine the result. Subclasses are encouraged to provide a more + * efficient implementation. + * + * @param instant instant to start from + * @param hourOfDay hour to use + * @param minuteOfHour minute to use + * @param secondOfMinute second to use + * @param millisOfSecond millisecond to use + * @return millisecond instant from 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if the values are invalid + */ + public abstract long getDateTimeMillis(long instant, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond); + + //----------------------------------------------------------------------- + /** + * Validates whether the values are valid for the fields of a partial instant. + * + * @param partial the partial instant to validate + * @param values the values to validate, not null, match fields in partial + * @throws IllegalArgumentException if the instant is invalid + */ + public abstract void validate(ReadablePartial partial, int[] values); + + /** + * Gets the values of a partial from an instant. + * + * @param partial the partial instant to use + * @param instant the instant to query + * @return the values of this partial extracted from the instant + */ + public abstract int[] get(ReadablePartial partial, long instant); + + /** + * Sets the partial into the instant. + * + * @param partial the partial instant to use + * @param instant the instant to update + * @return the updated instant + */ + public abstract long set(ReadablePartial partial, long instant); + + //----------------------------------------------------------------------- + /** + * Gets the values of a period from an interval. + * + * @param period the period instant to use + * @param startInstant the start instant of an interval to query + * @param endInstant the start instant of an interval to query + * @return the values of the period extracted from the interval + */ + public abstract int[] get(ReadablePeriod period, long startInstant, long endInstant); + + /** + * Gets the values of a period from an interval. + * + * @param period the period instant to use + * @param duration the duration to query + * @return the values of the period extracted from the duration + */ + public abstract int[] get(ReadablePeriod period, long duration); + + /** + * Adds the period to the instant, specifying the number of times to add. + * + * @param period the period to add, null means add nothing + * @param instant the instant to add to + * @param scalar the number of times to add + * @return the updated instant + */ + public abstract long add(ReadablePeriod period, long instant, int scalar); + + //----------------------------------------------------------------------- + /** + * Adds the duration to the instant, specifying the number of times to add. + * + * @param instant the instant to add to + * @param duration the duration to add + * @param scalar the number of times to add + * @return the updated instant + */ + public abstract long add(long instant, long duration, int scalar); + + // Millis + //----------------------------------------------------------------------- + /** + * Get the millis duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField millis(); + + /** + * Get the millis of second field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField millisOfSecond(); + + /** + * Get the millis of day field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField millisOfDay(); + + // Second + //----------------------------------------------------------------------- + /** + * Get the seconds duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField seconds(); + + /** + * Get the second of minute field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField secondOfMinute(); + + /** + * Get the second of day field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField secondOfDay(); + + // Minute + //----------------------------------------------------------------------- + /** + * Get the minutes duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField minutes(); + + /** + * Get the minute of hour field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField minuteOfHour(); + + /** + * Get the minute of day field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField minuteOfDay(); + + // Hour + //----------------------------------------------------------------------- + /** + * Get the hours duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField hours(); + + /** + * Get the hour of day (0-23) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField hourOfDay(); + + /** + * Get the hour of day (offset to 1-24) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField clockhourOfDay(); + + // Halfday + //----------------------------------------------------------------------- + /** + * Get the halfdays duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField halfdays(); + + /** + * Get the hour of am/pm (0-11) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField hourOfHalfday(); + + /** + * Get the hour of am/pm (offset to 1-12) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField clockhourOfHalfday(); + + /** + * Get the AM(0) PM(1) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField halfdayOfDay(); + + // Day + //----------------------------------------------------------------------- + /** + * Get the days duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField days(); + + /** + * Get the day of week field for this chronology. + * + *

DayOfWeek values are defined in {@link DateTimeConstants}. + * They use the ISO definitions, where 1 is Monday and 7 is Sunday. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField dayOfWeek(); + + /** + * Get the day of month field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField dayOfMonth(); + + /** + * Get the day of year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField dayOfYear(); + + // Week + //----------------------------------------------------------------------- + /** + * Get the weeks duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField weeks(); + + /** + * Get the week of a week based year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField weekOfWeekyear(); + + // Weekyear + //----------------------------------------------------------------------- + /** + * Get the weekyears duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField weekyears(); + + /** + * Get the year of a week based year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField weekyear(); + + /** + * Get the year of a week based year in a century field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField weekyearOfCentury(); + + // Month + //----------------------------------------------------------------------- + /** + * Get the months duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField months(); + + /** + * Get the month of year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField monthOfYear(); + + // Year + //----------------------------------------------------------------------- + /** + * Get the years duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField years(); + + /** + * Get the year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField year(); + + /** + * Get the year of era field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField yearOfEra(); + + /** + * Get the year of century field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField yearOfCentury(); + + // Century + //----------------------------------------------------------------------- + /** + * Get the centuries duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField centuries(); + + /** + * Get the century of era field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField centuryOfEra(); + + // Era + //----------------------------------------------------------------------- + /** + * Get the eras duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public abstract DurationField eras(); + + /** + * Get the era field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public abstract DateTimeField era(); + + //----------------------------------------------------------------------- + /** + * Gets a debugging toString. + * + * @return a debugging string + */ + public abstract String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/DateMidnight.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateMidnight.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateMidnight.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,975 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; +import java.util.Locale; + +import org.joda.time.base.BaseDateTime; +import org.joda.time.field.AbstractReadableInstantFieldProperty; + +/** + * DateMidnight defines a date where the time component is fixed at midnight. + * The class uses a time zone, thus midnight is local unless a UTC time zone is used. + *

+ * It is important to emphasise that this class represents the time of midnight on + * any given day. + * Note that midnight is defined as 00:00, which is at the very start of a day. + *

+ * This class does not represent a day, but the millisecond instant at midnight. + * If you need a class that represents the whole day, then an {@link Interval} or + * a {@link YearMonthDay} may be more suitable. + *

+ * This class uses a Chronology internally. The Chronology determines how the + * millisecond instant value is converted into the date time fields. + * The default Chronology is ISOChronology which is the agreed + * international standard and compatable with the modern Gregorian calendar. + * + *

Each individual field can be queried in two ways: + *

+ * The second technique also provides access to other useful methods on the + * field: + * + * + *

+ * DateMidnight is thread-safe and immutable, provided that the Chronology is as well. + * All standard Chronology classes supplied are thread-safe and immutable. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public final class DateMidnight + extends BaseDateTime + implements ReadableDateTime, Serializable { + + /** Serialization lock */ + private static final long serialVersionUID = 156371964018738L; + + // Constructors + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the default time zone. + * The constructed object will have a local time of midnight. + */ + public DateMidnight() { + super(); + } + + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the specified time zone. + * The constructed object will have a local time of midnight. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param zone the time zone, null means default zone + */ + public DateMidnight(DateTimeZone zone) { + super(zone); + } + + /** + * Constructs an instance set to the current system millisecond time + * using the specified chronology. + * The constructed object will have a local time of midnight. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param chronology the chronology, null means ISOChronology in default zone + */ + public DateMidnight(Chronology chronology) { + super(chronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the default time zone. + * The constructed object will have a local time of midnight. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + public DateMidnight(long instant) { + super(instant); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the specified time zone. + * The constructed object will have a local time of midnight. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param zone the time zone, null means default zone + */ + public DateMidnight(long instant, DateTimeZone zone) { + super(instant, zone); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using the specified chronology. + * The constructed object will have a local time of midnight. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param chronology the chronology, null means ISOChronology in default zone + */ + public DateMidnight(long instant, Chronology chronology) { + super(instant, chronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from an Object that represents a datetime. + * The constructed object will have a local time of midnight. + *

+ * If the object implies a chronology (such as GregorianCalendar does), + * then that chronology will be used. Otherwise, ISO default is used. + * Thus if a GregorianCalendar is passed in, the chronology used will + * be GJ, but if a Date is passed in the chronology will be ISO. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @throws IllegalArgumentException if the instant is invalid + */ + public DateMidnight(Object instant) { + super(instant, (Chronology) null); + } + + /** + * Constructs an instance from an Object that represents a datetime, + * forcing the time zone to that specified. + * The constructed object will have a local time of midnight. + *

+ * If the object implies a chronology (such as GregorianCalendar does), + * then that chronology will be used, but with the time zone adjusted. + * Otherwise, ISO is used in the specified time zone. + * If the specified time zone is null, the default zone is used. + * Thus if a GregorianCalendar is passed in, the chronology used will + * be GJ, but if a Date is passed in the chronology will be ISO. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @param zone the time zone, null means default time zone + * @throws IllegalArgumentException if the instant is invalid + */ + public DateMidnight(Object instant, DateTimeZone zone) { + super(instant, zone); + } + + /** + * Constructs an instance from an Object that represents a datetime, + * using the specified chronology. + * The constructed object will have a local time of midnight. + *

+ * If the chronology is null, ISO in the default time zone is used. + * Any chronology implied by the object (such as GregorianCalendar does) + * is ignored. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @param chronology the chronology, null means ISOChronology in default zone + * @throws IllegalArgumentException if the instant is invalid + */ + public DateMidnight(Object instant, Chronology chronology) { + super(instant, DateTimeUtils.getChronology(chronology)); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from datetime field values + * using ISOChronology in the default time zone. + * The constructed object will have a local time of midnight. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + */ + public DateMidnight(int year, int monthOfYear, int dayOfMonth) { + super(year, monthOfYear, dayOfMonth, 0, 0, 0, 0); + } + + /** + * Constructs an instance from datetime field values + * using ISOChronology in the specified time zone. + * The constructed object will have a local time of midnight. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param zone the time zone, null means default time zone + */ + public DateMidnight(int year, int monthOfYear, int dayOfMonth, DateTimeZone zone) { + super(year, monthOfYear, dayOfMonth, 0, 0, 0, 0, zone); + } + + /** + * Constructs an instance from datetime field values + * using the specified chronology. + * The constructed object will have a local time of midnight. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param chronology the chronology, null means ISOChronology in default zone + */ + public DateMidnight(int year, int monthOfYear, int dayOfMonth, Chronology chronology) { + super(year, monthOfYear, dayOfMonth, 0, 0, 0, 0, chronology); + } + + /** + * Rounds the specified instant as required by the subclass. + * This method must not access instance variables. + *

+ * This implementation performs no rounding and returns the instant. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @param chronology the chronology to use, not null + * @return the updated instant, rounded to midnight + */ + protected long checkInstant(long instant, Chronology chronology) { + return chronology.dayOfMonth().roundFloor(instant); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this instant with different millis. + * The returned object will have a local time of midnight. + *

+ * Only the millis will change, the chronology and time zone are kept. + * The returned object will be either be a new instance or this. + * + * @param newMillis the new millis, from 1970-01-01T00:00:00Z + * @return a copy of this instant with different millis + */ + public DateMidnight withMillis(long newMillis) { + Chronology chrono = getChronology(); + newMillis = checkInstant(newMillis, chrono); + return (newMillis == getMillis() ? this : new DateMidnight(newMillis, chrono)); + } + + /** + * Gets a copy of this instant with a different chronology, potentially + * changing the day in unexpected ways. + *

+ * This method creates a new DateMidnight using the midnight millisecond value + * and the new chronology. If the same or similar chronology is specified, but + * with a different time zone, the day may change. This occurs because the new + * DateMidnight rounds down the millisecond value to get to midnight, and the + * time zone change may result in a rounding down to a different day. + *

+ * For example, changing time zone from London (+00:00) to Paris (+01:00) will + * retain the same day, but changing from Paris to London will change the day. + * (When its midnight in London its the same day in Paris, but when its midnight + * in Paris its still the previous day in London) + *

+ * To avoid these unusual effects, use {@link #withZoneRetainFields(DateTimeZone)} + * to change time zones. + * + * @param newChronology the new chronology + * @return a copy of this instant with a different chronology + */ + public DateMidnight withChronology(Chronology newChronology) { + return (newChronology == getChronology() ? this : new DateMidnight(getMillis(), newChronology)); + } + + /** + * Gets a copy of this instant with a different time zone, preserving the day + * The returned object will have a local time of midnight in the new zone on + * the same day as the original instant. + * + * @param newZone the new time zone, null means default + * @return a copy of this instant with a different time zone + */ + public DateMidnight withZoneRetainFields(DateTimeZone newZone) { + newZone = DateTimeUtils.getZone(newZone); + DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); + if (newZone == originalZone) { + return this; + } + + long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); + return new DateMidnight(millis, getChronology().withZone(newZone)); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the partial set of fields replacing those + * from this instance. + *

+ * For example, if the partial is a YearMonthDay then the date fields + * would be changed in the returned instance. + * If the partial is null, then this is returned. + * + * @param partial the partial set of fields to apply to this datetime, null ignored + * @return a copy of this datetime with a different set of fields + * @throws IllegalArgumentException if any value is invalid + */ + public DateMidnight withFields(ReadablePartial partial) { + if (partial == null) { + return this; + } + return withMillis(getChronology().set(partial, getMillis())); + } + + /** + * Gets a copy of this datetime with the specified field set to a new value. + *

+ * For example, if the field type is dayOfMonth then the day of month + * field would be changed in the returned instance. + * If the field type is null, then this is returned. + *

+ * These three lines are equivalent: + *

+     * DateTime updated = dt.withField(DateTimeFieldType.dayOfMonth(), 6);
+     * DateTime updated = dt.dayOfMonth().setCopy(6);
+     * DateTime updated = dt.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
+     * 
+ * + * @param fieldType the field type to set, not null + * @param value the value to set + * @return a copy of this datetime with the field set + * @throws IllegalArgumentException if the value is null or invalid + */ + public DateMidnight withField(DateTimeFieldType fieldType, int value) { + if (fieldType == null) { + throw new IllegalArgumentException("Field must not be null"); + } + long instant = fieldType.getField(getChronology()).set(getMillis(), value); + return withMillis(instant); + } + + /** + * Gets a copy of this datetime with the value of the specified field increased. + *

+ * If the addition is zero or the field is null, then this is returned. + * These three lines are equivalent: + *

+     * DateTime added = dt.withFieldAdded(DateTimeFieldType.dayOfMonth(), 6);
+     * DateTime added = dt.dayOfMonth().addToCopy(6);
+     * DateTime added = dt.property(DateTimeFieldType.dayOfMonth()).addToCopy(6);
+     * 
+ * + * @param fieldType the field type to add to, not null + * @param amount the amount to add + * @return a copy of this datetime with the field updated + * @throws IllegalArgumentException if the value is null or invalid + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight withFieldAdded(DurationFieldType fieldType, int amount) { + if (fieldType == null) { + throw new IllegalArgumentException("Field must not be null"); + } + if (amount == 0) { + return this; + } + long instant = fieldType.getField(getChronology()).add(getMillis(), amount); + return withMillis(instant); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the addition is zero, then this is returned. + * + * @param durationToAdd the duration to add to this one + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight withDurationAdded(long durationToAdd, int scalar) { + if (durationToAdd == 0 || scalar == 0) { + return this; + } + long instant = getChronology().add(getMillis(), durationToAdd, scalar); + return withMillis(instant); + } + + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the addition is zero, then this is returned. + * + * @param durationToAdd the duration to add to this one, null means zero + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight withDurationAdded(ReadableDuration durationToAdd, int scalar) { + if (durationToAdd == null || scalar == 0) { + return this; + } + return withDurationAdded(durationToAdd.getMillis(), scalar); + } + + /** + * Gets a copy of this datetime with the specified period added. + *

+ * If the addition is zero, then this is returned. + *

+ * To add or subtract on a single field use the properties, for example: + *

+     * DateTime added = dt.dayOfMonth().addToCopy(6);
+     * 
+ * + * @param period the period to add to this one, null means zero + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this datetime with the period added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight withPeriodAdded(ReadablePeriod period, int scalar) { + if (period == null || scalar == 0) { + return this; + } + long instant = getChronology().add(period, getMillis(), scalar); + return withMillis(instant); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to add to this one + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight plus(long duration) { + return withDurationAdded(duration, 1); + } + + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to add to this one, null means zero + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight plus(ReadableDuration duration) { + return withDurationAdded(duration, 1); + } + + /** + * Gets a copy of this datetime with the specified period added. + *

+ * If the amount is zero or null, then this is returned. + *

+ * The following two lines are identical in effect: + *

+     * DateTime added = dt.hourOfDay().addToCopy(6);
+     * DateTime added = dt.plus(Period.hours(6));
+     * 
+ * + * @param period the duration to add to this one, null means zero + * @return a copy of this datetime with the period added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight plus(ReadablePeriod period) { + return withPeriodAdded(period, 1); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the specified duration take away. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to reduce this instant by + * @return a copy of this datetime with the duration taken away + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight minus(long duration) { + return withDurationAdded(duration, -1); + } + + /** + * Gets a copy of this datetime with the specified duration take away. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to reduce this instant by + * @return a copy of this datetime with the duration taken away + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight minus(ReadableDuration duration) { + return withDurationAdded(duration, -1); + } + + /** + * Gets a copy of this datetime with the specified period take away. + *

+ * If the amount is zero or null, then this is returned. + *

+ * The following two lines are identical in effect: + *

+     * DateTime added = dt.hourOfDay().addToCopy(-6);
+     * DateTime added = dt.minus(Period.hours(6));
+     * 
+ * + * @param period the period to reduce this instant by + * @return a copy of this datetime with the period taken away + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateMidnight minus(ReadablePeriod period) { + return withPeriodAdded(period, -1); + } + + //----------------------------------------------------------------------- + /** + * Gets the property object for the specified type, which contains many useful methods. + * + * @param type the field type to get the chronology for + * @return the property object + * @throws IllegalArgumentException if the field is null or unsupported + */ + public Property property(DateTimeFieldType type) { + DateTimeField field = type.getField(getChronology()); + if (field.isSupported() == false) { + throw new IllegalArgumentException("Field '" + type + "' is not supported"); + } + return new Property(this, field); + } + + //----------------------------------------------------------------------- + /** + * Converts this object to a YearMonthDay using the same millis and chronology. + * + * @return a YearMonthDay using the same millis and chronology + */ + public YearMonthDay toYearMonthDay() { + return new YearMonthDay(getMillis(), getChronology()); + } + + /** + * Converts this object to an Interval encompassing the whole of this day. + *

+ * The interval starts at midnight 00:00 and ends at 00:00 the following day, + * (which is not included in the interval, as intervals are half-open). + * + * @return a YearMonthDay using the same millis and chronology + */ + public Interval toInterval() { + Chronology chrono = getChronology(); + long start = getMillis(); + long end = DurationFieldType.days().getField(chrono).add(start, 1); + return new Interval(start, end, chrono); + } + + // Date properties + //----------------------------------------------------------------------- + /** + * Get the era property. + * + * @return the era property + */ + public Property era() { + return new Property(this, getChronology().era()); + } + + /** + * Get the century of era property. + * + * @return the year of era property + */ + public Property centuryOfEra() { + return new Property(this, getChronology().centuryOfEra()); + } + + /** + * Get the year of century property. + * + * @return the year of era property + */ + public Property yearOfCentury() { + return new Property(this, getChronology().yearOfCentury()); + } + + /** + * Get the year of era property. + * + * @return the year of era property + */ + public Property yearOfEra() { + return new Property(this, getChronology().yearOfEra()); + } + + /** + * Get the year property. + * + * @return the year property + */ + public Property year() { + return new Property(this, getChronology().year()); + } + + /** + * Get the year of a week based year property. + * + * @return the year of a week based year property + */ + public Property weekyear() { + return new Property(this, getChronology().weekyear()); + } + + /** + * Get the month of year property. + * + * @return the month of year property + */ + public Property monthOfYear() { + return new Property(this, getChronology().monthOfYear()); + } + + /** + * Get the week of a week based year property. + * + * @return the week of a week based year property + */ + public Property weekOfWeekyear() { + return new Property(this, getChronology().weekOfWeekyear()); + } + + /** + * Get the day of year property. + * + * @return the day of year property + */ + public Property dayOfYear() { + return new Property(this, getChronology().dayOfYear()); + } + + /** + * Get the day of month property. + * + * @return the day of month property + */ + public Property dayOfMonth() { + return new Property(this, getChronology().dayOfMonth()); + } + + /** + * Get the day of week property. + * + * @return the day of week property + */ + public Property dayOfWeek() { + return new Property(this, getChronology().dayOfWeek()); + } + + //----------------------------------------------------------------------- + /** + * DateMidnight.Property binds a DateMidnight to a DateTimeField allowing powerful + * datetime functionality to be easily accessed. + *

+ * The simplest use of this class is as an alternative get method, here used to + * get the year '1972' (as an int) and the month 'December' (as a String). + *

+     * DateMidnight dt = new DateMidnight(1972, 12, 3);
+     * int year = dt.year().get();
+     * String monthStr = dt.monthOfYear().getAsText();
+     * 
+ *

+ * Methods are also provided that allow date modification. These return new instances + * of DateMidnight - they do not modify the original. The example below yields two + * independent immutable date objects 20 years apart. + *

+     * DateMidnight dt = new DateMidnight(1972, 12, 3);
+     * DateMidnight dt20 = dt.year().addToCopy(20);
+     * 
+ * Serious modification of dates (ie. more than just changing one or two fields) + * should use the {@link org.joda.time.MutableDateTime MutableDateTime} class. + *

+ * DateMidnight.Property itself is thread-safe and immutable. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ + public static final class Property extends AbstractReadableInstantFieldProperty { + + /** Serialization lock */ + private static final long serialVersionUID = 257629620L; + + /** The instant this property is working against */ + private final DateMidnight iInstant; + /** The field this property is working against */ + private final DateTimeField iField; + + /** + * Constructor. + * + * @param instant the instant to set + * @param field the field to use + */ + Property(DateMidnight instant, DateTimeField field) { + super(); + iInstant = instant; + iField = field; + } + + //----------------------------------------------------------------------- + /** + * Gets the field being used. + * + * @return the field + */ + public DateTimeField getField() { + return iField; + } + + /** + * Gets the instant being used. + * + * @return the instant + */ + public ReadableInstant getReadableInstant() { + return iInstant; + } + + /** + * Gets the datetime being used. + * + * @return the datetime + */ + public DateMidnight getDateMidnight() { + return iInstant; + } + + //----------------------------------------------------------------------- + /** + * Adds to this field in a copy of this DateMidnight. + *

+ * The DateMidnight attached to this property is unchanged by this call. + * This operation is faster than converting a DateMidnight to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to add to the field in the copy + * @return a copy of the DateMidnight with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateMidnight addToCopy(int value) { + return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); + } + + /** + * Adds to this field in a copy of this DateMidnight. + *

+ * The DateMidnight attached to this property is unchanged by this call. + * This operation is faster than converting a DateMidnight to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to add to the field in the copy + * @return a copy of the DateMidnight with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateMidnight addToCopy(long value) { + return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); + } + + /** + * Adds to this field, possibly wrapped, in a copy of this DateMidnight. + * A wrapped operation only changes this field. + * Thus 31st January addWrapField one day goes to the 1st January. + *

+ * The DateMidnight attached to this property is unchanged by this call. + * This operation is faster than converting a DateMidnight to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to add to the field in the copy + * @return a copy of the DateMidnight with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateMidnight addWrapFieldToCopy(int value) { + return iInstant.withMillis(iField.addWrapField(iInstant.getMillis(), value)); + } + + //----------------------------------------------------------------------- + /** + * Sets this field in a copy of the DateMidnight. + *

+ * The DateMidnight attached to this property is unchanged by this call. + * This operation is faster than converting a DateMidnight to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to set the field in the copy to + * @return a copy of the DateMidnight with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateMidnight setCopy(int value) { + return iInstant.withMillis(iField.set(iInstant.getMillis(), value)); + } + + /** + * Sets this field in a copy of the DateMidnight to a parsed text value. + *

+ * The DateMidnight attached to this property is unchanged by this call. + * This operation is faster than converting a DateMidnight to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param text the text value to set + * @param locale optional locale to use for selecting a text symbol + * @return a copy of the DateMidnight with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public DateMidnight setCopy(String text, Locale locale) { + return iInstant.withMillis(iField.set(iInstant.getMillis(), text, locale)); + } + + /** + * Sets this field in a copy of the DateMidnight to a parsed text value. + *

+ * The DateMidnight attached to this property is unchanged by this call. + * This operation is faster than converting a DateMidnight to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param text the text value to set + * @return a copy of the DateMidnight with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public DateMidnight setCopy(String text) { + return setCopy(text, null); + } + + //----------------------------------------------------------------------- + /** + * Rounds to the lowest whole unit of this field on a copy of this DateMidnight. + * + * @return a copy of the DateMidnight with the field value changed + */ + public DateMidnight roundFloorCopy() { + return iInstant.withMillis(iField.roundFloor(iInstant.getMillis())); + } + + /** + * Rounds to the highest whole unit of this field on a copy of this DateMidnight. + * + * @return a copy of the DateMidnight with the field value changed + */ + public DateMidnight roundCeilingCopy() { + return iInstant.withMillis(iField.roundCeiling(iInstant.getMillis())); + } + + /** + * Rounds to the nearest whole unit of this field on a copy of this DateMidnight, + * favoring the floor if halfway. + * + * @return a copy of the DateMidnight with the field value changed + */ + public DateMidnight roundHalfFloorCopy() { + return iInstant.withMillis(iField.roundHalfFloor(iInstant.getMillis())); + } + + /** + * Rounds to the nearest whole unit of this field on a copy of this DateMidnight, + * favoring the ceiling if halfway. + * + * @return a copy of the DateMidnight with the field value changed + */ + public DateMidnight roundHalfCeilingCopy() { + return iInstant.withMillis(iField.roundHalfCeiling(iInstant.getMillis())); + } + + /** + * Rounds to the nearest whole unit of this field on a copy of this DateMidnight. + * If halfway, the ceiling is favored over the floor only if it makes this field's value even. + * + * @return a copy of the DateMidnight with the field value changed + */ + public DateMidnight roundHalfEvenCopy() { + return iInstant.withMillis(iField.roundHalfEven(iInstant.getMillis())); + } + + } +} Index: 3rdParty_sources/joda-time/org/joda/time/DateTime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateTime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateTime.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,1175 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; +import java.util.Locale; + +import org.joda.time.base.BaseDateTime; +import org.joda.time.chrono.ISOChronology; +import org.joda.time.field.AbstractReadableInstantFieldProperty; + +/** + * DateTime is the standard implementation of an unmodifiable datetime class. + * It holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. + *

+ * This class uses a Chronology internally. The Chronology determines how the + * millisecond instant value is converted into the date time fields. + * The default Chronology is ISOChronology which is the agreed + * international standard and compatable with the modern Gregorian calendar. + * + *

Each individual field can be queried in two ways: + *

+ * The second technique also provides access to other useful methods on the + * field: + * + * + *

+ * DateTime is thread-safe and immutable, provided that the Chronology is as well. + * All standard Chronology classes supplied are thread-safe and immutable. + * + * @author Stephen Colebourne + * @author Kandarp Shah + * @author Brian S O'Neill + * @since 1.0 + * @see MutableDateTime + */ +public final class DateTime + extends BaseDateTime + implements ReadableDateTime, Serializable { + + /** Serialization lock */ + private static final long serialVersionUID = -5171125899451703815L; + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the default time zone. + */ + public DateTime() { + super(); + } + + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param zone the time zone, null means default zone + */ + public DateTime(DateTimeZone zone) { + super(zone); + } + + /** + * Constructs an instance set to the current system millisecond time + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param chronology the chronology, null means ISOChronology in default zone + */ + public DateTime(Chronology chronology) { + super(chronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the default time zone. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + public DateTime(long instant) { + super(instant); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param zone the time zone, null means default zone + */ + public DateTime(long instant, DateTimeZone zone) { + super(instant, zone); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param chronology the chronology, null means ISOChronology in default zone + */ + public DateTime(long instant, Chronology chronology) { + super(instant, chronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from an Object that represents a datetime. + *

+ * If the object implies a chronology (such as GregorianCalendar does), + * then that chronology will be used. Otherwise, ISO default is used. + * Thus if a GregorianCalendar is passed in, the chronology used will + * be GJ, but if a Date is passed in the chronology will be ISO. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @throws IllegalArgumentException if the instant is invalid + */ + public DateTime(Object instant) { + super(instant, (Chronology) null); + } + + /** + * Constructs an instance from an Object that represents a datetime, + * forcing the time zone to that specified. + *

+ * If the object implies a chronology (such as GregorianCalendar does), + * then that chronology will be used, but with the time zone adjusted. + * Otherwise, ISO is used in the specified time zone. + * If the specified time zone is null, the default zone is used. + * Thus if a GregorianCalendar is passed in, the chronology used will + * be GJ, but if a Date is passed in the chronology will be ISO. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @param zone the time zone, null means default time zone + * @throws IllegalArgumentException if the instant is invalid + */ + public DateTime(Object instant, DateTimeZone zone) { + super(instant, zone); + } + + /** + * Constructs an instance from an Object that represents a datetime, + * using the specified chronology. + *

+ * If the chronology is null, ISO in the default time zone is used. + * Any chronology implied by the object (such as GregorianCalendar does) + * is ignored. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @param chronology the chronology, null means ISO in default zone + * @throws IllegalArgumentException if the instant is invalid + */ + public DateTime(Object instant, Chronology chronology) { + super(instant, DateTimeUtils.getChronology(chronology)); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from datetime field values + * using ISOChronology in the default time zone. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + */ + public DateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond) { + super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + + /** + * Constructs an instance from datetime field values + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @param zone the time zone, null means default time zone + */ + public DateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond, + DateTimeZone zone) { + super(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, zone); + } + + /** + * Constructs an instance from datetime field values + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @param chronology the chronology, null means ISOChronology in default zone + */ + public DateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond, + Chronology chronology) { + super(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, chronology); + } + + //----------------------------------------------------------------------- + /** + * Get this object as a DateTime by returning this. + * + * @return this + */ + public DateTime toDateTime() { + return this; + } + + /** + * Get this object as a DateTime using ISOChronology in the default zone, + * returning this if possible. + * + * @return a DateTime using the same millis + */ + public DateTime toDateTimeISO() { + if (getChronology() == ISOChronology.getInstance()) { + return this; + } + return super.toDateTimeISO(); + } + + /** + * Get this object as a DateTime, returning this if possible. + * + * @param zone time zone to apply, or default if null + * @return a DateTime using the same millis + */ + public DateTime toDateTime(DateTimeZone zone) { + zone = DateTimeUtils.getZone(zone); + if (getZone() == zone) { + return this; + } + return super.toDateTime(zone); + } + + /** + * Get this object as a DateTime, returning this if possible. + * + * @param chronology chronology to apply, or ISOChronology if null + * @return a DateTime using the same millis + */ + public DateTime toDateTime(Chronology chronology) { + chronology = DateTimeUtils.getChronology(chronology); + if (getChronology() == chronology) { + return this; + } + return super.toDateTime(chronology); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with different millis. + *

+ * The returned object will be a new instance of the same implementation type. + * Only the millis will change, the chronology and time zone are kept. + * The returned object will be either be a new instance or this. + * + * @param newMillis the new millis, from 1970-01-01T00:00:00Z + * @return a copy of this datetime with different millis + */ + public DateTime withMillis(long newMillis) { + return (newMillis == getMillis() ? this : new DateTime(newMillis, getChronology())); + } + + /** + * Gets a copy of this datetime with a different chronology. + *

+ * The returned object will be a new instance of the same implementation type. + * Only the chronology will change, the millis are kept. + * The returned object will be either be a new instance or this. + * + * @param newChronology the new chronology, null means ISO default + * @return a copy of this datetime with a different chronology + */ + public DateTime withChronology(Chronology newChronology) { + newChronology = DateTimeUtils.getChronology(newChronology); + return (newChronology == getChronology() ? this : new DateTime(getMillis(), newChronology)); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with a different time zone, preserving the + * millisecond instant. + *

+ * This method is useful for finding the local time in another timezone. + * For example, if this instant holds 12:30 in Europe/London, the result + * from this method with Europe/Paris would be 13:30. + *

+ * The returned object will be a new instance of the same implementation type. + * This method changes alters the time zone, and does not change the + * millisecond instant, with the effect that the field values usually change. + * The returned object will be either be a new instance or this. + * + * @param newZone the new time zone + * @return a copy of this datetime with a different time zone + * @see #withZoneRetainFields + */ + public DateTime withZone(DateTimeZone newZone) { + return withChronology(getChronology().withZone(newZone)); + } + + /** + * Gets a copy of this datetime with a different time zone, preserving the + * field values. + *

+ * This method is useful for finding the millisecond time in another timezone. + * For example, if this instant holds 12:30 in Europe/London (ie. 12:30Z), + * the result from this method with Europe/Paris would be 12:30 (ie. 11:30Z). + *

+ * The returned object will be a new instance of the same implementation type. + * This method alters the time zone and the millisecond instant to keep + * the field values the same. + * The returned object will be either be a new instance or this. + * + * @param newZone the new time zone, null means default + * @return a copy of this datetime with a different time zone + * @see #withZone + */ + public DateTime withZoneRetainFields(DateTimeZone newZone) { + newZone = DateTimeUtils.getZone(newZone); + DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); + if (newZone == originalZone) { + return this; + } + + long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); + return new DateTime(millis, getChronology().withZone(newZone)); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the specified date, retaining the time fields. + *

+ * If the date is already the date passed in, then this is returned. + *

+ * To set a single field use the properties, for example: + *

+     * DateTime set = monthOfYear().setCopy(6);
+     * 
+ * + * @param year the new year value + * @param monthOfYear the new monthOfYear value + * @param dayOfMonth the new dayOfMonth value + * @return a copy of this datetime with a different date + * @throws IllegalArgumentException if any value if invalid + */ + public DateTime withDate(int year, int monthOfYear, int dayOfMonth) { + Chronology chrono = getChronology(); + long instant = getMillis(); + instant = chrono.year().set(instant, year); + instant = chrono.monthOfYear().set(instant, monthOfYear); + instant = chrono.dayOfMonth().set(instant, dayOfMonth); + return withMillis(instant); + } + + /** + * Gets a copy of this datetime with the specified time, retaining the date fields. + *

+ * If the time is already the time passed in, then this is returned. + *

+ * To set a single field use the properties, for example: + *

+     * DateTime set = dt.hourOfDay().setCopy(6);
+     * 
+ * + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @return a copy of this datetime with a different time + * @throws IllegalArgumentException if any value if invalid + */ + public DateTime withTime(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { + Chronology chrono = getChronology(); + long instant = getMillis(); + instant = chrono.hourOfDay().set(instant, hourOfDay); + instant = chrono.minuteOfHour().set(instant, minuteOfHour); + instant = chrono.secondOfMinute().set(instant, secondOfMinute); + instant = chrono.millisOfSecond().set(instant, millisOfSecond); + return withMillis(instant); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the partial set of fields replacing those + * from this instance. + *

+ * For example, if the partial is a TimeOfDay then the time fields + * would be changed in the returned instance. + * If the partial is null, then this is returned. + * + * @param partial the partial set of fields to apply to this datetime, null ignored + * @return a copy of this datetime with a different set of fields + * @throws IllegalArgumentException if any value is invalid + */ + public DateTime withFields(ReadablePartial partial) { + if (partial == null) { + return this; + } + return withMillis(getChronology().set(partial, getMillis())); + } + + /** + * Gets a copy of this datetime with the specified field set to a new value. + *

+ * For example, if the field type is hourOfDay then the hour of day + * field would be changed in the returned instance. + * If the field type is null, then this is returned. + *

+ * These three lines are equivalent: + *

+     * DateTime updated = dt.withField(DateTimeFieldType.dayOfMonth(), 6);
+     * DateTime updated = dt.dayOfMonth().setCopy(6);
+     * DateTime updated = dt.property(DateTimeFieldType.dayOfMonth()).setCopy(6);
+     * 
+ * + * @param fieldType the field type to set, not null + * @param value the value to set + * @return a copy of this datetime with the field set + * @throws IllegalArgumentException if the value is null or invalid + */ + public DateTime withField(DateTimeFieldType fieldType, int value) { + if (fieldType == null) { + throw new IllegalArgumentException("Field must not be null"); + } + long instant = fieldType.getField(getChronology()).set(getMillis(), value); + return withMillis(instant); + } + + /** + * Gets a copy of this datetime with the value of the specified field increased. + *

+ * If the addition is zero or the field is null, then this is returned. + *

+ * These three lines are equivalent: + *

+     * DateTime added = dt.withField(DateTimeFieldType.dayOfMonth(), 6);
+     * DateTime added = dt.dayOfMonth().addToCopy(6);
+     * DateTime added = dt.property(DateTimeFieldType.dayOfMonth()).addToCopy(6);
+     * 
+ * + * @param fieldType the field type to add to, not null + * @param amount the amount to add + * @return a copy of this datetime with the field updated + * @throws IllegalArgumentException if the value is null or invalid + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime withFieldAdded(DurationFieldType fieldType, int amount) { + if (fieldType == null) { + throw new IllegalArgumentException("Field must not be null"); + } + if (amount == 0) { + return this; + } + long instant = fieldType.getField(getChronology()).add(getMillis(), amount); + return withMillis(instant); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the addition is zero, then this is returned. + * + * @param durationToAdd the duration to add to this one + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime withDurationAdded(long durationToAdd, int scalar) { + if (durationToAdd == 0 || scalar == 0) { + return this; + } + long instant = getChronology().add(getMillis(), durationToAdd, scalar); + return withMillis(instant); + } + + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the addition is zero, then this is returned. + * + * @param durationToAdd the duration to add to this one, null means zero + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime withDurationAdded(ReadableDuration durationToAdd, int scalar) { + if (durationToAdd == null || scalar == 0) { + return this; + } + return withDurationAdded(durationToAdd.getMillis(), scalar); + } + + /** + * Gets a copy of this datetime with the specified period added. + *

+ * If the addition is zero, then this is returned. + *

+ * To add or subtract on a single field use the properties, for example: + *

+     * DateTime added = dt.hourOfDay().addToCopy(6);
+     * 
+ * + * @param period the period to add to this one, null means zero + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this datetime with the period added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime withPeriodAdded(ReadablePeriod period, int scalar) { + if (period == null || scalar == 0) { + return this; + } + long instant = getChronology().add(period, getMillis(), scalar); + return withMillis(instant); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to add to this one + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime plus(long duration) { + return withDurationAdded(duration, 1); + } + + /** + * Gets a copy of this datetime with the specified duration added. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to add to this one, null means zero + * @return a copy of this datetime with the duration added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime plus(ReadableDuration duration) { + return withDurationAdded(duration, 1); + } + + /** + * Gets a copy of this datetime with the specified period added. + *

+ * If the amount is zero or null, then this is returned. + *

+ * The following two lines are identical in effect: + *

+     * DateTime added = dt.hourOfDay().addToCopy(6);
+     * DateTime added = dt.plus(Period.hours(6));
+     * 
+ * + * @param period the duration to add to this one, null means zero + * @return a copy of this datetime with the period added + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime plus(ReadablePeriod period) { + return withPeriodAdded(period, 1); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this datetime with the specified duration take away. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to reduce this instant by + * @return a copy of this datetime with the duration taken away + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime minus(long duration) { + return withDurationAdded(duration, -1); + } + + /** + * Gets a copy of this datetime with the specified duration take away. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to reduce this instant by + * @return a copy of this datetime with the duration taken away + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime minus(ReadableDuration duration) { + return withDurationAdded(duration, -1); + } + + /** + * Gets a copy of this datetime with the specified period take away. + *

+ * If the amount is zero or null, then this is returned. + *

+ * The following two lines are identical in effect: + *

+     * DateTime added = dt.hourOfDay().addToCopy(-6);
+     * DateTime added = dt.minus(Period.hours(6));
+     * 
+ * + * @param period the period to reduce this instant by + * @return a copy of this datetime with the period taken away + * @throws ArithmeticException if the new datetime exceeds the capacity of a long + */ + public DateTime minus(ReadablePeriod period) { + return withPeriodAdded(period, -1); + } + + //----------------------------------------------------------------------- + /** + * Gets the property object for the specified type, which contains many useful methods. + * + * @param type the field type to get the chronology for + * @return the property object + * @throws IllegalArgumentException if the field is null or unsupported + */ + public Property property(DateTimeFieldType type) { + DateTimeField field = type.getField(getChronology()); + if (field.isSupported() == false) { + throw new IllegalArgumentException("Field '" + type + "' is not supported"); + } + return new Property(this, field); + } + + //----------------------------------------------------------------------- + /** + * Converts this object to a DateMidnight using the same millis and chronology. + * + * @return a DateMidnight using the same millis and chronology + */ + public DateMidnight toDateMidnight() { + return new DateMidnight(getMillis(), getChronology()); + } + + /** + * Converts this object to a YearMonthDay using the same millis and chronology. + * + * @return a YearMonthDay using the same millis and chronology + */ + public YearMonthDay toYearMonthDay() { + return new YearMonthDay(getMillis(), getChronology()); + } + + /** + * Converts this object to a TimeOfDay using the same millis and chronology. + * + * @return a TimeOfDay using the same millis and chronology + */ + public TimeOfDay toTimeOfDay() { + return new TimeOfDay(getMillis(), getChronology()); + } + + // Date properties + //----------------------------------------------------------------------- + /** + * Get the era property. + * + * @return the era property + */ + public Property era() { + return new Property(this, getChronology().era()); + } + + /** + * Get the century of era property. + * + * @return the year of era property + */ + public Property centuryOfEra() { + return new Property(this, getChronology().centuryOfEra()); + } + + /** + * Get the year of century property. + * + * @return the year of era property + */ + public Property yearOfCentury() { + return new Property(this, getChronology().yearOfCentury()); + } + + /** + * Get the year of era property. + * + * @return the year of era property + */ + public Property yearOfEra() { + return new Property(this, getChronology().yearOfEra()); + } + + /** + * Get the year property. + * + * @return the year property + */ + public Property year() { + return new Property(this, getChronology().year()); + } + + /** + * Get the year of a week based year property. + * + * @return the year of a week based year property + */ + public Property weekyear() { + return new Property(this, getChronology().weekyear()); + } + + /** + * Get the month of year property. + * + * @return the month of year property + */ + public Property monthOfYear() { + return new Property(this, getChronology().monthOfYear()); + } + + /** + * Get the week of a week based year property. + * + * @return the week of a week based year property + */ + public Property weekOfWeekyear() { + return new Property(this, getChronology().weekOfWeekyear()); + } + + /** + * Get the day of year property. + * + * @return the day of year property + */ + public Property dayOfYear() { + return new Property(this, getChronology().dayOfYear()); + } + + /** + * Get the day of month property. + * + * @return the day of month property + */ + public Property dayOfMonth() { + return new Property(this, getChronology().dayOfMonth()); + } + + /** + * Get the day of week property. + * + * @return the day of week property + */ + public Property dayOfWeek() { + return new Property(this, getChronology().dayOfWeek()); + } + + // Time properties + //----------------------------------------------------------------------- + /** + * Get the hour of day field property + * + * @return the hour of day property + */ + public Property hourOfDay() { + return new Property(this, getChronology().hourOfDay()); + } + + /** + * Get the minute of day property + * + * @return the minute of day property + */ + public Property minuteOfDay() { + return new Property(this, getChronology().minuteOfDay()); + } + + /** + * Get the minute of hour field property + * + * @return the minute of hour property + */ + public Property minuteOfHour() { + return new Property(this, getChronology().minuteOfHour()); + } + + /** + * Get the second of day property + * + * @return the second of day property + */ + public Property secondOfDay() { + return new Property(this, getChronology().secondOfDay()); + } + + /** + * Get the second of minute field property + * + * @return the second of minute property + */ + public Property secondOfMinute() { + return new Property(this, getChronology().secondOfMinute()); + } + + /** + * Get the millis of day property + * + * @return the millis of day property + */ + public Property millisOfDay() { + return new Property(this, getChronology().millisOfDay()); + } + + /** + * Get the millis of second property + * + * @return the millis of second property + */ + public Property millisOfSecond() { + return new Property(this, getChronology().millisOfSecond()); + } + + //----------------------------------------------------------------------- + /** + * DateTime.Property binds a DateTime to a DateTimeField allowing powerful + * datetime functionality to be easily accessed. + *

+ * The simplest use of this class is as an alternative get method, here used to + * get the year '1972' (as an int) and the month 'December' (as a String). + *

+     * DateTime dt = new DateTime(1972, 12, 3, 0, 0, 0, 0);
+     * int year = dt.year().get();
+     * String monthStr = dt.month().getAsText();
+     * 
+ *

+ * Methods are also provided that allow date modification. These return new instances + * of DateTime - they do not modify the original. The example below yields two + * independent immutable date objects 20 years apart. + *

+     * DateTime dt = new DateTime(1972, 12, 3, 0, 0, 0, 0);
+     * DateTime dt20 = dt.year().addToCopy(20);
+     * 
+ * Serious modification of dates (ie. more than just changing one or two fields) + * should use the {@link org.joda.time.MutableDateTime MutableDateTime} class. + *

+ * DateTime.Propery itself is thread-safe and immutable, as well as the + * DateTime being operated on. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ + public static final class Property extends AbstractReadableInstantFieldProperty { + + /** Serialization version */ + private static final long serialVersionUID = -6983323811635733510L; + + /** The instant this property is working against */ + private final DateTime iInstant; + /** The field this property is working against */ + private final DateTimeField iField; + + /** + * Constructor. + * + * @param instant the instant to set + * @param field the field to use + */ + Property(DateTime instant, DateTimeField field) { + super(); + iInstant = instant; + iField = field; + } + + //----------------------------------------------------------------------- + /** + * Gets the field being used. + * + * @return the field + */ + public DateTimeField getField() { + return iField; + } + + /** + * Gets the instant being used. + * + * @return the instant + */ + public ReadableInstant getReadableInstant() { + return iInstant; + } + + /** + * Gets the datetime being used. + * + * @return the datetime + */ + public DateTime getDateTime() { + return iInstant; + } + + //----------------------------------------------------------------------- + /** + * Adds to this field in a copy of this DateTime. + *

+ * The DateTime attached to this property is unchanged by this call. + * This operation is faster than converting a DateTime to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to add to the field in the copy + * @return a copy of the DateTime with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateTime addToCopy(int value) { + return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); + } + + /** + * Adds to this field in a copy of this DateTime. + *

+ * The DateTime attached to this property is unchanged by this call. + * This operation is faster than converting a DateTime to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to add to the field in the copy + * @return a copy of the DateTime with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateTime addToCopy(long value) { + return iInstant.withMillis(iField.add(iInstant.getMillis(), value)); + } + + /** + * Adds to this field, possibly wrapped, in a copy of this DateTime. + * A wrapped operation only changes this field. + * Thus 31st January addWrapField one day goes to the 1st January. + *

+ * The DateTime attached to this property is unchanged by this call. + * This operation is faster than converting a DateTime to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to add to the field in the copy + * @return a copy of the DateTime with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateTime addWrapFieldToCopy(int value) { + return iInstant.withMillis(iField.addWrapField(iInstant.getMillis(), value)); + } + + //----------------------------------------------------------------------- + /** + * Sets this field in a copy of the DateTime. + *

+ * The DateTime attached to this property is unchanged by this call. + * This operation is faster than converting a DateTime to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param value the value to set the field in the copy to + * @return a copy of the DateTime with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public DateTime setCopy(int value) { + return iInstant.withMillis(iField.set(iInstant.getMillis(), value)); + } + + /** + * Sets this field in a copy of the DateTime to a parsed text value. + *

+ * The DateTime attached to this property is unchanged by this call. + * This operation is faster than converting a DateTime to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param text the text value to set + * @param locale optional locale to use for selecting a text symbol + * @return a copy of the DateTime with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public DateTime setCopy(String text, Locale locale) { + return iInstant.withMillis(iField.set(iInstant.getMillis(), text, locale)); + } + + /** + * Sets this field in a copy of the DateTime to a parsed text value. + *

+ * The DateTime attached to this property is unchanged by this call. + * This operation is faster than converting a DateTime to a MutableDateTime + * and back again when setting one field. When setting multiple fields, + * it is generally quicker to make the conversion to MutableDateTime. + * + * @param text the text value to set + * @return a copy of the DateTime with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public DateTime setCopy(String text) { + return setCopy(text, null); + } + + //----------------------------------------------------------------------- + /** + * Rounds to the lowest whole unit of this field on a copy of this DateTime. + * + * @return a copy of the DateTime with the field value changed + */ + public DateTime roundFloorCopy() { + return iInstant.withMillis(iField.roundFloor(iInstant.getMillis())); + } + + /** + * Rounds to the highest whole unit of this field on a copy of this DateTime. + * + * @return a copy of the DateTime with the field value changed + */ + public DateTime roundCeilingCopy() { + return iInstant.withMillis(iField.roundCeiling(iInstant.getMillis())); + } + + /** + * Rounds to the nearest whole unit of this field on a copy of this DateTime, + * favoring the floor if halfway. + * + * @return a copy of the DateTime with the field value changed + */ + public DateTime roundHalfFloorCopy() { + return iInstant.withMillis(iField.roundHalfFloor(iInstant.getMillis())); + } + + /** + * Rounds to the nearest whole unit of this field on a copy of this DateTime, + * favoring the ceiling if halfway. + * + * @return a copy of the DateTime with the field value changed + */ + public DateTime roundHalfCeilingCopy() { + return iInstant.withMillis(iField.roundHalfCeiling(iInstant.getMillis())); + } + + /** + * Rounds to the nearest whole unit of this field on a copy of this + * DateTime. If halfway, the ceiling is favored over the floor only if + * it makes this field's value even. + * + * @return a copy of the DateTime with the field value changed + */ + public DateTime roundHalfEvenCopy() { + return iInstant.withMillis(iField.roundHalfEven(iInstant.getMillis())); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/DateTimeComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateTimeComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateTimeComparator.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,295 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; +import java.util.Comparator; + +import org.joda.time.convert.ConverterManager; +import org.joda.time.convert.InstantConverter; + +/** + * DateTimeComparator provides comparators to compare one date with another. + *

+ * Dates may be specified using any object recognised by the + * {@link org.joda.time.convert.ConverterManager ConverterManager} class. + *

+ * The default objects recognised by the comparator are: + *

+ * + *

+ * DateTimeComparator is thread-safe and immutable. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public class DateTimeComparator implements Comparator, Serializable { + + /** Serialization lock */ + private static final long serialVersionUID = -6097339773320178364L; + + /** Singleton instance */ + private static final DateTimeComparator ALL_INSTANCE = new DateTimeComparator(null, null); + /** Singleton instance */ + private static final DateTimeComparator DATE_INSTANCE = new DateTimeComparator(DateTimeFieldType.dayOfYear(), null); + /** Singleton instance */ + private static final DateTimeComparator TIME_INSTANCE = new DateTimeComparator(null, DateTimeFieldType.dayOfYear()); + + /** The lower limit of fields to compare, null if no limit */ + private final DateTimeFieldType iLowerLimit; + /** The upper limit of fields to compare, null if no limit */ + private final DateTimeFieldType iUpperLimit; + + //----------------------------------------------------------------------- + /** + * Returns a DateTimeComparator the compares the entire date time value. + * + * @return a comparator over all fields + */ + public static DateTimeComparator getInstance() { + return ALL_INSTANCE; + } + + /** + * Returns a DateTimeComparator with a lower limit only. Fields of a + * magnitude less than the lower limit are excluded from comparisons. + * + * @param lowerLimit inclusive lower limit for fields to be compared, null means no limit + * @return a comparator over all fields above the lower limit + */ + public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit) { + return getInstance(lowerLimit, null); + } + + /** + * Returns a DateTimeComparator with a lower and upper limit. Fields of a + * magnitude less than the lower limit are excluded from comparisons. + * Fields of a magnitude greater than or equal to the upper limit are also + * excluded from comparisons. Either limit may be specified as null, which + * indicates an unbounded limit. + * + * @param lowerLimit inclusive lower limit for fields to be compared, null means no limit + * @param upperLimit exclusive upper limit for fields to be compared, null means no limit + * @return a comparator over all fields between the limits + */ + public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit) { + if (lowerLimit == null && upperLimit == null) { + return ALL_INSTANCE; + } + if (lowerLimit == DateTimeFieldType.dayOfYear() && upperLimit == null) { + return DATE_INSTANCE; + } + if (lowerLimit == null && upperLimit == DateTimeFieldType.dayOfYear()) { + return TIME_INSTANCE; + } + return new DateTimeComparator(lowerLimit, upperLimit); + } + + /** + * Returns a comparator that only considers date fields. + * Time of day is ignored. + * + * @return a comparator over all date fields + */ + public static DateTimeComparator getDateOnlyInstance() { + return DATE_INSTANCE; + } + + /** + * Returns a comparator that only considers time fields. + * Date is ignored. + * + * @return a comparator over all time fields + */ + public static DateTimeComparator getTimeOnlyInstance() { + return TIME_INSTANCE; + } + + /** + * Restricted constructor. + * + * @param lowerLimit the lower field limit, null means no limit + * @param upperLimit the upper field limit, null means no limit + */ + protected DateTimeComparator(DateTimeFieldType lowerLimit, DateTimeFieldType upperLimit) { + super(); + iLowerLimit = lowerLimit; + iUpperLimit = upperLimit; + } + + //----------------------------------------------------------------------- + /** + * Gets the field type that represents the lower limit of comparison. + * + * @return the field type, null if no upper limit + */ + public DateTimeFieldType getLowerLimit() { + return iLowerLimit; + } + + /** + * Gets the field type that represents the upper limit of comparison. + * + * @return the field type, null if no upper limit + */ + public DateTimeFieldType getUpperLimit() { + return iUpperLimit; + } + + /** + * Compare two objects against only the range of date time fields as + * specified in the constructor. + * + * @param lhsObj the first object, + * logically on the left of a < comparison, null means now + * @param rhsObj the second object, + * logically on the right of a < comparison, null means now + * @return zero if order does not matter, + * negative value if lhsObj < rhsObj, positive value otherwise. + * @throws IllegalArgumentException if either argument is not supported + */ + public int compare(Object lhsObj, Object rhsObj) { + InstantConverter conv = ConverterManager.getInstance().getInstantConverter(lhsObj); + Chronology lhsChrono = conv.getChronology(lhsObj, (Chronology) null); + long lhsMillis = conv.getInstantMillis(lhsObj, lhsChrono); + + conv = ConverterManager.getInstance().getInstantConverter(rhsObj); + Chronology rhsChrono = conv.getChronology(rhsObj, (Chronology) null); + long rhsMillis = conv.getInstantMillis(rhsObj, rhsChrono); + + if (iLowerLimit != null) { + lhsMillis = iLowerLimit.getField(lhsChrono).roundFloor(lhsMillis); + rhsMillis = iLowerLimit.getField(rhsChrono).roundFloor(rhsMillis); + } + + if (iUpperLimit != null) { + lhsMillis = iUpperLimit.getField(lhsChrono).remainder(lhsMillis); + rhsMillis = iUpperLimit.getField(rhsChrono).remainder(rhsMillis); + } + + if (lhsMillis < rhsMillis) { + return -1; + } else if (lhsMillis > rhsMillis) { + return 1; + } else { + return 0; + } + } + + //----------------------------------------------------------------------- + /** + * Support serialization singletons. + * + * @return the resolved singleton instance + */ + private Object readResolve() { + return getInstance(iLowerLimit, iUpperLimit); + } + + /** + * Compares this comparator to another. + * + * @param object the object to compare to + * @return true if equal + */ + public boolean equals(Object object) { + if (object instanceof DateTimeComparator) { + DateTimeComparator other = (DateTimeComparator) object; + return (iLowerLimit == other.getLowerLimit() || + (iLowerLimit != null && iLowerLimit.equals(other.getLowerLimit()))) && + (iUpperLimit == other.getUpperLimit() || + (iUpperLimit != null && iUpperLimit.equals(other.getUpperLimit()))); + } + return false; + } + + /** + * Gets a suitable hashcode. + * + * @return the hashcode + */ + public int hashCode() { + return (iLowerLimit == null ? 0 : iLowerLimit.hashCode()) + + (123 * (iUpperLimit == null ? 0 : iUpperLimit.hashCode())); + } + + /** + * Gets a debugging string. + * + * @return a debugging string + */ + public String toString() { + if (iLowerLimit == iUpperLimit) { + return "DateTimeComparator[" + + (iLowerLimit == null ? "" : iLowerLimit.getName()) + + "]"; + } else { + return "DateTimeComparator[" + + (iLowerLimit == null ? "" : iLowerLimit.getName()) + + "-" + + (iUpperLimit == null ? "" : iUpperLimit.getName()) + + "]"; + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/DateTimeConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateTimeConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateTimeConstants.java 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,196 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * DateTimeConstants is a non-instantiable class of constants used in + * the date time system. These are the ISO8601 constants, but should be + * used by all chronologies. + *

+ * DateTimeConstants is thread-safe and immutable. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public class DateTimeConstants { + + // These are ints not enumerations as they represent genuine int values + /** Constant (1) representing January, the first month (ISO) */ + public static final int JANUARY = 1; + + /** Constant (2) representing February, the second month (ISO) */ + public static final int FEBRUARY = 2; + + /** Constant (3) representing March, the third month (ISO) */ + public static final int MARCH = 3; + + /** Constant (4) representing April, the fourth month (ISO) */ + public static final int APRIL = 4; + + /** Constant (5) representing May, the fifth month (ISO) */ + public static final int MAY = 5; + + /** Constant (6) representing June, the sixth month (ISO) */ + public static final int JUNE = 6; + + /** Constant (7) representing July, the seventh month (ISO) */ + public static final int JULY = 7; + + /** Constant (8) representing August, the eighth month (ISO) */ + public static final int AUGUST = 8; + + /** Constant (9) representing September, the nineth month (ISO) */ + public static final int SEPTEMBER = 9; + + /** Constant (10) representing October, the tenth month (ISO) */ + public static final int OCTOBER = 10; + + /** Constant (11) representing November, the eleventh month (ISO) */ + public static final int NOVEMBER = 11; + + /** Constant (12) representing December, the twelfth month (ISO) */ + public static final int DECEMBER = 12; + + // These are ints not enumerations as they represent genuine int values + /** Constant (1) representing Monday, the first day of the week (ISO) */ + public static final int MONDAY = 1; + + /** Constant (2) representing Monday, the second day of the week (ISO) */ + public static final int TUESDAY = 2; + + /** Constant (3) representing Monday, the third day of the week (ISO) */ + public static final int WEDNESDAY = 3; + + /** Constant (4) representing Monday, the fourth day of the week (ISO) */ + public static final int THURSDAY = 4; + + /** Constant (5) representing Monday, the fifth day of the week (ISO) */ + public static final int FRIDAY = 5; + + /** Constant (6) representing Monday, the sixth day of the week (ISO) */ + public static final int SATURDAY = 6; + + /** Constant (7) representing Monday, the seventh day of the week (ISO) */ + public static final int SUNDAY = 7; + + + /** Constant (0) representing AM, the morning (from Calendar) */ + public static final int AM = 0; + + /** Constant (1) representing PM, the afternoon (from Calendar) */ + public static final int PM = 1; + + + /** Constant (0) representing BC, years before zero (from Calendar) */ + public static final int BC = 0; + /** Alternative constant (0) representing BCE, Before Common Era (secular) */ + public static final int BCE = 0; + + /** Constant (1) representing AD, years after zero (from Calendar) */ + public static final int AD = 1; + /** Alternative constant (1) representing CE, Common Era (secular) */ + public static final int CE = 1; + + + /** Milliseconds in one second (1000) (ISO) */ + public static final int MILLIS_PER_SECOND = 1000; + + /** Seconds in one minute (60) (ISO) */ + public static final int SECONDS_PER_MINUTE = 60; + /** Milliseconds in one minute (ISO) */ + public static final int MILLIS_PER_MINUTE = MILLIS_PER_SECOND * SECONDS_PER_MINUTE; + + /** Minutes in one hour (ISO) */ + public static final int MINUTES_PER_HOUR = 60; + /** Seconds in one hour (ISO) */ + public static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; + /** Milliseconds in one hour (ISO) */ + public static final int MILLIS_PER_HOUR = MILLIS_PER_MINUTE * MINUTES_PER_HOUR; + + /** Hours in a typical day (24) (ISO). Due to time zone offset changes, the + * number of hours per day can vary. */ + public static final int HOURS_PER_DAY = 24; + /** Minutes in a typical day (ISO). Due to time zone offset changes, the number + * of minutes per day can vary. */ + public static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY; + /** Seconds in a typical day (ISO). Due to time zone offset changes, the number + * of seconds per day can vary. */ + public static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY; + /** Milliseconds in a typical day (ISO). Due to time zone offset changes, the + * number of milliseconds per day can vary. */ + public static final int MILLIS_PER_DAY = MILLIS_PER_HOUR * HOURS_PER_DAY; + + /** Days in one week (7) (ISO) */ + public static final int DAYS_PER_WEEK = 7; + /** Hours in a typical week. Due to time zone offset changes, the number of + * hours per week can vary. */ + public static final int HOURS_PER_WEEK = HOURS_PER_DAY * DAYS_PER_WEEK; + /** Minutes in a typical week (ISO). Due to time zone offset changes, the number + * of minutes per week can vary. */ + public static final int MINUTES_PER_WEEK = MINUTES_PER_DAY * DAYS_PER_WEEK; + /** Seconds in a typical week (ISO). Due to time zone offset changes, the number + * of seconds per week can vary. */ + public static final int SECONDS_PER_WEEK = SECONDS_PER_DAY * DAYS_PER_WEEK; + /** Milliseconds in a typical week (ISO). Due to time zone offset changes, the + * number of milliseconds per week can vary. */ + public static final int MILLIS_PER_WEEK = MILLIS_PER_DAY * DAYS_PER_WEEK; + + /** + * Restrictive constructor + */ + protected DateTimeConstants() { + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/DateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateTimeField.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,662 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.util.Locale; + +/** + * Defines the calculation engine for date and time fields. + * The interface defines a set of methods that manipulate a millisecond datetime + * with regards to a single field, such as monthOfYear or secondOfMinute. + *

+ * This design is extensible so, if you wish, you can extract a different field from + * the milliseconds. A number of standard implementations are provided to assist. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class DateTimeField { + + /** + * Get the type of the field. + * + * @return field type + */ + public abstract DateTimeFieldType getType(); + + /** + * Get the name of the field. + *

+ * By convention, names follow a pattern of "dddOfRrr", where "ddd" represents + * the (singular) duration unit field name and "Rrr" represents the (singular) + * duration range field name. If the range field is not applicable, then + * the name of the field is simply the (singular) duration field name. + * + * @return field name + */ + public abstract String getName(); + + /** + * Returns true if this field is supported. + * + * @return true if this field is supported + */ + public abstract boolean isSupported(); + + /** + * Returns true if the set method is lenient. If so, it accepts values that + * are out of bounds. For example, a lenient day of month field accepts 32 + * for January, converting it to February 1. + * + * @return true if this field is lenient + */ + public abstract boolean isLenient(); + + // Main access API + //------------------------------------------------------------------------ + /** + * Get the value of this field from the milliseconds. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the value of the field, in the units of the field + */ + public abstract int get(long instant); + + /** + * Get the human-readable, text value of this field from the milliseconds. + * If the specified locale is null, the default locale is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public abstract String getAsText(long instant, Locale locale); + + /** + * Get the human-readable, text value of this field from the milliseconds. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the text value of the field + */ + public abstract String getAsText(long instant); + + /** + * Get the human-readable, text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + * + * @param partial the partial instant to query + * @param fieldValue the field value of this field, provided for performance + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public abstract String getAsText(ReadablePartial partial, int fieldValue, Locale locale); + + /** + * Get the human-readable, text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + * + * @param partial the partial instant to query + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public abstract String getAsText(ReadablePartial partial, Locale locale); + + /** + * Get the human-readable, short text value of this field from the + * milliseconds. If the specified locale is null, the default locale is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @param locale the locale to use for selecting a text symbol, null for default + * @return the short text value of the field + */ + public abstract String getAsShortText(long instant, Locale locale); + + /** + * Get the human-readable, short text value of this field from the + * milliseconds. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the short text value of the field + */ + public abstract String getAsShortText(long instant); + + /** + * Get the human-readable, short text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + * + * @param partial the partial instant to query + * @param fieldValue the field value of this field, provided for performance + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public abstract String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale); + + /** + * Get the human-readable, short text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + * + * @param partial the partial instant to query + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public abstract String getAsShortText(ReadablePartial partial, Locale locale); + + /** + * Adds a value (which may be negative) to the millis value, + * overflowing into larger fields if necessary. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field, larger fields will increase as required. + * Smaller fields should be unaffected, except where the result would be + * an invalid value for a smaller field. In this case the smaller field is + * adjusted to be in range. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 add six months is 2001-02-20
+ * 2000-08-20 add twenty months is 2002-04-20
+ * 2000-08-20 add minus nine months is 1999-11-20
+ * 2001-01-31 add one month is 2001-02-28
+ * 2001-01-31 add two months is 2001-03-31
+ * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the value to add, in the units of the field + * @return the updated milliseconds + */ + public abstract long add(long instant, int value); + + /** + * Adds a value (which may be negative) to the millis value, + * overflowing into larger fields if necessary. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the long value to add, in the units of the field + * @return the updated milliseconds + * @throws IllegalArgumentException if value is too large + * @see #add(long,int) + */ + public abstract long add(long instant, long value); + + /** + * Adds a value (which may be negative) to the partial instant, + * throwing an exception if the maximum size of the instant is reached. + *

+ * The value will be added to this field, overflowing into larger fields + * if necessary. Smaller fields should be unaffected, except where the + * result would be an invalid value for a smaller field. In this case the + * smaller field is adjusted to be in range. + *

+ * Partial instants only contain some fields. This may result in a maximum + * possible value, such as TimeOfDay being limited to 23:59:59:999. If this + * limit is breached by the add an exception is thrown. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 add six months is 2000-02-20
+ * 2000-08-20 add twenty months is 2000-04-20
+ * 2000-08-20 add minus nine months is 2000-11-20
+ * 2001-01-31 add one month is 2001-02-28
+ * 2001-01-31 add two months is 2001-03-31
+ * + * @param instant the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values of the partial instant which should be updated + * @param valueToAdd the value to add, in the units of the field + * @return the passed in values + * @throws IllegalArgumentException if the value is invalid or the maximum instant is reached + */ + public abstract int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); + + /** + * Adds a value (which may be negative) to the millis value, + * wrapping within this field. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it wraps. Larger fields are always + * unaffected. Smaller fields should be unaffected, except where the + * result would be an invalid value for a smaller field. In this case the + * smaller field is adjusted to be in range. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 addWrapField six months is 2000-02-20
+ * 2000-08-20 addWrapField twenty months is 2000-04-20
+ * 2000-08-20 addWrapField minus nine months is 2000-11-20
+ * 2001-01-31 addWrapField one month is 2001-02-28
+ * 2001-01-31 addWrapField two months is 2001-03-31
+ * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the value to add, in the units of the field + * @return the updated milliseconds + */ + public abstract long addWrapField(long instant, int value) ; + + /** + * Adds a value (which may be negative) to the partial instant, + * wrapping within this field. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it wraps. Larger fields are always + * unaffected. Smaller fields should be unaffected, except where the + * result would be an invalid value for a smaller field. In this case the + * smaller field is adjusted to be in range. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 addWrapField six months is 2000-02-20
+ * 2000-08-20 addWrapField twenty months is 2000-04-20
+ * 2000-08-20 addWrapField minus nine months is 2000-11-20
+ * 2001-01-31 addWrapField one month is 2001-02-28
+ * 2001-01-31 addWrapField two months is 2001-03-31
+ * + * @param instant the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values of the partial instant which should be updated + * @param valueToAdd the value to add, in the units of the field + * @return the passed in values + * @throws IllegalArgumentException if the value is invalid + */ + public abstract int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd); + + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *

+     * long instant = ...
+     * int v = ...
+     * int age = getDifference(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public abstract int getDifference(long minuendInstant, long subtrahendInstant); + + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *
+     * long instant = ...
+     * long v = ...
+     * long age = getDifferenceAsLong(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public abstract long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); + + /** + * Sets a value in the milliseconds supplied. + *

+ * The value of this field will be set. + * If the value is invalid, an exception if thrown. + *

+ * If setting this field would make other fields invalid, then those fields + * may be changed. For example if the current date is the 31st January, and + * the month is set to February, the day would be invalid. Instead, the day + * would be changed to the closest value - the 28th/29th February as appropriate. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param value the value to set, in the units of the field + * @return the updated milliseconds + * @throws IllegalArgumentException if the value is invalid + */ + public abstract long set(long instant, int value); + + /** + * Sets a value using the specified partial instant. + *

+ * The value of this field (specified by the index) will be set. + * If the value is invalid, an exception if thrown. + *

+ * If setting this field would make other fields invalid, then those fields + * may be changed. For example if the current date is the 31st January, and + * the month is set to February, the day would be invalid. Instead, the day + * would be changed to the closest value - the 28th/29th February as appropriate. + * + * @param instant the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values of the partial instant which should be updated + * @param newValue the value to set, in the units of the field + * @return the passed in values + * @throws IllegalArgumentException if the value is invalid + */ + public abstract int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue); + + /** + * Sets a value in the milliseconds supplied from a human-readable, text value. + * If the specified locale is null, the default locale is used. + *

+ * If setting this field would make other fields invalid, then those fields + * may be changed. For example if the current date is the 31st January, and + * the month is set to February, the day would be invalid. Instead, the day + * would be changed to the closest value - the 28th/29th February as appropriate. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param text the text value to set + * @param locale the locale to use for selecting a text symbol, null for default + * @return the updated milliseconds + * @throws IllegalArgumentException if the text value is invalid + */ + public abstract long set(long instant, String text, Locale locale); + + /** + * Sets a value in the milliseconds supplied from a human-readable, text value. + *

+ * If setting this field would make other fields invalid, then those fields + * may be changed. For example if the current date is the 31st January, and + * the month is set to February, the day would be invalid. Instead, the day + * would be changed to the closest value - the 28th/29th February as appropriate. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param text the text value to set + * @return the updated milliseconds + * @throws IllegalArgumentException if the text value is invalid + */ + public abstract long set(long instant, String text); + + /** + * Sets a value in the milliseconds supplied from a human-readable, text value. + * If the specified locale is null, the default locale is used. + *

+ * If setting this field would make other fields invalid, then those fields + * may be changed. For example if the current date is the 31st January, and + * the month is set to February, the day would be invalid. Instead, the day + * would be changed to the closest value - the 28th/29th February as appropriate. + * + * @param instant the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values of the partial instant which should be updated + * @param text the text value to set + * @param locale the locale to use for selecting a text symbol, null for default + * @return the passed in values + * @throws IllegalArgumentException if the text value is invalid + */ + public abstract int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale); + + // Extra information API + //------------------------------------------------------------------------ + /** + * Returns the duration per unit value of this field. For example, if this + * field represents "hour of day", then the duration is an hour. + * + * @return the duration of this field, or UnsupportedDurationField if field + * has no duration + */ + public abstract DurationField getDurationField(); + + /** + * Returns the range duration of this field. For example, if this field + * represents "hour of day", then the range duration is a day. + * + * @return the range duration of this field, or null if field has no range + */ + public abstract DurationField getRangeDurationField(); + + /** + * Returns whether this field is 'leap' for the specified instant. + *

+ * For example, a leap year would return true, a non leap year would return + * false. + * + * @param instant the instant to check for leap status + * @return true if the field is 'leap' + */ + public abstract boolean isLeap(long instant); + + /** + * Gets the amount by which this field is 'leap' for the specified instant. + *

+ * For example, a leap year would return one, a non leap year would return + * zero. + * + * @param instant the instant to check for leap status + * @return the amount, in units of the leap duration field, that the field is leap + */ + public abstract int getLeapAmount(long instant); + + /** + * If this field were to leap, then it would be in units described by the + * returned duration. If this field doesn't ever leap, null is returned. + * + * @return the leap duration field if field can be leap, null if it can't + */ + public abstract DurationField getLeapDurationField(); + + /** + * Get the minimum allowable value for this field. + * + * @return the minimum valid value for this field, in the units of the + * field + */ + public abstract int getMinimumValue(); + + /** + * Get the minimum value for this field evaluated at the specified time. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the minimum value for this field, in the units of the field + */ + public abstract int getMinimumValue(long instant); + + /** + * Get the minimum value for this field evaluated at the specified time. + * + * @param instant the partial instant to query + * @return the minimum value for this field, in the units of the field + */ + public abstract int getMinimumValue(ReadablePartial instant); + + /** + * Get the minimum value for this field using the partial instant and + * the specified values. + * + * @param instant the partial instant to query + * @param values the values to use + * @return the minimum value for this field, in the units of the field + */ + public abstract int getMinimumValue(ReadablePartial instant, int[] values); + + /** + * Get the maximum allowable value for this field. + * + * @return the maximum valid value for this field, in the units of the + * field + */ + public abstract int getMaximumValue(); + + /** + * Get the maximum value for this field evaluated at the specified time. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the maximum value for this field, in the units of the field + */ + public abstract int getMaximumValue(long instant); + + /** + * Get the maximum value for this field evaluated at the specified time. + * + * @param instant the partial instant to query + * @return the maximum value for this field, in the units of the field + */ + public abstract int getMaximumValue(ReadablePartial instant); + + /** + * Get the maximum value for this field using the partial instant and + * the specified values. + * + * @param instant the partial instant to query + * @param values the values to use + * @return the maximum value for this field, in the units of the field + */ + public abstract int getMaximumValue(ReadablePartial instant, int[] values); + + /** + * Get the maximum text value for this field. + * + * @param locale the locale to use for selecting a text symbol + * @return the maximum text length + */ + public abstract int getMaximumTextLength(Locale locale); + + /** + * Get the maximum short text value for this field. + * + * @param locale the locale to use for selecting a text symbol + * @return the maximum short text length + */ + public abstract int getMaximumShortTextLength(Locale locale); + + // Calculation API + //------------------------------------------------------------------------ + /** + * Round to the lowest whole unit of this field. After rounding, the value + * of this field and all fields of a higher magnitude are retained. The + * fractional millis that cannot be expressed in whole increments of this + * field are set to minimum. + *

+ * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the + * lowest whole hour is 2002-11-02T23:00:00.000. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public abstract long roundFloor(long instant); + + /** + * Round to the highest whole unit of this field. The value of this field + * and all fields of a higher magnitude may be incremented in order to + * achieve this result. The fractional millis that cannot be expressed in + * whole increments of this field are set to minimum. + *

+ * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the + * highest whole hour is 2002-11-03T00:00:00.000. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public abstract long roundCeiling(long instant); + + /** + * Round to the nearest whole unit of this field. If the given millisecond + * value is closer to the floor or is exactly halfway, this function + * behaves like roundFloor. If the millisecond value is closer to the + * ceiling, this function behaves like roundCeiling. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public abstract long roundHalfFloor(long instant); + + /** + * Round to the nearest whole unit of this field. If the given millisecond + * value is closer to the floor, this function behaves like roundFloor. If + * the millisecond value is closer to the ceiling or is exactly halfway, + * this function behaves like roundCeiling. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public abstract long roundHalfCeiling(long instant); + + /** + * Round to the nearest whole unit of this field. If the given millisecond + * value is closer to the floor, this function behaves like roundFloor. If + * the millisecond value is closer to the ceiling, this function behaves + * like roundCeiling. + *

+ * If the millisecond value is exactly halfway between the floor and + * ceiling, the ceiling is chosen over the floor only if it makes this + * field's value even. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public abstract long roundHalfEven(long instant); + + /** + * Returns the fractional duration milliseconds of this field. In other + * words, calling remainder returns the duration that roundFloor would + * subtract. + *

+ * For example, on a datetime of 2002-11-02T23:34:56.789, the remainder by + * hour is 34 minutes and 56.789 seconds. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to get the + * remainder + * @return remainder duration, in milliseconds + */ + public abstract long remainder(long instant); + + /** + * Get a suitable debug string. + * + * @return debug string + */ + public abstract String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/DateTimeFieldType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateTimeFieldType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateTimeFieldType.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,614 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +/** + * Identifies a field, such as year or minuteOfHour, in a chronology-neutral way. + *

+ * A field type defines the type of the field, such as hourOfDay. + * If does not directly enable any calculations, however it does provide a + * {@link #getField(Chronology)} method that returns the actual calculation engine + * for a particular chronology. + * It also provides access to the related {@link DurationFieldType}s. + *

+ * Instances of DateTimeFieldType are singletons. + * They can be compared using ==. + *

+ * If required, you can create your own field, for example a quarterOfYear. + * You must create a subclass of DateTimeFieldType that defines the field type. + * This class returns the actual calculation engine from {@link #getField(Chronology)}. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class DateTimeFieldType implements Serializable { + + /** Serialization version */ + private static final long serialVersionUID = -42615285973990L; + + /** Ordinal values for standard field types. */ + static final byte + ERA = 1, + YEAR_OF_ERA = 2, + CENTURY_OF_ERA = 3, + YEAR_OF_CENTURY = 4, + YEAR = 5, + DAY_OF_YEAR = 6, + MONTH_OF_YEAR = 7, + DAY_OF_MONTH = 8, + WEEKYEAR_OF_CENTURY = 9, + WEEKYEAR = 10, + WEEK_OF_WEEKYEAR = 11, + DAY_OF_WEEK = 12, + HALFDAY_OF_DAY = 13, + HOUR_OF_HALFDAY = 14, + CLOCKHOUR_OF_HALFDAY = 15, + CLOCKHOUR_OF_DAY = 16, + HOUR_OF_DAY = 17, + MINUTE_OF_DAY = 18, + MINUTE_OF_HOUR = 19, + SECOND_OF_DAY = 20, + SECOND_OF_MINUTE = 21, + MILLIS_OF_DAY = 22, + MILLIS_OF_SECOND = 23; + + /** The era field type. */ + private static final DateTimeFieldType ERA_TYPE = new StandardDateTimeFieldType( + "era", ERA, DurationFieldType.eras(), null); + /** The yearOfEra field type. */ + private static final DateTimeFieldType YEAR_OF_ERA_TYPE = new StandardDateTimeFieldType( + "yearOfEra", YEAR_OF_ERA, DurationFieldType.years(), DurationFieldType.eras()); + /** The centuryOfEra field type. */ + private static final DateTimeFieldType CENTURY_OF_ERA_TYPE = new StandardDateTimeFieldType( + "centuryOfEra", CENTURY_OF_ERA, DurationFieldType.centuries(), DurationFieldType.eras()); + /** The yearOfCentury field type. */ + private static final DateTimeFieldType YEAR_OF_CENTURY_TYPE = new StandardDateTimeFieldType( + "yearOfCentury", YEAR_OF_CENTURY, DurationFieldType.years(), DurationFieldType.centuries()); + /** The year field type. */ + private static final DateTimeFieldType YEAR_TYPE = new StandardDateTimeFieldType( + "year", YEAR, DurationFieldType.years(), null); + /** The dayOfYear field type. */ + private static final DateTimeFieldType DAY_OF_YEAR_TYPE = new StandardDateTimeFieldType( + "dayOfYear", DAY_OF_YEAR, DurationFieldType.days(), DurationFieldType.years()); + /** The monthOfYear field type. */ + private static final DateTimeFieldType MONTH_OF_YEAR_TYPE = new StandardDateTimeFieldType( + "monthOfYear", MONTH_OF_YEAR, DurationFieldType.months(), DurationFieldType.years()); + /** The dayOfMonth field type. */ + private static final DateTimeFieldType DAY_OF_MONTH_TYPE = new StandardDateTimeFieldType( + "dayOfMonth", DAY_OF_MONTH, DurationFieldType.days(), DurationFieldType.months()); + /** The weekyearOfCentury field type. */ + private static final DateTimeFieldType WEEKYEAR_OF_CENTURY_TYPE = new StandardDateTimeFieldType( + "weekyearOfCentury", WEEKYEAR_OF_CENTURY, DurationFieldType.weekyears(), DurationFieldType.centuries()); + /** The weekyear field type. */ + private static final DateTimeFieldType WEEKYEAR_TYPE = new StandardDateTimeFieldType( + "weekyear", WEEKYEAR, DurationFieldType.weekyears(), null); + /** The weekOfWeekyear field type. */ + private static final DateTimeFieldType WEEK_OF_WEEKYEAR_TYPE = new StandardDateTimeFieldType( + "weekOfWeekyear", WEEK_OF_WEEKYEAR, DurationFieldType.weeks(), DurationFieldType.weekyears()); + /** The dayOfWeek field type. */ + private static final DateTimeFieldType DAY_OF_WEEK_TYPE = new StandardDateTimeFieldType( + "dayOfWeek", DAY_OF_WEEK, DurationFieldType.days(), DurationFieldType.weeks()); + + /** The halfday field type. */ + private static final DateTimeFieldType HALFDAY_OF_DAY_TYPE = new StandardDateTimeFieldType( + "halfdayOfDay", HALFDAY_OF_DAY, DurationFieldType.halfdays(), DurationFieldType.days()); + /** The hourOfHalfday field type. */ + private static final DateTimeFieldType HOUR_OF_HALFDAY_TYPE = new StandardDateTimeFieldType( + "hourOfHalfday", HOUR_OF_HALFDAY, DurationFieldType.hours(), DurationFieldType.halfdays()); + /** The clockhourOfHalfday field type. */ + private static final DateTimeFieldType CLOCKHOUR_OF_HALFDAY_TYPE = new StandardDateTimeFieldType( + "clockhourOfHalfday", CLOCKHOUR_OF_HALFDAY, DurationFieldType.hours(), DurationFieldType.halfdays()); + /** The clockhourOfDay field type. */ + private static final DateTimeFieldType CLOCKHOUR_OF_DAY_TYPE = new StandardDateTimeFieldType( + "clockhourOfDay", CLOCKHOUR_OF_DAY, DurationFieldType.hours(), DurationFieldType.days()); + /** The hourOfDay field type. */ + private static final DateTimeFieldType HOUR_OF_DAY_TYPE = new StandardDateTimeFieldType( + "hourOfDay", HOUR_OF_DAY, DurationFieldType.hours(), DurationFieldType.days()); + /** The minuteOfDay field type. */ + private static final DateTimeFieldType MINUTE_OF_DAY_TYPE = new StandardDateTimeFieldType( + "minuteOfDay", MINUTE_OF_DAY, DurationFieldType.minutes(), DurationFieldType.days()); + /** The minuteOfHour field type. */ + private static final DateTimeFieldType MINUTE_OF_HOUR_TYPE = new StandardDateTimeFieldType( + "minuteOfHour", MINUTE_OF_HOUR, DurationFieldType.minutes(), DurationFieldType.hours()); + /** The secondOfDay field type. */ + private static final DateTimeFieldType SECOND_OF_DAY_TYPE = new StandardDateTimeFieldType( + "secondOfDay", SECOND_OF_DAY, DurationFieldType.seconds(), DurationFieldType.days()); + /** The secondOfMinute field type. */ + private static final DateTimeFieldType SECOND_OF_MINUTE_TYPE = new StandardDateTimeFieldType( + "secondOfMinute", SECOND_OF_MINUTE, DurationFieldType.seconds(), DurationFieldType.minutes()); + /** The millisOfDay field type. */ + private static final DateTimeFieldType MILLIS_OF_DAY_TYPE = new StandardDateTimeFieldType( + "millisOfDay", MILLIS_OF_DAY, DurationFieldType.millis(), DurationFieldType.days()); + /** The millisOfSecond field type. */ + private static final DateTimeFieldType MILLIS_OF_SECOND_TYPE = new StandardDateTimeFieldType( + "millisOfSecond", MILLIS_OF_SECOND, DurationFieldType.millis(), DurationFieldType.seconds()); + + /** The name of the field. */ + private final String iName; + + //----------------------------------------------------------------------- + /** + * Constructor. + * + * @param name the name to use + */ + protected DateTimeFieldType(String name) { + super(); + iName = name; + } + + //----------------------------------------------------------------------- + /** + * Get the millis of second field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType millisOfSecond() { + return MILLIS_OF_SECOND_TYPE; + } + + /** + * Get the millis of day field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType millisOfDay() { + return MILLIS_OF_DAY_TYPE; + } + + /** + * Get the second of minute field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType secondOfMinute() { + return SECOND_OF_MINUTE_TYPE; + } + + /** + * Get the second of day field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType secondOfDay() { + return SECOND_OF_DAY_TYPE; + } + + /** + * Get the minute of hour field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType minuteOfHour() { + return MINUTE_OF_HOUR_TYPE; + } + + /** + * Get the minute of day field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType minuteOfDay() { + return MINUTE_OF_DAY_TYPE; + } + + /** + * Get the hour of day (0-23) field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType hourOfDay() { + return HOUR_OF_DAY_TYPE; + } + + /** + * Get the hour of day (offset to 1-24) field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType clockhourOfDay() { + return CLOCKHOUR_OF_DAY_TYPE; + } + + /** + * Get the hour of am/pm (0-11) field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType hourOfHalfday() { + return HOUR_OF_HALFDAY_TYPE; + } + + /** + * Get the hour of am/pm (offset to 1-12) field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType clockhourOfHalfday() { + return CLOCKHOUR_OF_HALFDAY_TYPE; + } + + /** + * Get the AM(0) PM(1) field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType halfdayOfDay() { + return HALFDAY_OF_DAY_TYPE; + } + + //----------------------------------------------------------------------- + /** + * Get the day of week field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType dayOfWeek() { + return DAY_OF_WEEK_TYPE; + } + + /** + * Get the day of month field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType dayOfMonth() { + return DAY_OF_MONTH_TYPE; + } + + /** + * Get the day of year field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType dayOfYear() { + return DAY_OF_YEAR_TYPE; + } + + /** + * Get the week of a week based year field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType weekOfWeekyear() { + return WEEK_OF_WEEKYEAR_TYPE; + } + + /** + * Get the year of a week based year field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType weekyear() { + return WEEKYEAR_TYPE; + } + + /** + * Get the year of a week based year within a century field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType weekyearOfCentury() { + return WEEKYEAR_OF_CENTURY_TYPE; + } + + /** + * Get the month of year field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType monthOfYear() { + return MONTH_OF_YEAR_TYPE; + } + + /** + * Get the year field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType year() { + return YEAR_TYPE; + } + + /** + * Get the year of era field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType yearOfEra() { + return YEAR_OF_ERA_TYPE; + } + + /** + * Get the year of century field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType yearOfCentury() { + return YEAR_OF_CENTURY_TYPE; + } + + /** + * Get the century of era field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType centuryOfEra() { + return CENTURY_OF_ERA_TYPE; + } + + /** + * Get the era field type. + * + * @return the DateTimeFieldType constant + */ + public static DateTimeFieldType era() { + return ERA_TYPE; + } + + //----------------------------------------------------------------------- + /** + * Get the name of the field. + *

+ * By convention, names follow a pattern of "dddOfRrr", where "ddd" represents + * the (singular) duration unit field name and "Rrr" represents the (singular) + * duration range field name. If the range field is not applicable, then + * the name of the field is simply the (singular) duration field name. + * + * @return field name + */ + public String getName() { + return iName; + } + + /** + * Get the duration unit of the field. + * + * @return duration unit of the field, never null + */ + public abstract DurationFieldType getDurationType(); + + /** + * Get the duration range of the field. + * + * @return duration range of the field, null if unbounded + */ + public abstract DurationFieldType getRangeDurationType(); + + /** + * Gets a suitable field for this type from the given Chronology. + * + * @param chronology the chronology to use, null means ISOChronology in default zone + * @return a suitable field + */ + public abstract DateTimeField getField(Chronology chronology); + + /** + * Checks whether this field supported in the given Chronology. + * + * @param chronology the chronology to use, null means ISOChronology in default zone + * @return true if supported + */ + public boolean isSupported(Chronology chronology) { + return getField(chronology).isSupported(); + } + + /** + * Get a suitable debug string. + * + * @return debug string + */ + public String toString() { + return getName(); + } + + private static class StandardDateTimeFieldType extends DateTimeFieldType { + /** Serialization version */ + private static final long serialVersionUID = -9937958251642L; + + /** The ordinal of the standard field type, for switch statements */ + private final byte iOrdinal; + + /** The unit duration of the field. */ + private final transient DurationFieldType iUnitType; + /** The range duration of the field. */ + private final transient DurationFieldType iRangeType; + + /** + * Constructor. + * + * @param name the name to use + * @param ordinal the byte value for the oridinal index + * @param unitType the unit duration type + * @param rangeType the range duration type + */ + StandardDateTimeFieldType(String name, byte ordinal, + DurationFieldType unitType, DurationFieldType rangeType) { + super(name); + iOrdinal = ordinal; + iUnitType = unitType; + iRangeType = rangeType; + } + + /** @inheritdoc */ + public DurationFieldType getDurationType() { + return iUnitType; + } + + /** @inheritdoc */ + public DurationFieldType getRangeDurationType() { + return iRangeType; + } + + /** @inheritdoc */ + public DateTimeField getField(Chronology chronology) { + chronology = DateTimeUtils.getChronology(chronology); + + switch (iOrdinal) { + case ERA: + return chronology.era(); + case YEAR_OF_ERA: + return chronology.yearOfEra(); + case CENTURY_OF_ERA: + return chronology.centuryOfEra(); + case YEAR_OF_CENTURY: + return chronology.yearOfCentury(); + case YEAR: + return chronology.year(); + case DAY_OF_YEAR: + return chronology.dayOfYear(); + case MONTH_OF_YEAR: + return chronology.monthOfYear(); + case DAY_OF_MONTH: + return chronology.dayOfMonth(); + case WEEKYEAR_OF_CENTURY: + return chronology.weekyearOfCentury(); + case WEEKYEAR: + return chronology.weekyear(); + case WEEK_OF_WEEKYEAR: + return chronology.weekOfWeekyear(); + case DAY_OF_WEEK: + return chronology.dayOfWeek(); + case HALFDAY_OF_DAY: + return chronology.halfdayOfDay(); + case HOUR_OF_HALFDAY: + return chronology.hourOfHalfday(); + case CLOCKHOUR_OF_HALFDAY: + return chronology.clockhourOfHalfday(); + case CLOCKHOUR_OF_DAY: + return chronology.clockhourOfDay(); + case HOUR_OF_DAY: + return chronology.hourOfDay(); + case MINUTE_OF_DAY: + return chronology.minuteOfDay(); + case MINUTE_OF_HOUR: + return chronology.minuteOfHour(); + case SECOND_OF_DAY: + return chronology.secondOfDay(); + case SECOND_OF_MINUTE: + return chronology.secondOfMinute(); + case MILLIS_OF_DAY: + return chronology.millisOfDay(); + case MILLIS_OF_SECOND: + return chronology.millisOfSecond(); + default: + // Shouldn't happen. + throw new InternalError(); + } + } + + /** + * Ensure a singleton is returned. + * + * @return the singleton type + */ + private Object readResolve() { + switch (iOrdinal) { + case ERA: + return ERA_TYPE; + case YEAR_OF_ERA: + return YEAR_OF_ERA_TYPE; + case CENTURY_OF_ERA: + return CENTURY_OF_ERA_TYPE; + case YEAR_OF_CENTURY: + return YEAR_OF_CENTURY_TYPE; + case YEAR: + return YEAR_TYPE; + case DAY_OF_YEAR: + return DAY_OF_YEAR_TYPE; + case MONTH_OF_YEAR: + return MONTH_OF_YEAR_TYPE; + case DAY_OF_MONTH: + return DAY_OF_MONTH_TYPE; + case WEEKYEAR_OF_CENTURY: + return WEEKYEAR_OF_CENTURY_TYPE; + case WEEKYEAR: + return WEEKYEAR_TYPE; + case WEEK_OF_WEEKYEAR: + return WEEK_OF_WEEKYEAR_TYPE; + case DAY_OF_WEEK: + return DAY_OF_WEEK_TYPE; + case HALFDAY_OF_DAY: + return HALFDAY_OF_DAY_TYPE; + case HOUR_OF_HALFDAY: + return HOUR_OF_HALFDAY_TYPE; + case CLOCKHOUR_OF_HALFDAY: + return CLOCKHOUR_OF_HALFDAY_TYPE; + case CLOCKHOUR_OF_DAY: + return CLOCKHOUR_OF_DAY_TYPE; + case HOUR_OF_DAY: + return HOUR_OF_DAY_TYPE; + case MINUTE_OF_DAY: + return MINUTE_OF_DAY_TYPE; + case MINUTE_OF_HOUR: + return MINUTE_OF_HOUR_TYPE; + case SECOND_OF_DAY: + return SECOND_OF_DAY_TYPE; + case SECOND_OF_MINUTE: + return SECOND_OF_MINUTE_TYPE; + case MILLIS_OF_DAY: + return MILLIS_OF_DAY_TYPE; + case MILLIS_OF_SECOND: + return MILLIS_OF_SECOND_TYPE; + default: + // Shouldn't happen. + return this; + } + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/DateTimeUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateTimeUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateTimeUtils.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,375 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import org.joda.time.chrono.ISOChronology; + +/** + * DateTimeUtils provide public utility methods for the datetime library. + *

+ * DateTimeUtils is thread-safe although shared static variables are used. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public class DateTimeUtils { + + /** The singleton instance of the system millisecond provider */ + private static final SystemMillisProvider SYSTEM_MILLIS_PROVIDER = new SystemMillisProvider(); + + /** The millisecond provider currently in use */ + private static MillisProvider cMillisProvider = SYSTEM_MILLIS_PROVIDER; + + /** + * Restrictive constructor + */ + protected DateTimeUtils() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the current time in milliseconds. + *

+ * By default this returns System.currentTimeMillis(). + * This may be changed using other methods in this class. + * + * @return the current time in milliseconds from 1970-01-01T00:00:00Z + */ + public static final long currentTimeMillis() { + return cMillisProvider.getMillis(); + } + + /** + * Resets the current time to return the system time. + *

+ * This method changes the behaviour of {@link #currentTimeMillis()}. + * Whenever the current time is queried, {@link System#currentTimeMillis()} is used. + * + * @throws SecurityException if the application does not have sufficient security rights + */ + public static final void setCurrentMillisSystem() throws SecurityException { + checkPermission(); + cMillisProvider = SYSTEM_MILLIS_PROVIDER; + } + + /** + * Sets the current time to return a fixed millisecond time. + *

+ * This method changes the behaviour of {@link #currentTimeMillis()}. + * Whenever the current time is queried, the same millisecond time will be returned. + * + * @param fixedMillis the fixed millisecond time to use + * @throws SecurityException if the application does not have sufficient security rights + */ + public static final void setCurrentMillisFixed(long fixedMillis) throws SecurityException { + checkPermission(); + cMillisProvider = new FixedMillisProvider(fixedMillis); + } + + /** + * Sets the current time to return the system time plus an offset. + *

+ * This method changes the behaviour of {@link #currentTimeMillis()}. + * Whenever the current time is queried, {@link System#currentTimeMillis()} is used + * and then offset by adding the millisecond value specified here. + * + * @param offsetMillis the fixed millisecond time to use + * @throws SecurityException if the application does not have sufficient security rights + */ + public static final void setCurrentMillisOffset(long offsetMillis) throws SecurityException { + checkPermission(); + cMillisProvider = new OffsetMillisProvider(offsetMillis); + } + + /** + * Checks whether the provider may be changed using permission 'CurrentTime.setProvider'. + * + * @throws SecurityException if the provider may not be changed + */ + private static void checkPermission() throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("CurrentTime.setProvider")); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the millisecond instant from the specified instant object handling null. + *

+ * If the instant object is null, the {@link #currentTimeMillis()} + * will be returned. Otherwise, the millis from the object are returned. + * + * @param instant the instant to examine, null means now + * @return the time in milliseconds from 1970-01-01T00:00:00Z + */ + public static final long getInstantMillis(ReadableInstant instant) { + if (instant == null) { + return DateTimeUtils.currentTimeMillis(); + } + return instant.getMillis(); + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology from the specified instant object handling null. + *

+ * If the instant object is null, or the instant's chronology is + * null, {@link ISOChronology#getInstance()} will be returned. + * Otherwise, the chronology from the object is returned. + * + * @param instant the instant to examine, null means ISO in the default zone + * @return the chronology, never null + */ + public static final Chronology getInstantChronology(ReadableInstant instant) { + if (instant == null) { + return ISOChronology.getInstance(); + } + Chronology chrono = instant.getChronology(); + if (chrono == null) { + return ISOChronology.getInstance(); + } + return chrono; + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology from the specified instant based interval handling null. + *

+ * The chronology is obtained from the start if that is not null, or from the + * end if the start is null. The result is additionally checked, and if still + * null then {@link ISOChronology#getInstance()} will be returned. + * + * @param start the instant to examine and use as the primary source of the chronology + * @param end the instant to examine and use as the secondary source of the chronology + * @return the chronology, never null + */ + public static final Chronology getIntervalChronology(ReadableInstant start, ReadableInstant end) { + Chronology chrono = null; + if (start != null) { + chrono = start.getChronology(); + } else if (end != null) { + chrono = end.getChronology(); + } + if (chrono == null) { + chrono = ISOChronology.getInstance(); + } + return chrono; + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology from the specified interval object handling null. + *

+ * If the interval object is null, or the interval's chronology is + * null, {@link ISOChronology#getInstance()} will be returned. + * Otherwise, the chronology from the object is returned. + * + * @param interval the interval to examine, null means ISO in the default zone + * @return the chronology, never null + */ + public static final Chronology getIntervalChronology(ReadableInterval interval) { + if (interval == null) { + return ISOChronology.getInstance(); + } + Chronology chrono = interval.getChronology(); + if (chrono == null) { + return ISOChronology.getInstance(); + } + return chrono; + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology handling null. + *

+ * If the chronology is null, {@link ISOChronology#getInstance()} + * will be returned. Otherwise, the chronology is returned. + * + * @param chrono the chronology to use, null means ISO in the default zone + * @return the chronology, never null + */ + public static final Chronology getChronology(Chronology chrono) { + if (chrono == null) { + return ISOChronology.getInstance(); + } + return chrono; + } + + //----------------------------------------------------------------------- + /** + * Gets the zone handling null. + *

+ * If the zone is null, {@link DateTimeZone#getDefault()} + * will be returned. Otherwise, the zone specified is returned. + * + * @param zone the time zone to use, null means the default zone + * @return the time zone, never null + */ + public static final DateTimeZone getZone(DateTimeZone zone) { + if (zone == null) { + return DateTimeZone.getDefault(); + } + return zone; + } + + //----------------------------------------------------------------------- + /** + * Gets the period type handling null. + *

+ * If the zone is null, {@link PeriodType#standard()} + * will be returned. Otherwise, the type specified is returned. + * + * @param type the time zone to use, null means the standard type + * @return the type to use, never null + */ + public static final PeriodType getPeriodType(PeriodType type) { + if (type == null) { + return PeriodType.standard(); + } + return type; + } + + //----------------------------------------------------------------------- + /** + * Gets the millisecond duration from the specified duration object handling null. + *

+ * If the duration object is null, zero will be returned. + * Otherwise, the millis from the object are returned. + * + * @param duration the duration to examine, null means zero + * @return the duration in milliseconds + */ + public static final long getDurationMillis(ReadableDuration duration) { + if (duration == null) { + return 0L; + } + return duration.getMillis(); + } + + //----------------------------------------------------------------------- + /** + * Base class defining a millisecond provider. + */ + abstract static class MillisProvider { + /** + * Gets the current time. + * @return the current time in millis + */ + abstract long getMillis(); + } + + /** + * System millis provider. + */ + static class SystemMillisProvider extends MillisProvider { + /** + * Gets the current time. + * @return the current time in millis + */ + long getMillis() { + return System.currentTimeMillis(); + } + } + + /** + * Fixed millisecond provider. + */ + static class FixedMillisProvider extends MillisProvider { + /** The fixed millis value. */ + private final long iMillis; + + /** + * Constructor. + * @param offsetMillis the millis offset + */ + FixedMillisProvider(long fixedMillis) { + iMillis = fixedMillis; + } + + /** + * Gets the current time. + * @return the current time in millis + */ + long getMillis() { + return iMillis; + } + } + + /** + * Offset from system millis provider. + */ + static class OffsetMillisProvider extends MillisProvider { + /** The millis offset. */ + private final long iMillis; + + /** + * Constructor. + * @param offsetMillis the millis offset + */ + OffsetMillisProvider(long offsetMillis) { + iMillis = offsetMillis; + } + + /** + * Gets the current time. + * @return the current time in millis + */ + long getMillis() { + return System.currentTimeMillis() + iMillis; + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/DateTimeZone.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DateTimeZone.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DateTimeZone.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,952 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.lang.ref.Reference; +import java.lang.ref.SoftReference; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import org.joda.time.field.FieldUtils; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.DateTimeFormatterBuilder; +import org.joda.time.format.FormatUtils; +import org.joda.time.tz.DefaultNameProvider; +import org.joda.time.tz.FixedDateTimeZone; +import org.joda.time.tz.NameProvider; +import org.joda.time.tz.Provider; +import org.joda.time.tz.UTCProvider; +import org.joda.time.tz.ZoneInfoProvider; + +/** + * DateTimeZone represents a time zone. + *

+ * A time zone is a system of rules to convert time from one geographic + * location to another. For example, Paris, France is one hour ahead of + * London, England. Thus when it is 10:00 in London, it is 11:00 in Paris. + *

+ * All time zone rules are expressed, for historical reasons, relative to + * Greenwich, London. Local time in Greenwich is referred to as Greenwich Mean + * Time (GMT). This is similar, but not precisely identical, to Universal + * Coordinated Time, or UTC. This library only uses the term UTC. + *

+ * Using this system, America/Los_Angeles is expressed as UTC-08:00, or UTC-07:00 + * in the summer. The offset -08:00 indicates that America/Los_Angeles time is + * obtained from UTC by adding -08:00, that is, by subtracting 8 hours. + *

+ * The offset differs in the summer because of daylight saving time, or DST. + * The folowing definitions of time are generally used: + *

+ *

+ * Unlike the Java TimeZone class, DateTimeZone is immutable. It also only + * supports long format time zone ids. Thus EST and ECT are not accepted. + * However, the factory that accepts a TimeZone will attempt to convert from + * the old short id to a suitable long id. + *

+ * DateTimeZone is thread-safe and immutable, and all subclasses must be as + * well. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class DateTimeZone implements Serializable { + + /** Serialization version. */ + private static final long serialVersionUID = 5546345482340108586L; + + /** The time zone for Universal Coordinated Time */ + public static final DateTimeZone UTC = new FixedDateTimeZone("UTC", "UTC", 0, 0); + + /** The instance that is providing time zones. */ + private static Provider cProvider; + /** The instance that is providing time zone names. */ + private static NameProvider cNameProvider; + /** The set of ID strings. */ + private static Set cAvailableIDs; + /** The default time zone. */ + private static DateTimeZone cDefault; + /** A formatter for printing and parsing zones. */ + private static DateTimeFormatter cOffsetFormatter; + + /** Cache that maps fixed offset strings to softly referenced DateTimeZones */ + private static Map iFixedOffsetCache; + + /** Cache of old zone IDs to new zone IDs */ + private static Map cZoneIdConversion; + + static { + setProvider0(null); + setNameProvider0(null); + + // Because of the cyclic initializer dependencies between many of the + // main classes, and because cOffsetFormatter is built from those main + // classes, a user time zone with an explicit offset fails. Rather than + // duplicate all the code used by DateTimeFormatterBuilder's offset + // formatter, DateTimeFormatterBuilder's constructor tests if + // DateTimeZone.getDefault() is null, in which case it allows the + // chronology to be null. This breaks the dependency cycle and allows + // cOffsetFormatter to be defined. In order for this inelegant solution + // to work propery, cDefault must be left as null until after an + // attempt has been made to set the user time zone. + + try { + try { + cDefault = getInstance(System.getProperty("user.timezone")); + } catch (RuntimeException ex) { + // ignored + } + if (cDefault == null) { + cDefault = getInstance(java.util.TimeZone.getDefault()); + } + } catch (IllegalArgumentException ex) { + // ignored + } + + if (cDefault == null) { + cDefault = UTC; + } + } + + /** + * Gets the default time zone. + * + * @return the default datetime zone object + */ + public static DateTimeZone getDefault() { + return cDefault; + } + + /** + * Sets the default time zone. + * + * @param zone the default datetime zone object, must not be null + * @throws IllegalArgumentException if the zone is null + * @throws SecurityException if the application has insufficient security rights + */ + public static void setDefault(DateTimeZone zone) throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("DateTimeZone.setDefault")); + } + if (zone == null) { + throw new IllegalArgumentException("The datetime zone must not be null"); + } + cDefault = zone; + } + + /** + * Get the time zone by id. + *

+ * The time zone id may be one of those returned by getAvailableIDs. + * Short ids, as accepted by {@link java.util.TimeZone}, are not accepted. + * All IDs must be specified in the long format. + * The exception is UTC, which is an acceptable id. + *

+ * Alternatively a locale independent, fixed offset, datetime zone can + * be specified. The form [+-]hh:mm can be used. + * + * @param id the ID of the datetime zone, null means default + * @return the DateTimeZone object for the ID + * @throws IllegalArgumentException if the ID is not recognised + */ + public static DateTimeZone getInstance(String id) throws IllegalArgumentException { + if (id == null) { + return getDefault(); + } + if (id.equals("UTC")) { + return DateTimeZone.UTC; + } + DateTimeZone zone = cProvider.getZone(id); + if (zone != null) { + return zone; + } + if (id.startsWith("+") || id.startsWith("-")) { + int offset = -(int) offsetFormatter().parseMillis(id); + if (offset == 0L) { + return DateTimeZone.UTC; + } else { + StringBuffer buf = new StringBuffer(); + id = printTimeZone(offset); + return fixedOffsetZone(id, offset); + } + } + throw new IllegalArgumentException("The datetime zone id is not recognised: " + id); + } + + /** + * Get the time zone by the number of hours difference from UTC. + * This method assumes standard length hours. + *

+ * This factory is a convenient way of constructing zones with a fixed offset. + * + * @param hoursOffset the offset in hours from UTC + * @return the DateTimeZone object for the offset + * @throws IllegalArgumentException if the offset is too large or too small + */ + public static DateTimeZone getInstance(int hoursOffset) throws IllegalArgumentException { + return getInstance(hoursOffset, 0); + } + + /** + * Get the time zone by the number of hours and minutes difference from UTC. + * This method assumes 60 minutes in an hour, and standard length minutes. + *

+ * This factory is a convenient way of constructing zones with a fixed offset. + * The minutes value is always positive and in the range 0 to 59. + * If constructed with the values (-2, 30), the resultiong zone is '-02:30'. + * + * @param hoursOffset the offset in hours from UTC + * @param minutesOffset the offset in minutes from UTC, must be between 0 and 59 inclusive + * @return the DateTimeZone object for the offset + * @throws IllegalArgumentException if the offset or minute is too large or too small + */ + public static DateTimeZone getInstance(int hoursOffset, int minutesOffset) throws IllegalArgumentException { + if (hoursOffset == 0 && minutesOffset == 0) { + return DateTimeZone.UTC; + } + if (minutesOffset < 0 || minutesOffset > 59) { + throw new IllegalArgumentException("Minutes out of range: " + minutesOffset); + } + int offset = 0; + try { + int hoursInMinutes = FieldUtils.safeMultiplyToInt(hoursOffset, 60); + if (hoursInMinutes < 0) { + minutesOffset = FieldUtils.safeAdd(hoursInMinutes, -minutesOffset); + } else { + minutesOffset = FieldUtils.safeAdd(hoursInMinutes, minutesOffset); + } + offset = FieldUtils.safeMultiplyToInt(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE); + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Offset is too large"); + } + String id = printTimeZone(offset); + return fixedOffsetZone(id, offset); + } + + /** + * Get the time zone by Java TimeZone. + *

+ * DateTimeZone only accepts a subset of the IDs from TimeZone. The + * excluded IDs are the short three letter form (except UTC). This + * method will attempt to convert between time zones created using the + * short IDs and the full version. + * + * @param zone the zone to convert, null means default + * @return the DateTimeZone object for the zone + * @throws IllegalArgumentException if the zone is not recognised + */ + public static DateTimeZone getInstance(java.util.TimeZone zone) { + if (zone == null) { + return getDefault(); + } + final String id = zone.getID(); + if (id.equals("UTC")) { + return DateTimeZone.UTC; + } + + // Convert from old alias before consulting provider since they may differ. + DateTimeZone dtz = null; + String convId = getConvertedId(id); + if (convId != null) { + dtz = cProvider.getZone(convId); + } + if (dtz == null) { + dtz = cProvider.getZone(id); + } + if (dtz != null) { + return dtz; + } + + // Support GMT+/-hh:mm formats + if (convId == null) { + convId = zone.getDisplayName(); + if (convId.startsWith("GMT+") || convId.startsWith("GMT-")) { + convId = convId.substring(3); + int offset = -(int) offsetFormatter().parseMillis(convId); + if (offset == 0L) { + return DateTimeZone.UTC; + } else { + convId = printTimeZone(offset); + return fixedOffsetZone(convId, offset); + } + } + } + + throw new IllegalArgumentException("The datetime zone id is not recognised: " + id); + } + + /** + * Gets the zone using a fixed offset amount. + * + * @param id the zone id + * @param offset the offset in millis + * @return the zone + */ + private static synchronized DateTimeZone fixedOffsetZone(String id, int offset) { + if (iFixedOffsetCache == null) { + iFixedOffsetCache = new HashMap(); + } + DateTimeZone zone; + Reference ref = (Reference) iFixedOffsetCache.get(id); + if (ref != null) { + zone = (DateTimeZone) ref.get(); + if (zone != null) { + return zone; + } + } + zone = new FixedDateTimeZone(id, null, offset, offset); + iFixedOffsetCache.put(id, new SoftReference(zone)); + return zone; + } + + /** + * Gets all the available IDs supported. + * + * @return an unmodifiable Set of String IDs + */ + public static Set getAvailableIDs() { + return cAvailableIDs; + } + + //----------------------------------------------------------------------- + /** + * Gets the zone provider factory. + *

+ * The zone provider is a pluggable instance factory that supplies the + * actual instances of DateTimeZone. + * + * @return the provider + */ + public static Provider getProvider() { + return cProvider; + } + + /** + * Sets the zone provider factory. + *

+ * The zone provider is a pluggable instance factory that supplies the + * actual instances of DateTimeZone. + * + * @param provider provider to use, or null for default + * @throws SecurityException if you do not have the permission DateTimeZone.setProvider + * @throws IllegalArgumentException if the provider is invalid + */ + public static void setProvider(Provider provider) throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("DateTimeZone.setProvider")); + } + setProvider0(provider); + } + + /** + * Sets the zone provider factory without performing the security check. + * + * @param provider provider to use, or null for default + * @throws IllegalArgumentException if the provider is invalid + */ + private static void setProvider0(Provider provider) { + if (provider == null) { + provider = getDefaultProvider(); + } + Set ids = provider.getAvailableIDs(); + if (ids == null || ids.size() == 0) { + throw new IllegalArgumentException + ("The provider doesn't have any available ids"); + } + if (!ids.contains("UTC")) { + throw new IllegalArgumentException("The provider doesn't support UTC"); + } + if (!UTC.equals(provider.getZone("UTC"))) { + throw new IllegalArgumentException("Invalid UTC zone provided"); + } + cProvider = provider; + cAvailableIDs = ids; + } + + /** + * Gets the default zone provider. + *

+ * Tries the system property org.joda.time.DateTimeZone.Provider. + * Then tries a ZoneInfoProvider using the data in org/joda/time/tz/data. + * Then uses UTCProvider. + * + * @return the default name provider + */ + private static Provider getDefaultProvider() { + Provider provider = null; + + try { + String providerClass = + System.getProperty("org.joda.time.DateTimeZone.Provider"); + if (providerClass != null) { + try { + provider = (Provider) Class.forName(providerClass).newInstance(); + } catch (Exception ex) { + Thread thread = Thread.currentThread(); + thread.getThreadGroup().uncaughtException(thread, ex); + } + } + } catch (SecurityException ex) { + // ignored + } + + if (provider == null) { + try { + provider = new ZoneInfoProvider("org/joda/time/tz/data"); + } catch (Exception ex) { + Thread thread = Thread.currentThread(); + thread.getThreadGroup().uncaughtException(thread, ex); + } + } + + if (provider == null) { + provider = new UTCProvider(); + } + + return provider; + } + + //----------------------------------------------------------------------- + /** + * Gets the name provider factory. + *

+ * The name provider is a pluggable instance factory that supplies the + * names of each DateTimeZone. + * + * @return the provider + */ + public static NameProvider getNameProvider() { + return cNameProvider; + } + + /** + * Sets the name provider factory. + *

+ * The name provider is a pluggable instance factory that supplies the + * names of each DateTimeZone. + * + * @param nameProvider provider to use, or null for default + * @throws SecurityException if you do not have the permission DateTimeZone.setNameProvider + * @throws IllegalArgumentException if the provider is invalid + */ + public static void setNameProvider(NameProvider nameProvider) throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("DateTimeZone.setNameProvider")); + } + setNameProvider0(nameProvider); + } + + /** + * Sets the name provider factory without performing the security check. + * + * @param nameProvider provider to use, or null for default + * @throws IllegalArgumentException if the provider is invalid + */ + private static void setNameProvider0(NameProvider nameProvider) { + if (nameProvider == null) { + nameProvider = getDefaultNameProvider(); + } + cNameProvider = nameProvider; + } + + /** + * Gets the default name provider. + *

+ * Tries the system property org.joda.time.DateTimeZone.NameProvider. + * Then uses DefaultNameProvider. + * + * @return the default name provider + */ + private static NameProvider getDefaultNameProvider() { + NameProvider nameProvider = null; + try { + String providerClass = System.getProperty("org.joda.time.DateTimeZone.NameProvider"); + if (providerClass != null) { + try { + nameProvider = (NameProvider) Class.forName(providerClass).newInstance(); + } catch (Exception ex) { + Thread thread = Thread.currentThread(); + thread.getThreadGroup().uncaughtException(thread, ex); + } + } + } catch (SecurityException ex) { + // ignore + } + + if (nameProvider == null) { + nameProvider = new DefaultNameProvider(); + } + + return nameProvider; + } + + //----------------------------------------------------------------------- + /** + * Converts an old style id to a new style id. + * + * @param id the old style id + * @return the new style id, null if not found + */ + private static synchronized String getConvertedId(String id) { + Map map = cZoneIdConversion; + if (map == null) { + // Backwards compatibility with TimeZone. + map = new HashMap(); + map.put("GMT", "UTC"); + map.put("MIT", "Pacific/Apia"); + map.put("HST", "Pacific/Honolulu"); + map.put("AST", "America/Anchorage"); + map.put("PST", "America/Los_Angeles"); + map.put("MST", "America/Denver"); + map.put("PNT", "America/Phoenix"); + map.put("CST", "America/Chicago"); + map.put("EST", "America/New_York"); + map.put("IET", "America/Indianapolis"); + map.put("PRT", "America/Puerto_Rico"); + map.put("CNT", "America/St_Johns"); + map.put("AGT", "America/Buenos_Aires"); + map.put("BET", "America/Sao_Paulo"); + map.put("WET", "Europe/London"); + map.put("ECT", "Europe/Paris"); + map.put("ART", "Africa/Cairo"); + map.put("CAT", "Africa/Harare"); + map.put("EET", "Europe/Bucharest"); + map.put("EAT", "Africa/Addis_Ababa"); + map.put("MET", "Asia/Tehran"); + map.put("NET", "Asia/Yerevan"); + map.put("PLT", "Asia/Karachi"); + map.put("IST", "Asia/Calcutta"); + map.put("BST", "Asia/Dhaka"); + map.put("VST", "Asia/Saigon"); + map.put("CTT", "Asia/Shanghai"); + map.put("JST", "Asia/Tokyo"); + map.put("ACT", "Australia/Darwin"); + map.put("AET", "Australia/Sydney"); + map.put("SST", "Pacific/Guadalcanal"); + map.put("NST", "Pacific/Auckland"); + cZoneIdConversion = map; + } + return (String) map.get(id); + } + + /** + * Gets a printer/parser for managing the offset id formatting. + * + * @return the formatter + */ + private static synchronized DateTimeFormatter offsetFormatter() { + if (cOffsetFormatter == null) { + cOffsetFormatter = new DateTimeFormatterBuilder() + .appendTimeZoneOffset(null, true, 2, 4) + .toFormatter(); + } + return cOffsetFormatter; + } + + /** + * Formats a timezone offset string. + *

+ * This method is kept separate from the formatting classe to speed and + * simplify startup and classloading. + * + * @param offset the offset in milliseconds + * @return the time zone string + */ + private static String printTimeZone(int offset) { + StringBuffer buf = new StringBuffer(); + if (offset >= 0) { + buf.append('+'); + } else { + buf.append('-'); + offset = -offset; + } + + int hours = offset / DateTimeConstants.MILLIS_PER_HOUR; + FormatUtils.appendPaddedInteger(buf, hours, 2); + offset -= hours * (int) DateTimeConstants.MILLIS_PER_HOUR; + + int minutes = offset / DateTimeConstants.MILLIS_PER_MINUTE; + buf.append(':'); + FormatUtils.appendPaddedInteger(buf, minutes, 2); + offset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; + if (offset == 0) { + return buf.toString(); + } + + int seconds = offset / DateTimeConstants.MILLIS_PER_SECOND; + buf.append(':'); + FormatUtils.appendPaddedInteger(buf, seconds, 2); + offset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; + if (offset == 0) { + return buf.toString(); + } + + buf.append('.'); + FormatUtils.appendPaddedInteger(buf, offset, 3); + return buf.toString(); + } + + // Instance fields and methods + //-------------------------------------------------------------------- + + private final String iID; + + /** + * Constructor. + * + * @param id the id to use + * @throws IllegalArgumentException if the id is null + */ + protected DateTimeZone(String id) { + if (id == null) { + throw new IllegalArgumentException("Id must not be null"); + } + iID = id; + } + + // Principal methods + //-------------------------------------------------------------------- + + /** + * Gets the ID of this datetime zone. + * + * @return the ID of this datetime zone + */ + public final String getID() { + return iID; + } + + /** + * Returns a non-localized name that is unique to this time zone. It can be + * combined with id to form a unique key for fetching localized names. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for + * @return name key or null if id should be used for names + */ + public abstract String getNameKey(long instant); + + /** + * Gets the short name of this datetime zone suitable for display using + * the default locale. + *

+ * If the name is not available for the locale, then this method returns a + * string in the format [+-]hh:mm. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for + * @return the human-readable short name in the default locale + */ + public final String getShortName(long instant) { + return getShortName(instant, null); + } + + /** + * Gets the short name of this datetime zone suitable for display using + * the specified locale. + *

+ * If the name is not available for the locale, then this method returns a + * string in the format [+-]hh:mm. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for + * @param locale the locale to get the name for + * @return the human-readable short name in the specified locale + */ + public String getShortName(long instant, Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + String nameKey = getNameKey(instant); + if (nameKey == null) { + return iID; + } + String name = cNameProvider.getShortName(locale, iID, nameKey); + if (name != null) { + return name; + } + return printTimeZone(getOffset(instant)); + } + + /** + * Gets the long name of this datetime zone suitable for display using + * the default locale. + *

+ * If the name is not available for the locale, then this method returns a + * string in the format [+-]hh:mm. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for + * @return the human-readable long name in the default locale + */ + public final String getName(long instant) { + return getName(instant, null); + } + + /** + * Gets the long name of this datetime zone suitable for display using + * the specified locale. + *

+ * If the name is not available for the locale, then this method returns a + * string in the format [+-]hh:mm. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z to get the name for + * @param locale the locale to get the name for + * @return the human-readable long name in the specified locale + */ + public String getName(long instant, Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + String nameKey = getNameKey(instant); + if (nameKey == null) { + return iID; + } + String name = cNameProvider.getName(locale, iID, nameKey); + if (name != null) { + return name; + } + return printTimeZone(getOffset(instant)); + } + + /** + * Gets the millisecond offset to add to UTC to get local time. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z to get the offset for + * @return the millisecond offset to add to UTC to get local time + */ + public abstract int getOffset(long instant); + + /** + * Gets the millisecond offset to add to UTC to get local time. + * + * @param instant instant to get the offset for, null means now + * @return the millisecond offset to add to UTC to get local time + */ + public final int getOffset(ReadableInstant instant) { + if (instant == null) { + return getOffset(DateTimeUtils.currentTimeMillis()); + } + return getOffset(instant.getMillis()); + } + + /** + * Gets the standard millisecond offset to add to UTC to get local time, + * when standard time is in effect. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z to get the offset for + * @return the millisecond offset to add to UTC to get local time + */ + public abstract int getStandardOffset(long instant); + + /** + * Gets the millisecond offset to subtract from local time to get UTC time. + * This offset can be used to undo adding the offset obtained by getOffset. + * + *

+     * millisLocal == millisUTC   + getOffset(millisUTC)
+     * millisUTC   == millisLocal - getOffsetFromLocal(millisLocal)
+     * 
+ * + * Note: After calculating millisLocal, some error may be introduced. At + * offset transitions (due to DST or other historical changes), ranges of + * local times may map to different UTC times. + * + * @param instantLocal the millisecond instant, relative to this time zone, to + * get the offset for + * @return the millisecond offset to subtract from local time to get UTC time + */ + public int getOffsetFromLocal(long instantLocal) { + return getOffset(instantLocal - getOffset(instantLocal)); + } + + /** + * Gets the millisecond instant in another zone keeping the same local time. + *

+ * The conversion is performed by converting the specified UTC millis to local + * millis in this zone, then converting back to UTC millis in the new zone. + * + * @param newZone the new zone, null means default + * @param oldInstant the UTC millisecond instant to convert + * @return the UTC millisecond instant with the same local time in the new zone + */ + public long getMillisKeepLocal(DateTimeZone newZone, long oldInstant) { + if (newZone == null) { + newZone = DateTimeZone.getDefault(); + } + long instantLocal = oldInstant + getOffset(oldInstant); + return instantLocal - newZone.getOffsetFromLocal(instantLocal); + } + + /** + * Returns true if this time zone has no transitions. + * + * @return true if no transitions + */ + public abstract boolean isFixed(); + + /** + * Advances the given instant to where the time zone offset or name changes. + * If the instant returned is exactly the same as passed in, then + * no changes occur after the given instant. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z + * @return milliseconds from 1970-01-01T00:00:00Z + */ + public abstract long nextTransition(long instant); + + /** + * Retreats the given instant to where the time zone offset or name changes. + * If the instant returned is exactly the same as passed in, then + * no changes occur before the given instant. + * + * @param instant milliseconds from 1970-01-01T00:00:00Z + * @return milliseconds from 1970-01-01T00:00:00Z + */ + public abstract long previousTransition(long instant); + + // Basic methods + //-------------------------------------------------------------------- + + /** + * Get the datetime zone as a {@link java.util.TimeZone}. + * + * @return the equivalent TimeZone object + */ + public java.util.TimeZone toTimeZone() { + return java.util.TimeZone.getTimeZone(iID); + } + + /** + * Compare this datetime zone with another. + * + * @param object the object to compare with + * @return true if equal, based on the ID and all internal rules + */ + public abstract boolean equals(Object object); + + /** + * Gets a hash code compatable with equals. + * + * @return suitable hashcode + */ + public int hashCode() { + return 57 + getID().hashCode(); + } + + /** + * Gets the datetime zone as a string, which is simply its ID. + * @return the id of the zone + */ + public String toString() { + return getID(); + } + + /** + * By default, when DateTimeZones are serialized, only a "stub" object + * referring to the id is written out. When the stub is read in, it + * replaces itself with a DateTimeZone object. + * @return a stub object to go in the stream + */ + protected Object writeReplace() throws ObjectStreamException { + return new Stub(iID); + } + + /** + * Used to serialize DateTimeZones by id. + */ + private static final class Stub implements Serializable { + /** Serialization lock. */ + private static final long serialVersionUID = -6471952376487863581L; + /** The ID of the zone. */ + private transient String iID; + + /** + * Constructor. + * @param id the id of the zone + */ + Stub(String id) { + iID = id; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeUTF(iID); + } + + private void readObject(ObjectInputStream in) throws IOException { + iID = in.readUTF(); + } + + private Object readResolve() throws ObjectStreamException { + return getInstance(iID); + } + } +} Index: 3rdParty_sources/joda-time/org/joda/time/Duration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/Duration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/Duration.java 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,247 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +import org.joda.time.base.BaseDuration; +import org.joda.time.field.FieldUtils; + +/** + * An immutable duration specifying a length of time in milliseconds. + *

+ * A duration is defined by a fixed number of milliseconds. + * There is no concept of fields, such as days or seconds, as these fields can vary in length. + * A duration may be converted to a {@link Period} to obtain field values. + * This conversion will typically cause a loss of precision however. + *

+ * Duration is thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public final class Duration + extends BaseDuration + implements ReadableDuration, Serializable { + + /** Constant representing zero millisecond duration */ + public static final Duration ZERO = new Duration(0L); + + /** Serialization version */ + private static final long serialVersionUID = 2471658376918L; + + /** + * Creates a duration from the given millisecond duration. + * + * @param duration the duration, in milliseconds + */ + public Duration(long duration) { + super(duration); + } + + /** + * Creates a duration from the given interval endpoints. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @throws ArithmeticException if the duration exceeds a 64 bit long + */ + public Duration(long startInstant, long endInstant) { + super(startInstant, endInstant); + } + + /** + * Creates a duration from the given interval endpoints. + * + * @param start interval start, null means now + * @param end interval end, null means now + * @throws ArithmeticException if the duration exceeds a 64 bit long + */ + public Duration(ReadableInstant start, ReadableInstant end) { + super(start, end); + } + + /** + * Creates a duration from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param duration duration to convert + * @throws IllegalArgumentException if duration is invalid + */ + public Duration(Object duration) { + super(duration); + } + + //----------------------------------------------------------------------- + /** + * Get this duration as an immutable Duration object + * by returning this. + * + * @return this + */ + public Duration toDuration() { + return this; + } + + //----------------------------------------------------------------------- + /** + * Creates a new Duration instance with a different milisecond length. + * + * @param duration the new length of the duration + * @return the new duration instance + */ + public Duration withMillis(long duration) { + if (duration == getMillis()) { + return this; + } + return new Duration(duration); + } + + /** + * Returns a new duration with this length plus that specified multiplied by the scalar. + * This instance is immutable and is not altered. + *

+ * If the addition is zero, this instance is returned. + * + * @param durationToAdd the duration to add to this one + * @param scalar the amount of times to add, such as -1 to subtract once + * @return the new duration instance + */ + public Duration withDurationAdded(long durationToAdd, int scalar) { + if (durationToAdd == 0 || scalar == 0) { + return this; + } + long add = FieldUtils.safeMultiply(durationToAdd, scalar); + long duration = FieldUtils.safeAdd(getMillis(), add); + return new Duration(duration); + } + + /** + * Returns a new duration with this length plus that specified multiplied by the scalar. + * This instance is immutable and is not altered. + *

+ * If the addition is zero, this instance is returned. + * + * @param durationToAdd the duration to add to this one, null means zero + * @param scalar the amount of times to add, such as -1 to subtract once + * @return the new duration instance + */ + public Duration withDurationAdded(ReadableDuration durationToAdd, int scalar) { + if (durationToAdd == null || scalar == 0) { + return this; + } + return withDurationAdded(durationToAdd.getMillis(), scalar); + } + + //----------------------------------------------------------------------- + /** + * Returns a new duration with this length plus that specified. + * This instance is immutable and is not altered. + *

+ * If the addition is zero, this instance is returned. + * + * @param amount the duration to add to this one + * @return the new duration instance + */ + public Duration plus(long amount) { + return withDurationAdded(amount, 1); + } + + /** + * Returns a new duration with this length plus that specified. + * This instance is immutable and is not altered. + *

+ * If the amount is zero, this instance is returned. + * + * @param amount the duration to add to this one, null means zero + * @return the new duration instance + */ + public Duration plus(ReadableDuration amount) { + if (amount == null) { + return this; + } + return withDurationAdded(amount.getMillis(), 1); + } + + /** + * Returns a new duration with this length minus that specified. + * This instance is immutable and is not altered. + *

+ * If the addition is zero, this instance is returned. + * + * @param amount the duration to take away from this one + * @return the new duration instance + */ + public Duration minus(long amount) { + return withDurationAdded(amount, -1); + } + + /** + * Returns a new duration with this length minus that specified. + * This instance is immutable and is not altered. + *

+ * If the amount is zero, this instance is returned. + * + * @param amount the duration to take away from this one, null means zero + * @return the new duration instance + */ + public Duration minus(ReadableDuration amount) { + if (amount == null) { + return this; + } + return withDurationAdded(amount.getMillis(), -1); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/DurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DurationField.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,326 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines the calculation engine for duration fields. + * The interface defines a set of methods that manipulate a millisecond duration + * with regards to a single field, such as months or seconds. + *

+ * This design is extensible so, if you wish, you can extract a different field from + * the millisecond duration. A number of standard implementations are provided to assist. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class DurationField implements Comparable { + + /** + * Get the type of the field. + * + * @return field type + */ + public abstract DurationFieldType getType(); + + /** + * Get the name of the field. + *

+ * By convention, names are plural. + * + * @return field name + */ + public abstract String getName(); + + /** + * Returns true if this field is supported. + * + * @return true if this field is supported + */ + public abstract boolean isSupported(); + + /** + * Is this field precise. A precise field can calculate its value from + * milliseconds without needing a reference date. Put another way, a + * precise field's unit size is not variable. + * + * @return true if precise + * @see #getUnitMillis() + */ + public abstract boolean isPrecise(); + + /** + * Returns the amount of milliseconds per unit value of this field. For + * example, if this field represents "seconds", then this returns the + * milliseconds in one second. + *

+ * For imprecise fields, the unit size is variable, and so this method + * returns a suitable average value. + * + * @return the unit size of this field, in milliseconds + * @see #isPrecise() + */ + public abstract long getUnitMillis(); + + //------------------------------------------------------------------------ + /** + * Get the value of this field from the milliseconds, which is approximate + * if this field is imprecise. + * + * @param duration the milliseconds to query, which may be negative + * @return the value of the field, in the units of the field, which may be + * negative + * @throws ArithmeticException if the value is too large for an int + */ + public abstract int getValue(long duration); + + /** + * Get the value of this field from the milliseconds, which is approximate + * if this field is imprecise. + * + * @param duration the milliseconds to query, which may be negative + * @return the value of the field, in the units of the field, which may be + * negative + */ + public abstract long getValueAsLong(long duration); + + /** + * Get the value of this field from the milliseconds relative to an + * instant. For precise fields this method produces the same result as for + * the single argument get method. + *

+ * If the millisecond duration is positive, then the instant is treated as a + * "start instant". If negative, the instant is treated as an "end instant". + * + * @param duration the milliseconds to query, which may be negative + * @param instant the start instant to calculate relative to + * @return the value of the field, in the units of the field, which may be + * negative + * @throws ArithmeticException if the value is too large for an int + */ + public abstract int getValue(long duration, long instant); + + /** + * Get the value of this field from the milliseconds relative to an + * instant. For precise fields this method produces the same result as for + * the single argument get method. + *

+ * If the millisecond duration is positive, then the instant is treated as a + * "start instant". If negative, the instant is treated as an "end instant". + * + * @param duration the milliseconds to query, which may be negative + * @param instant the start instant to calculate relative to + * @return the value of the field, in the units of the field, which may be + * negative + */ + public abstract long getValueAsLong(long duration, long instant); + + //------------------------------------------------------------------------ + /** + * Get the millisecond duration of this field from its value, which is + * approximate if this field is imprecise. + * + * @param value the value of the field, which may be negative + * @return the milliseconds that the field represents, which may be + * negative + */ + public abstract long getMillis(int value); + + /** + * Get the millisecond duration of this field from its value, which is + * approximate if this field is imprecise. + * + * @param value the value of the field, which may be negative + * @return the milliseconds that the field represents, which may be + * negative + */ + public abstract long getMillis(long value); + + /** + * Get the millisecond duration of this field from its value relative to an + * instant. For precise fields this method produces the same result as for + * the single argument getMillis method. + *

+ * If the value is positive, then the instant is treated as a "start + * instant". If negative, the instant is treated as an "end instant". + * + * @param value the value of the field, which may be negative + * @param instant the instant to calculate relative to + * @return the millisecond duration that the field represents, which may be + * negative + */ + public abstract long getMillis(int value, long instant); + + /** + * Get the millisecond duration of this field from its value relative to an + * instant. For precise fields this method produces the same result as for + * the single argument getMillis method. + *

+ * If the value is positive, then the instant is treated as a "start + * instant". If negative, the instant is treated as an "end instant". + * + * @param value the value of the field, which may be negative + * @param instant the instant to calculate relative to + * @return the millisecond duration that the field represents, which may be + * negative + */ + public abstract long getMillis(long value, long instant); + + /** + * Adds a duration value (which may be negative) to the instant. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the value to add, in the units of the field + * @return the updated milliseconds + */ + public abstract long add(long instant, int value); + + /** + * Adds a duration value (which may be negative) to the instant. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the value to add, in the units of the field + * @return the updated milliseconds + */ + public abstract long add(long instant, long value); + + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *

+     * long instant = ...
+     * int v = ...
+     * int age = getDifference(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public abstract int getDifference(long minuendInstant, long subtrahendInstant); + + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *
+     * long instant = ...
+     * long v = ...
+     * long age = getDifferenceAsLong(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public abstract long getDifferenceAsLong(long minuendInstant, long subtrahendInstant); + + /** + * Compares this duration field with another duration field for ascending + * unit millisecond order. This ordering is inconsistent with equals, as it + * ignores name and precision. + * + * @param durationField a duration field to check against + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object type is not supported + */ + public abstract int compareTo(Object durationField); + + /** + * Returns a localized unit name of this field, using the given value as an + * aid. For example, the unit name may differ if it is plural. + * + * @param value the duration value to use for selecting a unit name + * @param locale the locale to use for selecting a name, null for default + */ + //String getUnitName(long value, Locale locale); + + /** + * Returns a localized unit name of this field, using the given value as an + * aid. For example, the unit name may differ if it is plural. + * + * @param value the duration value to use for selecting a unit name + */ + //String getUnitName(long value); + + /** + * Get the maximum length string returned by getUnitName. + * + * @param locale the locale to use for selecting a unit name, null for + * default + * @return the maximum name length + */ + //int getMaximumUnitNameLength(Locale locale); + + //------------------------------------------------------------------------ + /** + * Get a suitable debug string. + * + * @return debug string + */ + public abstract String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/DurationFieldType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/DurationFieldType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/DurationFieldType.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,373 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +/** + * Identifies a duration field, such as years or minutes, in a chronology-neutral way. + *

+ * A duration field type defines the type of the field, such as hours. + * If does not directly enable any calculations, however it does provide a + * {@link #getField(Chronology)} method that returns the actual calculation engine + * for a particular chronology. + *

+ * Instances of DurationFieldType are singletons. + * They can be compared using ==. + *

+ * If required, you can create your own field, for example a quarters. + * You must create a subclass of DurationFieldType that defines the field type. + * This class returns the actual calculation engine from {@link #getField(Chronology)}. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class DurationFieldType implements Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 8765135187319L; + + // Ordinals for standard field types. + static final byte + ERAS = 1, + CENTURIES = 2, + WEEKYEARS = 3, + YEARS = 4, + MONTHS = 5, + WEEKS = 6, + DAYS = 7, + HALFDAYS = 8, + HOURS = 9, + MINUTES = 10, + SECONDS = 11, + MILLIS = 12; + + /** The eras field type. */ + static final DurationFieldType ERAS_TYPE = new StandardDurationFieldType("eras", ERAS); + /** The centuries field type. */ + static final DurationFieldType CENTURIES_TYPE = new StandardDurationFieldType("centuries", CENTURIES); + /** The weekyears field type. */ + static final DurationFieldType WEEKYEARS_TYPE = new StandardDurationFieldType("weekyears", WEEKYEARS); + /** The years field type. */ + static final DurationFieldType YEARS_TYPE = new StandardDurationFieldType("years", YEARS); + /** The months field type. */ + static final DurationFieldType MONTHS_TYPE = new StandardDurationFieldType("months", MONTHS); + /** The weeks field type. */ + static final DurationFieldType WEEKS_TYPE = new StandardDurationFieldType("weeks", WEEKS); + /** The days field type. */ + static final DurationFieldType DAYS_TYPE = new StandardDurationFieldType("days", DAYS); + /** The halfdays field type. */ + static final DurationFieldType HALFDAYS_TYPE = new StandardDurationFieldType("halfdays", HALFDAYS); + /** The hours field type. */ + static final DurationFieldType HOURS_TYPE = new StandardDurationFieldType("hours", HOURS); + /** The minutes field type. */ + static final DurationFieldType MINUTES_TYPE = new StandardDurationFieldType("minutes", MINUTES); + /** The seconds field type. */ + static final DurationFieldType SECONDS_TYPE = new StandardDurationFieldType("seconds", SECONDS); + /** The millis field type. */ + static final DurationFieldType MILLIS_TYPE = new StandardDurationFieldType("millis", MILLIS); + + /** The name of the field type. */ + private final String iName; + + //----------------------------------------------------------------------- + /** + * Constructor. + * + * @param name the name to use, which by convention, are plural. + */ + protected DurationFieldType(String name) { + super(); + iName = name; + } + + //----------------------------------------------------------------------- + /** + * Get the millis field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType millis() { + return MILLIS_TYPE; + } + + /** + * Get the seconds field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType seconds() { + return SECONDS_TYPE; + } + + /** + * Get the minutes field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType minutes() { + return MINUTES_TYPE; + } + + /** + * Get the hours field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType hours() { + return HOURS_TYPE; + } + + /** + * Get the halfdays field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType halfdays() { + return HALFDAYS_TYPE; + } + + //----------------------------------------------------------------------- + /** + * Get the days field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType days() { + return DAYS_TYPE; + } + + /** + * Get the weeks field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType weeks() { + return WEEKS_TYPE; + } + + /** + * Get the weekyears field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType weekyears() { + return WEEKYEARS_TYPE; + } + + /** + * Get the months field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType months() { + return MONTHS_TYPE; + } + + /** + * Get the years field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType years() { + return YEARS_TYPE; + } + + /** + * Get the centuries field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType centuries() { + return CENTURIES_TYPE; + } + + /** + * Get the eras field type. + * + * @return the DateTimeFieldType constant + */ + public static DurationFieldType eras() { + return ERAS_TYPE; + } + + //----------------------------------------------------------------------- + /** + * Get the name of the field. + * By convention, names are plural. + * + * @return field name + */ + public String getName() { + return iName; + } + + /** + * Gets a suitable field for this type from the given Chronology. + * + * @param chronology the chronology to use, null means ISOChronology in default zone + * @return a suitable field + */ + public abstract DurationField getField(Chronology chronology); + + /** + * Checks whether this field supported in the given Chronology. + * + * @param chronology the chronology to use, null means ISOChronology in default zone + * @return true if supported + */ + public boolean isSupported(Chronology chronology) { + return getField(chronology).isSupported(); + } + + /** + * Get a suitable debug string. + * + * @return debug string + */ + public String toString() { + return getName(); + } + + private static class StandardDurationFieldType extends DurationFieldType { + /** Serialization version */ + private static final long serialVersionUID = 31156755687123L; + + /** The ordinal of the standard field type, for switch statements */ + private final byte iOrdinal; + + /** + * Constructor. + * + * @param name the name to use + */ + StandardDurationFieldType(String name, byte ordinal) { + super(name); + iOrdinal = ordinal; + } + + public DurationField getField(Chronology chronology) { + chronology = DateTimeUtils.getChronology(chronology); + + switch (iOrdinal) { + case ERAS: + return chronology.eras(); + case CENTURIES: + return chronology.centuries(); + case WEEKYEARS: + return chronology.weekyears(); + case YEARS: + return chronology.years(); + case MONTHS: + return chronology.months(); + case WEEKS: + return chronology.weeks(); + case DAYS: + return chronology.days(); + case HALFDAYS: + return chronology.halfdays(); + case HOURS: + return chronology.hours(); + case MINUTES: + return chronology.minutes(); + case SECONDS: + return chronology.seconds(); + case MILLIS: + return chronology.millis(); + default: + // Shouldn't happen. + throw new InternalError(); + } + } + + /** + * Ensure a singleton is returned. + * + * @return the singleton type + */ + private Object readResolve() { + switch (iOrdinal) { + case ERAS: + return ERAS_TYPE; + case CENTURIES: + return CENTURIES_TYPE; + case WEEKYEARS: + return WEEKYEARS_TYPE; + case YEARS: + return YEARS_TYPE; + case MONTHS: + return MONTHS_TYPE; + case WEEKS: + return WEEKS_TYPE; + case DAYS: + return DAYS_TYPE; + case HALFDAYS: + return HALFDAYS_TYPE; + case HOURS: + return HOURS_TYPE; + case MINUTES: + return MINUTES_TYPE; + case SECONDS: + return SECONDS_TYPE; + case MILLIS: + return MILLIS_TYPE; + default: + // Shouldn't happen. + return this; + } + } + + } +} Index: 3rdParty_sources/joda-time/org/joda/time/Instant.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/Instant.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/Instant.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,261 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +import org.joda.time.base.AbstractInstant; +import org.joda.time.convert.ConverterManager; +import org.joda.time.convert.InstantConverter; + +/** + * Instant is the standard implementation of a fully immutable instant in time. + * It holds the instant as milliseconds from the Java Epoch of 1970-01-01T00:00:00Z. + *

+ * The chronology used is always ISO in the UTC time zone. + * This corresponds to the definition of the Java Epoch. + *

+ * An Instant can be used to compare two DateTime objects: + *

+ * boolean sameInstant = dt1.toInstant().equals(dt2.toInstant());
+ * 
+ * This code will return true if the two DateTime objects represent + * the same instant regardless of chronology or time zone. + *

+ * Note that the following code will also perform the same check: + *

+ * boolean sameInstant = dt1.isEqual(dt2);
+ * 
+ *

+ * Instant is thread-safe and immutable. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public final class Instant + extends AbstractInstant + implements ReadableInstant, Serializable { + + /** Serialization lock */ + private static final long serialVersionUID = 3299096530934209741L; + + /** The millis from 1970-01-01T00:00:00Z */ + private final long iMillis; + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the current system millisecond time. + */ + public Instant() { + super(); + iMillis = DateTimeUtils.currentTimeMillis(); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + public Instant(long instant) { + super(); + iMillis = instant; + } + + /** + * Constructs an instance from an Object that represents a datetime. + *

+ * The recognised object types are defined in {@link ConverterManager} and + * include String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @throws IllegalArgumentException if the instant is invalid + */ + public Instant(Object instant) { + super(); + InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant); + iMillis = converter.getInstantMillis(instant, Chronology.getISOUTC()); + } + + //----------------------------------------------------------------------- + /** + * Get this object as an Instant by returning this. + * + * @return this + */ + public Instant toInstant() { + return this; + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this instant with different millis. + *

+ * The returned object will be either be a new Instant or this. + * + * @param newMillis the new millis, from 1970-01-01T00:00:00Z + * @return a copy of this instant with different millis + */ + public Instant withMillis(long newMillis) { + return (newMillis == iMillis ? this : new Instant(newMillis)); + } + + /** + * Gets a copy of this instant with the specified duration added. + *

+ * If the addition is zero, then this is returned. + * + * @param durationToAdd the duration to add to this one + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this instant with the duration added + * @throws ArithmeticException if the new instant exceeds the capacity of a long + */ + public Instant withDurationAdded(long durationToAdd, int scalar) { + if (durationToAdd == 0 || scalar == 0) { + return this; + } + long instant = getChronology().add(getMillis(), durationToAdd, scalar); + return withMillis(instant); + } + + /** + * Gets a copy of this instant with the specified duration added. + *

+ * If the addition is zero, then this is returned. + * + * @param durationToAdd the duration to add to this one, null means zero + * @param scalar the amount of times to add, such as -1 to subtract once + * @return a copy of this instant with the duration added + * @throws ArithmeticException if the new instant exceeds the capacity of a long + */ + public Instant withDurationAdded(ReadableDuration durationToAdd, int scalar) { + if (durationToAdd == null || scalar == 0) { + return this; + } + return withDurationAdded(durationToAdd.getMillis(), scalar); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this instant with the specified duration added. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to add to this one + * @return a copy of this instant with the duration added + * @throws ArithmeticException if the new instant exceeds the capacity of a long + */ + public Instant plus(long duration) { + return withDurationAdded(duration, 1); + } + + /** + * Gets a copy of this instant with the specified duration added. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to add to this one, null means zero + * @return a copy of this instant with the duration added + * @throws ArithmeticException if the new instant exceeds the capacity of a long + */ + public Instant plus(ReadableDuration duration) { + return withDurationAdded(duration, 1); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of this instant with the specified duration taken away. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to reduce this instant by + * @return a copy of this instant with the duration taken away + * @throws ArithmeticException if the new instant exceeds the capacity of a long + */ + public Instant minus(long duration) { + return withDurationAdded(duration, -1); + } + + /** + * Gets a copy of this instant with the specified duration taken away. + *

+ * If the amount is zero or null, then this is returned. + * + * @param duration the duration to reduce this instant by + * @return a copy of this instant with the duration taken away + * @throws ArithmeticException if the new instant exceeds the capacity of a long + */ + public Instant minus(ReadableDuration duration) { + return withDurationAdded(duration, -1); + } + + //----------------------------------------------------------------------- + /** + * Gets the milliseconds of the instant. + * + * @return the number of milliseconds since 1970-01-01T00:00:00Z + */ + public long getMillis() { + return iMillis; + } + + /** + * Gets the chronology of the instant, which is ISO in the UTC zone. + * + * @return ISO in the UTC zone + */ + public Chronology getChronology() { + return Chronology.getISOUTC(); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/Interval.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/Interval.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/Interval.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,353 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +import org.joda.time.base.BaseInterval; + +/** + * Interval is the standard implementation of an immutable time interval. + *

+ * A time interval represents a period of time between two instants. + * Intervals are inclusive of the start instant and exclusive of the end. + * The end instant is always greater than or equal to the start instant. + *

+ * Intervals have a fixed millisecond duration. + * This is the difference between the start and end instants. + * The duration is represented separately by {@link ReadableDuration}. + * As a result, intervals are not comparable. + * To compare the length of two intervals, you should compare their durations. + *

+ * An interval can also be converted to a {@link ReadablePeriod}. + * This represents the difference between the start and end points in terms of fields + * such as years and days. + *

+ * Interval is thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Sean Geoghegan + * @author Stephen Colebourne + * @since 1.0 + */ +public final class Interval + extends BaseInterval + implements ReadableInterval, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 4922451897541386752L; + + //----------------------------------------------------------------------- + /** + * Constructs an interval from a start and end instant with the ISO default chronology. + * + * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @throws IllegalArgumentException if the end is before the start + */ + public Interval(long startInstant, long endInstant) { + super(startInstant, endInstant, null); + } + + /** + * Constructs an interval from a start and end instant with a chronology. + * + * @param chronology the chronology to use, null is ISO default + * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @throws IllegalArgumentException if the end is before the start + */ + public Interval(long startInstant, long endInstant, Chronology chronology) { + super(startInstant, endInstant, chronology); + } + + /** + * Constructs an interval from a start and end instant. + *

+ * The chronology used is that of the start instant. + * + * @param start start of this interval, null means now + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + */ + public Interval(ReadableInstant start, ReadableInstant end) { + super(start, end); + } + + /** + * Constructs an interval from a start instant and a duration. + * + * @param start start of this interval, null means now + * @param duration the duration of this interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + public Interval(ReadableInstant start, ReadableDuration duration) { + super(start, duration); + } + + /** + * Constructs an interval from a millisecond duration and an end instant. + * + * @param duration the duration of this interval, null means zero length + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + public Interval(ReadableDuration duration, ReadableInstant end) { + super(duration, end); + } + + /** + * Constructs an interval from a start instant and a time period. + *

+ * When forming the interval, the chronology from the instant is used + * if present, otherwise the chronology of the period is used. + * + * @param start start of this interval, null means now + * @param period the period of this interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + public Interval(ReadableInstant start, ReadablePeriod period) { + super(start, period); + } + + /** + * Constructs an interval from a time period and an end instant. + *

+ * When forming the interval, the chronology from the instant is used + * if present, otherwise the chronology of the period is used. + * + * @param period the period of this interval, null means zero length + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + public Interval(ReadablePeriod period, ReadableInstant end) { + super(period, end); + } + + /** + * Constructs a time interval by converting or copying from another object. + * + * @param interval the time interval to copy + * @throws IllegalArgumentException if the interval is invalid + */ + public Interval(Object interval) { + super(interval, null); + } + + /** + * Constructs a time interval by converting or copying from another object, + * overriding the chronology. + * + * @param interval the time interval to copy + * @param chronology the chronology to use, null means ISO default + * @throws IllegalArgumentException if the interval is invalid + */ + public Interval(Object interval, Chronology chronology) { + super(interval, chronology); + } + + //----------------------------------------------------------------------- + /** + * Get this interval as an immutable Interval object + * by returning this. + * + * @return this + */ + public Interval toInterval() { + return this; + } + + //----------------------------------------------------------------------- + /** + * Creates a new interval with the same start and end, but a different chronology. + * + * @param chronology the chronology to use, null means ISO default + * @return an interval with a different chronology + */ + public Interval withChronology(Chronology chronology) { + if (getChronology() == chronology) { + return this; + } + return new Interval(getStartMillis(), getEndMillis(), chronology); + } + + /** + * Creates a new interval with the specified start millisecond instant. + * + * @param startInstant the start instant for the new interval + * @return an interval with the end from this interval and the specified start + * @throws IllegalArgumentException if the resulting interval has end before start + */ + public Interval withStartMillis(long startInstant) { + if (startInstant == getStartMillis()) { + return this; + } + return new Interval(startInstant, getEndMillis(), getChronology()); + } + + /** + * Creates a new interval with the specified start instant. + * + * @param start the start instant for the new interval, null means now + * @return an interval with the end from this interval and the specified start + * @throws IllegalArgumentException if the resulting interval has end before start + */ + public Interval withStart(ReadableInstant start) { + long startMillis = DateTimeUtils.getInstantMillis(start); + return withStartMillis(startMillis); + } + + /** + * Creates a new interval with the specified start millisecond instant. + * + * @param endInstant the end instant for the new interval + * @return an interval with the start from this interval and the specified end + * @throws IllegalArgumentException if the resulting interval has end before start + */ + public Interval withEndMillis(long endInstant) { + if (endInstant == getEndMillis()) { + return this; + } + return new Interval(getStartMillis(), endInstant, getChronology()); + } + + /** + * Creates a new interval with the specified end instant. + * + * @param end the end instant for the new interval, null means now + * @return an interval with the start from this interval and the specified end + * @throws IllegalArgumentException if the resulting interval has end before start + */ + public Interval withEnd(ReadableInstant end) { + long endMillis = DateTimeUtils.getInstantMillis(end); + return withEndMillis(endMillis); + } + + //----------------------------------------------------------------------- + /** + * Creates a new interval with the specified duration after the start instant. + * + * @param duration the duration to add to the start to get the new end instant, null means zero + * @return an interval with the start from this interval and a calculated end + * @throws IllegalArgumentException if the duration is negative + */ + public Interval withDurationAfterStart(ReadableDuration duration) { + long durationMillis = DateTimeUtils.getDurationMillis(duration); + if (durationMillis == toDurationMillis()) { + return this; + } + Chronology chrono = getChronology(); + long startMillis = getStartMillis(); + long endMillis = chrono.add(startMillis, durationMillis, 1); + return new Interval(startMillis, endMillis, chrono); + } + + /** + * Creates a new interval with the specified duration before the end instant. + * + * @param duration the duration to add to the start to get the new end instant, null means zero + * @return an interval with the start from this interval and a calculated end + * @throws IllegalArgumentException if the duration is negative + */ + public Interval withDurationBeforeEnd(ReadableDuration duration) { + long durationMillis = DateTimeUtils.getDurationMillis(duration); + if (durationMillis == toDurationMillis()) { + return this; + } + Chronology chrono = getChronology(); + long endMillis = getEndMillis(); + long startMillis = chrono.add(endMillis, durationMillis, -1); + return new Interval(startMillis, endMillis, chrono); + } + + //----------------------------------------------------------------------- + /** + * Creates a new interval with the specified period after the start instant. + * + * @param period the period to add to the start to get the new end instant, null means zero + * @return an interval with the start from this interval and a calculated end + * @throws IllegalArgumentException if the period is negative + */ + public Interval withPeriodAfterStart(ReadablePeriod period) { + if (period == null) { + return withDurationAfterStart(null); + } + Chronology chrono = getChronology(); + long startMillis = getStartMillis(); + long endMillis = chrono.add(period, startMillis, 1); + return new Interval(startMillis, endMillis, chrono); + } + + /** + * Creates a new interval with the specified period before the end instant. + * + * @param period the period to add to the start to get the new end instant, null means zero + * @return an interval with the start from this interval and a calculated end + * @throws IllegalArgumentException if the period is negative + */ + public Interval withPeriodBeforeEnd(ReadablePeriod period) { + if (period == null) { + return withDurationBeforeEnd(null); + } + Chronology chrono = getChronology(); + long endMillis = getEndMillis(); + long startMillis = chrono.add(period, endMillis, -1); + return new Interval(startMillis, endMillis, chrono); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/JodaTimePermission.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/JodaTimePermission.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/JodaTimePermission.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,98 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.security.BasicPermission; + +/** + * JodaTimePermission is used for securing global method calls in the Joda-Time + * library. Since this class extends BasicPermission, asterisks may be used to + * denote wildcard permissions. The following permissions are supported: + * + *

+ * DateTimeZone
+ *   .setDefault                 Allows a default DateTimeZone to be set
+ *   .setProvider                Allows the DateTimeZone instance provider to be set
+ *   .setNameProvider            Allows the DateTimeZone name provider to be set
+ *
+ * ConverterManager
+ *   .alterInstantConverters     Allows an instant converter to be added or removed
+ *   .alterPartialConverters     Allows a partial converter to be added or removed
+ *   .alterDurationConverters    Allows a duration converter to be added or removed
+ *   .alterPeriodConverters      Allows a period converter to be added or removed
+ *   .alterIntervalConverters    Allows an interval converter to be added or removed
+ *
+ * CurrentTime.setProvider       Allows the current time provider to be set
+ * 
+ *

+ * JodaTimePermission is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public class JodaTimePermission extends BasicPermission { + + /** Serialization version */ + private static final long serialVersionUID = 1408944367355875472L; + + /** + * Constructs a new permission object. + * + * @param name the permission name + */ + public JodaTimePermission(String name) { + super(name); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/MutableDateTime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/MutableDateTime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/MutableDateTime.java 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,1374 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; +import java.util.Locale; + +import org.joda.time.base.BaseDateTime; +import org.joda.time.chrono.ISOChronology; +import org.joda.time.field.AbstractReadableInstantFieldProperty; +import org.joda.time.field.FieldUtils; +import org.joda.time.format.ISODateTimeFormat; + +/** + * MutableDateTime is the standard implementation of a modifiable datetime class. + * It holds the datetime as milliseconds from the Java epoch of 1970-01-01T00:00:00Z. + *

+ * This class uses a Chronology internally. The Chronology determines how the + * millisecond instant value is converted into the date time fields. + * The default Chronology is ISOChronology which is the agreed + * international standard and compatable with the modern Gregorian calendar. + *

+ * Each individual field can be accessed in two ways: + *

    + *
  • getHourOfDay() + *
  • hourOfDay().get() + *
+ * The second technique also provides access to other useful methods on the + * field: + *
    + *
  • get numeric value + *
  • set numeric value + *
  • add to numeric value + *
  • add to numeric value wrapping with the field + *
  • get text vlaue + *
  • get short text value + *
  • set text value + *
  • field maximum value + *
  • field minimum value + *
+ * + *

+ * MutableDateTime is mutable and not thread-safe, unless concurrent threads + * are not invoking mutator methods. + * + * @author Guy Allard + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + * @see DateTime + */ +public class MutableDateTime + extends BaseDateTime + implements ReadWritableDateTime, Cloneable, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 2852608688135209575L; + + /** Rounding is disabled */ + public static final int ROUND_NONE = 0; + /** Rounding mode as described by {@link DateTimeField#roundFloor} */ + public static final int ROUND_FLOOR = 1; + /** Rounding mode as described by {@link DateTimeField#roundCeiling} */ + public static final int ROUND_CEILING = 2; + /** Rounding mode as described by {@link DateTimeField#roundHalfFloor} */ + public static final int ROUND_HALF_FLOOR = 3; + /** Rounding mode as described by {@link DateTimeField#roundHalfCeiling} */ + public static final int ROUND_HALF_CEILING = 4; + /** Rounding mode as described by {@link DateTimeField#roundHalfEven} */ + public static final int ROUND_HALF_EVEN = 5; + + /** The field to round on */ + private DateTimeField iRoundingField; + /** The mode of rounding */ + private int iRoundingMode; + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the default time zone. + */ + public MutableDateTime() { + super(); + } + + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param zone the time zone, null means default zone + */ + public MutableDateTime(DateTimeZone zone) { + super(zone); + } + + /** + * Constructs an instance set to the current system millisecond time + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param chronology the chronology, null means ISOChronology in default zone + */ + public MutableDateTime(Chronology chronology) { + super(chronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the default time zone. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + public MutableDateTime(long instant) { + super(instant); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param zone the time zone, null means default zone + */ + public MutableDateTime(long instant, DateTimeZone zone) { + super(instant, zone); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param chronology the chronology, null means ISOChronology in default zone + */ + public MutableDateTime(long instant, Chronology chronology) { + super(instant, chronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from an Object that represents a datetime. + *

+ * If the object implies a chronology (such as GregorianCalendar does), + * then that chronology will be used. Otherwise, ISO default is used. + * Thus if a GregorianCalendar is passed in, the chronology used will + * be GJ, but if a Date is passed in the chronology will be ISO. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @throws IllegalArgumentException if the instant is invalid + */ + public MutableDateTime(Object instant) { + super(instant, (Chronology) null); + } + + /** + * Constructs an instance from an Object that represents a datetime, + * forcing the time zone to that specified. + *

+ * If the object implies a chronology (such as GregorianCalendar does), + * then that chronology will be used, but with the time zone adjusted. + * Otherwise, ISO is used in the specified time zone. + * If the specified time zone is null, the default zone is used. + * Thus if a GregorianCalendar is passed in, the chronology used will + * be GJ, but if a Date is passed in the chronology will be ISO. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @param zone the time zone, null means default time zone + * @throws IllegalArgumentException if the instant is invalid + */ + public MutableDateTime(Object instant, DateTimeZone zone) { + super(instant, zone); + } + + /** + * Constructs an instance from an Object that represents a datetime, + * using the specified chronology. + *

+ * If the chronology is null, ISO in the default time zone is used. + * Any chronology implied by the object (such as GregorianCalendar does) + * is ignored. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object, null means now + * @param chronology the chronology, null means ISOChronology in default zone + * @throws IllegalArgumentException if the instant is invalid + */ + public MutableDateTime(Object instant, Chronology chronology) { + super(instant, DateTimeUtils.getChronology(chronology)); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from datetime field values + * using ISOChronology in the default time zone. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + */ + public MutableDateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond) { + super(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + + /** + * Constructs an instance from datetime field values + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @param zone the time zone, null means default time zone + */ + public MutableDateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond, + DateTimeZone zone) { + super(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, zone); + } + + /** + * Constructs an instance from datetime field values + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @param chronology the chronology, null means ISOChronology in default zone + */ + public MutableDateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond, + Chronology chronology) { + super(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, chronology); + } + + //----------------------------------------------------------------------- + /** + * Gets the field used for rounding this instant, returning null if rounding + * is not enabled. + * + * @return the rounding field + */ + public DateTimeField getRoundingField() { + return iRoundingField; + } + + /** + * Gets the rounding mode for this instant, returning ROUND_NONE if rounding + * is not enabled. + * + * @return the rounding mode constant + */ + public int getRoundingMode() { + return iRoundingMode; + } + + /** + * Sets the status of rounding to use the specified field and ROUND_FLOOR mode. + * A null field will disable rounding. + * Once set, the instant is then rounded using the new field and mode. + *

+ * Enabling rounding will cause all subsequent calls to {@link #setMillis(long)} + * to be rounded. This can be used to control the precision of the instant, + * for example by setting a rounding field of minuteOfDay, the seconds and + * milliseconds will always be zero. + * + * @param field rounding field or null to disable + */ + public void setRounding(DateTimeField field) { + setRounding(field, MutableDateTime.ROUND_FLOOR); + } + + /** + * Sets the status of rounding to use the specified field and mode. + * A null field or mode of ROUND_NONE will disable rounding. + * Once set, the instant is then rounded using the new field and mode. + *

+ * Enabling rounding will cause all subsequent calls to {@link #setMillis(long)} + * to be rounded. This can be used to control the precision of the instant, + * for example by setting a rounding field of minuteOfDay, the seconds and + * milliseconds will always be zero. + * + * @param field rounding field or null to disable + * @param mode rounding mode or ROUND_NONE to disable + * @throws IllegalArgumentException if mode is unknown, no exception if field is null + */ + public void setRounding(DateTimeField field, int mode) { + if (field != null && (mode < ROUND_NONE || mode > ROUND_HALF_EVEN)) { + throw new IllegalArgumentException("Illegal rounding mode: " + mode); + } + iRoundingField = (mode == ROUND_NONE ? null : field); + iRoundingMode = (field == null ? ROUND_NONE : mode); + setMillis(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Set the milliseconds of the datetime. + *

+ * All changes to the millisecond field occurs via this method. + * + * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the + * datetime to + */ + public void setMillis(long instant) { + switch (iRoundingMode) { + case ROUND_NONE: + break; + case ROUND_FLOOR: + instant = iRoundingField.roundFloor(instant); + break; + case ROUND_CEILING: + instant = iRoundingField.roundCeiling(instant); + break; + case ROUND_HALF_FLOOR: + instant = iRoundingField.roundHalfFloor(instant); + break; + case ROUND_HALF_CEILING: + instant = iRoundingField.roundHalfCeiling(instant); + break; + case ROUND_HALF_EVEN: + instant = iRoundingField.roundHalfEven(instant); + break; + } + + super.setMillis(instant); + } + + /** + * Sets the millisecond instant of this instant from another. + *

+ * This method does not change the chronology of this instant, just the + * millisecond instant. + * + * @param instant the instant to use, null means now + */ + public void setMillis(ReadableInstant instant) { + long instantMillis = DateTimeUtils.getInstantMillis(instant); + setMillis(instantMillis); // set via this class not super + } + + //----------------------------------------------------------------------- + /** + * Add an amount of time to the datetime. + * + * @param duration the millis to add + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + public void add(long duration) { + setMillis(FieldUtils.safeAdd(getMillis(), duration)); // set via this class not super + } + + /** + * Adds a duration to this instant. + *

+ * This will typically change the value of most fields. + * + * @param duration the duration to add, null means add zero + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + public void add(ReadableDuration duration) { + add(duration, 1); + } + + /** + * Adds a duration to this instant specifying how many times to add. + *

+ * This will typically change the value of most fields. + * + * @param duration the duration to add, null means add zero + * @param scalar direction and amount to add, which may be negative + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + public void add(ReadableDuration duration, int scalar) { + if (duration != null) { + add(FieldUtils.safeMultiply(duration.getMillis(), scalar)); + } + } + + /** + * Adds a period to this instant. + *

+ * This will typically change the value of most fields. + * + * @param period the period to add, null means add zero + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + public void add(ReadablePeriod period) { + add(period, 1); + } + + /** + * Adds a period to this instant specifying how many times to add. + *

+ * This will typically change the value of most fields. + * + * @param period the period to add, null means add zero + * @param scalar direction and amount to add, which may be negative + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + public void add(ReadablePeriod period, int scalar) { + if (period != null) { + setMillis(getChronology().add(period, getMillis(), scalar)); // set via this class not super + } + } + + //----------------------------------------------------------------------- + /** + * Set the chronology of the datetime. + *

+ * All changes to the chronology occur via this method. + * + * @param chronology the chronology to use, null means ISOChronology in default zone + */ + public void setChronology(Chronology chronology) { + super.setChronology(chronology); + } + + //----------------------------------------------------------------------- + /** + * Sets the time zone of the datetime, changing the chronology and field values. + *

+ * Changing the zone using this method retains the millisecond instant. + * The millisecond instant is adjusted in the new zone to compensate. + * + * chronology. Setting the time zone does not affect the millisecond value + * of this instant. + *

+ * If the chronology already has this time zone, no change occurs. + * + * @param newZone the time zone to use, null means default zone + * @see #setZoneRetainFields + */ + public void setZone(DateTimeZone newZone) { + newZone = DateTimeUtils.getZone(newZone); + Chronology chrono = getChronology(); + if (chrono.getZone() != newZone) { + setChronology(chrono.withZone(newZone)); // set via this class not super + } + } + + /** + * Sets the time zone of the datetime, changing the chronology and millisecond. + *

+ * Changing the zone using this method retains the field values. + * The millisecond instant is adjusted in the new zone to compensate. + *

+ * If the chronology already has this time zone, no change occurs. + * + * @param newZone the time zone to use, null means default zone + * @see #setZone + */ + public void setZoneRetainFields(DateTimeZone newZone) { + newZone = DateTimeUtils.getZone(newZone); + DateTimeZone originalZone = DateTimeUtils.getZone(getZone()); + if (newZone == originalZone) { + return; + } + + long millis = originalZone.getMillisKeepLocal(newZone, getMillis()); + setChronology(getChronology().withZone(newZone)); // set via this class not super + setMillis(millis); + } + + //----------------------------------------------------------------------- + /** + * Sets the value of one of the fields of the instant, such as hourOfDay. + * + * @param type a field type, usually obtained from DateTimeFieldType, not null + * @param value the value to set the field to + * @throws IllegalArgumentException if the value is null or invalid + */ + public void set(DateTimeFieldType type, int value) { + if (type == null) { + throw new IllegalArgumentException("Field must not be null"); + } + setMillis(type.getField(getChronology()).set(getMillis(), value)); + } + + /** + * Adds to the instant specifying the duration and multiple to add. + * + * @param type a field type, usually obtained from DateTimeFieldType, not null + * @param amount the amount to add of this duration + * @throws IllegalArgumentException if the value is null or invalid + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + public void add(DurationFieldType type, int amount) { + if (type == null) { + throw new IllegalArgumentException("Field must not be null"); + } + setMillis(type.getField(getChronology()).add(getMillis(), amount)); + } + + //----------------------------------------------------------------------- + /** + * Set the year to the specified value. + * + * @param year the year + * @throws IllegalArgumentException if the value is invalid + */ + public void setYear(final int year) { + setMillis(getChronology().year().set(getMillis(), year)); + } + + /** + * Add a number of years to the date. + * + * @param years the years to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addYears(final int years) { + setMillis(getChronology().years().add(getMillis(), years)); + } + + //----------------------------------------------------------------------- + /** + * Set the weekyear to the specified value. + * + * @param weekyear the weekyear + * @throws IllegalArgumentException if the value is invalid + */ + public void setWeekyear(final int weekyear) { + setMillis(getChronology().weekyear().set(getMillis(), weekyear)); + } + + /** + * Add a number of weekyears to the date. + * + * @param weekyears the weekyears to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addWeekyears(final int weekyears) { + setMillis(getChronology().weekyears().add(getMillis(), weekyears)); + } + + //----------------------------------------------------------------------- + /** + * Set the month of the year to the specified value. + * + * @param monthOfYear the month of the year + * @throws IllegalArgumentException if the value is invalid + */ + public void setMonthOfYear(final int monthOfYear) { + setMillis(getChronology().monthOfYear().set(getMillis(), monthOfYear)); + } + + /** + * Add a number of months to the date. + * + * @param months the months to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addMonths(final int months) { + setMillis(getChronology().months().add(getMillis(), months)); + } + + //----------------------------------------------------------------------- + /** + * Set the week of weekyear to the specified value. + * + * @param weekOfWeekyear the week of the weekyear + * @throws IllegalArgumentException if the value is invalid + */ + public void setWeekOfWeekyear(final int weekOfWeekyear) { + setMillis(getChronology().weekOfWeekyear().set(getMillis(), weekOfWeekyear)); + } + + /** + * Add a number of weeks to the date. + * + * @param weeks the weeks to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addWeeks(final int weeks) { + setMillis(getChronology().weeks().add(getMillis(), weeks)); + } + + //----------------------------------------------------------------------- + /** + * Set the day of year to the specified value. + * + * @param dayOfYear the day of the year + * @throws IllegalArgumentException if the value is invalid + */ + public void setDayOfYear(final int dayOfYear) { + setMillis(getChronology().dayOfYear().set(getMillis(), dayOfYear)); + } + + /** + * Set the day of the month to the specified value. + * + * @param dayOfMonth the day of the month + * @throws IllegalArgumentException if the value is invalid + */ + public void setDayOfMonth(final int dayOfMonth) { + setMillis(getChronology().dayOfMonth().set(getMillis(), dayOfMonth)); + } + + /** + * Set the day of week to the specified value. + * + * @param dayOfWeek the day of the week + * @throws IllegalArgumentException if the value is invalid + */ + public void setDayOfWeek(final int dayOfWeek) { + setMillis(getChronology().dayOfWeek().set(getMillis(), dayOfWeek)); + } + + /** + * Add a number of days to the date. + * + * @param days the days to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addDays(final int days) { + setMillis(getChronology().days().add(getMillis(), days)); + } + + //----------------------------------------------------------------------- + /** + * Set the hour of the day to the specified value. + * + * @param hourOfDay the hour of day + * @throws IllegalArgumentException if the value is invalid + */ + public void setHourOfDay(final int hourOfDay) { + setMillis(getChronology().hourOfDay().set(getMillis(), hourOfDay)); + } + + /** + * Add a number of hours to the date. + * + * @param hours the hours to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addHours(final int hours) { + setMillis(getChronology().hours().add(getMillis(), hours)); + } + + //----------------------------------------------------------------------- + /** + * Set the minute of the day to the specified value. + * + * @param minuteOfDay the minute of day + * @throws IllegalArgumentException if the value is invalid + */ + public void setMinuteOfDay(final int minuteOfDay) { + setMillis(getChronology().minuteOfDay().set(getMillis(), minuteOfDay)); + } + + /** + * Set the minute of the hour to the specified value. + * + * @param minuteOfHour the minute of hour + * @throws IllegalArgumentException if the value is invalid + */ + public void setMinuteOfHour(final int minuteOfHour) { + setMillis(getChronology().minuteOfHour().set(getMillis(), minuteOfHour)); + } + + /** + * Add a number of minutes to the date. + * + * @param minutes the minutes to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addMinutes(final int minutes) { + setMillis(getChronology().minutes().add(getMillis(), minutes)); + } + + //----------------------------------------------------------------------- + /** + * Set the second of the day to the specified value. + * + * @param secondOfDay the second of day + * @throws IllegalArgumentException if the value is invalid + */ + public void setSecondOfDay(final int secondOfDay) { + setMillis(getChronology().secondOfDay().set(getMillis(), secondOfDay)); + } + + /** + * Set the second of the minute to the specified value. + * + * @param secondOfMinute the second of minute + * @throws IllegalArgumentException if the value is invalid + */ + public void setSecondOfMinute(final int secondOfMinute) { + setMillis(getChronology().secondOfMinute().set(getMillis(), secondOfMinute)); + } + + /** + * Add a number of seconds to the date. + * + * @param seconds the seconds to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addSeconds(final int seconds) { + setMillis(getChronology().seconds().add(getMillis(), seconds)); + } + + //----------------------------------------------------------------------- + /** + * Set the millis of the day to the specified value. + * + * @param millisOfDay the millis of day + * @throws IllegalArgumentException if the value is invalid + */ + public void setMillisOfDay(final int millisOfDay) { + setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); + } + + /** + * Set the millis of the second to the specified value. + * + * @param millisOfSecond the millis of second + * @throws IllegalArgumentException if the value is invalid + */ + public void setMillisOfSecond(final int millisOfSecond) { + setMillis(getChronology().millisOfSecond().set(getMillis(), millisOfSecond)); + } + + /** + * Add a number of milliseconds to the date. The implementation of this + * method differs from the {@link #add(long)} method in that a + * DateTimeField performs the addition. + * + * @param millis the milliseconds to add + * @throws IllegalArgumentException if the value is invalid + */ + public void addMillis(final int millis) { + setMillis(getChronology().millis().add(getMillis(), millis)); + } + + //----------------------------------------------------------------------- + /** + * Set the date from milliseconds. + * The time part of this object will be unaffected. + * + * @param instant an instant to copy the date from, time part ignored + * @throws IllegalArgumentException if the value is invalid + */ + public void setDate(final long instant) { + setMillis(getChronology().millisOfDay().set(instant, getMillisOfDay())); + } + + /** + * Set the date from another instant. + * The time part of this object will be unaffected. + * + * @param instant an instant to copy the date from, time part ignored + * @throws IllegalArgumentException if the object is invalid + */ + public void setDate(final ReadableInstant instant) { + long instantMillis = DateTimeUtils.getInstantMillis(instant); + Chronology instantChrono = DateTimeUtils.getInstantChronology(instant); + DateTimeZone zone = instantChrono.getZone(); + if (zone != null) { + instantMillis = zone.getMillisKeepLocal(DateTimeZone.UTC, instantMillis); + } + setDate(instantMillis); + } + + /** + * Set the date from fields. + * The time part of this object will be unaffected. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @throws IllegalArgumentException if the value is invalid + */ + public void setDate( + final int year, + final int monthOfYear, + final int dayOfMonth) { + Chronology c = getChronology(); + long instantMidnight = c.getDateTimeMillis(year, monthOfYear, dayOfMonth, 0); + setDate(instantMidnight); + } + + //----------------------------------------------------------------------- + /** + * Set the time from milliseconds. + * The date part of this object will be unaffected. + * + * @param millis an instant to copy the time from, date part ignored + * @throws IllegalArgumentException if the value is invalid + */ + public void setTime(final long millis) { + int millisOfDay = ISOChronology.getInstanceUTC().millisOfDay().get(millis); + setMillis(getChronology().millisOfDay().set(getMillis(), millisOfDay)); + } + + /** + * Set the time from another instant. + * The date part of this object will be unaffected. + * + * @param instant an instant to copy the time from, date part ignored + * @throws IllegalArgumentException if the object is invalid + */ + public void setTime(final ReadableInstant instant) { + long instantMillis = DateTimeUtils.getInstantMillis(instant); + Chronology instantChrono = DateTimeUtils.getInstantChronology(instant); + DateTimeZone zone = instantChrono.getZone(); + if (zone != null) { + instantMillis = zone.getMillisKeepLocal(DateTimeZone.UTC, instantMillis); + } + setTime(instantMillis); + } + + /** + * Set the time from fields. + * The date part of this object will be unaffected. + * + * @param hour the hour + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @throws IllegalArgumentException if the value is invalid + */ + public void setTime( + final int hour, + final int minuteOfHour, + final int secondOfMinute, + final int millisOfSecond) { + long instant = getChronology().getDateTimeMillis( + getMillis(), hour, minuteOfHour, secondOfMinute, millisOfSecond); + setMillis(instant); + } + + /** + * Set the date and time from fields. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @throws IllegalArgumentException if the value is invalid + */ + public void setDateTime( + final int year, + final int monthOfYear, + final int dayOfMonth, + final int hourOfDay, + final int minuteOfHour, + final int secondOfMinute, + final int millisOfSecond) { + long instant = getChronology().getDateTimeMillis( + year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + setMillis(instant); + } + + //----------------------------------------------------------------------- + /** + * Get the era property. + * + * @return the era property + */ + public Property era() { + return new Property(this, getChronology().era()); + } + + /** + * Get the century of era property. + * + * @return the year of era property + */ + public Property centuryOfEra() { + return new Property(this, getChronology().centuryOfEra()); + } + + /** + * Get the year of century property. + * + * @return the year of era property + */ + public Property yearOfCentury() { + return new Property(this, getChronology().yearOfCentury()); + } + + /** + * Get the year of era property. + * + * @return the year of era property + */ + public Property yearOfEra() { + return new Property(this, getChronology().yearOfEra()); + } + + /** + * Get the year property. + * + * @return the year property + */ + public Property year() { + return new Property(this, getChronology().year()); + } + + /** + * Get the year of a week based year property. + * + * @return the year of a week based year property + */ + public Property weekyear() { + return new Property(this, getChronology().weekyear()); + } + + /** + * Get the month of year property. + * + * @return the month of year property + */ + public Property monthOfYear() { + return new Property(this, getChronology().monthOfYear()); + } + + /** + * Get the week of a week based year property. + * + * @return the week of a week based year property + */ + public Property weekOfWeekyear() { + return new Property(this, getChronology().weekOfWeekyear()); + } + + /** + * Get the day of year property. + * + * @return the day of year property + */ + public Property dayOfYear() { + return new Property(this, getChronology().dayOfYear()); + } + + /** + * Get the day of month property. + *

+ * The values for day of month are defined in {@link DateTimeConstants}. + * + * @return the day of month property + */ + public Property dayOfMonth() { + return new Property(this, getChronology().dayOfMonth()); + } + + /** + * Get the day of week property. + *

+ * The values for day of week are defined in {@link DateTimeConstants}. + * + * @return the day of week property + */ + public Property dayOfWeek() { + return new Property(this, getChronology().dayOfWeek()); + } + + //----------------------------------------------------------------------- + /** + * Get the hour of day field property + * + * @return the hour of day property + */ + public Property hourOfDay() { + return new Property(this, getChronology().hourOfDay()); + } + + /** + * Get the minute of day property + * + * @return the minute of day property + */ + public Property minuteOfDay() { + return new Property(this, getChronology().minuteOfDay()); + } + + /** + * Get the minute of hour field property + * + * @return the minute of hour property + */ + public Property minuteOfHour() { + return new Property(this, getChronology().minuteOfHour()); + } + + /** + * Get the second of day property + * + * @return the second of day property + */ + public Property secondOfDay() { + return new Property(this, getChronology().secondOfDay()); + } + + /** + * Get the second of minute field property + * + * @return the second of minute property + */ + public Property secondOfMinute() { + return new Property(this, getChronology().secondOfMinute()); + } + + /** + * Get the millis of day property + * + * @return the millis of day property + */ + public Property millisOfDay() { + return new Property(this, getChronology().millisOfDay()); + } + + /** + * Get the millis of second property + * + * @return the millis of second property + */ + public Property millisOfSecond() { + return new Property(this, getChronology().millisOfSecond()); + } + + //----------------------------------------------------------------------- + /** + * Clone this object without having to cast the returned object. + * + * @return a clone of the this object. + */ + public MutableDateTime copy() { + return (MutableDateTime) clone(); + } + + //----------------------------------------------------------------------- + /** + * Clone this object. + * + * @return a clone of this object. + */ + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException ex) { + throw new InternalError("Clone error"); + } + } + + /** + * Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZ). + * + * @return ISO8601 time formatted string. + */ + public String toString() { + return ISODateTimeFormat.getInstance().dateTime().print(this); + } + + /** + * MutableDateTime.Property binds a MutableDateTime to a + * DateTimeField allowing powerful datetime functionality to be easily + * accessed. + *

+ * The example below shows how to use the property to change the value of a + * MutableDateTime object. + *

+     * MutableDateTime dt = new MutableDateTime(1972, 12, 3, 13, 32, 19, 123);
+     * dt.year().add(20);
+     * dt.second().roundFloor().minute().set(10);
+     * 
+ *

+ * MutableDateTime.Propery itself is thread-safe and immutable, but the + * MutableDateTime being operated on is not. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ + public static final class Property extends AbstractReadableInstantFieldProperty { + + /** Serialization version */ + private static final long serialVersionUID = -4481126543819298617L; + + /** The instant this property is working against */ + private final MutableDateTime iInstant; + /** The field this property is working against */ + private final DateTimeField iField; + + /** + * Constructor. + * + * @param instant the instant to set + * @param field the field to use + */ + Property(MutableDateTime instant, DateTimeField field) { + super(); + iInstant = instant; + iField = field; + } + + //----------------------------------------------------------------------- + /** + * Gets the field being used. + * + * @return the field + */ + public DateTimeField getField() { + return iField; + } + + /** + * Gets the instant being used. + * + * @return the instant + */ + public ReadableInstant getReadableInstant() { + return iInstant; + } + + /** + * Gets the mutable datetime being used. + * + * @return the mutable datetime + */ + public MutableDateTime getMutableDateTime() { + return iInstant; + } + + //----------------------------------------------------------------------- + /** + * Adds a value to the millis value. + * + * @param value the value to add + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#add(long,int) + */ + public MutableDateTime add(int value) { + iInstant.setMillis(getField().add(iInstant.getMillis(), value)); + return iInstant; + } + + /** + * Adds a value to the millis value. + * + * @param value the value to add + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#add(long,long) + */ + public MutableDateTime add(long value) { + iInstant.setMillis(getField().add(iInstant.getMillis(), value)); + return iInstant; + } + + /** + * Adds a value, possibly wrapped, to the millis value. + * + * @param value the value to add + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#addWrapField + */ + public MutableDateTime addWrapField(int value) { + iInstant.setMillis(getField().addWrapField(iInstant.getMillis(), value)); + return iInstant; + } + + //----------------------------------------------------------------------- + /** + * Sets a value. + * + * @param value the value to set. + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#set(long,int) + */ + public MutableDateTime set(int value) { + iInstant.setMillis(getField().set(iInstant.getMillis(), value)); + return iInstant; + } + + /** + * Sets a text value. + * + * @param text the text value to set + * @param locale optional locale to use for selecting a text symbol + * @return the mutable datetime being used, so calls can be chained + * @throws IllegalArgumentException if the text value isn't valid + * @see DateTimeField#set(long,java.lang.String,java.util.Locale) + */ + public MutableDateTime set(String text, Locale locale) { + iInstant.setMillis(getField().set(iInstant.getMillis(), text, locale)); + return iInstant; + } + + /** + * Sets a text value. + * + * @param text the text value to set + * @return the mutable datetime being used, so calls can be chained + * @throws IllegalArgumentException if the text value isn't valid + * @see DateTimeField#set(long,java.lang.String) + */ + public MutableDateTime set(String text) { + set(text, null); + return iInstant; + } + + //----------------------------------------------------------------------- + /** + * Round to the lowest whole unit of this field. + * + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#roundFloor + */ + public MutableDateTime roundFloor() { + iInstant.setMillis(getField().roundFloor(iInstant.getMillis())); + return iInstant; + } + + /** + * Round to the highest whole unit of this field. + * + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#roundCeiling + */ + public MutableDateTime roundCeiling() { + iInstant.setMillis(getField().roundCeiling(iInstant.getMillis())); + return iInstant; + } + + /** + * Round to the nearest whole unit of this field, favoring the floor if + * halfway. + * + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#roundHalfFloor + */ + public MutableDateTime roundHalfFloor() { + iInstant.setMillis(getField().roundHalfFloor(iInstant.getMillis())); + return iInstant; + } + + /** + * Round to the nearest whole unit of this field, favoring the ceiling if + * halfway. + * + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#roundHalfCeiling + */ + public MutableDateTime roundHalfCeiling() { + iInstant.setMillis(getField().roundHalfCeiling(iInstant.getMillis())); + return iInstant; + } + + /** + * Round to the nearest whole unit of this field. If halfway, the ceiling + * is favored over the floor only if it makes this field's value even. + * + * @return the mutable datetime being used, so calls can be chained + * @see DateTimeField#roundHalfEven + */ + public MutableDateTime roundHalfEven() { + iInstant.setMillis(getField().roundHalfEven(iInstant.getMillis())); + return iInstant; + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/MutableInterval.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/MutableInterval.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/MutableInterval.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,421 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +import org.joda.time.base.BaseInterval; +import org.joda.time.field.FieldUtils; + +/** + * MutableInterval is the standard implementation of a mutable time interval. + *

+ * A time interval represents a period of time between two instants. + * Intervals are inclusive of the start instant and exclusive of the end. + * The end instant is always greater than or equal to the start instant. + *

+ * Intervals have a fixed millisecond duration. + * This is the difference between the start and end instants. + * The duration is represented separately by {@link ReadableDuration}. + * As a result, intervals are not comparable. + * To compare the length of two intervals, you should compare their durations. + *

+ * An interval can also be converted to a {@link ReadablePeriod}. + * This represents the difference between the start and end points in terms of fields + * such as years and days. + *

+ * If performing significant calculations on an interval, it may be faster to + * convert an Interval object to a MutableInterval one. + *

+ * MutableInterval is mutable and not thread-safe, unless concurrent threads + * are not invoking mutator methods. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public class MutableInterval + extends BaseInterval + implements ReadWritableInterval, Cloneable, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = -5982824024992428470L; + + //----------------------------------------------------------------------- + /** + * Constructs a zero length time interval from 1970-01-01 to 1970-01-01. + */ + public MutableInterval() { + super(0L, 0L, null); + } + + /** + * Constructs an interval from a start and end instant with the ISO default chronology. + * + * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @throws IllegalArgumentException if the end is before the start + */ + public MutableInterval(long startInstant, long endInstant) { + super(startInstant, endInstant, null); + } + + /** + * Constructs an interval from a start and end instant with a chronology. + * + * @param chronology the chronology to use, null is ISO default + * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @throws IllegalArgumentException if the end is before the start + */ + public MutableInterval(long startInstant, long endInstant, Chronology chronology) { + super(startInstant, endInstant, chronology); + } + + /** + * Constructs an interval from a start and end instant. + *

+ * The chronology used is that of the start instant. + * + * @param start start of this interval, null means now + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + */ + public MutableInterval(ReadableInstant start, ReadableInstant end) { + super(start, end); + } + + /** + * Constructs an interval from a start instant and a duration. + * + * @param start start of this interval, null means now + * @param duration the duration of this interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + public MutableInterval(ReadableInstant start, ReadableDuration duration) { + super(start, duration); + } + + /** + * Constructs an interval from a millisecond duration and an end instant. + * + * @param duration the duration of this interval, null means zero length + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + public MutableInterval(ReadableDuration duration, ReadableInstant end) { + super(duration, end); + } + + /** + * Constructs an interval from a start instant and a time period. + *

+ * When forming the interval, the chronology from the instant is used + * if present, otherwise the chronology of the period is used. + * + * @param start start of this interval, null means now + * @param period the period of this interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + public MutableInterval(ReadableInstant start, ReadablePeriod period) { + super(start, period); + } + + /** + * Constructs an interval from a time period and an end instant. + *

+ * When forming the interval, the chronology from the instant is used + * if present, otherwise the chronology of the period is used. + * + * @param period the period of this interval, null means zero length + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + public MutableInterval(ReadablePeriod period, ReadableInstant end) { + super(period, end); + } + + /** + * Constructs a time interval by converting or copying from another object. + * + * @param interval the time interval to copy + * @throws IllegalArgumentException if the interval is invalid + */ + public MutableInterval(Object interval) { + super(interval, null); + } + + /** + * Constructs a time interval by converting or copying from another object, + * overriding the chronology. + * + * @param interval the time interval to copy + * @param chronology the chronology to use, null means ISO default + * @throws IllegalArgumentException if the interval is invalid + */ + public MutableInterval(Object interval, Chronology chronology) { + super(interval, chronology); + } + + //----------------------------------------------------------------------- + /** + * Sets this interval from two millisecond instants retaining the chronology. + * + * @param startInstant the start of the time interval + * @param endInstant the start of the time interval + * @throws IllegalArgumentException if the end is before the start + */ + public void setInterval(long startInstant, long endInstant) { + super.setInterval(startInstant, endInstant, getChronology()); + } + + /** + * Sets this interval to be the same as another. + * + * @param interval the interval to copy + * @throws IllegalArgumentException if the interval is null + */ + public void setInterval(ReadableInterval interval) { + if (interval == null) { + throw new IllegalArgumentException("Interval must not be null"); + } + long startMillis = interval.getStartMillis(); + long endMillis = interval.getEndMillis(); + Chronology chrono = interval.getChronology(); + super.setInterval(startMillis, endMillis, chrono); + } + + /** + * Sets this interval from two instants, replacing the chronology with + * that from the start instant. + * + * @param start the start of the time interval + * @param end the start of the time interval + * @throws IllegalArgumentException if the end is before the start + */ + public void setInterval(ReadableInstant start, ReadableInstant end) { + if (start == null && end == null) { + long now = DateTimeUtils.currentTimeMillis(); + setInterval(now, now); + } else { + long startMillis = DateTimeUtils.getInstantMillis(start); + long endMillis = DateTimeUtils.getInstantMillis(end); + Chronology chrono = DateTimeUtils.getInstantChronology(start); + super.setInterval(startMillis, endMillis, chrono); + } + } + + //----------------------------------------------------------------------- + /** + * Sets the chronology of this time interval. + * + * @param chrono the chronology to use, null means ISO default + */ + public void setChronology(Chronology chrono) { + super.setInterval(getStartMillis(), getEndMillis(), chrono); + } + + /** + * Sets the start of this time interval. + * + * @param startInstant the start of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if the end is before the start + */ + public void setStartMillis(long startInstant) { + super.setInterval(startInstant, getEndMillis(), getChronology()); + } + + /** + * Sets the start of this time interval as an Instant. + * + * @param start the start of the time interval, null means now + * @throws IllegalArgumentException if the end is before the start + */ + public void setStart(ReadableInstant start) { + long startMillis = DateTimeUtils.getInstantMillis(start); + super.setInterval(startMillis, getEndMillis(), getChronology()); + } + + /** + * Sets the end of this time interval. + * + * @param endInstant the end of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if the end is before the start + */ + public void setEndMillis(long endInstant) { + super.setInterval(getStartMillis(), endInstant, getChronology()); + } + + /** + * Sets the end of this time interval as an Instant. + * + * @param end the end of the time interval, null means now + * @throws IllegalArgumentException if the end is before the start + */ + public void setEnd(ReadableInstant end) { + long endMillis = DateTimeUtils.getInstantMillis(end); + super.setInterval(getStartMillis(), endMillis, getChronology()); + } + + //----------------------------------------------------------------------- + /** + * Sets the duration of this time interval, preserving the start instant. + * + * @param duration new duration for interval + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + public void setDurationAfterStart(long duration) { + setEndMillis(FieldUtils.safeAdd(getStartMillis(), duration)); + } + + /** + * Sets the duration of this time interval, preserving the end instant. + * + * @param duration new duration for interval + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + public void setDurationBeforeEnd(long duration) { + setStartMillis(FieldUtils.safeAdd(getEndMillis(), -duration)); + } + + //----------------------------------------------------------------------- + /** + * Sets the duration of this time interval, preserving the start instant. + * + * @param duration new duration for interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + public void setDurationAfterStart(ReadableDuration duration) { + long durationMillis = DateTimeUtils.getDurationMillis(duration); + setEndMillis(FieldUtils.safeAdd(getStartMillis(), durationMillis)); + } + + /** + * Sets the duration of this time interval, preserving the end instant. + * + * @param duration new duration for interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + public void setDurationBeforeEnd(ReadableDuration duration) { + long durationMillis = DateTimeUtils.getDurationMillis(duration); + setStartMillis(FieldUtils.safeAdd(getEndMillis(), -durationMillis)); + } + + //----------------------------------------------------------------------- + /** + * Sets the period of this time interval, preserving the start instant + * and using the ISOChronology in the default zone for calculations. + * + * @param period new period for interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + public void setPeriodAfterStart(ReadablePeriod period) { + if (period == null) { + setEndMillis(getStartMillis()); + } else { + setEndMillis(getChronology().add(period, getStartMillis(), 1)); + } + } + + /** + * Sets the period of this time interval, preserving the end instant + * and using the ISOChronology in the default zone for calculations. + * + * @param period new period for interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + public void setPeriodBeforeEnd(ReadablePeriod period) { + if (period == null) { + setStartMillis(getEndMillis()); + } else { + setStartMillis(getChronology().add(period, getEndMillis(), -1)); + } + } + + //----------------------------------------------------------------------- + /** + * Clone this object without having to cast the returned object. + * + * @return a clone of the this object. + */ + public MutableInterval copy() { + return (MutableInterval) clone(); + } + + /** + * Clone this object. + * + * @return a clone of this object. + */ + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException ex) { + throw new InternalError("Clone error"); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/MutablePeriod.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/MutablePeriod.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/MutablePeriod.java 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,966 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +import org.joda.time.base.BasePeriod; +import org.joda.time.field.FieldUtils; + +/** + * Standard mutable time period implementation. + *

+ * MutablePeriod is mutable and not thread-safe, unless concurrent threads + * are not invoking mutator methods. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + * @see Period + */ +public class MutablePeriod + extends BasePeriod + implements ReadWritablePeriod, Cloneable, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 3436451121567212165L; + + /** + * Creates a zero-length period using the standard period type. + */ + public MutablePeriod() { + super(0L, null, null); + } + + /** + * Creates a zero-length period using the specified period type. + * + * @param type which set of fields this period supports + */ + public MutablePeriod(PeriodType type) { + super(0L, type, null); + } + + /** + * Create a period from a set of field values using the standard set of fields. + * + * @param hours amount of hours in this period + * @param minutes amount of minutes in this period + * @param seconds amount of seconds in this period + * @param millis amount of milliseconds in this period + */ + public MutablePeriod(int hours, int minutes, int seconds, int millis) { + super(0, 0, 0, 0, hours, minutes, seconds, millis, PeriodType.standard()); + } + + /** + * Create a period from a set of field values using the standard set of fields. + * + * @param years amount of years in this period + * @param months amount of months in this period + * @param weeks amount of weeks in this period + * @param days amount of days in this period + * @param hours amount of hours in this period + * @param minutes amount of minutes in this period + * @param seconds amount of seconds in this period + * @param millis amount of milliseconds in this period + */ + public MutablePeriod(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis) { + super(years, months, weeks, days, hours, minutes, seconds, millis, PeriodType.standard()); + } + + /** + * Create a period from a set of field values. + * + * @param years amount of years in this period, which must be zero if unsupported + * @param months amount of months in this period, which must be zero if unsupported + * @param weeks amount of weeks in this period, which must be zero if unsupported + * @param days amount of days in this period, which must be zero if unsupported + * @param hours amount of hours in this period, which must be zero if unsupported + * @param minutes amount of minutes in this period, which must be zero if unsupported + * @param seconds amount of seconds in this period, which must be zero if unsupported + * @param millis amount of milliseconds in this period, which must be zero if unsupported + * @param type which set of fields this period supports, null means AllType + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + public MutablePeriod(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis, PeriodType type) { + super(years, months, weeks, days, hours, minutes, seconds, millis, type); + } + + /** + * Creates a period from the given millisecond duration using the standard + * set of fields. + *

+ * Only precise fields in the period type will be used. + * For the standard period type this is the time fields only. + * Thus the year, month, week and day fields will not be populated. + *

+ * If the duration is small, less than one day, then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is larger than one day then all the remaining duration will + * be stored in the largest available precise field, hours in this case. + *

+ * For example, a duration equal to (365 + 60 + 5) days will be converted to + * ((365 + 60 + 5) * 24) hours by this constructor. + *

+ * For more control over the conversion process, you have two options: + *

    + *
  • convert the duration to an {@link Interval}, and from there obtain the period + *
  • specify a period type that contains precise definitions of the day and larger + * fields, such as the UTC or precise types. + *
+ * + * @param duration the duration, in milliseconds + */ + public MutablePeriod(long duration) { + super(duration, null, null); + } + + /** + * Creates a period from the given millisecond duration. + *

+ * Only precise fields in the period type will be used. + * Imprecise fields will not be populated. + *

+ * If the duration is small then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is large then all the remaining duration will + * be stored in the largest available precise field. + * For details as to which fields are precise, review the period type javadoc. + * + * @param duration the duration, in milliseconds + * @param type which set of fields this period supports, null means standard + */ + public MutablePeriod(long duration, PeriodType type) { + super(duration, type, null); + } + + /** + * Creates a period from the given millisecond duration using the standard + * set of fields. + *

+ * Only precise fields in the period type will be used. + * Imprecise fields will not be populated. + *

+ * If the duration is small then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is large then all the remaining duration will + * be stored in the largest available precise field. + * For details as to which fields are precise, review the period type javadoc. + * + * @param duration the duration, in milliseconds + * @param chronology the chronology to use to split the duration, null means ISO default + */ + public MutablePeriod(long duration, Chronology chronology) { + super(duration, null, chronology); + } + + /** + * Creates a period from the given millisecond duration. + *

+ * Only precise fields in the period type will be used. + * Imprecise fields will not be populated. + *

+ * If the duration is small then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is large then all the remaining duration will + * be stored in the largest available precise field. + * For details as to which fields are precise, review the period type javadoc. + * + * @param duration the duration, in milliseconds + * @param type which set of fields this period supports, null means standard + * @param chronology the chronology to use to split the duration, null means ISO default + */ + public MutablePeriod(long duration, PeriodType type, Chronology chronology) { + super(duration, type, chronology); + } + + /** + * Creates a period from the given interval endpoints using the standard + * set of fields. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + */ + public MutablePeriod(long startInstant, long endInstant) { + super(startInstant, endInstant, null, null); + } + + /** + * Creates a period from the given interval endpoints. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param type which set of fields this period supports, null means standard + */ + public MutablePeriod(long startInstant, long endInstant, PeriodType type) { + super(startInstant, endInstant, type, null); + } + + /** + * Creates a period from the given interval endpoints using the standard + * set of fields. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param chrono the chronology to use, null means ISO in default zone + */ + public MutablePeriod(long startInstant, long endInstant, Chronology chrono) { + super(startInstant, endInstant, null, chrono); + } + + /** + * Creates a period from the given interval endpoints. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param type which set of fields this period supports, null means standard + * @param chrono the chronology to use, null means ISO in default zone + */ + public MutablePeriod(long startInstant, long endInstant, PeriodType type, Chronology chrono) { + super(startInstant, endInstant, type, chrono); + } + + /** + * Creates a period from the given interval endpoints using the standard + * set of fields. + *

+ * The chronology of the start instant is used, unless that is null when the + * chronology of the end instant is used instead. + * + * @param startInstant interval start, null means now + * @param endInstant interval end, null means now + */ + public MutablePeriod(ReadableInstant startInstant, ReadableInstant endInstant) { + super(startInstant, endInstant, null); + } + + /** + * Creates a period from the given interval endpoints. + *

+ * The chronology of the start instant is used, unless that is null when the + * chronology of the end instant is used instead. + * + * @param startInstant interval start, null means now + * @param endInstant interval end, null means now + * @param type which set of fields this period supports, null means AllType + */ + public MutablePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) { + super(startInstant, endInstant, type); + } + + /** + * Creates a period from the given start point and the duration. + * + * @param startInstant the interval start, null means now + * @param duration the duration of the interval, null means zero-length + */ + public MutablePeriod(ReadableInstant startInstant, ReadableDuration duration) { + super(startInstant, duration, null); + } + + /** + * Creates a period from the given start point and the duration. + * + * @param startInstant the interval start, null means now + * @param duration the duration of the interval, null means zero-length + * @param type which set of fields this period supports, null means standard + */ + public MutablePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { + super(startInstant, duration, type); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public MutablePeriod(Object period) { + super(period, null, null); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @param type which set of fields this period supports, null means use converter + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public MutablePeriod(Object period, PeriodType type) { + super(period, type, null); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @param chrono the chronology to use, null means ISO in default zone + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public MutablePeriod(Object period, Chronology chrono) { + super(period, null, chrono); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @param type which set of fields this period supports, null means use converter + * @param chrono the chronology to use, null means ISO in default zone + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public MutablePeriod(Object period, PeriodType type, Chronology chrono) { + super(period, type, chrono); + } + + //----------------------------------------------------------------------- + /** + * Clears the period, setting all values back to zero. + */ + public void clear() { + super.setValues(new int[size()]); + } + + /** + * Sets the value of one of the fields by index. + * + * @param index the field index + * @param value the new value for the field + * @throws IndexOutOfBoundsException if the index is invalid + */ + public void setValue(int index, int value) { + super.setValue(index, value); + } + + /** + * Sets the value of one of the fields. + *

+ * The field type specified must be one of those that is supported by the period. + * + * @param field a DurationFieldType instance that is supported by this period, not null + * @param value the new value for the field + * @throws IllegalArgumentException if the field is null or not supported + */ + public void set(DurationFieldType field, int value) { + super.setField(field, value); + } + + /** + * Sets all the fields in one go from another ReadablePeriod. + * + * @param period the period to set, null means zero length period + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + public void setPeriod(ReadablePeriod period) { + super.setPeriod(period); + } + + /** + * Sets all the fields in one go. + * + * @param years amount of years in this period, which must be zero if unsupported + * @param months amount of months in this period, which must be zero if unsupported + * @param weeks amount of weeks in this period, which must be zero if unsupported + * @param days amount of days in this period, which must be zero if unsupported + * @param hours amount of hours in this period, which must be zero if unsupported + * @param minutes amount of minutes in this period, which must be zero if unsupported + * @param seconds amount of seconds in this period, which must be zero if unsupported + * @param millis amount of milliseconds in this period, which must be zero if unsupported + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + public void setPeriod(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis) { + super.setPeriod(years, months, weeks, days, hours, minutes, seconds, millis); + } + + /** + * Sets all the fields in one go from an interval using the ISO chronology + * and dividing the fields using the period type. + * + * @param interval the interval to set, null means zero length + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(ReadableInterval interval) { + if (interval == null) { + setPeriod(0L); + } else { + Chronology chrono = DateTimeUtils.getChronology(interval.getChronology()); + setPeriod(interval.getStartMillis(), interval.getEndMillis(), chrono); + } + } + + /** + * Sets all the fields in one go from two instants representing an interval. + *

+ * The chronology of the start instant is used, unless that is null when the + * chronology of the end instant is used instead. + * + * @param start the start instant, null means now + * @param end the end instant, null means now + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(ReadableInstant start, ReadableInstant end) { + if (start == end) { + setPeriod(0L); + } else { + long startMillis = DateTimeUtils.getInstantMillis(start); + long endMillis = DateTimeUtils.getInstantMillis(end); + Chronology chrono = DateTimeUtils.getIntervalChronology(start, end); + setPeriod(startMillis, endMillis, chrono); + } + } + + /** + * Sets all the fields in one go from a millisecond interval using ISOChronology + * and dividing the fields using the period type. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(long startInstant, long endInstant) { + setPeriod(startInstant, endInstant, null); + } + + /** + * Sets all the fields in one go from a millisecond interval. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param chrono the chronology to use, not null + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(long startInstant, long endInstant, Chronology chrono) { + chrono = DateTimeUtils.getChronology(chrono); + setValues(chrono.get(this, startInstant, endInstant)); + } + + /** + * Sets all the fields in one go from a duration dividing the + * fields using the period type. + *

+ * When dividing the duration, only precise fields in the period type will be used. + * For large durations, all the remaining duration will be stored in the largest + * available precise field. + * + * @param duration the duration to set, null means zero length + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(ReadableDuration duration) { + setPeriod(duration, null); + } + + /** + * Sets all the fields in one go from a duration dividing the + * fields using the period type. + *

+ * When dividing the duration, only precise fields in the period type will be used. + * For large durations, all the remaining duration will be stored in the largest + * available precise field. + * + * @param duration the duration to set, null means zero length + * @param chrono the chronology to use, null means ISO default + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(ReadableDuration duration, Chronology chrono) { + long durationMillis = DateTimeUtils.getDurationMillis(duration); + setPeriod(durationMillis, chrono); + } + + /** + * Sets all the fields in one go from a millisecond duration dividing the + * fields using the period type. + *

+ * When dividing the duration, only precise fields in the period type will be used. + * For large durations, all the remaining duration will be stored in the largest + * available precise field. + * + * @param duration the duration, in milliseconds + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(long duration) { + setPeriod(duration, null); + } + + /** + * Sets all the fields in one go from a millisecond duration. + *

+ * When dividing the duration, only precise fields in the period type will be used. + * For large durations, all the remaining duration will be stored in the largest + * available precise field. + * + * @param duration the duration, in milliseconds + * @param chrono the chronology to use, not null + * @throws ArithmeticException if the set exceeds the capacity of the period + */ + public void setPeriod(long duration, Chronology chrono) { + chrono = DateTimeUtils.getChronology(chrono); + setValues(chrono.get(this, duration)); + } + + //----------------------------------------------------------------------- + /** + * Adds to the value of one of the fields. + *

+ * The field type specified must be one of those that is supported by the period. + * + * @param field a DurationFieldType instance that is supported by this period, not null + * @param value the value to add to the field + * @throws IllegalArgumentException if the field is null or not supported + */ + public void add(DurationFieldType field, int value) { + super.addField(field, value); + } + + /** + * Adds a period to this one by adding each field in turn. + * + * @param period the period to add, null means add nothing + * @throws IllegalArgumentException if the period being added contains a field + * not supported by this period + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void add(ReadablePeriod period) { + super.addPeriod(period); + } + + /** + * Adds to each field of this period. + * + * @param years amount of years to add to this period, which must be zero if unsupported + * @param months amount of months to add to this period, which must be zero if unsupported + * @param weeks amount of weeks to add to this period, which must be zero if unsupported + * @param days amount of days to add to this period, which must be zero if unsupported + * @param hours amount of hours to add to this period, which must be zero if unsupported + * @param minutes amount of minutes to add to this period, which must be zero if unsupported + * @param seconds amount of seconds to add to this period, which must be zero if unsupported + * @param millis amount of milliseconds to add to this period, which must be zero if unsupported + * @throws IllegalArgumentException if the period being added contains a field + * not supported by this period + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void add(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis) { + setPeriod( + FieldUtils.safeAdd(getYears(), years), + FieldUtils.safeAdd(getMonths(), months), + FieldUtils.safeAdd(getWeeks(), weeks), + FieldUtils.safeAdd(getDays(), days), + FieldUtils.safeAdd(getHours(), hours), + FieldUtils.safeAdd(getMinutes(), minutes), + FieldUtils.safeAdd(getSeconds(), seconds), + FieldUtils.safeAdd(getMillis(), millis) + ); + } + + /** + * Adds an interval to this one by dividing the interval into + * fields and calling {@link #add(ReadablePeriod)}. + * + * @param interval the interval to add, null means add nothing + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void add(ReadableInterval interval) { + if (interval != null) { + add(interval.toPeriod(getPeriodType())); + } + } + + /** + * Adds a duration to this one by dividing the duration into + * fields and calling {@link #add(ReadablePeriod)}. + * + * @param duration the duration to add, null means add nothing + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void add(ReadableDuration duration) { + if (duration != null) { + add(new Period(duration.getMillis(), getPeriodType())); + } + } + + /** + * Adds a millisecond duration to this one by dividing the duration into + * fields and calling {@link #add(ReadablePeriod)}. + *

+ * When dividing the duration, only precise fields in the period type will be used. + * For large durations, all the remaining duration will be stored in the largest + * available precise field. + * + * @param duration the duration, in milliseconds + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void add(long duration) { + add(new Period(duration, getPeriodType())); + } + + /** + * Adds a millisecond duration to this one by dividing the duration into + * fields and calling {@link #add(ReadablePeriod)}. + *

+ * When dividing the duration, only precise fields in the period type will be used. + * For large durations, all the remaining duration will be stored in the largest + * available precise field. + * + * @param duration the duration, in milliseconds + * @param chrono the chronology to use, null means ISO default + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void add(long duration, Chronology chrono) { + add(new Period(duration, getPeriodType(), chrono)); + } + + //----------------------------------------------------------------------- + /** + * Merges all the fields from the specified period into this one. + *

+ * Fields that are not present in the specified period are left unaltered. + * + * @param period the period to set, null ignored + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + public void mergePeriod(ReadablePeriod period) { + super.mergePeriod(period); + } + + //----------------------------------------------------------------------- + /** + * Gets the years field part of the period. + * + * @return the number of years in the period, zero if unsupported + */ + public int getYears() { + return getPeriodType().getIndexedField(this, PeriodType.YEAR_INDEX); + } + + /** + * Gets the months field part of the period. + * + * @return the number of months in the period, zero if unsupported + */ + public int getMonths() { + return getPeriodType().getIndexedField(this, PeriodType.MONTH_INDEX); + } + + /** + * Gets the weeks field part of the period. + * + * @return the number of weeks in the period, zero if unsupported + */ + public int getWeeks() { + return getPeriodType().getIndexedField(this, PeriodType.WEEK_INDEX); + } + + /** + * Gets the days field part of the period. + * + * @return the number of days in the period, zero if unsupported + */ + public int getDays() { + return getPeriodType().getIndexedField(this, PeriodType.DAY_INDEX); + } + + //----------------------------------------------------------------------- + /** + * Gets the hours field part of the period. + * + * @return the number of hours in the period, zero if unsupported + */ + public int getHours() { + return getPeriodType().getIndexedField(this, PeriodType.HOUR_INDEX); + } + + /** + * Gets the minutes field part of the period. + * + * @return the number of minutes in the period, zero if unsupported + */ + public int getMinutes() { + return getPeriodType().getIndexedField(this, PeriodType.MINUTE_INDEX); + } + + /** + * Gets the seconds field part of the period. + * + * @return the number of seconds in the period, zero if unsupported + */ + public int getSeconds() { + return getPeriodType().getIndexedField(this, PeriodType.SECOND_INDEX); + } + + /** + * Gets the millis field part of the period. + * + * @return the number of millis in the period, zero if unsupported + */ + public int getMillis() { + return getPeriodType().getIndexedField(this, PeriodType.MILLI_INDEX); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of years of the period. + * + * @param years the number of years + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setYears(int years) { + super.setField(DurationFieldType.years(), years); + } + + /** + * Adds the specified years to the number of years in the period. + * + * @param years the number of years + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addYears(int years) { + super.addField(DurationFieldType.years(), years); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of months of the period. + * + * @param months the number of months + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setMonths(int months) { + super.setField(DurationFieldType.months(), months); + } + + /** + * Adds the specified months to the number of months in the period. + * + * @param months the number of months + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addMonths(int months) { + super.addField(DurationFieldType.months(), months); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of weeks of the period. + * + * @param weeks the number of weeks + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setWeeks(int weeks) { + super.setField(DurationFieldType.weeks(), weeks); + } + + /** + * Adds the specified weeks to the number of weeks in the period. + * + * @param weeks the number of weeks + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addWeeks(int weeks) { + super.addField(DurationFieldType.weeks(), weeks); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of days of the period. + * + * @param days the number of days + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setDays(int days) { + super.setField(DurationFieldType.days(), days); + } + + /** + * Adds the specified days to the number of days in the period. + * + * @param days the number of days + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addDays(int days) { + super.addField(DurationFieldType.days(), days); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of hours of the period. + * + * @param hours the number of hours + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setHours(int hours) { + super.setField(DurationFieldType.hours(), hours); + } + + /** + * Adds the specified hours to the number of hours in the period. + * + * @param hours the number of hours + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addHours(int hours) { + super.addField(DurationFieldType.hours(), hours); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of minutes of the period. + * + * @param minutes the number of minutes + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setMinutes(int minutes) { + super.setField(DurationFieldType.minutes(), minutes); + } + + /** + * Adds the specified minutes to the number of minutes in the period. + * + * @param minutes the number of minutes + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addMinutes(int minutes) { + super.addField(DurationFieldType.minutes(), minutes); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of seconds of the period. + * + * @param seconds the number of seconds + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setSeconds(int seconds) { + super.setField(DurationFieldType.seconds(), seconds); + } + + /** + * Adds the specified seconds to the number of seconds in the period. + * + * @param seconds the number of seconds + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addSeconds(int seconds) { + super.addField(DurationFieldType.seconds(), seconds); + } + + //----------------------------------------------------------------------- + /** + * Sets the number of millis of the period. + * + * @param millis the number of millis + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + public void setMillis(int millis) { + super.setField(DurationFieldType.millis(), millis); + } + + /** + * Adds the specified millis to the number of millis in the period. + * + * @param millis the number of millis + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + public void addMillis(int millis) { + super.addField(DurationFieldType.millis(), millis); + } + + // Misc + //----------------------------------------------------------------------- + /** + * Clone this object without having to cast the returned object. + * + * @return a clone of the this object. + */ + public MutablePeriod copy() { + return (MutablePeriod) clone(); + } + + /** + * Clone this object. + * + * @return a clone of this object. + */ + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException ex) { + throw new InternalError("Clone error"); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/Period.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/Period.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/Period.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,1032 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; + +import org.joda.time.base.BasePeriod; + +/** + * An immutable time period specifying a set of duration field values. + *

+ * A time period is divided into a number of fields, such as hours and seconds. + * Which fields are supported is defined by the PeriodType class. + * The default is the standard period type, which supports years, months, weeks, days, + * hours, minutes, seconds and millis. + *

+ * When this time period is added to an instant, the effect is of adding each field in turn. + * As a result, this takes into account daylight savings time. + * Adding a time period of 1 day to the day before daylight savings starts will only add + * 23 hours rather than 24 to ensure that the time remains the same. + * If this is not the behaviour you want, then see {@link Duration}. + *

+ * Period is thread-safe and immutable, provided that the PeriodType is as well. + * All standard PeriodType classes supplied are thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + * @see MutablePeriod + */ +public final class Period + extends BasePeriod + implements ReadablePeriod, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 741052353876488155L; + + //----------------------------------------------------------------------- + /** + * Create a period with a specified number of years. + * The standard period type is used. + * + * @param years the amount of years in this period + * @return the period + */ + public static Period years(int years) { + return new Period(new int[] {years, 0, 0, 0, 0, 0, 0, 0, 0}, PeriodType.standard()); + } + + /** + * Create a period with a specified number of months. + * The standard period type is used. + * + * @param months the amount of months in this period + * @return the period + */ + public static Period months(int months) { + return new Period(new int[] {0, months, 0, 0, 0, 0, 0, 0}, PeriodType.standard()); + } + + /** + * Create a period with a specified number of weeks. + * The standard period type is used. + * + * @param weeks the amount of weeks in this period + * @return the period + */ + public static Period weeks(int weeks) { + return new Period(new int[] {0, 0, weeks, 0, 0, 0, 0, 0}, PeriodType.standard()); + } + + /** + * Create a period with a specified number of days. + * The standard period type is used. + * + * @param days the amount of days in this period + * @return the period + */ + public static Period days(int days) { + return new Period(new int[] {0, 0, 0, days, 0, 0, 0, 0}, PeriodType.standard()); + } + + /** + * Create a period with a specified number of hours. + * The standard period type is used. + * + * @param hours the amount of hours in this period + * @return the period + */ + public static Period hours(int hours) { + return new Period(new int[] {0, 0, 0, 0, hours, 0, 0, 0}, PeriodType.standard()); + } + + /** + * Create a period with a specified number of minutes. + * The standard period type is used. + * + * @param minutes the amount of minutes in this period + * @return the period + */ + public static Period minutes(int minutes) { + return new Period(new int[] {0, 0, 0, 0, 0, minutes, 0, 0}, PeriodType.standard()); + } + + /** + * Create a period with a specified number of seconds. + * The standard period type is used. + * + * @param seconds the amount of seconds in this period + * @return the period + */ + public static Period seconds(int seconds) { + return new Period(new int[] {0, 0, 0, 0, 0, 0, seconds, 0}, PeriodType.standard()); + } + + /** + * Create a period with a specified number of millis. + * The standard period type is used. + * + * @param millis the amount of millis in this period + * @return the period + */ + public static Period millis(int millis) { + return new Period(new int[] {0, 0, 0, 0, 0, 0, 0, millis}, PeriodType.standard()); + } + + //----------------------------------------------------------------------- + /** + * Creates a new empty period with the standard set of fields. + *

+ * One way to initialise a period is as follows: + *

+     * Period = new Period().withYears(6).withMonths(3).withSeconds(23);
+     * 
+ * Bear in mind that this creates four period instances in total, three of + * which are immediately discarded. + * The alterative is more efficient, but less readable: + *
+     * Period = new Period(6, 3, 0, 0, 0, 0, 23, 0);
+     * 
+ * The following is also slightly less wasteful: + *
+     * Period = Period.years(6).withMonths(3).withSeconds(23);
+     * 
+ */ + public Period() { + super(0L, null, null); + } + + /** + * Create a period from a set of field values using the standard set of fields. + * + * @param hours amount of hours in this period + * @param minutes amount of minutes in this period + * @param seconds amount of seconds in this period + * @param millis amount of milliseconds in this period + */ + public Period(int hours, int minutes, int seconds, int millis) { + super(0, 0, 0, 0, hours, minutes, seconds, millis, PeriodType.standard()); + } + + /** + * Create a period from a set of field values using the standard set of fields. + * + * @param years amount of years in this period + * @param months amount of months in this period + * @param weeks amount of weeks in this period + * @param days amount of days in this period + * @param hours amount of hours in this period + * @param minutes amount of minutes in this period + * @param seconds amount of seconds in this period + * @param millis amount of milliseconds in this period + */ + public Period(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis) { + super(years, months, weeks, days, hours, minutes, seconds, millis, PeriodType.standard()); + } + + /** + * Create a period from a set of field values. + *

+ * There is usually little need to use this constructor. + * The period type is used primarily to define how to split an interval into a period. + * As this constructor already is split, the period type does no real work. + * + * @param years amount of years in this period, which must be zero if unsupported + * @param months amount of months in this period, which must be zero if unsupported + * @param weeks amount of weeks in this period, which must be zero if unsupported + * @param days amount of days in this period, which must be zero if unsupported + * @param hours amount of hours in this period, which must be zero if unsupported + * @param minutes amount of minutes in this period, which must be zero if unsupported + * @param seconds amount of seconds in this period, which must be zero if unsupported + * @param millis amount of milliseconds in this period, which must be zero if unsupported + * @param type which set of fields this period supports, null means AllType + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + public Period(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis, PeriodType type) { + super(years, months, weeks, days, hours, minutes, seconds, millis, type); + } + + /** + * Creates a period from the given millisecond duration using the standard + * set of fields. + *

+ * Only precise fields in the period type will be used. + * For the standard period type this is the time fields only. + * Thus the year, month, week and day fields will not be populated. + *

+ * If the duration is small, less than one day, then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is larger than one day then all the remaining duration will + * be stored in the largest available precise field, hours in this case. + *

+ * For example, a duration equal to (365 + 60 + 5) days will be converted to + * ((365 + 60 + 5) * 24) hours by this constructor. + *

+ * For more control over the conversion process, you have two options: + *

    + *
  • convert the duration to an {@link Interval}, and from there obtain the period + *
  • specify a period type that contains precise definitions of the day and larger + * fields, such as UTC + *
+ * + * @param duration the duration, in milliseconds + */ + public Period(long duration) { + super(duration, null, null); + } + + /** + * Creates a period from the given millisecond duration. + *

+ * Only precise fields in the period type will be used. + * Imprecise fields will not be populated. + *

+ * If the duration is small then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is large then all the remaining duration will + * be stored in the largest available precise field. + * For details as to which fields are precise, review the period type javadoc. + * + * @param duration the duration, in milliseconds + * @param type which set of fields this period supports, null means standard + */ + public Period(long duration, PeriodType type) { + super(duration, type, null); + } + + /** + * Creates a period from the given millisecond duration using the standard + * set of fields. + *

+ * Only precise fields in the period type will be used. + * Imprecise fields will not be populated. + *

+ * If the duration is small then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is large then all the remaining duration will + * be stored in the largest available precise field. + * For details as to which fields are precise, review the period type javadoc. + * + * @param duration the duration, in milliseconds + * @param chronology the chronology to use to split the duration, null means ISO default + */ + public Period(long duration, Chronology chronology) { + super(duration, null, chronology); + } + + /** + * Creates a period from the given millisecond duration. + *

+ * Only precise fields in the period type will be used. + * Imprecise fields will not be populated. + *

+ * If the duration is small then this method will perform + * as you might expect and split the fields evenly. + *

+ * If the duration is large then all the remaining duration will + * be stored in the largest available precise field. + * For details as to which fields are precise, review the period type javadoc. + * + * @param duration the duration, in milliseconds + * @param type which set of fields this period supports, null means standard + * @param chronology the chronology to use to split the duration, null means ISO default + */ + public Period(long duration, PeriodType type, Chronology chronology) { + super(duration, type, chronology); + } + + /** + * Creates a period from the given interval endpoints using the standard + * set of fields. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + */ + public Period(long startInstant, long endInstant) { + super(startInstant, endInstant, null, null); + } + + /** + * Creates a period from the given interval endpoints. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param type which set of fields this period supports, null means standard + */ + public Period(long startInstant, long endInstant, PeriodType type) { + super(startInstant, endInstant, type, null); + } + + /** + * Creates a period from the given interval endpoints using the standard + * set of fields. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param chrono the chronology to use, null means ISO in default zone + */ + public Period(long startInstant, long endInstant, Chronology chrono) { + super(startInstant, endInstant, null, chrono); + } + + /** + * Creates a period from the given interval endpoints. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param type which set of fields this period supports, null means standard + * @param chrono the chronology to use, null means ISO in default zone + */ + public Period(long startInstant, long endInstant, PeriodType type, Chronology chrono) { + super(startInstant, endInstant, type, chrono); + } + + /** + * Creates a period from the given interval endpoints using the standard + * set of fields. + * + * @param startInstant interval start, null means now + * @param endInstant interval end, null means now + */ + public Period(ReadableInstant startInstant, ReadableInstant endInstant) { + super(startInstant, endInstant, null); + } + + /** + * Creates a period from the given interval endpoints. + * + * @param startInstant interval start, null means now + * @param endInstant interval end, null means now + * @param type which set of fields this period supports, null means standard + */ + public Period(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) { + super(startInstant, endInstant, type); + } + + /** + * Creates a period from the given start point and the duration. + * + * @param startInstant the interval start, null means now + * @param duration the duration of the interval, null means zero-length + */ + public Period(ReadableInstant startInstant, ReadableDuration duration) { + super(startInstant, duration, null); + } + + /** + * Creates a period from the given start point and the duration. + * + * @param startInstant the interval start, null means now + * @param duration the duration of the interval, null means zero-length + * @param type which set of fields this period supports, null means standard + */ + public Period(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { + super(startInstant, duration, type); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public Period(Object period) { + super(period, null, null); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @param type which set of fields this period supports, null means use converter + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public Period(Object period, PeriodType type) { + super(period, type, null); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @param chrono the chronology to use, null means ISO in default zone + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public Period(Object period, Chronology chrono) { + super(period, null, chrono); + } + + /** + * Creates a period from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param period period to convert + * @param type which set of fields this period supports, null means use converter + * @param chrono the chronology to use, null means ISO in default zone + * @throws IllegalArgumentException if period is invalid + * @throws UnsupportedOperationException if an unsupported field's value is non-zero + */ + public Period(Object period, PeriodType type, Chronology chrono) { + super(period, type, chrono); + } + + /** + * Constructor used when we trust ourselves. + * + * @param values the values to use, not null, not cloned + * @param type which set of fields this period supports, not null + */ + private Period(int[] values, PeriodType type) { + super(values, type); + } + + //----------------------------------------------------------------------- + /** + * Get this period as an immutable Period object + * by returning this. + * + * @return this + */ + public Period toPeriod() { + return this; + } + + //----------------------------------------------------------------------- + /** + * Gets the years field part of the period. + * + * @return the number of years in the period, zero if unsupported + */ + public int getYears() { + return getPeriodType().getIndexedField(this, PeriodType.YEAR_INDEX); + } + + /** + * Gets the months field part of the period. + * + * @return the number of months in the period, zero if unsupported + */ + public int getMonths() { + return getPeriodType().getIndexedField(this, PeriodType.MONTH_INDEX); + } + + /** + * Gets the weeks field part of the period. + * + * @return the number of weeks in the period, zero if unsupported + */ + public int getWeeks() { + return getPeriodType().getIndexedField(this, PeriodType.WEEK_INDEX); + } + + /** + * Gets the days field part of the period. + * + * @return the number of days in the period, zero if unsupported + */ + public int getDays() { + return getPeriodType().getIndexedField(this, PeriodType.DAY_INDEX); + } + + //----------------------------------------------------------------------- + /** + * Gets the hours field part of the period. + * + * @return the number of hours in the period, zero if unsupported + */ + public int getHours() { + return getPeriodType().getIndexedField(this, PeriodType.HOUR_INDEX); + } + + /** + * Gets the minutes field part of the period. + * + * @return the number of minutes in the period, zero if unsupported + */ + public int getMinutes() { + return getPeriodType().getIndexedField(this, PeriodType.MINUTE_INDEX); + } + + /** + * Gets the seconds field part of the period. + * + * @return the number of seconds in the period, zero if unsupported + */ + public int getSeconds() { + return getPeriodType().getIndexedField(this, PeriodType.SECOND_INDEX); + } + + /** + * Gets the millis field part of the period. + * + * @return the number of millis in the period, zero if unsupported + */ + public int getMillis() { + return getPeriodType().getIndexedField(this, PeriodType.MILLI_INDEX); + } + + //----------------------------------------------------------------------- + /** + * Creates a new Period instance with the same field values but + * different PeriodType. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param type the period type to use, null means standard + * @return the new period instance + * @throws IllegalArgumentException if the new period won't accept all of the current fields + */ + public Period withPeriodType(PeriodType type) { + type = DateTimeUtils.getPeriodType(type); + if (type.equals(getPeriodType())) { + return this; + } + return new Period(this, type); + } + + /** + * Creates a new Period instance with the fields from the specified period + * copied on top of those from this period. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param period the period to copy from, null ignored + * @return the new period instance + * @throws IllegalArgumentException if a field type is unsupported + */ + public Period withFields(ReadablePeriod period) { + if (period == null) { + return this; + } + int[] newValues = getValues(); // cloned + newValues = super.mergePeriodInto(newValues, period); + return new Period(newValues, getPeriodType()); + } + + //----------------------------------------------------------------------- + /** + * Creates a new Period instance with the specified field set to a new value. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param field the field to set, not null + * @param value the value to set to + * @return the new period instance + * @throws IllegalArgumentException if the field type is null or unsupported + */ + public Period withField(DurationFieldType field, int value) { + if (field == null) { + throw new IllegalArgumentException("Field must not be null"); + } + int[] newValues = getValues(); // cloned + super.setFieldInto(newValues, field, value); + return new Period(newValues, getPeriodType()); + } + + /** + * Creates a new Period instance with the valueToAdd added to the specified field. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param field the field to set, not null + * @param value the value to add + * @return the new period instance + * @throws IllegalArgumentException if the field type is null or unsupported + */ + public Period withFieldAdded(DurationFieldType field, int value) { + if (field == null) { + throw new IllegalArgumentException("Field must not be null"); + } + if (value == 0) { + return this; + } + int[] newValues = getValues(); // cloned + super.addFieldInto(newValues, field, value); + return new Period(newValues, getPeriodType()); + } + + //----------------------------------------------------------------------- + /** + * Returns a new period with the specified number of years. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param years the amount of years to add, may be negative + * @return the new period with the increased years + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withYears(int years) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.YEAR_INDEX, values, years); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period with the specified number of months. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param months the amount of months to add, may be negative + * @return the new period with the increased months + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withMonths(int months) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.MONTH_INDEX, values, months); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period with the specified number of weeks. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param weeks the amount of weeks to add, may be negative + * @return the new period with the increased weeks + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withWeeks(int weeks) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.WEEK_INDEX, values, weeks); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period with the specified number of days. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param days the amount of days to add, may be negative + * @return the new period with the increased days + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withDays(int days) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.DAY_INDEX, values, days); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period with the specified number of hours. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param hours the amount of hours to add, may be negative + * @return the new period with the increased hours + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withHours(int hours) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.HOUR_INDEX, values, hours); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period with the specified number of minutes. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param minutes the amount of minutes to add, may be negative + * @return the new period with the increased minutes + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withMinutes(int minutes) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.MINUTE_INDEX, values, minutes); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period with the specified number of seconds. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param seconds the amount of seconds to add, may be negative + * @return the new period with the increased seconds + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withSeconds(int seconds) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.SECOND_INDEX, values, seconds); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period with the specified number of millis. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param millis the amount of millis to add, may be negative + * @return the new period with the increased millis + * @throws UnsupportedOperationException if the field is not supported + */ + public Period withMillis(int millis) { + int[] values = getValues(); // cloned + getPeriodType().setIndexedField(this, PeriodType.MILLI_INDEX, values, millis); + return new Period(values, getPeriodType()); + } + + //----------------------------------------------------------------------- + /** + * Returns a new period with the specified number of years added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param years the amount of years to add, may be negative + * @return the new period with the increased years + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusYears(int years) { + if (years == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.YEAR_INDEX, values, years); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period plus the specified number of months added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param months the amount of months to add, may be negative + * @return the new period plus the increased months + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusMonths(int months) { + if (months == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.MONTH_INDEX, values, months); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period plus the specified number of weeks added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param weeks the amount of weeks to add, may be negative + * @return the new period plus the increased weeks + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusWeeks(int weeks) { + if (weeks == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.WEEK_INDEX, values, weeks); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period plus the specified number of days added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param days the amount of days to add, may be negative + * @return the new period plus the increased days + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusDays(int days) { + if (days == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.DAY_INDEX, values, days); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period plus the specified number of hours added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param hours the amount of hours to add, may be negative + * @return the new period plus the increased hours + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusHours(int hours) { + if (hours == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.HOUR_INDEX, values, hours); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period plus the specified number of minutes added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param minutes the amount of minutes to add, may be negative + * @return the new period plus the increased minutes + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusMinutes(int minutes) { + if (minutes == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.MINUTE_INDEX, values, minutes); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period plus the specified number of seconds added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param seconds the amount of seconds to add, may be negative + * @return the new period plus the increased seconds + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusSeconds(int seconds) { + if (seconds == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.SECOND_INDEX, values, seconds); + return new Period(values, getPeriodType()); + } + + /** + * Returns a new period plus the specified number of millis added. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param millis the amount of millis to add, may be negative + * @return the new period plus the increased millis + * @throws UnsupportedOperationException if the field is not supported + */ + public Period plusMillis(int millis) { + if (millis == 0) { + return this; + } + int[] values = getValues(); // cloned + getPeriodType().addIndexedField(this, PeriodType.MILLI_INDEX, values, millis); + return new Period(values, getPeriodType()); + } + + //----------------------------------------------------------------------- + /** + * Returns a new period with the specified number of years taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param years the amount of years to take away, may be negative + * @return the new period with the increased years + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusYears(int years) { + return plusYears(-years); + } + + /** + * Returns a new period minus the specified number of months taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param months the amount of months to take away, may be negative + * @return the new period minus the increased months + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusMonths(int months) { + return plusMonths(-months); + } + + /** + * Returns a new period minus the specified number of weeks taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param weeks the amount of weeks to take away, may be negative + * @return the new period minus the increased weeks + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusWeeks(int weeks) { + return plusWeeks(-weeks); + } + + /** + * Returns a new period minus the specified number of days taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param days the amount of days to take away, may be negative + * @return the new period minus the increased days + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusDays(int days) { + return plusDays(-days); + } + + /** + * Returns a new period minus the specified number of hours taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param hours the amount of hours to take away, may be negative + * @return the new period minus the increased hours + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusHours(int hours) { + return plusHours(-hours); + } + + /** + * Returns a new period minus the specified number of minutes taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param minutes the amount of minutes to take away, may be negative + * @return the new period minus the increased minutes + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusMinutes(int minutes) { + return plusMinutes(-minutes); + } + + /** + * Returns a new period minus the specified number of seconds taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param seconds the amount of seconds to take away, may be negative + * @return the new period minus the increased seconds + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusSeconds(int seconds) { + return plusSeconds(-seconds); + } + + /** + * Returns a new period minus the specified number of millis taken away. + *

+ * This period instance is immutable and unaffected by this method call. + * + * @param millis the amount of millis to take away, may be negative + * @return the new period minus the increased millis + * @throws UnsupportedOperationException if the field is not supported + */ + public Period minusMillis(int millis) { + return plusMillis(-millis); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/PeriodType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/PeriodType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/PeriodType.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,714 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; +import java.util.Arrays; + +import org.joda.time.field.FieldUtils; + +/** + * Controls a period implementation by specifying which duration fields are to be used. + *

+ * The following implementations are provided: + *

    + *
  • Standard - years, months, weeks, days, hours, minutes, seconds, millis + *
  • YearMonthDayTime - years, months, days, hours, minutes, seconds, millis + *
  • YearWeekDayTime - years, weeks, days, hours, minutes, seconds, millis + *
  • YearDayTime - years, days, hours, minutes, seconds, millis + *
  • DayTime - days, hours, minutes, seconds, millis + *
  • Time - hours, minutes, seconds, millis + *
  • plus one for each single type + *
+ * + *

+ * PeriodType is thread-safe and immutable, and all subclasses must be as well. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public class PeriodType implements Serializable { + /** Serialization version */ + private static final long serialVersionUID = 2274324892792009998L; + + static int YEAR_INDEX = 0; + static int MONTH_INDEX = 1; + static int WEEK_INDEX = 2; + static int DAY_INDEX = 3; + static int HOUR_INDEX = 4; + static int MINUTE_INDEX = 5; + static int SECOND_INDEX = 6; + static int MILLI_INDEX = 7; + + private static PeriodType cStandard; + private static PeriodType cYMDTime; + private static PeriodType cYWDTime; + private static PeriodType cYDTime; + private static PeriodType cDTime; + private static PeriodType cTime; + + private static PeriodType cYears; + private static PeriodType cMonths; + private static PeriodType cWeeks; + private static PeriodType cDays; + private static PeriodType cHours; + private static PeriodType cMinutes; + private static PeriodType cSeconds; + private static PeriodType cMillis; + + /** + * Gets a type that defines all standard fields. + *

    + *
  • years + *
  • months + *
  • weeks + *
  • days + *
  • hours + *
  • minutes + *
  • seconds + *
  • milliseconds + *
+ * + * @return the period type + */ + public static PeriodType standard() { + PeriodType type = cStandard; + if (type == null) { + type = new PeriodType( + "Standard", + new DurationFieldType[] { + DurationFieldType.years(), DurationFieldType.months(), + DurationFieldType.weeks(), DurationFieldType.days(), + DurationFieldType.hours(), DurationFieldType.minutes(), + DurationFieldType.seconds(), DurationFieldType.millis(), + }, + new int[] { 0, 1, 2, 3, 4, 5, 6, 7, } + ); + cStandard = type; + } + return type; + } + + /** + * Gets a type that defines all standard fields except weeks. + *
    + *
  • years + *
  • months + *
  • days + *
  • hours + *
  • minutes + *
  • seconds + *
  • milliseconds + *
+ * + * @return the period type + */ + public static PeriodType yearMonthDayTime() { + PeriodType type = cYMDTime; + if (type == null) { + type = new PeriodType( + "YearMonthDayTime", + new DurationFieldType[] { + DurationFieldType.years(), DurationFieldType.months(), + DurationFieldType.days(), + DurationFieldType.hours(), DurationFieldType.minutes(), + DurationFieldType.seconds(), DurationFieldType.millis(), + }, + new int[] { 0, 1, -1, 2, 3, 4, 5, 6, } + ); + cYMDTime = type; + } + return type; + } + + /** + * Gets a type that defines all standard fields except months. + *
    + *
  • years + *
  • weeks + *
  • days + *
  • hours + *
  • minutes + *
  • seconds + *
  • milliseconds + *
+ * + * @return the period type + */ + public static PeriodType yearWeekDayTime() { + PeriodType type = cYWDTime; + if (type == null) { + type = new PeriodType( + "YearWeekDayTime", + new DurationFieldType[] { + DurationFieldType.years(), + DurationFieldType.weeks(), DurationFieldType.days(), + DurationFieldType.hours(), DurationFieldType.minutes(), + DurationFieldType.seconds(), DurationFieldType.millis(), + }, + new int[] { 0, -1, 1, 2, 3, 4, 5, 6, } + ); + cYWDTime = type; + } + return type; + } + + /** + * Gets a type that defines all standard fields except months and weeks. + *
    + *
  • years + *
  • days + *
  • hours + *
  • minutes + *
  • seconds + *
  • milliseconds + *
+ * + * @return the period type + */ + public static PeriodType yearDayTime() { + PeriodType type = cYDTime; + if (type == null) { + type = new PeriodType( + "YearDayTime", + new DurationFieldType[] { + DurationFieldType.years(), DurationFieldType.days(), + DurationFieldType.hours(), DurationFieldType.minutes(), + DurationFieldType.seconds(), DurationFieldType.millis(), + }, + new int[] { 0, -1, -1, 1, 2, 3, 4, 5, } + ); + cYDTime = type; + } + return type; + } + + /** + * Gets a type that defines all standard fields from days downwards. + *
    + *
  • days + *
  • hours + *
  • minutes + *
  • seconds + *
  • milliseconds + *
+ * + * @return the period type + */ + public static PeriodType dayTime() { + PeriodType type = cDTime; + if (type == null) { + type = new PeriodType( + "DayTime", + new DurationFieldType[] { + DurationFieldType.days(), + DurationFieldType.hours(), DurationFieldType.minutes(), + DurationFieldType.seconds(), DurationFieldType.millis(), + }, + new int[] { -1, -1, -1, 0, 1, 2, 3, 4, } + ); + cDTime = type; + } + return type; + } + + /** + * Gets a type that defines all standard time fields. + *
    + *
  • hours + *
  • minutes + *
  • seconds + *
  • milliseconds + *
+ * + * @return the period type + */ + public static PeriodType time() { + PeriodType type = cTime; + if (type == null) { + type = new PeriodType( + "Time", + new DurationFieldType[] { + DurationFieldType.hours(), DurationFieldType.minutes(), + DurationFieldType.seconds(), DurationFieldType.millis(), + }, + new int[] { -1, -1, -1, -1, 0, 1, 2, 3, } + ); + cTime = type; + } + return type; + } + + /** + * Gets a type that defines just the years field. + * + * @return the period type + */ + public static PeriodType years() { + PeriodType type = cYears; + if (type == null) { + type = new PeriodType( + "Years", + new DurationFieldType[] { DurationFieldType.years() }, + new int[] { 0, -1, -1, -1, -1, -1, -1, -1, } + ); + cYears = type; + } + return type; + } + + /** + * Gets a type that defines just the months field. + * + * @return the period type + */ + public static PeriodType months() { + PeriodType type = cMonths; + if (type == null) { + type = new PeriodType( + "Months", + new DurationFieldType[] { DurationFieldType.months() }, + new int[] { -1, 0, -1, -1, -1, -1, -1, -1, } + ); + cMonths = type; + } + return type; + } + + /** + * Gets a type that defines just the weeks field. + * + * @return the period type + */ + public static PeriodType weeks() { + PeriodType type = cWeeks; + if (type == null) { + type = new PeriodType( + "Weeks", + new DurationFieldType[] { DurationFieldType.weeks() }, + new int[] { -1, -1, 0, -1, -1, -1, -1, -1, } + ); + cWeeks = type; + } + return type; + } + + /** + * Gets a type that defines just the days field. + * + * @return the period type + */ + public static PeriodType days() { + PeriodType type = cDays; + if (type == null) { + type = new PeriodType( + "Days", + new DurationFieldType[] { DurationFieldType.days() }, + new int[] { -1, -1, -1, 0, -1, -1, -1, -1, } + ); + cDays = type; + } + return type; + } + + /** + * Gets a type that defines just the hours field. + * + * @return the period type + */ + public static PeriodType hours() { + PeriodType type = cHours; + if (type == null) { + type = new PeriodType( + "Hours", + new DurationFieldType[] { DurationFieldType.hours() }, + new int[] { -1, -1, -1, -1, 0, -1, -1, -1, } + ); + cHours = type; + } + return type; + } + + /** + * Gets a type that defines just the minutes field. + * + * @return the period type + */ + public static PeriodType minutes() { + PeriodType type = cMinutes; + if (type == null) { + type = new PeriodType( + "Minutes", + new DurationFieldType[] { DurationFieldType.minutes() }, + new int[] { -1, -1, -1, -1, -1, 0, -1, -1, } + ); + cMinutes = type; + } + return type; + } + + /** + * Gets a type that defines just the seconds field. + * + * @return the period type + */ + public static PeriodType seconds() { + PeriodType type = cSeconds; + if (type == null) { + type = new PeriodType( + "Seconds", + new DurationFieldType[] { DurationFieldType.seconds() }, + new int[] { -1, -1, -1, -1, -1, -1, 0, -1, } + ); + cSeconds = type; + } + return type; + } + + /** + * Gets a type that defines just the millis field. + * + * @return the period type + */ + public static PeriodType millis() { + PeriodType type = cMillis; + if (type == null) { + type = new PeriodType( + "Millis", + new DurationFieldType[] { DurationFieldType.millis() }, + new int[] { -1, -1, -1, -1, -1, -1, -1, 0, } + ); + cMillis = type; + } + return type; + } + + //----------------------------------------------------------------------- + /** The name of the type */ + private final String iName; + /** The array of types */ + private final DurationFieldType[] iTypes; + /** The array of indices */ + private final int[] iIndices; + + /** + * Constructor. + * + * @param name the name + * @param types the types + * @param indices the indices + */ + protected PeriodType(String name, DurationFieldType[] types, int[] indices) { + super(); + iName = name; + iTypes = types; + iIndices = indices; + } + + //----------------------------------------------------------------------- + /** + * Gets the name of the period type. + * + * @return the name + */ + public String getName() { + return iName; + } + + /** + * Gets the number of fields in the period type. + * + * @return the number of fields + */ + public int size() { + return iTypes.length; + } + + /** + * Gets the field type by index. + * + * @param index the index to retrieve + * @return the field type + * @throws IndexOutOfBoundsException if the index is invalid + */ + public DurationFieldType getFieldType(int index) { + return iTypes[index]; + } + + /** + * Checks whether the field specified is supported by this period. + * + * @param type the type to check, may be null which returns false + * @return true if the field is supported + */ + public boolean isSupported(DurationFieldType type) { + return (indexOf(type) >= 0); + } + + /** + * Gets the index of the field in this period. + * + * @param type the type to check, may be null which returns -1 + * @return the index of -1 if not supported + */ + public int indexOf(DurationFieldType type) { + for (int i = 0, isize = size(); i < isize; i++) { + if (iTypes[i] == type) { + return i; + } + } + return -1; + } + + /** + * Gets a debugging to string. + * + * @return a string + */ + public String toString() { + String name = getName(); + return "PeriodType[" + getName() + "]"; + } + + //----------------------------------------------------------------------- + /** + * Gets the indexed field part of the period. + * + * @param period the period to query + * @param index the index to use + * @return the value of the field, zero if unsupported + */ + int getIndexedField(ReadablePeriod period, int index) { + int realIndex = iIndices[index]; + return (realIndex == -1 ? 0 : period.getValue(realIndex)); + } + + /** + * Sets the indexed field part of the period. + * + * @param period the period to query + * @param index the index to use + * @param values the array to populate + * @param newValue the value to set + * @throws IllegalArgumentException if not supported + */ + boolean setIndexedField(ReadablePeriod period, int index, int[] values, int newValue) { + int realIndex = iIndices[index]; + if (realIndex == -1) { + throw new IllegalArgumentException("Field is not supported"); + } + values[realIndex] = newValue; + return true; + } + + /** + * Adds to the indexed field part of the period. + * + * @param period the period to query + * @param index the index to use + * @param values the array to populate + * @param valueToAdd the value to add + * @throws IllegalArgumentException if not supported + */ + boolean addIndexedField(ReadablePeriod period, int index, int[] values, int valueToAdd) { + int realIndex = iIndices[index]; + if (realIndex == -1) { + throw new IllegalArgumentException("Field is not supported"); + } + values[realIndex] = FieldUtils.safeAdd(values[realIndex], valueToAdd); + return true; + } + + //----------------------------------------------------------------------- + /** + * Returns a version of this PeriodType instance that does not support years. + * + * @return a new period type that supports the original set of fields except years + */ + public PeriodType withYearsRemoved() { + return withFieldRemoved(0, "NoYears"); + } + + /** + * Returns a version of this PeriodType instance that does not support months. + * + * @return a new period type that supports the original set of fields except months + */ + public PeriodType withMonthsRemoved() { + return withFieldRemoved(1, "NoMonths"); + } + + /** + * Returns a version of this PeriodType instance that does not support weeks. + * + * @return a new period type that supports the original set of fields except weeks + */ + public PeriodType withWeeksRemoved() { + return withFieldRemoved(2, "NoWeeks"); + } + + /** + * Returns a version of this PeriodType instance that does not support days. + * + * @return a new period type that supports the original set of fields except days + */ + public PeriodType withDaysRemoved() { + return withFieldRemoved(3, "NoDays"); + } + + /** + * Returns a version of this PeriodType instance that does not support hours. + * + * @return a new period type that supports the original set of fields except hours + */ + public PeriodType withHoursRemoved() { + return withFieldRemoved(4, "NoHours"); + } + + /** + * Returns a version of this PeriodType instance that does not support minutes. + * + * @return a new period type that supports the original set of fields except minutes + */ + public PeriodType withMinutesRemoved() { + return withFieldRemoved(5, "NoMinutes"); + } + + /** + * Returns a version of this PeriodType instance that does not support seconds. + * + * @return a new period type that supports the original set of fields except seconds + */ + public PeriodType withSecondsRemoved() { + return withFieldRemoved(6, "NoSeconds"); + } + + /** + * Returns a version of this PeriodType instance that does not support milliseconds. + * + * @return a new period type that supports the original set of fields except milliseconds + */ + public PeriodType withMillisRemoved() { + return withFieldRemoved(7, "NoMillis"); + } + + /** + * Removes the field specified by indices index. + * + * @param indicesIndex the index to remove + * @param name the name addition + * @return the new type + */ + private PeriodType withFieldRemoved(int indicesIndex, String name) { + int fieldIndex = iIndices[indicesIndex]; + if (fieldIndex == -1) { + return this; + } + + DurationFieldType[] types = new DurationFieldType[size() - 1]; + for (int i = 0; i < iTypes.length; i++) { + if (i < fieldIndex) { + types[i] = iTypes[i]; + } else if (i > fieldIndex) { + types[i - 1] = iTypes[i]; + } + } + + int[] indices = new int[8]; + for (int i = 0; i < indices.length; i++) { + if (i < indicesIndex) { + indices[i] = iIndices[i]; + } else if (i > indicesIndex) { + indices[i] = (iIndices[i] == -1 ? -1 : iIndices[i] - 1); + } else { + indices[i] = -1; + } + } + return new PeriodType(getName() + name, types, indices); + } + + //----------------------------------------------------------------------- + /** + * Compares this type to another object. + * To be equal, the object must be a PeriodType with the same set of fields. + * + * @param obj the object to compare to + * @return true if equal + */ + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof PeriodType == false) { + return false; + } + PeriodType other = (PeriodType) obj; + return (Arrays.equals(iTypes, other.iTypes)); + } + + /** + * Returns a hashcode based on the field types. + * + * @return a suitable hashcode + */ + public int hashCode() { + int hash = 0; + for (int i = 0; i < iTypes.length; i++) { + hash += iTypes[i].hashCode(); + } + return hash; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadWritableDateTime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadWritableDateTime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadWritableDateTime.java 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,304 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines an instant in time that can be queried and modified using datetime fields. + *

+ * The implementation of this interface will be mutable. + * It may provide more advanced methods than those in the interface. + *

+ * Methods in your application should be defined using ReadWritableDateTime + * as a parameter if the method wants to manipulate and change a date in simple ways. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + */ +public interface ReadWritableDateTime extends ReadableDateTime, ReadWritableInstant { + + //----------------------------------------------------------------------- + /** + * Set the year to the specified value. + * + * @param year the year + * @throws IllegalArgumentException if the value is invalid + */ + void setYear(int year); + + /** + * Add a number of years to the date. + * + * @param years the years to add + * @throws IllegalArgumentException if the value is invalid + */ + void addYears(int years); + + //----------------------------------------------------------------------- + /** + * Set the weekyear to the specified value. + * + * @param weekyear the weekyear + * @throws IllegalArgumentException if the value is invalid + */ + void setWeekyear(int weekyear); + + /** + * Add a number of weekyears to the date. + * + * @param weekyears the weekyears to add + * @throws IllegalArgumentException if the value is invalid + */ + void addWeekyears(int weekyears); + + //----------------------------------------------------------------------- + /** + * Set the month of the year to the specified value. + * + * @param monthOfYear the month of the year + * @throws IllegalArgumentException if the value is invalid + */ + void setMonthOfYear(int monthOfYear); + + /** + * Add a number of months to the date. + * + * @param months the months to add + * @throws IllegalArgumentException if the value is invalid + */ + void addMonths(int months); + + //----------------------------------------------------------------------- + /** + * Set the week of weekyear to the specified value. + * + * @param weekOfWeekyear the week of the weekyear + * @throws IllegalArgumentException if the value is invalid + */ + void setWeekOfWeekyear(int weekOfWeekyear); + + /** + * Add a number of weeks to the date. + * + * @param weeks the weeks to add + * @throws IllegalArgumentException if the value is invalid + */ + void addWeeks(int weeks); + + //----------------------------------------------------------------------- + /** + * Set the day of year to the specified value. + * + * @param dayOfYear the day of the year + * @throws IllegalArgumentException if the value is invalid + */ + void setDayOfYear(int dayOfYear); + + /** + * Set the day of the month to the specified value. + * + * @param dayOfMonth the day of the month + * @throws IllegalArgumentException if the value is invalid + */ + void setDayOfMonth(int dayOfMonth); + + /** + * Set the day of week to the specified value. + * + * @param dayOfWeek the day of the week + * @throws IllegalArgumentException if the value is invalid + */ + void setDayOfWeek(int dayOfWeek); + + /** + * Add a number of days to the date. + * + * @param days the days to add + * @throws IllegalArgumentException if the value is invalid + */ + void addDays(int days); + + //----------------------------------------------------------------------- + /** + * Set the hour of the day to the specified value. + * + * @param hourOfDay the hour of day + * @throws IllegalArgumentException if the value is invalid + */ + void setHourOfDay(int hourOfDay); + + /** + * Add a number of hours to the date. + * + * @param hours the hours to add + * @throws IllegalArgumentException if the value is invalid + */ + void addHours(int hours); + + //----------------------------------------------------------------------- + /** + * Set the minute of the day to the specified value. + * + * @param minuteOfDay the minute of day + * @throws IllegalArgumentException if the value is invalid + */ + void setMinuteOfDay(int minuteOfDay); + + /** + * Set the minute of the hour to the specified value. + * + * @param minuteOfHour the minute of hour + * @throws IllegalArgumentException if the value is invalid + */ + void setMinuteOfHour(int minuteOfHour); + + /** + * Add a number of minutes to the date. + * + * @param minutes the minutes to add + * @throws IllegalArgumentException if the value is invalid + */ + void addMinutes(int minutes); + + //----------------------------------------------------------------------- + /** + * Set the second of the day to the specified value. + * + * @param secondOfDay the second of day + * @throws IllegalArgumentException if the value is invalid + */ + void setSecondOfDay(int secondOfDay); + + /** + * Set the second of the minute to the specified value. + * + * @param secondOfMinute the second of minute + * @throws IllegalArgumentException if the value is invalid + */ + void setSecondOfMinute(int secondOfMinute); + + /** + * Add a number of seconds to the date. + * + * @param seconds the seconds to add + * @throws IllegalArgumentException if the value is invalid + */ + void addSeconds(int seconds); + + //----------------------------------------------------------------------- + /** + * Set the millis of the day to the specified value. + * + * @param millisOfDay the millis of day + * @throws IllegalArgumentException if the value is invalid + */ + void setMillisOfDay(int millisOfDay); + + /** + * Set the millis of the second to the specified value. + * + * @param millisOfSecond the millis of second + * @throws IllegalArgumentException if the value is invalid + */ + void setMillisOfSecond(int millisOfSecond); + + /** + * Add a number of milliseconds to the date. The implementation of this + * method differs from the {@link #add(long)} method in that a + * DateTimeField performs the addition. + * + * @param millis the milliseconds to add + * @throws IllegalArgumentException if the value is invalid + */ + void addMillis(int millis); + + /** + * Set the date from fields. + * The time part of this object will be unaffected. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @throws IllegalArgumentException if any value is invalid + */ + void setDate(int year, int monthOfYear, int dayOfMonth); + + /** + * Set the time from fields. + * The date part of this object will be unaffected. + * + * @param hour the hour + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @throws IllegalArgumentException if any value is invalid + */ + void setTime(int hour, int minuteOfHour, int secondOfMinute, int millisOfSecond); + + /** + * Set the date and time from fields. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @throws IllegalArgumentException if any value is invalid + */ + void setDateTime( + int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadWritableInstant.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadWritableInstant.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadWritableInstant.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,197 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines an instant in the datetime continuum that can be queried and modified. + * This interface expresses the datetime as milliseconds from 1970-01-01T00:00:00Z. + *

+ * The implementation of this interface will be mutable. + * It may provide more advanced methods than those in the interface. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public interface ReadWritableInstant extends ReadableInstant { + + /** + * Sets the value as the number of milliseconds since + * the epoch, 1970-01-01T00:00:00Z. + * + * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the + * instant to + * @throws IllegalArgumentException if the value is invalid + */ + void setMillis(long instant); + + /** + * Sets the millisecond instant of this instant from another. + *

+ * This method does not change the chronology of this instant, just the + * millisecond instant. + * + * @param instant the instant to use, null means now + */ + void setMillis(ReadableInstant instant); + + /** + * Sets the chronology of the datetime, which has no effect if not applicable. + * + * @param chronology the chronology to use, null means ISOChronology in default zone + * @throws IllegalArgumentException if the value is invalid + */ + void setChronology(Chronology chronology); + + /** + * Sets the time zone of the datetime, changing the chronology and field values. + *

+ * Changing the zone using this method retains the millisecond instant. + * The millisecond instant is adjusted in the new zone to compensate. + * + * chronology. Setting the time zone does not affect the millisecond value + * of this instant. + *

+ * If the chronology already has this time zone, no change occurs. + * + * @param zone the time zone to use, null means default zone + * @see #setZoneRetainFields + */ + void setZone(DateTimeZone zone); + + /** + * Sets the time zone of the datetime, changing the chronology and millisecond. + *

+ * Changing the zone using this method retains the field values. + * The millisecond instant is adjusted in the new zone to compensate. + *

+ * If the chronology already has this time zone, no change occurs. + * + * @param zone the time zone to use, null means default zone + * @see #setZone + */ + void setZoneRetainFields(DateTimeZone zone); + + //----------------------------------------------------------------------- + /** + * Adds a millisecond duration to this instant. + *

+ * This will typically change the value of ost fields. + * + * @param duration the millis to add + * @throws IllegalArgumentException if the value is invalid + */ + void add(long duration); + + /** + * Adds a duration to this instant. + *

+ * This will typically change the value of most fields. + * + * @param duration the duration to add, null means add zero + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + void add(ReadableDuration duration); + + /** + * Adds a duration to this instant specifying how many times to add. + *

+ * This will typically change the value of most fields. + * + * @param duration the duration to add, null means add zero + * @param scalar direction and amount to add, which may be negative + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + void add(ReadableDuration duration, int scalar); + + /** + * Adds a period to this instant. + *

+ * This will typically change the value of most fields. + * + * @param period the period to add, null means add zero + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + void add(ReadablePeriod period); + + /** + * Adds a period to this instant specifying how many times to add. + *

+ * This will typically change the value of most fields. + * + * @param period the period to add, null means add zero + * @param scalar direction and amount to add, which may be negative + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + void add(ReadablePeriod period, int scalar); + + //----------------------------------------------------------------------- + /** + * Sets the value of one of the fields of the instant, such as hourOfDay. + * + * @param type a field type, usually obtained from DateTimeFieldType, null ignored + * @param value the value to set the field to + * @throws IllegalArgumentException if the value is invalid + */ + void set(DateTimeFieldType type, int value); + + /** + * Adds to the instant specifying the duration and multiple to add. + * + * @param type a field type, usually obtained from DateTimeFieldType, null ignored + * @param amount the amount to add of this duration + * @throws ArithmeticException if the result exceeds the capacity of the instant + */ + void add(DurationFieldType type, int amount); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadWritableInterval.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadWritableInterval.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadWritableInterval.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,173 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Writable interface for an interval. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public interface ReadWritableInterval extends ReadableInterval { + + /** + * Sets this interval from two millisecond instants. + * + * @param startInstant the start of the time interval + * @param endInstant the start of the time interval + * @throws IllegalArgumentException if the end is before the start + */ + void setInterval(long startInstant, long endInstant); + + /** + * Sets this interval to be the same as another. + * + * @param interval the interval to copy + * @throws IllegalArgumentException if the end is before the start + */ + void setInterval(ReadableInterval interval); + + /** + * Sets this interval from two instants. + * + * @param startInstant the start of the time interval + * @param endInstant the start of the time interval + * @throws IllegalArgumentException if the end is before the start + */ + void setInterval(ReadableInstant startInstant, ReadableInstant endInstant); + + //----------------------------------------------------------------------- + /** + * Sets the chronology of this time interval. + * + * @param chrono the chronology to use, null means ISO default + */ + void setChronology(Chronology chrono); + + //----------------------------------------------------------------------- + /** + * Sets the start of this time interval. + * + * @param millisInstant the start of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if the end is before the start + */ + void setStartMillis(long millisInstant); + + /** + * Sets the start of this time interval as an Instant. + * + * @param instant the start of the time interval + * @throws IllegalArgumentException if the end is before the start + */ + void setStart(ReadableInstant instant); + + //----------------------------------------------------------------------- + /** + * Sets the end of this time interval. + * + * @param millisInstant the end of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if the end is before the start + */ + void setEndMillis(long millisInstant); + + /** + * Sets the end of this time interval as an Instant. + * + * @param instant the end of the time interval + * @throws IllegalArgumentException if the end is before the start + */ + void setEnd(ReadableInstant instant); + + //----------------------------------------------------------------------- + /** + * Sets the duration of this time interval, preserving the start instant. + * + * @param duration new duration for interval + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + void setDurationAfterStart(ReadableDuration duration); + + /** + * Sets the duration of this time interval, preserving the end instant. + * + * @param duration new duration for interval + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + void setDurationBeforeEnd(ReadableDuration duration); + + //----------------------------------------------------------------------- + /** + * Sets the period of this time interval, preserving the start instant. + * + * @param period new period for interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + void setPeriodAfterStart(ReadablePeriod period); + + /** + * Sets the period of this time interval, preserving the end instant. + * + * @param period new period for interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + void setPeriodBeforeEnd(ReadablePeriod period); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadWritablePeriod.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadWritablePeriod.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadWritablePeriod.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,318 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines a duration of time that can be queried and modified using datetime fields. + *

+ * The implementation of this interface will be mutable. + * It may provide more advanced methods than those in the interface. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public interface ReadWritablePeriod extends ReadablePeriod { + + /** + * Clears the period, setting all values back to zero. + */ + void clear(); + + /** + * Sets the value of one of the fields by index. + * + * @param index the field index + * @param value the new value for the field + * @throws IndexOutOfBoundsException if the index is invalid + */ + void setValue(int index, int value); + + /** + * Sets the value of one of the fields. + *

+ * The field type specified must be one of those that is supported by the period. + * + * @param field a DurationFieldType instance that is supported by this period + * @param value the new value for the field + * @throws IllegalArgumentException if the field is null or not supported + */ + void set(DurationFieldType field, int value); + + /** + * Sets all the fields in one go from another ReadablePeriod. + * + * @param period the period to set, null means zero length period + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + void setPeriod(ReadablePeriod period); + + /** + * Sets all the fields in one go. + * + * @param years amount of years in this period, which must be zero if unsupported + * @param months amount of months in this period, which must be zero if unsupported + * @param weeks amount of weeks in this period, which must be zero if unsupported + * @param days amount of days in this period, which must be zero if unsupported + * @param hours amount of hours in this period, which must be zero if unsupported + * @param minutes amount of minutes in this period, which must be zero if unsupported + * @param seconds amount of seconds in this period, which must be zero if unsupported + * @param millis amount of milliseconds in this period, which must be zero if unsupported + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + void setPeriod(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis); + + /** + * Sets all the fields in one go from an interval dividing the + * fields using the period type. + * + * @param interval the interval to set, null means zero length + */ + void setPeriod(ReadableInterval interval); + + //----------------------------------------------------------------------- + /** + * Adds to the value of one of the fields. + *

+ * The field type specified must be one of those that is supported by the period. + * + * @param field a DurationFieldType instance that is supported by this period + * @param value the value to add to the field + * @throws IllegalArgumentException if the field is null or not supported + */ + void add(DurationFieldType field, int value); + + /** + * Adds a period to this one by adding each field in turn. + * + * @param period the period to add, null means add nothing + * @throws IllegalArgumentException if the period being added contains a field + * not supported by this period + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void add(ReadablePeriod period); + + /** + * Adds to each field of this period. + * + * @param years amount of years to add to this period, which must be zero if unsupported + * @param months amount of months to add to this period, which must be zero if unsupported + * @param weeks amount of weeks to add to this period, which must be zero if unsupported + * @param days amount of days to add to this period, which must be zero if unsupported + * @param hours amount of hours to add to this period, which must be zero if unsupported + * @param minutes amount of minutes to add to this period, which must be zero if unsupported + * @param seconds amount of seconds to add to this period, which must be zero if unsupported + * @param millis amount of milliseconds to add to this period, which must be zero if unsupported + * @throws IllegalArgumentException if the period being added contains a field + * not supported by this period + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void add(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis); + + /** + * Adds an interval to this one by dividing the interval into + * fields and then adding each field in turn. + * + * @param interval the interval to add, null means add nothing + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void add(ReadableInterval interval); + + //----------------------------------------------------------------------- + /** + * Sets the number of years of the period. + * + * @param years the number of years + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setYears(int years); + + /** + * Adds the specified years to the number of years in the period. + * + * @param years the number of years + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addYears(int years); + + //----------------------------------------------------------------------- + /** + * Sets the number of months of the period. + * + * @param months the number of months + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setMonths(int months); + + /** + * Adds the specified months to the number of months in the period. + * + * @param months the number of months + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addMonths(int months); + + //----------------------------------------------------------------------- + /** + * Sets the number of weeks of the period. + * + * @param weeks the number of weeks + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setWeeks(int weeks); + + /** + * Adds the specified weeks to the number of weeks in the period. + * + * @param weeks the number of weeks + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addWeeks(int weeks); + + //----------------------------------------------------------------------- + /** + * Sets the number of days of the period. + * + * @param days the number of days + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setDays(int days); + + /** + * Adds the specified days to the number of days in the period. + * + * @param days the number of days + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addDays(int days); + + //----------------------------------------------------------------------- + /** + * Sets the number of hours of the period. + * + * @param hours the number of hours + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setHours(int hours); + + /** + * Adds the specified hours to the number of hours in the period. + * + * @param hours the number of hours + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addHours(int hours); + + //----------------------------------------------------------------------- + /** + * Sets the number of minutes of the period. + * + * @param minutes the number of minutes + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setMinutes(int minutes); + + /** + * Adds the specified minutes to the number of minutes in the period. + * + * @param minutes the number of minutes + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addMinutes(int minutes); + + //----------------------------------------------------------------------- + /** + * Sets the number of seconds of the period. + * + * @param seconds the number of seconds + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setSeconds(int seconds); + + /** + * Adds the specified seconds to the number of seconds in the period. + * + * @param seconds the number of seconds + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addSeconds(int seconds); + + //----------------------------------------------------------------------- + /** + * Sets the number of millis of the period. + * + * @param millis the number of millis + * @throws IllegalArgumentException if field is not supported and the value is non-zero + */ + void setMillis(int millis); + + /** + * Adds the specified millis to the number of millis in the period. + * + * @param millis the number of millis + * @throws IllegalArgumentException if field is not supported and the value is non-zero + * @throws ArithmeticException if the addition exceeds the capacity of the period + */ + void addMillis(int millis); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadableDateTime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadableDateTime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadableDateTime.java 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,240 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.util.Locale; + +/** + * Defines an instant in time that can be queried using datetime fields. + *

+ * The implementation of this interface may be mutable or immutable. + * This interface only gives access to retrieve data, never to change it. + *

+ * Methods in your application should be defined using ReadableDateTime + * as a parameter if the method only wants to read the datetime, and not perform + * any advanced manipulations. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public interface ReadableDateTime extends ReadableInstant { + + /** + * Get the day of week field value. + *

+ * The values for the day of week are defined in {@link DateTimeConstants}. + * + * @return the day of week + */ + int getDayOfWeek(); + + /** + * Get the day of month field value. + * + * @return the day of month + */ + int getDayOfMonth(); + + /** + * Get the day of year field value. + * + * @return the day of year + */ + int getDayOfYear(); + + /** + * Get the week of weekyear field value. + * + * @return the week of a week based year + */ + int getWeekOfWeekyear(); + + /** + * Get the weekyear field value. + * + * @return the year of a week based year + */ + int getWeekyear(); + + /** + * Get the month of year field value. + * + * @return the month of year + */ + int getMonthOfYear(); + + /** + * Get the year field value. + * + * @return the year + */ + int getYear(); + + /** + * Get the year of era field value. + * + * @return the year of era + */ + int getYearOfEra(); + + /** + * Get the year of century field value. + * + * @return the year of century + */ + int getYearOfCentury(); + + /** + * Get the year of era field value. + * + * @return the year of era + */ + int getCenturyOfEra(); + + /** + * Get the era field value. + * + * @return the era + */ + int getEra(); + + // Time field access methods + //----------------------------------------------------------- + + /** + * Get the millis of second field value. + * + * @return the millis of second + */ + int getMillisOfSecond(); + + /** + * Get the millis of day field value. + * + * @return the millis of day + */ + int getMillisOfDay(); + + /** + * Get the second of minute field value. + * + * @return the second of minute + */ + int getSecondOfMinute(); + + /** + * Get the second of day field value. + * + * @return the second of day + */ + int getSecondOfDay(); + + /** + * Get the minute of hour field value. + * + * @return the minute of hour + */ + int getMinuteOfHour(); + + /** + * Get the minute of day field value. + * + * @return the minute of day + */ + int getMinuteOfDay(); + + /** + * Get the hour of day field value. + * + * @return the hour of day + */ + int getHourOfDay(); + + /** + * Get this object as a DateTime. + *

+ * If the implementation of the interface is a DateTime, it is returned directly. + * + * @return a DateTime using the same millis + */ + DateTime toDateTime(); + + /** + * Get this object as a MutableDateTime, always returning a new instance. + * + * @return a MutableDateTime using the same millis + */ + MutableDateTime toMutableDateTime(); + + /** + * Output the instant using the specified format pattern. + * + * @param pattern pattern specification + * @throws IllegalArgumentException if pattern is invalid + * @see org.joda.time.format.DateTimeFormat + */ + String toString(String pattern) throws IllegalArgumentException; + + /** + * Output the instant using the specified format pattern. + * + * @param pattern pattern specification + * @param locale Locale to use, or null for default + * @throws IllegalArgumentException if pattern is invalid + * @see org.joda.time.format.DateTimeFormat + */ + String toString(String pattern, Locale locale) throws IllegalArgumentException; + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadableDuration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadableDuration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadableDuration.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,183 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines an exact duration of time in milliseconds. + *

+ * The implementation of this interface may be mutable or immutable. This + * interface only gives access to retrieve data, never to change it. + *

+ * Methods that are passed a duration as a parameter will treat null + * as a zero length duration. + * + * @see ReadableInterval + * @see ReadablePeriod + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public interface ReadableDuration extends Comparable { + + /** + * Gets the total length of this duration in milliseconds. + * + * @return the total length of the time duration in milliseconds. + */ + long getMillis(); + + //----------------------------------------------------------------------- + /** + * Get this duration as an immutable Duration object. + *

+ * This will either typecast this instance, or create a new Duration. + * + * @return a Duration created using the millisecond duration from this instance + */ + Duration toDuration(); + + //----------------------------------------------------------------------- + /** + * Converts this duration to a Period instance using the standard period type + * and the ISO chronology. + *

+ * Only precise fields in the period type will be used. Thus, only the hour, + * minute, second and millisecond fields on the period will be used. + * The year, month, week and day fields will not be populated. + *

+ * If the duration is small, less than one day, then this method will perform + * as you might expect and split the fields evenly. + * If the duration is larger than one day then all the remaining duration will + * be stored in the largest available field, hours in this case. + *

+ * For example, a duration effectively equal to (365 + 60 + 5) days will be + * converted to ((365 + 60 + 5) * 24) hours by this constructor. + *

+ * For more control over the conversion process, you must pair the duration with + * an instant, see {@link Period#Period(ReadableInstant,ReadableDuration)}. + * + * @return a Period created using the millisecond duration from this instance + */ + Period toPeriod(); + + //----------------------------------------------------------------------- + /** + * Compares this duration with the specified duration based on length. + * + * @param obj a duration to check against + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws NullPointerException if the object is null + * @throws ClassCastException if the given object is not supported + */ + int compareTo(Object obj); + + /** + * Is the length of this duration equal to the duration passed in. + * + * @param duration another duration to compare to, null means zero milliseconds + * @return true if this duration is equal to than the duration passed in + */ + boolean isEqual(ReadableDuration duration); + + /** + * Is the length of this duration longer than the duration passed in. + * + * @param duration another duration to compare to, null means zero milliseconds + * @return true if this duration is equal to than the duration passed in + */ + boolean isLongerThan(ReadableDuration duration); + + /** + * Is the length of this duration shorter than the duration passed in. + * + * @param duration another duration to compare to, null means zero milliseconds + * @return true if this duration is equal to than the duration passed in + */ + boolean isShorterThan(ReadableDuration duration); + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on the millisecond length. All ReadableDuration instances are accepted. + * + * @param readableDuration a readable duration to check against + * @return true if the length of the duration is equal + */ + boolean equals(Object readableDuration); + + /** + * Gets a hash code for the duration that is compatable with the + * equals method. + * The following formula must be used: + *

+     *  long len = getMillis();
+     *  return (int) (len ^ (len >>> 32));
+     * 
+ * + * @return a hash code + */ + int hashCode(); + + //----------------------------------------------------------------------- + /** + * Gets the value as a String in the ISO8601 duration format using hours, + * minutes and seconds (including fractional milliseconds). + *

+ * For example, "PT6H3M7S" represents 6 hours, 3 minutes, 7 seconds. + * + * @return the value as an ISO8601 string + */ + String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadableInstant.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadableInstant.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadableInstant.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,204 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines an instant in the datetime continuum. + * This interface expresses the datetime as milliseconds from 1970-01-01T00:00:00Z. + *

+ * The implementation of this interface may be mutable or immutable. + * This interface only gives access to retrieve data, never to change it. + *

+ * Methods in your application should be defined using ReadableInstant + * as a parameter if the method only wants to read the instant without needing to know + * the specific datetime fields. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public interface ReadableInstant extends Comparable { + + /** + * Get the value as the number of milliseconds since + * the epoch, 1970-01-01T00:00:00Z. + * + * @return the value as milliseconds + */ + long getMillis(); + + /** + * Gets the chronology of the instant. + *

+ * The {@link Chronology} provides conversion from the millisecond + * value to meaningful fields in a particular calendar system. + * + * @return the Chronology, never null + */ + Chronology getChronology(); + + /** + * Gets the time zone of the instant from the chronology. + * + * @return the DateTimeZone that the instant is using, never null + */ + DateTimeZone getZone(); + + /** + * Get the value of one of the fields of a datetime. + *

+ * This method uses the chronology of the instant to obtain the value. + * + * @param type a field type, usually obtained from DateTimeFieldType, not null + * @return the value of that field + * @throws IllegalArgumentException if the field type is null + */ + int get(DateTimeFieldType type); + + //----------------------------------------------------------------------- + /** + * Get the value as a simple immutable Instant object. + *

+ * This can be useful if you don't trust the implementation + * of the interface to be well-behaved, or to get a guaranteed + * immutable object. + * + * @return the value as an Instant object + */ + Instant toInstant(); + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for ascending + * millisecond instant order. This ordering is inconsistent with + * equals, as it ignores the Chronology. + *

+ * All ReadableInstant instances are accepted. + * + * @param readableInstant a readable instant to check against + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object type is not supported + */ + int compareTo(Object readableInstant); + + //----------------------------------------------------------------------- + /** + * Is this instant equal to the instant passed in + * comparing solely by millisecond. + * + * @param instant an instant to check against, null means now + * @return true if the instant is equal to the instant passed in + */ + boolean isEqual(ReadableInstant instant); + + /** + * Is this instant after the instant passed in + * comparing solely by millisecond. + * + * @param instant an instant to check against, null means now + * @return true if the instant is after the instant passed in + */ + boolean isAfter(ReadableInstant instant); + + /** + * Is this instant before the instant passed in + * comparing solely by millisecond. + * + * @param instant an instant to check against, null means now + * @return true if the instant is before the instant passed in + */ + boolean isBefore(ReadableInstant instant); + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on the millisecond instant and the Chronology. All ReadableInstant + * instances are accepted. + *

+ * To compare two instants for absolute time (ie. UTC milliseconds + * ignoring the chronology), use {@link #isEqual(ReadableInstant)} or + * {@link #compareTo(Object)}. + * + * @param readableInstant a readable instant to check against + * @return true if millisecond and chronology are equal, false if + * not or the instant is null or of an incorrect type + */ + boolean equals(Object readableInstant); + + /** + * Gets a hash code for the instant that is compatible with the + * equals method. + *

+ * The formula used must be as follows: + *

+     * ((int) (getMillis() ^ (getMillis() >>> 32))) +
+     * (getChronology().hashCode())
+     * 
+ * + * @return a hash code as defined above + */ + int hashCode(); + + //----------------------------------------------------------------------- + /** + * Get the value as a String in a recognisable ISO8601 format. + *

+ * The string output is in ISO8601 format to enable the String + * constructor to correctly parse it. + * + * @return the value as an ISO8601 string + */ + String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadableInterval.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadableInterval.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadableInterval.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,291 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Readable interface for an interval of time between two instants. + *

+ * A time interval represents a period of time between two instants. + * Intervals are inclusive of the start instant and exclusive of the end. + * The end instant is always greater than or equal to the start instant. + *

+ * Intervals have a fixed millisecond duration. + * This is the difference between the start and end instants. + * The duration is represented separately by {@link ReadableDuration}. + * As a result, intervals are not comparable. + * To compare the length of two intervals, you should compare their durations. + *

+ * An interval can also be converted to a {@link ReadablePeriod}. + * This represents the difference between the start and end points in terms of fields + * such as years and days. + *

+ * Methods that are passed an interval as a parameter will treat null + * as a zero length interval at the current instant in time. + * + * @author Sean Geoghegan + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public interface ReadableInterval { + + /** + * Gets the chronology of the interval, which is the chronology of the first datetime. + * + * @return the chronology of the interval + */ + Chronology getChronology(); + + /** + * Gets the start of this time interval which is inclusive. + * + * @return the start of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + */ + long getStartMillis(); + + /** + * Gets the start of this time interval, which is inclusive, as a DateTime. + * + * @return the start of the time interval + */ + DateTime getStart(); + + /** + * Gets the end of this time interval which is exclusive. + * + * @return the end of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + */ + long getEndMillis(); + + /** + * Gets the end of this time interval, which is exclusive, as a DateTime. + * + * @return the end of the time interval + */ + DateTime getEnd(); + + //----------------------------------------------------------------------- + /** + * Does this time interval contain the specified instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param instant the instant, null means now + * @return true if this time interval contains the instant + */ + boolean contains(ReadableInstant instant); + + /** + * Does this time interval contain the specified time interval completely. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the time interval to compare to, null means now + * @return true if this time interval contains the time interval + */ + boolean contains(ReadableInterval interval); + + /** + * Does this time interval overlap the specified time interval. + *

+ * The intervals overlap if at least some of the time interval is in common. + * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the time interval to compare to, null means now + * @return true if the time intervals overlap + */ + boolean overlaps(ReadableInterval interval); + + //----------------------------------------------------------------------- + /** + * Is this time interval after the specified instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param instant the instant to compare to, null means now + * @return true if this time interval is after the instant + */ + boolean isAfter(ReadableInstant instant); + + /** + * Is this time interval entirely after the specified interval. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the interval to compare to, null means now + * @return true if this time interval is after the interval specified + */ + boolean isAfter(ReadableInterval interval); + + /** + * Is this time interval before the specified instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param instant the instant to compare to, null means now + * @return true if this time interval is before the instant + */ + boolean isBefore(ReadableInstant instant); + + /** + * Is this time interval entirely before the specified interval. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the interval to compare to, null means now + * @return true if this time interval is before the interval specified + */ + boolean isBefore(ReadableInterval interval); + + //----------------------------------------------------------------------- + /** + * Get this interval as an immutable Interval object. + *

+ * This will either typecast this instance, or create a new Interval. + * + * @return the interval as an Interval object + */ + Interval toInterval(); + + /** + * Get this time interval as a MutableInterval. + *

+ * This will always return a new MutableInterval with the same interval. + * + * @return the time interval as a MutableInterval object + */ + MutableInterval toMutableInterval(); + + //----------------------------------------------------------------------- + /** + * Gets the millisecond duration of this time interval. + * + * @return the millisecond duration of the time interval + * @throws ArithmeticException if the duration exceeds the capacity of a long + */ + Duration toDuration(); + + /** + * Gets the millisecond duration of this time interval. + * + * @return the millisecond duration of the time interval + * @throws ArithmeticException if the duration exceeds the capacity of a long + */ + long toDurationMillis(); + + /** + * Converts the duration of the interval to a period using the + * standard period type. + *

+ * This method should be used to exract the field values describing the + * difference between the start and end instants. + * + * @return a time period derived from the interval + */ + Period toPeriod(); + + /** + * Converts the duration of the interval to a period using the + * specified period type. + *

+ * This method should be used to exract the field values describing the + * difference between the start and end instants. + * + * @param type the requested type of the duration, null means standard + * @return a time period derived from the interval + */ + Period toPeriod(PeriodType type); + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on start and end millis plus the chronology. + * All ReadableInterval instances are accepted. + *

+ * To compare the duration of two time intervals, use {@link #toDuration()} + * to get the durations and compare those. + * + * @param readableInterval a readable interval to check against + * @return true if the start and end millis are equal + */ + boolean equals(Object readableInterval); + + /** + * Gets a hash code for the time interval that is compatable with the + * equals method. + *

+ * The formula used must be as follows: + *

int result = 97;
+     * result = 31 * result + ((int) (getStartMillis() ^ (getStartMillis() >>> 32)));
+     * result = 31 * result + ((int) (getEndMillis() ^ (getEndMillis() >>> 32)));
+     * result = 31 * result + getChronology().hashCode();
+     * return result;
+ * + * @return a hash code + */ + int hashCode(); + + //----------------------------------------------------------------------- + /** + * Get the value as a String in the ISO8601 interval format. + *

+ * For example, "2004-06-09T12:30:00.000/2004-07-10T13:30:00.000". + * + * @return the value as an ISO8601 string + */ + String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadablePartial.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadablePartial.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadablePartial.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,213 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines a partial time that does not support every datetime field, and is + * thus a local time. + *

+ * A ReadablePartial supports a subset of those fields on the chronology. + * It cannot be compared to a ReadableInstant, as it does not fully + * specify an instant in time. The time it does specify is a local time, and does + * not include a time zone. + *

+ * A ReadablePartial can be converted to a ReadableInstant + * using one of the resolve methods. These work by providing a full base + * instant that can be used to 'fill in the gaps' and specify a time zone. + * + * @author Stephen Colebourne + */ +public interface ReadablePartial { + + /** + * Gets the number of fields that this partial supports. + * + * @return the number of fields supported + */ + int size(); + + /** + * Gets the field type at the specified index. + * + * @param index the index to retrieve + * @return the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + DateTimeFieldType getFieldType(int index); + + /** + * Gets the field at the specified index. + * + * @param index the index to retrieve + * @return the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + DateTimeField getField(int index); + + /** + * Gets the value at the specified index. + * + * @param index the index to retrieve + * @return the value of the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + int getValue(int index); + + /** + * Gets the chronology of the partial which is never null. + *

+ * The {@link Chronology} is the calculation engine behind the partial and + * provides conversion and validation of the fields in a particular calendar system. + * + * @return the chronology, never null + */ + Chronology getChronology(); + + /** + * Gets the value of one of the fields. + *

+ * The field type specified must be one of those that is supported by the partial. + * + * @param field a DateTimeFieldType instance that is supported by this partial + * @return the value of that field + * @throws IllegalArgumentException if the field is null or not supported + */ + int get(DateTimeFieldType field); + + /** + * Checks whether the field type specified is supported by this partial. + * + * @param field the field to check, may be null which returns false + * @return true if the field is supported + */ + boolean isSupported(DateTimeFieldType field); + + /** + * Converts this partial to a full datetime using the specified time zone and + * filing in any gaps using the current datetime. + *

+ * This method obtains the current datetime, creates a chronology from that + * on this instance plus the time zone specified, and then sets the fields + * from this instant on top. + *

+ * For example, if this partial represents a time, then the result of this + * method will be the datetime from the specified base instant plus the + * time from this partial. + * + * @param zone the zone to use, null means default + * @return the combined datetime + */ + DateTime toDateTime(DateTimeZone zone); + + /** + * Converts this partial to a full datetime by resolving it against another + * datetime. + *

+ * This method takes the specified datetime and sets the fields from this + * instant on top. The chronology from the base instant is used. + *

+ * For example, if this partial represents a time, then the result of this + * method will be the datetime from the specified base instant plus the + * time from this partial. + * + * @param baseInstant the instant that provides the missing fields, null means now + * @return the combined datetime + */ + DateTime toDateTime(ReadableInstant baseInstant); + + //----------------------------------------------------------------------- + /** + * Compares this partial with the specified object for equality based + * on the supported fields, chronology and values. + *

+ * Two instances of ReadablePartial are equal if they have the same + * chronology, same field types (in same order) and same values. + * + * @param partial the object to compare to + * @return true if equal + */ + boolean equals(Object partial); + + /** + * Gets a hash code for the partial that is compatible with the + * equals method. + *

+ * The formula used must be: + *

+     *  int total = 157;
+     *  for (int i = 0; i < fields.length; i++) {
+     *      total = 23 * total + values[i];
+     *      total = 23 * total + fieldTypes[i].hashCode();
+     *  }
+     *  total += chronology.hashCode();
+     *  return total;
+     * 
+ * + * @return a suitable hash code + */ + int hashCode(); + + //----------------------------------------------------------------------- + /** + * Get the value as a String in a recognisable ISO8601 format, only + * displaying supported fields. + *

+ * The string output is in ISO8601 format to enable the String + * constructor to correctly parse it. + * + * @return the value as an ISO8601 string + */ + String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/ReadablePeriod.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/ReadablePeriod.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/ReadablePeriod.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,193 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +/** + * Defines a time period specified in terms of individual duration fields + * such as years and days. + *

+ * The implementation of this interface may be mutable or immutable. This + * interface only gives access to retrieve data, never to change it. + *

+ * Periods are split up into multiple fields, for example days and seconds. + * Implementations are not required to evenly distribute the values across the fields. + * The value for each field may be positive or negative. + *

+ * When a time period is added to an instant, the effect is to add each field in turn. + * For example, a time period could be defined as 3 months, 2 days and -1 hours. + * In most circumstances this would be the same as 3 months, 1 day, and 23 hours. + * However, when adding across a daylight savings boundary, a day may be 23 or 25 hours long. + * Thus, the time period is always added field by field to the datetime. + *

+ * Periods are independent of chronology, and can only be treated as durations + * when paired with a time via an interval. + * + * @see ReadableDuration + * @see ReadableInterval + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public interface ReadablePeriod { + + /** + * Gets the period type that defines which fields are included in the period. + * + * @return the period type + */ + PeriodType getPeriodType(); + + /** + * Gets the number of fields that this period supports. + * + * @return the number of fields supported + */ + int size(); + + /** + * Gets the field type at the specified index. + * + * @param index the index to retrieve + * @return the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + DurationFieldType getFieldType(int index); + + /** + * Gets the value at the specified index. + * + * @param index the index to retrieve + * @return the value of the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + int getValue(int index); + + /** + * Gets the value of one of the fields. + *

+ * If the field type specified is not supported by the period then zero + * is returned. + * + * @param field the field type to query, null returns zero + * @return the value of that field, zero if field not supported + */ + int get(DurationFieldType field); + + /** + * Checks whether the field type specified is supported by this period. + * + * @param field the field to check, may be null which returns false + * @return true if the field is supported + */ + boolean isSupported(DurationFieldType field); + + //----------------------------------------------------------------------- + /** + * Get this period as an immutable Period object. + *

+ * This will either typecast this instance, or create a new Period. + * + * @return a Duration using the same field set and values + */ + Period toPeriod(); + + /** + * Get this object as a MutablePeriod. + *

+ * This will always return a new MutablePeriod with the same fields. + * + * @return a MutablePeriod using the same field set and values + */ + MutablePeriod toMutablePeriod(); + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on the value and type of each supported field. + * All ReadablePeriod instances are accepted. + * + * @param readablePeriod a readable period to check against + * @return true if all the field values and types are equal, false if + * not or the period is null or of an incorrect type + */ + boolean equals(Object readablePeriod); + + /** + * Gets a hash code for the period that is compatible with the equals method. + * The hashcode is calculated as follows: + *

+     *  int total = 17;
+     *  for (int i = 0; i < fields.length; i++) {
+     *      total = 27 * total + getValue(i);
+     *      total = 27 * total + getFieldType(i).hashCode();
+     *  }
+     *  return total;
+     * 
+ * + * @return a hash code + */ + int hashCode(); + + //----------------------------------------------------------------------- + /** + * Gets the value as a String in the style of the ISO8601 duration format. + * Technically, the output can breach the ISO specification as weeks may be included. + *

+ * For example, "PT6H3M5S" represents 6 hours, 3 minutes, 5 seconds. + * + * @return the value as an ISO8601 style string + */ + String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/TimeOfDay.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/TimeOfDay.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/TimeOfDay.java 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,703 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; +import java.util.Locale; + +import org.joda.time.base.BasePartial; +import org.joda.time.field.AbstractPartialFieldProperty; +import org.joda.time.format.ISODateTimeFormat; + +/** + * TimeOfDay is an immutable partial supporting the hour, minute, second + * and millisecond fields. + *

+ * Calculations on TimeOfDay are performed using a {@link Chronology}. + * This chronology is set to be in the UTC time zone for all calculations. + *

+ * Each individual field can be queried in two ways: + *

    + *
  • getHourOfDay() + *
  • hourOfDay().get() + *
+ * The second technique also provides access to other useful methods on the + * field: + *
    + *
  • numeric value - hourOfDay().get() + *
  • text value - hourOfDay().getAsText() + *
  • short text value - hourOfDay().getAsShortText() + *
  • maximum/minimum values - hourOfDay().getMaximumValue() + *
  • add/subtract - hourOfDay().addToCopy() + *
  • set - hourOfDay().setCopy() + *
+ *

+ * TimeOfDay is thread-safe and immutable, provided that the Chronology is as well. + * All standard Chronology classes supplied are thread-safe and immutable. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public final class TimeOfDay + extends BasePartial + implements ReadablePartial, Serializable { + // NOTE: No toDateTime(YearMonthDay) as semantics are confusing when + // different chronologies + + /** Serialization version */ + private static final long serialVersionUID = 3633353405803318660L; + /** The singleton set of field types */ + private static final DateTimeFieldType[] FIELD_TYPES = new DateTimeFieldType[] { + DateTimeFieldType.hourOfDay(), + DateTimeFieldType.minuteOfHour(), + DateTimeFieldType.secondOfMinute(), + DateTimeFieldType.millisOfSecond(), + }; + + /** Constant for midnight. */ + public static final TimeOfDay MIDNIGHT = new TimeOfDay(0, 0, 0, 0); + + /** The index of the hourOfDay field in the field array */ + public static final int HOUR_OF_DAY = 0; + /** The index of the minuteOfHour field in the field array */ + public static final int MINUTE_OF_HOUR = 1; + /** The index of the secondOfMinute field in the field array */ + public static final int SECOND_OF_MINUTE = 2; + /** The index of the millisOfSecond field in the field array */ + public static final int MILLIS_OF_SECOND = 3; + + //----------------------------------------------------------------------- + /** + * Constructs a TimeOfDay from the specified millis of day using the + * ISO chronology. + *

+ * The millisOfDay value may exceed the number of millis in one day, + * but additional days will be ignored. + * This method uses the UTC time zone internally. + * + * @param millisOfDay the number of milliseconds into a day to convert + */ + public static TimeOfDay fromMillisOfDay(long millisOfDay) { + return fromMillisOfDay(millisOfDay, null); + } + + /** + * Constructs a TimeOfDay from the specified millis of day using the + * specified chronology. + *

+ * The millisOfDay value may exceed the number of millis in one day, + * but additional days will be ignored. + * This method uses the UTC time zone internally. + * + * @param millisOfDay the number of milliseconds into a day to convert + * @param chrono the chronology, null means ISO chronology + */ + public static TimeOfDay fromMillisOfDay(long millisOfDay, Chronology chrono) { + chrono = DateTimeUtils.getChronology(chrono); + chrono = chrono.withUTC(); + return new TimeOfDay(millisOfDay, chrono); + } + + // Constructors + //----------------------------------------------------------------------- + /** + * Constructs a TimeOfDay with the current time, using ISOChronology in + * the default zone to extract the fields. + *

+ * The constructor uses the default time zone, resulting in the local time + * being initialised. Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + */ + public TimeOfDay() { + super(); + } + + /** + * Constructs a TimeOfDay with the current time, using the specified chronology + * and zone to extract the fields. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public TimeOfDay(Chronology chronology) { + super(chronology); + } + + /** + * Constructs a TimeOfDay extracting the partial fields from the specified + * milliseconds using the ISOChronology in the default zone. + *

+ * The constructor uses the default time zone, resulting in the local time + * being initialised. Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + public TimeOfDay(long instant) { + super(instant); + } + + /** + * Constructs a TimeOfDay extracting the partial fields from the specified + * milliseconds using the chronology provided. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public TimeOfDay(long instant, Chronology chronology) { + super(instant, chronology); + } + + /** + * Constructs a TimeOfDay from an Object that represents a time. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + *

+ * The chronology used will be derived from the object, defaulting to ISO. + * + * @param instant the datetime object, null means now + * @throws IllegalArgumentException if the instant is invalid + */ + public TimeOfDay(Object instant) { + super(instant, null); + } + + /** + * Constructs a TimeOfDay from an Object that represents a time, using the + * specified chronology. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * The specified chronology overrides that of the object. + * + * @param instant the datetime object, null means now + * @param chronology the chronology, null means ISO default + * @throws IllegalArgumentException if the instant is invalid + */ + public TimeOfDay(Object instant, Chronology chronology) { + super(instant, DateTimeUtils.getChronology(chronology)); + } + + /** + * Constructs a TimeOfDay with specified hour and minute and zero seconds and milliseconds + * using ISOChronology in the default zone. + *

+ * The constructor uses the no time zone initialising the fields as provided. + * Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + * + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + */ + public TimeOfDay(int hourOfDay, int minuteOfHour) { + this(hourOfDay, minuteOfHour, 0, 0, null); + } + + /** + * Constructs a TimeOfDay with specified hour and minute and zero seconds and milliseconds. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public TimeOfDay(int hourOfDay, int minuteOfHour, Chronology chronology) { + this(hourOfDay, minuteOfHour, 0, 0, chronology); + } + + /** + * Constructs a TimeOfDay with specified time field values and zero milliseconds + * using ISOChronology in the default zone. + *

+ * The constructor uses the no time zone initialising the fields as provided. + * Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + * + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + */ + public TimeOfDay(int hourOfDay, int minuteOfHour, int secondOfMinute) { + this(hourOfDay, minuteOfHour, secondOfMinute, 0, null); + } + + /** + * Constructs a TimeOfDay with specified time field values and zero milliseconds. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public TimeOfDay(int hourOfDay, int minuteOfHour, int secondOfMinute, Chronology chronology) { + this(hourOfDay, minuteOfHour, secondOfMinute, 0, chronology); + } + + /** + * Constructs a TimeOfDay with specified time field values using + * ISOChronology in the default zone. + *

+ * The constructor uses the no time zone initialising the fields as provided. + * Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + * + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + */ + public TimeOfDay(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) { + this(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond, null); + } + + /** + * Constructs a TimeOfDay with specified time field values and chronology. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public TimeOfDay(int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond, Chronology chronology) { + super(new int[] {hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond}, chronology); + } + + /** + * Constructs a TimeOfDay with chronology from this instance and new values. + * + * @param partial the partial to base this new instance on + * @param values the new set of values + */ + TimeOfDay(TimeOfDay partial, int[] values) { + super(partial, values); + } + + /** + * Constructs a TimeOfDay with values from this instance and a new chronology. + * + * @param partial the partial to base this new instance on + * @param chrono the new chronology + */ + TimeOfDay(TimeOfDay partial, Chronology chrono) { + super(partial, chrono); + } + + //----------------------------------------------------------------------- + /** + * Gets the number of fields in this partial. + * + * @return the field count + */ + public int size() { + return 4; + } + + /** + * Gets the field for a specific index in the chronology specified. + *

+ * This method must not use any instance variables. + * + * @param index the index to retrieve + * @param chrono the chronology to use + * @return the field + */ + protected DateTimeField getField(int index, Chronology chrono) { + switch (index) { + case HOUR_OF_DAY: + return chrono.hourOfDay(); + case MINUTE_OF_HOUR: + return chrono.minuteOfHour(); + case SECOND_OF_MINUTE: + return chrono.secondOfMinute(); + case MILLIS_OF_SECOND: + return chrono.millisOfSecond(); + default: + throw new IndexOutOfBoundsException("Invalid index: " + index); + } + } + + /** + * Gets the field type at the specified index. + * + * @param index the index to retrieve + * @return the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + public DateTimeFieldType getFieldType(int index) { + return FIELD_TYPES[index]; + } + + /** + * Gets an array of the field type of each of the fields that this partial supports. + *

+ * The fields are returned largest to smallest, Hour, Minute, Second, Millis. + * + * @return the array of field types (cloned), largest to smallest + */ + public DateTimeFieldType[] getFieldTypes() { + return (DateTimeFieldType[]) FIELD_TYPES.clone(); + } + + //----------------------------------------------------------------------- + /** + * Creates a new TimeOfDay instance with the specified chronology. + * This instance is immutable and unaffected by this method call. + *

+ * This method retains the values of the fields, thus the result will + * typically refer to a different instant. + *

+ * The time zone of the specified chronology is ignored, as TimeOfDay + * operates without a time zone. + * + * @param newChronology the new chronology, null means ISO + * @return a copy of this datetime with a different chronology + */ + public TimeOfDay withChronologyRetainFields(Chronology newChronology) { + newChronology = DateTimeUtils.getChronology(newChronology); + newChronology = newChronology.withUTC(); + if (newChronology == getChronology()) { + return this; + } else { + return new TimeOfDay(this, newChronology); + } + } + + /** + * Gets the property object for the specified type, which contains many useful methods. + * + * @param type the field type to get the chronology for + * @return the property object + * @throws IllegalArgumentException if the field is null or unsupported + */ + public Property property(DateTimeFieldType type) { + return new Property(this, indexOfSupported(type)); + } + + //----------------------------------------------------------------------- + /** + * Get the hour of day (0-23) field value. + * + * @return the hour of day + */ + public int getHourOfDay() { + return getValue(HOUR_OF_DAY); + } + + /** + * Get the minute of hour field value. + * + * @return the minute of hour + */ + public int getMinuteOfHour() { + return getValue(MINUTE_OF_HOUR); + } + + /** + * Get the second of minute field value. + * + * @return the second of minute + */ + public int getSecondOfMinute() { + return getValue(SECOND_OF_MINUTE); + } + + /** + * Get the millis of second field value. + * + * @return the millis of second + */ + public int getMillisOfSecond() { + return getValue(MILLIS_OF_SECOND); + } + + //----------------------------------------------------------------------- + /** + * Get the hour of day (0-23) field property + * + * @return the hour of day property + */ + public Property hourOfDay() { + return new Property(this, HOUR_OF_DAY); + } + + /** + * Get the minute of hour field property + * + * @return the minute of hour property + */ + public Property minuteOfHour() { + return new Property(this, MINUTE_OF_HOUR); + } + + /** + * Get the second of minute field property + * + * @return the second of minute property + */ + public Property secondOfMinute() { + return new Property(this, SECOND_OF_MINUTE); + } + + /** + * Get the millis of second property + * + * @return the millis of second property + */ + public Property millisOfSecond() { + return new Property(this, MILLIS_OF_SECOND); + } + + //----------------------------------------------------------------------- + /** + * Output the time in the ISO8601 format THH:mm:ss.SSS. + * + * @return ISO8601 formatted string + */ + public String toString() { + return ISODateTimeFormat.getInstance().tTime().print(this); + } + + //----------------------------------------------------------------------- + /** + * The property class for TimeOfDay. + *

+ * This class binds a TimeOfDay to a DateTimeField. + * + * @author Stephen Colebourne + * @since 1.0 + */ + public static class Property extends AbstractPartialFieldProperty implements Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 5598459141741063833L; + + /** The partial */ + private final TimeOfDay iTimeOfDay; + /** The field index */ + private final int iFieldIndex; + + /** + * Constructs a property. + * + * @param partial the partial instance + * @param fieldIndex the index in the partial + */ + Property(TimeOfDay partial, int fieldIndex) { + super(); + iTimeOfDay = partial; + iFieldIndex = fieldIndex; + } + + /** + * Gets the field that this property uses. + * + * @return the field + */ + public DateTimeField getField() { + return iTimeOfDay.getField(iFieldIndex); + } + + /** + * Gets the partial that this property belongs to. + * + * @return the partial + */ + public ReadablePartial getReadablePartial() { + return iTimeOfDay; + } + + /** + * Gets the partial that this property belongs to. + * + * @return the partial + */ + public TimeOfDay getTimeOfDay() { + return iTimeOfDay; + } + + /** + * Gets the value of this field. + * + * @return the field value + */ + public int get() { + return iTimeOfDay.getValue(iFieldIndex); + } + + //----------------------------------------------------------------------- + /** + * Adds to the value of this field in a copy of this TimeOfDay. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it will affect larger fields. + * Smaller fields are unaffected. + *

+ * If the result would be too large, beyond 23:59:59:999, then an + * IllegalArgumentException is thrown. + *

+ * The TimeOfDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param valueToAdd the value to add to the field in the copy + * @return a copy of the TimeOfDay with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public TimeOfDay addToCopy(int valueToAdd) { + int[] newValues = iTimeOfDay.getValues(); + newValues = getField().add(iTimeOfDay, iFieldIndex, newValues, valueToAdd); + return new TimeOfDay(iTimeOfDay, newValues); + } + + /** + * Adds to the value of this field in a copy of this TimeOfDay wrapping + * within this field if the maximum value is reached. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it wraps within this field. + * Other fields are unaffected. + *

+ * For example, + * 12:59:37 addWrapField one minute returns 12:00:37. + *

+ * The TimeOfDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param valueToAdd the value to add to the field in the copy + * @return a copy of the TimeOfDay with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public TimeOfDay addWrapFieldToCopy(int valueToAdd) { + int[] newValues = iTimeOfDay.getValues(); + newValues = getField().addWrapField(iTimeOfDay, iFieldIndex, newValues, valueToAdd); + return new TimeOfDay(iTimeOfDay, newValues); + } + + //----------------------------------------------------------------------- + /** + * Sets this field in a copy of the TimeOfDay. + *

+ * The TimeOfDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param value the value to set the field in the copy to + * @return a copy of the TimeOfDay with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public TimeOfDay setCopy(int value) { + int[] newValues = iTimeOfDay.getValues(); + newValues = getField().set(iTimeOfDay, iFieldIndex, newValues, value); + return new TimeOfDay(iTimeOfDay, newValues); + } + + /** + * Sets this field in a copy of the TimeOfDay to a parsed text value. + *

+ * The TimeOfDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param text the text value to set + * @param locale optional locale to use for selecting a text symbol + * @return a copy of the TimeOfDay with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public TimeOfDay setCopy(String text, Locale locale) { + int[] newValues = iTimeOfDay.getValues(); + newValues = getField().set(iTimeOfDay, iFieldIndex, newValues, text, locale); + return new TimeOfDay(iTimeOfDay, newValues); + } + + /** + * Sets this field in a copy of the TimeOfDay to a parsed text value. + *

+ * The TimeOfDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param text the text value to set + * @return a copy of the TimeOfDay with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public TimeOfDay setCopy(String text) { + return setCopy(text, null); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/YearMonthDay.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/YearMonthDay.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/YearMonthDay.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,660 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time; + +import java.io.Serializable; +import java.util.Locale; + +import org.joda.time.base.BasePartial; +import org.joda.time.field.AbstractPartialFieldProperty; +import org.joda.time.format.ISODateTimeFormat; + +/** + * YearMonthDay is an immutable partial supporting the year, monthOfYear + * and dayOfMonth fields. + *

+ * Calculations on YearMonthDay are performed using a {@link Chronology}. + * This chronology is set to be in the UTC time zone for all calculations. + *

+ * Each individual field can be queried in two ways: + *

    + *
  • getMonthOfYear() + *
  • monthOfYear().get() + *
+ * The second technique also provides access to other useful methods on the + * field: + *
    + *
  • numeric value - monthOfYear().get() + *
  • text value - monthOfYear().getAsText() + *
  • short text value - monthOfYear().getAsShortText() + *
  • maximum/minimum values - monthOfYear().getMaximumValue() + *
  • add/subtract - monthOfYear().addToCopy() + *
  • set - monthOfYear().setCopy() + *
+ *

+ * YearMonthDay is thread-safe and immutable, provided that the Chronology is as well. + * All standard Chronology classes supplied are thread-safe and immutable. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public final class YearMonthDay + extends BasePartial + implements ReadablePartial, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 797544782896179L; + /** The singleton set of field types */ + private static final DateTimeFieldType[] FIELD_TYPES = new DateTimeFieldType[] { + DateTimeFieldType.year(), + DateTimeFieldType.monthOfYear(), + DateTimeFieldType.dayOfMonth(), + }; + + /** The index of the year field in the field array */ + public static final int YEAR = 0; + /** The index of the monthOfYear field in the field array */ + public static final int MONTH_OF_YEAR = 1; + /** The index of the dayOfMonth field in the field array */ + public static final int DAY_OF_MONTH = 2; + + // Constructors + //----------------------------------------------------------------------- + /** + * Constructs a YearMonthDay with the current time, using ISOChronology in + * the default zone to extract the fields. + *

+ * The constructor uses the default time zone, resulting in the local time + * being initialised. Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + */ + public YearMonthDay() { + super(); + } + + /** + * Constructs a YearMonthDay with the current time, using the specified chronology + * and zone to extract the fields. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public YearMonthDay(Chronology chronology) { + super(chronology); + } + + /** + * Constructs a YearMonthDay extracting the partial fields from the specified + * milliseconds using the ISOChronology in the default zone. + *

+ * The constructor uses the default time zone, resulting in the local time + * being initialised. Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + public YearMonthDay(long instant) { + super(instant); + } + + /** + * Constructs a YearMonthDay extracting the partial fields from the specified + * milliseconds using the chronology provided. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public YearMonthDay(long instant, Chronology chronology) { + super(instant, chronology); + } + + /** + * Constructs a YearMonthDay from an Object that represents a time. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + *

+ * The chronology used will be derived from the object, defaulting to ISO. + * + * @param instant the datetime object, null means now + * @throws IllegalArgumentException if the instant is invalid + */ + public YearMonthDay(Object instant) { + super(instant, null); + } + + /** + * Constructs a YearMonthDay from an Object that represents a time, using the + * specified chronology. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * The specified chronology overrides that of the object. + * + * @param instant the datetime object, null means now + * @param chronology the chronology, null means ISO default + * @throws IllegalArgumentException if the instant is invalid + */ + public YearMonthDay(Object instant, Chronology chronology) { + super(instant, DateTimeUtils.getChronology(chronology)); + } + + /** + * Constructs a YearMonthDay with specified time field values + * using ISOChronology in the default zone. + *

+ * The constructor uses the no time zone initialising the fields as provided. + * Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + */ + public YearMonthDay(int year, int monthOfYear, int dayOfMonth) { + this(year, monthOfYear, dayOfMonth, null); + } + + /** + * Constructs a YearMonthDay with specified time field values. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param chronology the chronology, null means ISOChronology in the default zone + */ + public YearMonthDay(int year, int monthOfYear, int dayOfMonth, Chronology chronology) { + super(new int[] {year, monthOfYear, dayOfMonth}, chronology); + } + + /** + * Constructs a YearMonthDay with chronology from this instance and new values. + * + * @param partial the partial to base this new instance on + * @param values the new set of values + */ + YearMonthDay(YearMonthDay partial, int[] values) { + super(partial, values); + } + + /** + * Constructs a YearMonthDay with values from this instance and a new chronology. + * + * @param partial the partial to base this new instance on + * @param chrono the new chronology + */ + YearMonthDay(YearMonthDay partial, Chronology chrono) { + super(partial, chrono); + } + + //----------------------------------------------------------------------- + /** + * Gets the number of fields in this partial. + * + * @return the field count + */ + public int size() { + return 3; + } + + /** + * Gets the field for a specific index in the chronology specified. + *

+ * This method must not use any instance variables. + * + * @param index the index to retrieve + * @param chrono the chronology to use + * @return the field + */ + protected DateTimeField getField(int index, Chronology chrono) { + switch (index) { + case YEAR: + return chrono.year(); + case MONTH_OF_YEAR: + return chrono.monthOfYear(); + case DAY_OF_MONTH: + return chrono.dayOfMonth(); + default: + throw new IndexOutOfBoundsException("Invalid index: " + index); + } + } + + /** + * Gets the field type at the specified index. + * + * @param index the index to retrieve + * @return the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + public DateTimeFieldType getFieldType(int index) { + return FIELD_TYPES[index]; + } + + /** + * Gets an array of the field type of each of the fields that this partial supports. + *

+ * The fields are returned largest to smallest, Year, Month, Day + * + * @return the array of field types (cloned), largest to smallest + */ + public DateTimeFieldType[] getFieldTypes() { + return (DateTimeFieldType[]) FIELD_TYPES.clone(); + } + + //----------------------------------------------------------------------- + /** + * Creates a new YearMonthDay instance with the specified chronology. + * This instance is immutable and unaffected by this method call. + *

+ * This method retains the values of the fields, thus the result will + * typically refer to a different instant. + *

+ * The time zone of the specified chronology is ignored, as TimeOfDay + * operates without a time zone. + * + * @param newChronology the new chronology, null means ISO + * @return a copy of this datetime with a different chronology + */ + public YearMonthDay withChronologyRetainFields(Chronology newChronology) { + newChronology = DateTimeUtils.getChronology(newChronology); + newChronology = newChronology.withUTC(); + if (newChronology == getChronology()) { + return this; + } else { + return new YearMonthDay(this, newChronology); + } + } + + /** + * Gets the property object for the specified type, which contains many useful methods. + * + * @param type the field type to get the chronology for + * @return the property object + * @throws IllegalArgumentException if the field is null or unsupported + */ + public Property property(DateTimeFieldType type) { + return new Property(this, indexOfSupported(type)); + } + + //----------------------------------------------------------------------- + /** + * Converts this object to a DateMidnight in the default time zone. + * + * @return the DateMidnight instance in the default zone + */ + public DateMidnight toDateMidnight() { + return toDateMidnight(null); + } + + /** + * Converts this object to a DateMidnight. + * + * @param zone the zone to get the DateMidnight in, null means default + * @return the DateMidnight instance + */ + public DateMidnight toDateMidnight(DateTimeZone zone) { + Chronology chrono = getChronology().withZone(zone); + return new DateMidnight(getYear(), getMonthOfYear(), getDayOfMonth(), chrono); + } + + //----------------------------------------------------------------------- + /** + * Converts this object to a DateTime using a TimeOfDay to fill in the + * missing fields and using the default time zone. + * This instance is immutable and unaffected by this method call. + *

+ * The resulting chronology is determined by the chronology of this + * YearMonthDay plus the time zone. + * The chronology of the time is ignored - only the field values are used. + * + * @param time the time of day to use, null means current time + * @return the DateTime instance + */ + public DateTime toDateTime(TimeOfDay time) { + return toDateTime(time, null); + } + + /** + * Converts this object to a DateTime using a TimeOfDay to fill in the + * missing fields. + * This instance is immutable and unaffected by this method call. + *

+ * The resulting chronology is determined by the chronology of this + * YearMonthDay plus the time zone. + * The chronology of the time is ignored - only the field values are used. + * + * @param time the time of day to use, null means current time + * @param zone the zone to get the DateTime in, null means default + * @return the DateTime instance + */ + public DateTime toDateTime(TimeOfDay time, DateTimeZone zone) { + Chronology chrono = getChronology().withZone(zone); + long instant = DateTimeUtils.currentTimeMillis(); + instant = chrono.set(this, instant); + if (time != null) { + instant = chrono.set(time, instant); + } + return new DateTime(instant, chrono); + } + + //----------------------------------------------------------------------- + /** + * Converts this object to an Interval representing the whole day + * in the default time zone. + * + * @return the DateMidnight instance in the default zone + */ + public Interval toInterval() { + return toInterval(null); + } + + /** + * Converts this object to an Interval representing the whole day. + * + * @param zone the zone to get the Interval in, null means default + * @return the DateMidnight instance + */ + public Interval toInterval(DateTimeZone zone) { + zone = DateTimeUtils.getZone(zone); + return toDateMidnight(zone).toInterval(); + } + + //----------------------------------------------------------------------- + /** + * Get the year field value. + * + * @return the year + */ + public int getYear() { + return getValue(YEAR); + } + + /** + * Get the month of year field value. + * + * @return the month of year + */ + public int getMonthOfYear() { + return getValue(MONTH_OF_YEAR); + } + + /** + * Get the day of month field value. + * + * @return the day of month + */ + public int getDayOfMonth() { + return getValue(DAY_OF_MONTH); + } + + //----------------------------------------------------------------------- + /** + * Get the year field property + * + * @return the year property + */ + public Property year() { + return new Property(this, YEAR); + } + + /** + * Get the month of year field property + * + * @return the month of year property + */ + public Property monthOfYear() { + return new Property(this, MONTH_OF_YEAR); + } + + /** + * Get the day of month field property + * + * @return the day of month property + */ + public Property dayOfMonth() { + return new Property(this, DAY_OF_MONTH); + } + + //----------------------------------------------------------------------- + /** + * Output the time in the ISO8601 format YYYY-MM-DD. + * + * @return ISO8601 formatted string + */ + public String toString() { + return ISODateTimeFormat.getInstance().yearMonthDay().print(this); + } + + //----------------------------------------------------------------------- + /** + * The property class for YearMonthDay. + *

+ * This class binds a YearMonthDay to a DateTimeField. + * + * @author Stephen Colebourne + * @since 1.0 + */ + public static class Property extends AbstractPartialFieldProperty implements Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 5727734012190224363L; + + /** The partial */ + private final YearMonthDay iYearMonthDay; + /** The field index */ + private final int iFieldIndex; + + /** + * Constructs a property. + * + * @param partial the partial instance + * @param fieldIndex the index in the partial + */ + Property(YearMonthDay partial, int fieldIndex) { + super(); + iYearMonthDay = partial; + iFieldIndex = fieldIndex; + } + + /** + * Gets the field that this property uses. + * + * @return the field + */ + public DateTimeField getField() { + return iYearMonthDay.getField(iFieldIndex); + } + + /** + * Gets the partial that this property belongs to. + * + * @return the partial + */ + public ReadablePartial getReadablePartial() { + return iYearMonthDay; + } + + /** + * Gets the partial that this property belongs to. + * + * @return the partial + */ + public YearMonthDay getYearMonthDay() { + return iYearMonthDay; + } + + /** + * Gets the value of this field. + * + * @return the field value + */ + public int get() { + return iYearMonthDay.getValue(iFieldIndex); + } + + //----------------------------------------------------------------------- + /** + * Adds to the value of this field in a copy of this YearMonthDay. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it will affect larger fields. + * Smaller fields are unaffected. + *

+ * If the result would be too large, beyond the maximum year, then an + * IllegalArgumentException is thrown. + *

+ * The YearMonthDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param valueToAdd the value to add to the field in the copy + * @return a copy of the YearMonthDay with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public YearMonthDay addToCopy(int valueToAdd) { + int[] newValues = iYearMonthDay.getValues(); + newValues = getField().add(iYearMonthDay, iFieldIndex, newValues, valueToAdd); + return new YearMonthDay(iYearMonthDay, newValues); + } + + /** + * Adds to the value of this field in a copy of this YearMonthDay wrapping + * within this field if the maximum value is reached. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it wraps within this field. + * Other fields are unaffected. + *

+ * For example, + * 2004-12-20 addWrapField one month returns 2004-01-20. + *

+ * The YearMonthDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param valueToAdd the value to add to the field in the copy + * @return a copy of the YearMonthDay with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public YearMonthDay addWrapFieldToCopy(int valueToAdd) { + int[] newValues = iYearMonthDay.getValues(); + newValues = getField().addWrapField(iYearMonthDay, iFieldIndex, newValues, valueToAdd); + return new YearMonthDay(iYearMonthDay, newValues); + } + + //----------------------------------------------------------------------- + /** + * Sets this field in a copy of the YearMonthDay. + *

+ * The YearMonthDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param value the value to set the field in the copy to + * @return a copy of the YearMonthDay with the field value changed + * @throws IllegalArgumentException if the value isn't valid + */ + public YearMonthDay setCopy(int value) { + int[] newValues = iYearMonthDay.getValues(); + newValues = getField().set(iYearMonthDay, iFieldIndex, newValues, value); + return new YearMonthDay(iYearMonthDay, newValues); + } + + /** + * Sets this field in a copy of the YearMonthDay to a parsed text value. + *

+ * The YearMonthDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param text the text value to set + * @param locale optional locale to use for selecting a text symbol + * @return a copy of the YearMonthDay with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public YearMonthDay setCopy(String text, Locale locale) { + int[] newValues = iYearMonthDay.getValues(); + newValues = getField().set(iYearMonthDay, iFieldIndex, newValues, text, locale); + return new YearMonthDay(iYearMonthDay, newValues); + } + + /** + * Sets this field in a copy of the YearMonthDay to a parsed text value. + *

+ * The YearMonthDay attached to this property is unchanged by this call. + * Instead, a new instance is returned. + * + * @param text the text value to set + * @return a copy of the YearMonthDay with the field value changed + * @throws IllegalArgumentException if the text value isn't valid + */ + public YearMonthDay setCopy(String text) { + return setCopy(text, null); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/overview.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/overview.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/overview.html 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,78 @@ + + + +org.joda.time package + + + +

+Joda-Time is a library designed as a complete alternative to the JDK date +and time classes. It includes date, duration, time period and interval classes +and has a pluggable API for various calendar systems. +

+

+The library consists of quite a large number of classes, however most are +internal to the implementation. All the key interfaces and classes are in the main +package while the format package will be of interest for formatting. +

+

+Joda-Time is standalone and has no dependencies other than JDK 1.3. +(The jar file may work on JDK 1.2, but it is untested.) +It is licenced under an Apache/BSD style licence. +

+ + \ No newline at end of file Index: 3rdParty_sources/joda-time/org/joda/time/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/package.html 17 Aug 2012 14:54:51 -0000 1.1 @@ -0,0 +1,223 @@ + + + +org.joda.time package + + + +

+Provides support for dates, times, time zones, durations, intervals, and +partials. This package aims to fully replace the Java Date, +Calendar, and TimeZone classes. This implementation +covers both the Gregorian/Julian calendar system and the ISO8601 +standard. Additional calendar systems and extensions can be created as well. +

+

+The ISO8601 standard is the international standard for dates, times, durations, +and intervals. It defines text representations, the first day of the week as +Monday, and the first week in a year as having a Thursday in it. This standard +is being increasingly used in computer interchange and is the agreed format for +XML. For most uses, the ISO standard is the same as Gregorian, and is thus the +preferred format. +

+ +

Interfaces

+

+The main API concepts are defined by interfaces: +

+
    +
  • ReadableInstant - an instant in time +
  • ReadableDateTime - an instant in time with field accessors such as dayOfWeek +
  • ReadablePartial - a definition for local times that are not defined to the millisecond, such as the time of day +
  • ReadableDuration - a duration defined in milliseconds +
  • ReadablePeriod - a time period defined in fields such as hours and minutes +
  • ReadableInterval - a period of time between two instants +
+
    +
  • ReadWritableInstant - an instant that can be modified +
  • ReadWritableDateTime - a datetime that can be modified +
  • ReadWritablePeriod - a time period that can be modified +
  • ReadWritableInterval - an interval that can be modified +
+

+These define the public interface to dates, times, periods, intervals and durations. +As with java.util.Date and Calendar, the design is +millisecond based with an epoch of 1970-01-01. +This should enable easy conversions. +

+ +

Implementations

+

+The basic implementation of the ReadableInstant interface is +Instant. This is a simple immutable class that stores the +millisecond value and integrates with Java Date and Calendar. +The class follows the definition of the millisecond instant fully, thus +it references the ISO-8601 calendar system and UTC time zone. +If you are dealing with an instant in time but do not know, or do not want to specify, +which calendar system it refers to, then you should use this class. +

+

+The main implementation class for datetimes is the DateTime class. +This implements the ReadableDateTime interface, providing +convenient methods to access the fields of the datetime. Conversion methods +allow integration with the Java Date and Calendar classes. +

+

+Like Instant, DateTime is immutable, and it +can be used safely in a multi-threaded environment. +In order to be fully immutable, key clases are declared as final. +Abstract superclasses are provided should you need to define your own implementations. +

+

+The concrete implementations of the ReadWritable... interfaces are +named the same as their immutable counterparts, but with a "Mutable" prefix. +For example, MutableDateTime implements +ReadWritableDateTime, making datetime editing easy. +Note that it is possible to use the immutable DateTime for modifying datetimes, +however each modification method returns a new instance of DateTime. +

+ +

Interface usage

+

+The interfaces in Joda-Time are not designed to operate in the same way as those +in the Java Collections Framework (List/Map/Set etc). +The Joda-Time interfaces represent a core subset of the functionality available +via the actual classes. +Thus, much of the work of an application will probably use methods on the class, not +on the interface. +Your application must determine whether it should define dates in terms of the +interfaces, or in terms of the classes. +

+

+The interfaces provide simple methods to access an instance of the immutable class, +which is implemented either via typecast or object creation. +Thus, if you hold a reference to a ReadableInstant, and you call the method +toDateTime(), the same instance will be returned (typecast) if it +already was a DateTime. + +

Chronologies and Fields

+

+In order to enable the package to be easily extended, each field of the +datetime, such as the month, is calculated by an implementation of +DateTimeField. Likewise, duration fields are calculated by +specialized DurationField instances. If desired, users can write +their own implementations to retrieve an unusual field from the millisecond +value. +

+

+The datetime and duration fields that together represent a calendar system are +grouped into a Chronology. The chronology represents all the +information to convert from a millisecond value to human understandable fields +in a specific calendar system. Chronologies are provided for ISO, +Gregorian/Julian (GJ), Coptic and Buddhist. +More implementations are sought from the community. +

+

+The chronology and field classes are singletons. +This design results in a low overhead on the date and time classes. +The Java Calendar class performs poorly because it has many internal +fields that are constantly kept in sync. +This design only calculates fields when required, resulting in lightweight and +simple date time classes. +

+

+When reviewing the library for the first time, it is easy to mistake the number +of classes with complexity. +The library is in fact clearly divided between user packages and implementation packages +in the javadoc. +Most users will should not need to be concerned with the back-end implementation. +

+ +

Partials

+

+Partials are like instants, except they do not completely specify a point in +time. The main interface is ReadablePartial, and implementations +include TimeOfDay (contains hour, minute, second, and millis) and +YearMonthDay. +

+

+The API of a partial is remarkably similar to an instant, however there are +internal differences. DateTime and Instant store a +long millisecond value internally and calculate field values on demand. The +partial classes work the other way around, storing field values internally +and providing a means to resolve to a millisecond value on demand. +

+

+Since a partial does not represent a specific point in time, it must be +resolved to create a full instant. For example, a TimeOfDay +might represent 12:30. To convert to a DateTime requires the +specification of a date, and is performed using the resolve +methods of ReadablePartial. For example, +

+    new TimeOfDay("12:30").resolveDateTime(new DateTime("2004-06-07T06:00"));
+
+equals +
+    new DateTime("2004-06-07T12:30");
+
+

+ +

Formatting

+

+Formatting is provided by the format subpackage. Comprehensive +support is provided for outputting dates and times in multiple formats. A +pattern similar to Java SimpleDateFormat can be used, but a more +advanced programmatic technique is available via the builder classes. +

+ + + \ No newline at end of file Index: 3rdParty_sources/joda-time/org/joda/time/base/AbstractDateTime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/AbstractDateTime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/AbstractDateTime.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,338 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.Locale; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadableDateTime; +import org.joda.time.format.DateTimeFormat; + +/** + * AbstractDateTime provides the common behaviour for datetime classes. + *

+ * This class should generally not be used directly by API users. + * The {@link ReadableDateTime} interface should be used when different + * kinds of date/time objects are to be referenced. + *

+ * Whenever you want to implement ReadableDateTime you should + * extend this class. + *

+ * AbstractDateTime subclasses may be mutable and not thread-safe. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class AbstractDateTime + extends AbstractInstant + implements ReadableDateTime { + + //----------------------------------------------------------------------- + /** + * Constructor. + */ + protected AbstractDateTime() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Get the value of one of the fields of a datetime. + *

+ * This method uses the chronology of the datetime to obtain the value. + * It is essentially a generic way of calling one of the get methods. + * + * @param type a field type, usually obtained from DateTimeFieldType + * @return the value of that field + * @throws IllegalArgumentException if the field type is null + */ + public int get(DateTimeFieldType type) { + if (type == null) { + throw new IllegalArgumentException("The DateTimeFieldType must not be null"); + } + return type.getField(getChronology()).get(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Get the era field value. + * + * @return the era + */ + public int getEra() { + return getChronology().era().get(getMillis()); + } + + /** + * Get the year of era field value. + * + * @return the year of era + */ + public int getCenturyOfEra() { + return getChronology().centuryOfEra().get(getMillis()); + } + + /** + * Get the year of era field value. + * + * @return the year of era + */ + public int getYearOfEra() { + return getChronology().yearOfEra().get(getMillis()); + } + + /** + * Get the year of century field value. + * + * @return the year of century + */ + public int getYearOfCentury() { + return getChronology().yearOfCentury().get(getMillis()); + } + + /** + * Get the year field value. + * + * @return the year + */ + public int getYear() { + return getChronology().year().get(getMillis()); + } + + /** + * Get the weekyear field value. + * + * @return the year of a week based year + */ + public int getWeekyear() { + return getChronology().weekyear().get(getMillis()); + } + + /** + * Get the month of year field value. + * + * @return the month of year + */ + public int getMonthOfYear() { + return getChronology().monthOfYear().get(getMillis()); + } + + /** + * Get the week of weekyear field value. + * + * @return the week of a week based year + */ + public int getWeekOfWeekyear() { + return getChronology().weekOfWeekyear().get(getMillis()); + } + + /** + * Get the day of year field value. + * + * @return the day of year + */ + public int getDayOfYear() { + return getChronology().dayOfYear().get(getMillis()); + } + + /** + * Get the day of month field value. + *

+ * The values for the day of month are defined in {@link org.joda.time.DateTimeConstants}. + * + * @return the day of month + */ + public int getDayOfMonth() { + return getChronology().dayOfMonth().get(getMillis()); + } + + /** + * Get the day of week field value. + *

+ * The values for the day of week are defined in {@link org.joda.time.DateTimeConstants}. + * + * @return the day of week + */ + public int getDayOfWeek() { + return getChronology().dayOfWeek().get(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Get the hour of day field value. + * + * @return the hour of day + */ + public int getHourOfDay() { + return getChronology().hourOfDay().get(getMillis()); + } + + /** + * Get the minute of day field value. + * + * @return the minute of day + */ + public int getMinuteOfDay() { + return getChronology().minuteOfDay().get(getMillis()); + } + + /** + * Get the minute of hour field value. + * + * @return the minute of hour + */ + public int getMinuteOfHour() { + return getChronology().minuteOfHour().get(getMillis()); + } + + /** + * Get the second of day field value. + * + * @return the second of day + */ + public int getSecondOfDay() { + return getChronology().secondOfDay().get(getMillis()); + } + + /** + * Get the second of minute field value. + * + * @return the second of minute + */ + public int getSecondOfMinute() { + return getChronology().secondOfMinute().get(getMillis()); + } + + /** + * Get the millis of day field value. + * + * @return the millis of day + */ + public int getMillisOfDay() { + return getChronology().millisOfDay().get(getMillis()); + } + + /** + * Get the millis of second field value. + * + * @return the millis of second + */ + public int getMillisOfSecond() { + return getChronology().millisOfSecond().get(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Get the date time as a java.util.Calendar. + * The locale is passed in, enabling Calendar to select the correct + * localized subclass. + * + * @param locale the locale to get the Calendar for, or default if null + * @return a localized Calendar initialised with this datetime + */ + public Calendar toCalendar(Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + DateTimeZone zone = getZone(); + Calendar cal = Calendar.getInstance(zone.toTimeZone(), locale); + cal.setTime(toDate()); + return cal; + } + + /** + * Get the date time as a java.util.GregorianCalendar. + * + * @return a GregorianCalendar initialised with this datetime + */ + public GregorianCalendar toGregorianCalendar() { + DateTimeZone zone = getZone(); + GregorianCalendar cal = new GregorianCalendar(zone.toTimeZone()); + cal.setTime(toDate()); + return cal; + } + + //----------------------------------------------------------------------- + /** + * Output the instant using the specified format pattern. + * + * @param pattern the pattern specification, null means use toString + * @see org.joda.time.format.DateTimeFormat + */ + public String toString(String pattern) { + if (pattern == null) { + return toString(); + } + return DateTimeFormat.getInstance().forPattern(pattern).print(this); + } + + /** + * Output the instant using the specified format pattern. + * + * @param pattern the pattern specification, null means use toString + * @param locale Locale to use, null means default + * @see org.joda.time.format.DateTimeFormat + */ + public String toString(String pattern, Locale locale) throws IllegalArgumentException { + if (pattern == null) { + return toString(); + } + return DateTimeFormat.getInstance(locale).forPattern(pattern).print(this); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/AbstractDuration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/AbstractDuration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/AbstractDuration.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,241 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import org.joda.time.Duration; +import org.joda.time.Period; +import org.joda.time.ReadableDuration; +import org.joda.time.format.FormatUtils; + +/** + * AbstractDuration provides the common behaviour for duration classes. + *

+ * This class should generally not be used directly by API users. The + * {@link ReadableDuration} interface should be used when different + * kinds of durations are to be referenced. + *

+ * AbstractDuration subclasses may be mutable and not thread-safe. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class AbstractDuration implements ReadableDuration { + + /** + * Constructor. + */ + protected AbstractDuration() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Get this duration as an immutable Duration object. + * + * @return a Duration created using the millisecond duration from this instance + */ + public Duration toDuration() { + return new Duration(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Converts this duration to a Period instance using the standard period type + * and the ISO chronology. + *

+ * Only precise fields in the period type will be used. Thus, only the hour, + * minute, second and millisecond fields on the period will be used. + * The year, month, week and day fields will not be populated. + *

+ * If the duration is small, less than one day, then this method will perform + * as you might expect and split the fields evenly. + * If the duration is larger than one day then all the remaining duration will + * be stored in the largest available field, hours in this case. + *

+ * For example, a duration effectively equal to (365 + 60 + 5) days will be + * converted to ((365 + 60 + 5) * 24) hours by this constructor. + *

+ * For more control over the conversion process, you must pair the duration with + * an instant, see {@link Period#Period(ReadableInstant,ReadableDuration)}. + * + * @return a Period created using the millisecond duration from this instance + */ + public Period toPeriod() { + return new Period(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Compares this duration with the specified duration based on length. + * + * @param obj a duration to check against + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws NullPointerException if the object is null + * @throws ClassCastException if the given object is not supported + */ + public int compareTo(Object obj) { + // Comparable contract means we cannot handle null or other types gracefully + ReadableDuration thisDuration = (ReadableDuration) this; + ReadableDuration otherDuration = (ReadableDuration) obj; + + long thisMillis = thisDuration.getMillis(); + long otherMillis = otherDuration.getMillis(); + + // cannot do (thisMillis - otherMillis) as it can overflow + if (thisMillis < otherMillis) { + return -1; + } + if (thisMillis > otherMillis) { + return 1; + } + return 0; + } + + /** + * Is the length of this duration equal to the duration passed in. + * + * @param duration another duration to compare to, null means zero milliseconds + * @return true if this duration is equal to than the duration passed in + */ + public boolean isEqual(ReadableDuration duration) { + if (duration == null) { + duration = Duration.ZERO; + } + return compareTo(duration) == 0; + } + + /** + * Is the length of this duration longer than the duration passed in. + * + * @param duration another duration to compare to, null means zero milliseconds + * @return true if this duration is equal to than the duration passed in + */ + public boolean isLongerThan(ReadableDuration duration) { + if (duration == null) { + duration = Duration.ZERO; + } + return compareTo(duration) > 0; + } + + /** + * Is the length of this duration shorter than the duration passed in. + * + * @param duration another duration to compare to, null means zero milliseconds + * @return true if this duration is equal to than the duration passed in + */ + public boolean isShorterThan(ReadableDuration duration) { + if (duration == null) { + duration = Duration.ZERO; + } + return compareTo(duration) < 0; + } + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on the millisecond length. All ReadableDuration instances are accepted. + * + * @param duration a readable duration to check against + * @return true if the length of the duration is equal + */ + public boolean equals(Object duration) { + if (this == duration) { + return true; + } + if (duration instanceof ReadableDuration == false) { + return false; + } + ReadableDuration other = (ReadableDuration) duration; + return (getMillis() == other.getMillis()); + } + + /** + * Gets a hash code for the duration that is compatible with the + * equals method. + * + * @return a hash code + */ + public int hashCode() { + long len = getMillis(); + return (int) (len ^ (len >>> 32)); + } + + //----------------------------------------------------------------------- + /** + * Gets the value as a String in the ISO8601 duration format including + * only seconds and milliseconds. + *

+ * For example, "PT72.345S" represents 1 minute, 12 seconds and 345 milliseconds. + *

+ * For more control over the output, see + * {@link org.joda.time.format.PeriodFormatterBuilder PeriodFormatterBuilder}. + * + * @return the value as an ISO8601 string + */ + public String toString() { + long millis = getMillis(); + StringBuffer buf = new StringBuffer(); + buf.append("PT"); + FormatUtils.appendUnpaddedInteger(buf, millis / 1000); + long part = Math.abs(millis % 1000); + if (part > 0) { + buf.append('.'); + FormatUtils.appendPaddedInteger(buf, part, 3); + } + buf.append('S'); + return buf.toString(); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/AbstractInstant.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/AbstractInstant.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/AbstractInstant.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,447 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import java.util.Date; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.Instant; +import org.joda.time.MutableDateTime; +import org.joda.time.ReadableInstant; +import org.joda.time.chrono.ISOChronology; +import org.joda.time.format.ISODateTimeFormat; + +/** + * AbstractInstant provides the common behaviour for instant classes. + *

+ * This class has no concept of a chronology, all methods work on the + * millisecond instant. + *

+ * This class should generally not be used directly by API users. The + * {@link ReadableInstant} interface should be used when different + * kinds of date/time objects are to be referenced. + *

+ * Whenever you want to implement ReadableInstant you should + * extend this class. + *

+ * AbstractInstant itself is thread-safe and immutable, but subclasses may be + * mutable and not thread-safe. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class AbstractInstant implements ReadableInstant { + + /** + * Constructor. + */ + protected AbstractInstant() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the time zone of the instant from the chronology. + * + * @return the DateTimeZone that the instant is using, never null + */ + public DateTimeZone getZone() { + return getChronology().getZone(); + } + + /** + * Get the value of one of the fields of a datetime using the chronology of the instant. + *

+ * This method uses the chronology of the instant to obtain the value. + * For example: + *

+     * DateTime dt = new DateTime();
+     * int year = dt.get(DateTimeFieldType.year());
+     * 
+ * + * @param type a field type, usually obtained from DateTimeFieldType, not null + * @return the value of that field + * @throws IllegalArgumentException if the field type is null + */ + public int get(DateTimeFieldType type) { + if (type == null) { + throw new IllegalArgumentException("The DateTimeFieldType must not be null"); + } + return type.getField(getChronology()).get(getMillis()); + } + + /** + * Get the value of one of the fields of a datetime. + *

+ * This could be used to get a field using a different Chronology. + * For example: + *

+     * Instant dt = new Instant();
+     * int gjYear = dt.get(Chronology.getCoptic().year());
+     * 
+ * + * @param field the DateTimeField to use, not null + * @return the value + * @throws IllegalArgumentException if the field is null + */ + public int get(DateTimeField field) { + if (field == null) { + throw new IllegalArgumentException("The DateTimeField must not be null"); + } + return field.get(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Get this object as an Instant. + * + * @return an Instant using the same millis + */ + public Instant toInstant() { + return new Instant(getMillis()); + } + + /** + * Get this object as a DateTime. + * + * @return a DateTime using the same millis + */ + public DateTime toDateTime() { + return new DateTime(getMillis()); + } + + /** + * Get this object as a DateTime using ISOChronology in the default zone. + * + * @return a DateTime using the same millis with ISOChronology in the default zone. + */ + public DateTime toDateTimeISO() { + return new DateTime(getMillis(), ISOChronology.getInstance()); + } + + /** + * Get this object as a DateTime using the same chronology but a different zone. + * + * @param zone time zone to apply, or default if null + * @return a DateTime using the same millis + */ + public DateTime toDateTime(DateTimeZone zone) { + Chronology chrono = DateTimeUtils.getChronology(getChronology()); + chrono = chrono.withZone(zone); + return new DateTime(getMillis(), chrono); + } + + /** + * Get this object as a DateTime. + * + * @param chronology chronology to apply, or ISOChronology if null + * @return a DateTime using the same millis + */ + public DateTime toDateTime(Chronology chronology) { + return new DateTime(getMillis(), chronology); + } + + // NOTE: Although the toMutableDateTime methods could check to see if this + // is already a MutableDateTime and return this casted, it makes it too + // easy to mistakenly modify ReadableDateTime input parameters. Always + // returning a copy prevents this. + + /** + * Get this object as a MutableDateTime. + * + * @return a MutableDateTime using the same millis + */ + public MutableDateTime toMutableDateTime() { + return new MutableDateTime(getMillis()); + } + + /** + * Get this object as a MutableDateTime using ISOChronology in the default zone. + * + * @return a MutableDateTime using the same millis with ISOChronology in the default zone. + */ + public MutableDateTime toMutableDateTimeISO() { + return new MutableDateTime(getMillis(), ISOChronology.getInstance()); + } + + /** + * Get this object as a MutableDateTime using the same chronology but a different zone. + * + * @param zone time zone to apply, or default if null + * @return a MutableDateTime using the same millis + */ + public MutableDateTime toMutableDateTime(DateTimeZone zone) { + Chronology chrono = DateTimeUtils.getChronology(getChronology()); + chrono = chrono.withZone(zone); + return new MutableDateTime(getMillis(), chrono); + } + + /** + * Get this object as a MutableDateTime. + * + * @param chronology chronology to apply, or ISOChronology if null + * @return a MutableDateTime using the same millis + */ + public MutableDateTime toMutableDateTime(Chronology chronology) { + return new MutableDateTime(getMillis(), chronology); + } + + //----------------------------------------------------------------------- + /** + * Get the date time as a java.util.Date. + * + * @return a Date initialised with this datetime + */ + public Date toDate() { + return new Date(getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on the millisecond instant and the Chronology. + *

+ * All ReadableInstant instances are accepted. + *

+ * See {@link #isEqual(ReadableInstant)} for an equals method that + * ignores the Chronology. + * + * @param readableInstant a readable instant to check against + * @return true if millisecond and chronology are equal, false if + * not or the instant is null or of an incorrect type + */ + public boolean equals(Object readableInstant) { + // must be to fulfil ReadableInstant contract + if (this == readableInstant) { + return true; + } + if (readableInstant instanceof ReadableInstant) { + ReadableInstant otherInstant = (ReadableInstant) readableInstant; + if (getMillis() == otherInstant.getMillis()) { + Chronology chrono = getChronology(); + if (chrono == otherInstant.getChronology()) { + return true; + } + if (chrono != null && chrono.equals(otherInstant.getChronology())) { + return true; + } + } + } + return false; + } + + /** + * Gets a hash code for the instant as defined in ReadableInstant. + * + * @return a suitable hash code + */ + public int hashCode() { + // must be to fulfil ReadableInstant contract + return + ((int) (getMillis() ^ (getMillis() >>> 32))) + + (getChronology().hashCode()); + } + + /** + * Compares this object with the specified object for ascending + * millisecond instant order. This ordering is inconsistent with + * equals, as it ignores the Chronology. + *

+ * All ReadableInstant instances are accepted. + * + * @param instant a readable instant to check against + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object type is not supported + */ + public int compareTo(Object instant) { + if (this == instant) { + return 0; + } + + ReadableInstant otherInstant = (ReadableInstant) instant; + + long otherMillis = otherInstant.getMillis(); + long thisMillis = getMillis(); + + // cannot do (thisMillis - otherMillis) as can overflow + if (thisMillis == otherMillis) { + return 0; + } + if (thisMillis < otherMillis) { + return -1; + } else { + return 1; + } + } + + //----------------------------------------------------------------------- + /** + * Is this instant after the millisecond instant passed in + * comparing solely by millisecond. + * + * @param instant a millisecond instant to check against + * @return true if this instant is after the instant passed in + */ + public boolean isAfter(long instant) { + return (getMillis() > instant); + } + + /** + * Is this instant after the current instant + * comparing solely by millisecond. + * + * @return true if this instant is after the current instant + */ + public boolean isAfterNow() { + return isAfter(DateTimeUtils.currentTimeMillis()); + } + + /** + * Is this instant after the instant passed in + * comparing solely by millisecond. + * + * @param instant an instant to check against, null means now + * @return true if the instant is after the instant passed in + */ + public boolean isAfter(ReadableInstant instant) { + long instantMillis = DateTimeUtils.getInstantMillis(instant); + return isAfter(instantMillis); + } + + //----------------------------------------------------------------------- + /** + * Is this instant before the millisecond instant passed in + * comparing solely by millisecond. + * + * @param instant a millisecond instant to check against + * @return true if this instant is before the instant passed in + */ + public boolean isBefore(long instant) { + return (getMillis() < instant); + } + + /** + * Is this instant before the current instant + * comparing solely by millisecond. + * + * @return true if this instant is before the current instant + */ + public boolean isBeforeNow() { + return isBefore(DateTimeUtils.currentTimeMillis()); + } + + /** + * Is this instant before the instant passed in + * comparing solely by millisecond. + * + * @param instant an instant to check against, null means now + * @return true if the instant is before the instant passed in + */ + public boolean isBefore(ReadableInstant instant) { + long instantMillis = DateTimeUtils.getInstantMillis(instant); + return isBefore(instantMillis); + } + + //----------------------------------------------------------------------- + /** + * Is this instant equal to the millisecond instant passed in + * comparing solely by millisecond. + * + * @param instant a millisecond instant to check against + * @return true if this instant is before the instant passed in + */ + public boolean isEqual(long instant) { + return (getMillis() == instant); + } + + /** + * Is this instant equal to the current instant + * comparing solely by millisecond. + * + * @return true if this instant is before the current instant + */ + public boolean isEqualNow() { + return isEqual(DateTimeUtils.currentTimeMillis()); + } + + /** + * Is this instant equal to the instant passed in + * comparing solely by millisecond. + * + * @param instant an instant to check against, null means now + * @return true if the instant is equal to the instant passed in + */ + public boolean isEqual(ReadableInstant instant) { + long instantMillis = DateTimeUtils.getInstantMillis(instant); + return isEqual(instantMillis); + } + + //----------------------------------------------------------------------- + /** + * Output the date time in ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZ). + * + * @return ISO8601 time formatted string. + */ + public String toString() { + return ISODateTimeFormat.getInstance().dateTime().print(this); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/AbstractInterval.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/AbstractInterval.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/AbstractInterval.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,448 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeUtils; +import org.joda.time.Duration; +import org.joda.time.Interval; +import org.joda.time.MutableInterval; +import org.joda.time.Period; +import org.joda.time.PeriodType; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadableInterval; +import org.joda.time.field.FieldUtils; +import org.joda.time.format.DateTimePrinter; +import org.joda.time.format.ISODateTimeFormat; + +/** + * AbstractInterval provides the common behaviour for time intervals. + *

+ * This class should generally not be used directly by API users. The + * {@link ReadableInterval} interface should be used when different + * kinds of intervals are to be referenced. + *

+ * AbstractInterval subclasses may be mutable and not thread-safe. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class AbstractInterval implements ReadableInterval { + + /** + * Constructor. + */ + protected AbstractInterval() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Validates an interval. + * + * @param start the start instant in milliseconds + * @param end the end instant in milliseconds + * @throws IllegalArgumentException if the interval is invalid + */ + protected void checkInterval(long start, long end) { + if (end < start) { + throw new IllegalArgumentException("The end instant must be greater or equal to the start"); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the start of this time interval, which is inclusive, as a DateTime. + * + * @return the start of the time interval + */ + public DateTime getStart() { + return new DateTime(getStartMillis(), getChronology()); + } + + /** + * Gets the end of this time interval, which is exclusive, as a DateTime. + * + * @return the end of the time interval + */ + public DateTime getEnd() { + return new DateTime(getEndMillis(), getChronology()); + } + + //----------------------------------------------------------------------- + /** + * Does this time interval contain the specified millisecond instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param millisInstant the instant to compare to, + * millisecond instant from 1970-01-01T00:00:00Z + * @return true if this time interval contains the millisecond + */ + public boolean contains(long millisInstant) { + long thisStart = getStartMillis(); + long thisEnd = getEndMillis(); + return (millisInstant >= thisStart && millisInstant < thisEnd); + } + + /** + * Does this time interval contain the current instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @return true if this time interval contains the current instant + */ + public boolean containsNow() { + return contains(DateTimeUtils.currentTimeMillis()); + } + + /** + * Does this time interval contain the specified instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param instant the instant, null means now + * @return true if this time interval contains the instant + */ + public boolean contains(ReadableInstant instant) { + if (instant == null) { + return containsNow(); + } + return contains(instant.getMillis()); + } + + /** + * Does this time interval contain the specified time interval completely. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the time interval to compare to, null means now + * @return true if this time interval contains the time interval + */ + public boolean contains(ReadableInterval interval) { + if (interval == null) { + return containsNow(); + } + long otherStart = interval.getStartMillis(); + long otherEnd = interval.getEndMillis(); + long thisStart = getStartMillis(); + long thisEnd = getEndMillis(); + return (otherStart >= thisStart && otherStart < thisEnd && otherEnd <= thisEnd); + } + + /** + * Does this time interval overlap the specified time interval. + *

+ * The intervals overlap if at least some of the time interval is in common. + * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the time interval to compare to, null means now + * @return true if the time intervals overlap + */ + public boolean overlaps(ReadableInterval interval) { + if (interval == null) { + return containsNow(); + } + long otherStart = interval.getStartMillis(); + long otherEnd = interval.getEndMillis(); + long thisStart = getStartMillis(); + long thisEnd = getEndMillis(); + return (thisStart < otherEnd && otherStart < thisEnd); + } + + //----------------------------------------------------------------------- + /** + * Is this time interval before the specified millisecond instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param millisInstant the instant to compare to, + * millisecond instant from 1970-01-01T00:00:00Z + * @return true if this time interval is before the instant + */ + public boolean isBefore(long millisInstant) { + return (getEndMillis() <= millisInstant); + } + + /** + * Is this time interval before the current instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @return true if this time interval is before the current instant + */ + public boolean isBeforeNow() { + return isBefore(DateTimeUtils.currentTimeMillis()); + } + + /** + * Is this time interval before the specified instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param instant the instant to compare to, null means now + * @return true if this time interval is before the instant + */ + public boolean isBefore(ReadableInstant instant) { + if (instant == null) { + return isBeforeNow(); + } + return isBefore(instant.getMillis()); + } + + /** + * Is this time interval entirely before the specified instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the interval to compare to, null means now + * @return true if this time interval is before the interval specified + */ + public boolean isBefore(ReadableInterval interval) { + if (interval == null) { + return isBeforeNow(); + } + return isBefore(interval.getStartMillis()); + } + + //----------------------------------------------------------------------- + /** + * Is this time interval after the specified millisecond instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param millisInstant the instant to compare to, + * millisecond instant from 1970-01-01T00:00:00Z + * @return true if this time interval is after the instant + */ + public boolean isAfter(long millisInstant) { + return (getStartMillis() > millisInstant); + } + + /** + * Is this time interval after the current instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @return true if this time interval is after the current instant + */ + public boolean isAfterNow() { + return isAfter(DateTimeUtils.currentTimeMillis()); + } + + /** + * Is this time interval after the specified instant. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param instant the instant to compare to, null means now + * @return true if this time interval is after the instant + */ + public boolean isAfter(ReadableInstant instant) { + if (instant == null) { + return isAfterNow(); + } + return isAfter(instant.getMillis()); + } + + /** + * Is this time interval entirely after the specified interval. + *

+ * Intervals are inclusive of the start instant and exclusive of the end. + * + * @param interval the interval to compare to, null means now + * @return true if this time interval is after the interval specified + */ + public boolean isAfter(ReadableInterval interval) { + if (interval == null) { + return isAfterNow(); + } + return isAfter(interval.getEndMillis()); + } + + //----------------------------------------------------------------------- + /** + * Get this interval as an immutable Interval object. + * + * @return the interval as an Interval object + */ + public Interval toInterval() { + return new Interval(getStartMillis(), getEndMillis(), getChronology()); + } + + /** + * Get this time interval as a MutableInterval. + *

+ * This will always return a new MutableInterval with the same interval. + * + * @return the time interval as a MutableInterval object + */ + public MutableInterval toMutableInterval() { + return new MutableInterval(getStartMillis(), getEndMillis(), getChronology()); + } + + //----------------------------------------------------------------------- + /** + * Gets the duration of this time interval in milliseconds. + *

+ * The duration is equal to the end millis minus the start millis. + * + * @return the duration of the time interval in milliseconds + * @throws ArithmeticException if the duration exceeds the capacity of a long + */ + public long toDurationMillis() { + return FieldUtils.safeAdd(getEndMillis(), -getStartMillis()); + } + + /** + * Gets the duration of this time interval. + *

+ * The duration is equal to the end millis minus the start millis. + * + * @return the duration of the time interval + * @throws ArithmeticException if the duration exceeds the capacity of a long + */ + public Duration toDuration() { + long durMillis = toDurationMillis(); + if (durMillis == 0) { + return Duration.ZERO; + } else { + return new Duration(durMillis); + } + } + + //----------------------------------------------------------------------- + /** + * Converts the duration of the interval to a Period using the + * All period type. + *

+ * This method should be used to exract the field values describing the + * difference between the start and end instants. + * + * @return a time period derived from the interval + */ + public Period toPeriod() { + return new Period(getStartMillis(), getEndMillis(), getChronology()); + } + + /** + * Converts the duration of the interval to a Period using the + * specified period type. + *

+ * This method should be used to exract the field values describing the + * difference between the start and end instants. + * + * @param type the requested type of the duration, null means AllType + * @return a time period derived from the interval + */ + public Period toPeriod(PeriodType type) { + return new Period(getStartMillis(), getEndMillis(), type, getChronology()); + } + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on start and end millis plus the chronology. + * All ReadableInterval instances are accepted. + *

+ * To compare the duration of two time intervals, use {@link #toDuration()} + * to get the durations and compare those. + * + * @param readableInterval a readable interval to check against + * @return true if the start and end millis are equal + */ + public boolean equals(Object readableInterval) { + if (this == readableInterval) { + return true; + } + if (readableInterval instanceof ReadableInterval == false) { + return false; + } + ReadableInterval other = (ReadableInterval) readableInterval; + return (getStartMillis() == other.getStartMillis() && + getEndMillis() == other.getEndMillis() && + getChronology() == other.getChronology()); + } + + /** + * Hashcode compatible with equals method. + * + * @return suitable hashcode + */ + public int hashCode() { + long start = getStartMillis(); + long end = getEndMillis(); + int result = 97; + result = 31 * result + ((int) (start ^ (start >>> 32))); + result = 31 * result + ((int) (end ^ (end >>> 32))); + result = 31 * result + getChronology().hashCode(); + return result; + } + + /** + * Output a string in ISO8601 interval format. + * + * @return re-parsable string + */ + public String toString() { + DateTimePrinter printer = ISODateTimeFormat.getInstance().dateHourMinuteSecondFraction(); + StringBuffer buf = new StringBuffer(48); + printer.printTo(buf, getStartMillis(), getChronology()); + buf.append('/'); + printer.printTo(buf, getEndMillis(), getChronology()); + return buf.toString(); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/AbstractPartial.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/AbstractPartial.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/AbstractPartial.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,313 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadablePartial; + +/** + * AbstractPartial provides a standard base implementation of most methods + * in the ReadablePartial interface. + *

+ * Calculations on are performed using a {@link Chronology}. + * This chronology is set to be in the UTC time zone for all calculations. + *

+ * The methods on this class uses {@link ReadablePartial#size()}, + * {@link ReadablePartial#getField(int)} and {@link ReadablePartial#getValue(int)} + * to calculate their results. Subclasses may have a better implementation. + *

+ * AbstractPartial allows subclasses may be mutable and not thread-safe. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class AbstractPartial implements ReadablePartial { + + //----------------------------------------------------------------------- + /** + * Constructor. + */ + protected AbstractPartial() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the field for a specific index in the chronology specified. + *

+ * This method must not use any instance variables. + * + * @param index the index to retrieve + * @param chrono the chronology to use + * @return the field + * @throws IndexOutOfBoundsException if the index is invalid + */ + protected abstract DateTimeField getField(int index, Chronology chrono); + + //----------------------------------------------------------------------- + /** + * Gets the field type at the specifed index. + * + * @param index the index + * @return the field type + * @throws IndexOutOfBoundsException if the index is invalid + */ + public DateTimeFieldType getFieldType(int index) { + return getField(index, getChronology()).getType(); + } + + /** + * Gets an array of the field types that this partial supports. + *

+ * The fields are returned largest to smallest, for example Hour, Minute, Second. + * + * @return the fields supported in an array that may be altered, largest to smallest + */ + public DateTimeFieldType[] getFieldTypes() { + DateTimeFieldType[] result = new DateTimeFieldType[size()]; + for (int i = 0; i < result.length; i++) { + result[i] = getFieldType(i); + } + return result; + } + + /** + * Gets the field at the specifed index. + * + * @param index the index + * @return the field + * @throws IndexOutOfBoundsException if the index is invalid + */ + public DateTimeField getField(int index) { + return getField(index, getChronology()); + } + + /** + * Gets an array of the fields that this partial supports. + *

+ * The fields are returned largest to smallest, for example Hour, Minute, Second. + * + * @return the fields supported in an array that may be altered, largest to smallest + */ + public DateTimeField[] getFields() { + DateTimeField[] result = new DateTimeField[size()]; + for (int i = 0; i < result.length; i++) { + result[i] = getField(i); + } + return result; + } + + /** + * Gets an array of the value of each of the fields that this partial supports. + *

+ * The fields are returned largest to smallest, for example Hour, Minute, Second. + * Each value corresponds to the same array index as getFields() + * + * @return the current values of each field in an array that may be altered, largest to smallest + */ + public int[] getValues() { + int[] result = new int[size()]; + for (int i = 0; i < result.length; i++) { + result[i] = getValue(i); + } + return result; + } + + //----------------------------------------------------------------------- + /** + * Get the value of one of the fields of a datetime. + *

+ * The field specified must be one of those that is supported by the partial. + * + * @param type a DateTimeFieldType instance that is supported by this partial + * @return the value of that field + * @throws IllegalArgumentException if the field is null or not supported + */ + public int get(DateTimeFieldType type) { + return getValue(indexOfSupported(type)); + } + + /** + * Checks whether the field specified is supported by this partial. + * + * @param type the type to check, may be null which returns false + * @return true if the field is supported + */ + public boolean isSupported(DateTimeFieldType type) { + return (indexOf(type) != -1); + } + + /** + * Gets the index of the specified field, or -1 if the field is unsupported. + * + * @param type the type to check, may be null which returns -1 + * @return the index of the field, -1 if unsupported + */ + public int indexOf(DateTimeFieldType type) { + for (int i = 0, isize = size(); i < isize; i++) { + if (getFieldType(i) == type) { + return i; + } + } + return -1; + } + + /** + * Gets the index of the specified field, throwing an exception if the + * field is unsupported. + * + * @param type the type to check, may be null which returns -1 + * @return the index of the field, -1 if unsupported + * @throws IllegalArgumentException if the field is null or not supported + */ + protected int indexOfSupported(DateTimeFieldType type) { + int index = indexOf(type); + if (index == -1) { + throw new IllegalArgumentException("Field '" + type + "' is not supported"); + } + return index; + } + + //----------------------------------------------------------------------- + /** + * Converts this partial to a full datetime using the specified time zone and + * filing in any gaps using the current datetime. + *

+ * This method obtains the current datetime, creates a chronology from that + * on this instance plus the time zone specified, and then sets the fields + * from this instant on top. + *

+ * For example, if this partial represents a time, then the result of this + * method will be the datetime from the specified base instant plus the + * time from this partial. + * + * @param zone the zone to use, null means default + * @return the combined datetime + */ + public DateTime toDateTime(DateTimeZone zone) { + Chronology chrono = getChronology().withZone(zone); + long instantMillis = DateTimeUtils.currentTimeMillis(); + long resolved = chrono.set(this, instantMillis); + return new DateTime(resolved, chrono); + } + + /** + * Resolves this partial against another complete instant to create a new + * full instant. The combination is performed using the chronology of the + * specified instant. + *

+ * For example, if this partial represents a time, then the result of this + * method will be the datetime from the specified base instant plus the + * time from this partial. + * + * @param baseInstant the instant that provides the missing fields, null means now + * @return the combined datetime + */ + public DateTime toDateTime(ReadableInstant baseInstant) { + Chronology chrono = DateTimeUtils.getInstantChronology(baseInstant); + long instantMillis = DateTimeUtils.getInstantMillis(baseInstant); + long resolved = chrono.set(this, instantMillis); + return new DateTime(resolved, chrono); + } + + //----------------------------------------------------------------------- + /** + * Compares this ReadablePartial with another returning true if the chronology, + * field types and values are equal. + * + * @param partial an object to check against + * @return true if fields and values are equal + */ + public boolean equals(Object partial) { + if (this == partial) { + return true; + } + if (partial instanceof ReadablePartial == false) { + return false; + } + ReadablePartial other = (ReadablePartial) partial; + if (size() != other.size()) { + return false; + } + for (int i = 0, isize = size(); i < isize; i++) { + if (getValue(i) != other.getValue(i) || getFieldType(i) != other.getFieldType(i)) { + return false; + } + } + return (getChronology() == other.getChronology()); + } + + /** + * Gets a hash code for the ReadablePartial that is compatible with the + * equals method. + * + * @return a suitable hash code + */ + public int hashCode() { + int total = 157; + for (int i = 0, isize = size(); i < isize; i++) { + total = 23 * total + getValue(i); + total = 23 * total + getFieldType(i).hashCode(); + } + total += getChronology().hashCode(); + return total; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/AbstractPeriod.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/AbstractPeriod.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/AbstractPeriod.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,232 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import org.joda.time.DurationFieldType; +import org.joda.time.MutablePeriod; +import org.joda.time.Period; +import org.joda.time.ReadablePeriod; +import org.joda.time.format.ISOPeriodFormat; + +/** + * AbstractPeriod provides the common behaviour for period classes. + *

+ * This class should generally not be used directly by API users. The + * {@link ReadablePeriod} interface should be used when different + * kinds of periods are to be referenced. + *

+ * AbstractPeriod subclasses may be mutable and not thread-safe. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class AbstractPeriod implements ReadablePeriod { + + /** + * Constructor. + */ + protected AbstractPeriod() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets an array of the field types that this period supports. + *

+ * The fields are returned largest to smallest, for example Hours, Minutes, Seconds. + * + * @return the fields supported in an array that may be altered, largest to smallest + */ + public DurationFieldType[] getFieldTypes() { + DurationFieldType[] result = new DurationFieldType[size()]; + for (int i = 0; i < result.length; i++) { + result[i] = getFieldType(i); + } + return result; + } + + /** + * Gets an array of the value of each of the fields that this period supports. + *

+ * The fields are returned largest to smallest, for example Hours, Minutes, Seconds. + * Each value corresponds to the same array index as getFields() + * + * @return the current values of each field in an array that may be altered, largest to smallest + */ + public int[] getValues() { + int[] result = new int[size()]; + for (int i = 0; i < result.length; i++) { + result[i] = getValue(i); + } + return result; + } + + //----------------------------------------------------------------------- + /** + * Gets the value of one of the fields. + *

+ * If the field type specified is not supported by the period then zero + * is returned. + * + * @param type the field type to query, null returns zero + * @return the value of that field, zero if field not supported + */ + public int get(DurationFieldType type) { + int index = indexOf(type); + if (index == -1) { + return 0; + } + return getValue(index); + } + + /** + * Checks whether the field specified is supported by this period. + * + * @param type the type to check, may be null which returns false + * @return true if the field is supported + */ + public boolean isSupported(DurationFieldType type) { + return getPeriodType().isSupported(type); + } + + /** + * Gets the index of the field in this period. + * + * @param type the type to check, may be null which returns -1 + * @return the index of -1 if not supported + */ + public int indexOf(DurationFieldType type) { + return getPeriodType().indexOf(type); + } + + //----------------------------------------------------------------------- + /** + * Get this period as an immutable Period object. + * + * @return a Period using the same field set and values + */ + public Period toPeriod() { + return new Period(this); + } + + /** + * Get this object as a MutablePeriod. + *

+ * This will always return a new MutablePeriod with the same fields. + * + * @return a MutablePeriod using the same field set and values + */ + public MutablePeriod toMutablePeriod() { + return new MutablePeriod(this); + } + + //----------------------------------------------------------------------- + /** + * Compares this object with the specified object for equality based + * on the value of each field. All ReadablePeriod instances are accepted. + * + * @param period a readable period to check against + * @return true if all the field values are equal, false if + * not or the period is null or of an incorrect type + */ + public boolean equals(Object period) { + if (this == period) { + return true; + } + if (period instanceof ReadablePeriod == false) { + return false; + } + ReadablePeriod other = (ReadablePeriod) period; + if (size() != other.size()) { + return false; + } + for (int i = 0, isize = size(); i < isize; i++) { + if (getValue(i) != other.getValue(i) || getFieldType(i) != other.getFieldType(i)) { + return false; + } + } + return true; + } + + /** + * Gets a hash code for the period as defined by ReadablePeriod. + * + * @return a hash code + */ + public int hashCode() { + int total = 17; + for (int i = 0, isize = size(); i < isize; i++) { + total = 27 * total + getValue(i); + total = 27 * total + getFieldType(i).hashCode(); + } + return total; + } + + //----------------------------------------------------------------------- + /** + * Gets the value as a String in the ISO8601 duration format. + *

+ * For example, "P6H3M7S" represents 6 hours, 3 minutes, 7 seconds. + *

+ * For more control over the output, see + * {@link org.joda.time.format.PeriodFormatterBuilder PeriodFormatterBuilder}. + * + * @return the value as an ISO8601 string + */ + public String toString() { + return ISOPeriodFormat.getInstance().standard().print(this); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/BaseDateTime.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/BaseDateTime.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/BaseDateTime.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,370 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import java.io.Serializable; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadableDateTime; +import org.joda.time.chrono.ISOChronology; +import org.joda.time.convert.ConverterManager; +import org.joda.time.convert.InstantConverter; + +/** + * BaseDateTime is an abstract implementation of ReadableDateTime that stores + * data in long and Chronology fields. + *

+ * This class should generally not be used directly by API users. + * The {@link ReadableDateTime} interface should be used when different + * kinds of date/time objects are to be referenced. + *

+ * BaseDateTime subclasses may be mutable and not thread-safe. + * + * @author Stephen Colebourne + * @author Kandarp Shah + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class BaseDateTime + extends AbstractDateTime + implements ReadableDateTime, Serializable { + + /** Serialization lock */ + private static final long serialVersionUID = -6728882245981L; + + /** The millis from 1970-01-01T00:00:00Z */ + private long iMillis; + /** The chronology to use */ + private Chronology iChronology; + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the default time zone. + */ + public BaseDateTime() { + this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance()); + } + + /** + * Constructs an instance set to the current system millisecond time + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param zone the time zone, null means default zone + */ + public BaseDateTime(DateTimeZone zone) { + this(DateTimeUtils.currentTimeMillis(), ISOChronology.getInstance(zone)); + } + + /** + * Constructs an instance set to the current system millisecond time + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param chronology the chronology, null means ISOChronology in default zone + */ + public BaseDateTime(Chronology chronology) { + this(DateTimeUtils.currentTimeMillis(), chronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the default time zone. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + public BaseDateTime(long instant) { + this(instant, ISOChronology.getInstance()); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param zone the time zone, null means default zone + */ + public BaseDateTime(long instant, DateTimeZone zone) { + this(instant, ISOChronology.getInstance(zone)); + } + + /** + * Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param chronology the chronology, null means ISOChronology in default zone + */ + public BaseDateTime(long instant, Chronology chronology) { + super(); + iChronology = checkChronology(chronology); + iMillis = checkInstant(instant, iChronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from an Object that represents a datetime, + * forcing the time zone to that specified. + *

+ * If the object contains no chronology, ISOChronology is used. + * If the specified time zone is null, the default zone is used. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object + * @param zone the time zone + * @throws IllegalArgumentException if the instant is invalid + */ + public BaseDateTime(Object instant, DateTimeZone zone) { + super(); + InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant); + Chronology chrono = checkChronology(converter.getChronology(instant, zone)); + iChronology = chrono; + iMillis = checkInstant(converter.getInstantMillis(instant, chrono), chrono); + } + + /** + * Constructs an instance from an Object that represents a datetime, + * using the specified chronology. + *

+ * If the chronology is null, ISO in the default time zone is used. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + * + * @param instant the datetime object + * @param chronology the chronology + * @throws IllegalArgumentException if the instant is invalid + */ + public BaseDateTime(Object instant, Chronology chronology) { + super(); + InstantConverter converter = ConverterManager.getInstance().getInstantConverter(instant); + iChronology = checkChronology(converter.getChronology(instant, chronology)); + iMillis = checkInstant(converter.getInstantMillis(instant, chronology), iChronology); + } + + //----------------------------------------------------------------------- + /** + * Constructs an instance from datetime field values + * using ISOChronology in the default time zone. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + */ + public BaseDateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond) { + this(year, monthOfYear, dayOfMonth, hourOfDay, + minuteOfHour, secondOfMinute, millisOfSecond, ISOChronology.getInstance()); + } + + /** + * Constructs an instance from datetime field values + * using ISOChronology in the specified time zone. + *

+ * If the specified time zone is null, the default zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @param zone the time zone, null means default time zone + */ + public BaseDateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond, + DateTimeZone zone) { + this(year, monthOfYear, dayOfMonth, hourOfDay, + minuteOfHour, secondOfMinute, millisOfSecond, ISOChronology.getInstance(zone)); + } + + /** + * Constructs an instance from datetime field values + * using the specified chronology. + *

+ * If the chronology is null, ISOChronology + * in the default time zone is used. + * + * @param year the year + * @param monthOfYear the month of the year + * @param dayOfMonth the day of the month + * @param hourOfDay the hour of the day + * @param minuteOfHour the minute of the hour + * @param secondOfMinute the second of the minute + * @param millisOfSecond the millisecond of the second + * @param chronology the chronology, null means ISOChronology in default zone + */ + public BaseDateTime( + int year, + int monthOfYear, + int dayOfMonth, + int hourOfDay, + int minuteOfHour, + int secondOfMinute, + int millisOfSecond, + Chronology chronology) { + super(); + iChronology = checkChronology(chronology); + long instant = iChronology.getDateTimeMillis(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + iMillis = checkInstant(instant, iChronology); + } + + //----------------------------------------------------------------------- + /** + * Checks the specified chronology before storing it, potentially altering it. + * This method must not access any instance variables. + *

+ * This implementation converts nulls to ISOChronology in the default zone. + * + * @param chronology the chronology to use, may be null + * @return the chronology to store in this datetime, not null + */ + protected Chronology checkChronology(Chronology chronology) { + return DateTimeUtils.getChronology(chronology); + } + + /** + * Checks the specified instant before storing it, potentially altering it. + * This method must not access any instance variables. + *

+ * This implementation simply returns the instant. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @param chronology the chronology to use, not null + * @return the instant to store in this datetime + */ + protected long checkInstant(long instant, Chronology chronology) { + return instant; + } + + //----------------------------------------------------------------------- + /** + * Gets the milliseconds of the datetime instant from the Java epoch + * of 1970-01-01T00:00:00Z. + * + * @return the number of milliseconds since 1970-01-01T00:00:00Z + */ + public long getMillis() { + return iMillis; + } + + /** + * Gets the chronology of the datetime. + * + * @return the Chronology that the datetime is using + */ + public Chronology getChronology() { + return iChronology; + } + + //----------------------------------------------------------------------- + /** + * Sets the milliseconds of the datetime. + *

+ * All changes to the millisecond field occurs via this method. + * Override and block this method to make a subclass immutable. + * + * @param instant the milliseconds since 1970-01-01T00:00:00Z to set the datetime to + */ + protected void setMillis(long instant) { + iMillis = checkInstant(instant, iChronology); + } + + /** + * Sets the chronology of the datetime. + *

+ * All changes to the chronology field occurs via this method. + * Override and block this method to make a subclass immutable. + * + * @param chronology the chronology to set + */ + protected void setChronology(Chronology chronology) { + iChronology = checkChronology(chronology); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/BaseDuration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/BaseDuration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/BaseDuration.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,265 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import java.io.Serializable; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.Interval; +import org.joda.time.Period; +import org.joda.time.PeriodType; +import org.joda.time.ReadableDuration; +import org.joda.time.ReadableInstant; +import org.joda.time.convert.ConverterManager; +import org.joda.time.convert.DurationConverter; +import org.joda.time.field.FieldUtils; + +/** + * BaseDuration is an abstract implementation of ReadableDuration that stores + * data in a long duration milliseconds field. + *

+ * This class should generally not be used directly by API users. + * The {@link ReadableDuration} interface should be used when different + * kinds of duration objects are to be referenced. + *

+ * BaseDuration subclasses may be mutable and not thread-safe. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class BaseDuration + extends AbstractDuration + implements ReadableDuration, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 2581698638990L; + + /** The duration length */ + private long iMillis; + + /** + * Creates a duration from the given millisecond duration. + * + * @param duration the duration, in milliseconds + */ + protected BaseDuration(long duration) { + super(); + iMillis = duration; + } + + /** + * Creates a duration from the given interval endpoints. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @throws ArithmeticException if the duration exceeds a 64 bit long + */ + protected BaseDuration(long startInstant, long endInstant) { + super(); + iMillis = FieldUtils.safeAdd(endInstant, -startInstant); + } + + /** + * Creates a duration from the given interval endpoints. + * + * @param start interval start, null means now + * @param end interval end, null means now + * @throws ArithmeticException if the duration exceeds a 64 bit long + */ + protected BaseDuration(ReadableInstant start, ReadableInstant end) { + super(); + if (start == end) { + iMillis = 0L; + } else { + long startMillis = DateTimeUtils.getInstantMillis(start); + long endMillis = DateTimeUtils.getInstantMillis(end); + iMillis = FieldUtils.safeAdd(endMillis, -startMillis); + } + } + + /** + * Creates a duration from the specified object using the + * {@link org.joda.time.convert.ConverterManager ConverterManager}. + * + * @param duration duration to convert + * @throws IllegalArgumentException if duration is invalid + */ + protected BaseDuration(Object duration) { + super(); + DurationConverter converter = ConverterManager.getInstance().getDurationConverter(duration); + iMillis = converter.getDurationMillis(duration); + } + + //----------------------------------------------------------------------- + /** + * Gets the length of this duration in milliseconds. + * + * @return the length of the duration in milliseconds. + */ + public long getMillis() { + return iMillis; + } + + //----------------------------------------------------------------------- + /** + * Sets the length of this duration in milliseconds. + * + * @param duration the new length of the duration + */ + protected void setMillis(long duration) { + iMillis = duration; + } + + //----------------------------------------------------------------------- + /** + * Converts this duration to a Period instance using the specified period type + * and the ISO chronology. + *

+ * Only precise fields in the period type will be used. + * At most these are hours, minutes, seconds and millis - the period + * type may restrict the selection further. + *

+ * For more control over the conversion process, you must pair the duration with + * an instant, see {@link #toPeriodFrom(ReadableInstant, PeriodType)}. + * + * @param type the period type to use, null means standard + * @return a Period created using the millisecond duration from this instance + */ + public Period toPeriod(PeriodType type) { + return new Period(getMillis(), type); + } + + /** + * Converts this duration to a Period instance using the standard period type + * and the specified chronology. + *

+ * Only precise fields in the period type will be used. + * Exactly which fields are precise depends on the chronology. + * Only the time fields are precise for ISO chronology with a time zone. + * However, ISO UTC also has precise days and weeks. + *

+ * For more control over the conversion process, you must pair the duration with + * an instant, see {@link #toPeriodFrom(ReadableInstant)}. + * + * @param chrono the chronology to use, null means ISO default + * @return a Period created using the millisecond duration from this instance + */ + public Period toPeriod(Chronology chrono) { + return new Period(getMillis(), chrono); + } + + /** + * Converts this duration to a Period instance using the specified period type + * and chronology. + *

+ * Only precise fields in the period type will be used. + * Exactly which fields are precise depends on the chronology. + * Only the time fields are precise for ISO chronology with a time zone. + * However, ISO UTC also has precise days and weeks. + *

+ * For more control over the conversion process, you must pair the duration with + * an instant, see {@link #toPeriodFrom(ReadableInstant, PeriodType)}. + * + * @param type the period type to use, null means standard + * @param chrono the chronology to use, null means ISO default + * @return a Period created using the millisecond duration from this instance + */ + public Period toPeriod(PeriodType type, Chronology chrono) { + return new Period(getMillis(), type, chrono); + } + + /** + * Converts this duration to a Period instance by adding the duration to a start + * instant to obtain an interval using the standard period type. + *

+ * This conversion will determine the fields of a period accurately. + * The results are based on the instant millis, the chronology of the instant, + * the standard period type and the length of this duration. + * + * @param startInstant the instant to calculate the period from, null means now + * @return a Period created using the millisecond duration from this instance + */ + public Period toPeriodFrom(ReadableInstant startInstant) { + return new Period(startInstant, this); + } + + /** + * Converts this duration to a Period instance by adding the duration to a start + * instant to obtain an interval. + *

+ * This conversion will determine the fields of a period accurately. + * The results are based on the instant millis, the chronology of the instant, + * the period type and the length of this duration. + * + * @param startInstant the instant to calculate the period from, null means now + * @param type the period type determining how to split the duration into fields, null means All type + * @return a Period created using the millisecond duration from this instance + */ + public Period toPeriodFrom(ReadableInstant startInstant, PeriodType type) { + return new Period(startInstant, this, type); + } + + /** + * Converts this duration to an Interval starting at the specified instant. + * + * @param startInstant the instant to start the instant from, null means now + * @return an Interval starting at the specified instant + */ + public Interval toIntervalFrom(ReadableInstant startInstant) { + return new Interval(startInstant, this); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/BaseInterval.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/BaseInterval.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/BaseInterval.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,291 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import java.io.Serializable; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.MutableInterval; +import org.joda.time.ReadWritableInterval; +import org.joda.time.ReadableDuration; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadableInterval; +import org.joda.time.ReadablePeriod; +import org.joda.time.convert.ConverterManager; +import org.joda.time.convert.IntervalConverter; +import org.joda.time.field.FieldUtils; + +/** + * BaseInterval is an abstract implementation of ReadableInterval that stores + * data in two long millisecond fields. + *

+ * This class should generally not be used directly by API users. + * The {@link ReadableInterval} interface should be used when different + * kinds of interval objects are to be referenced. + *

+ * BaseInterval subclasses may be mutable and not thread-safe. + * + * @author Brian S O'Neill + * @author Sean Geoghegan + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class BaseInterval + extends AbstractInterval + implements ReadableInterval, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 576586928732749278L; + + /** The chronology of the interval */ + private Chronology iChronology; + /** The start of the interval */ + private long iStartMillis; + /** The end of the interval */ + private long iEndMillis; + + /** + * Constructs an interval from a start and end instant. + * + * @param startInstant start of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @param endInstant end of this interval, as milliseconds from 1970-01-01T00:00:00Z. + * @param chrono the chronology to use, null is ISO default + * @throws IllegalArgumentException if the end is before the start + */ + protected BaseInterval(long startInstant, long endInstant, Chronology chrono) { + super(); + iChronology = DateTimeUtils.getChronology(chrono); + checkInterval(startInstant, endInstant); + iStartMillis = startInstant; + iEndMillis = endInstant; + } + + /** + * Constructs an interval from a start and end instant. + * + * @param start start of this interval, null means now + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + */ + protected BaseInterval(ReadableInstant start, ReadableInstant end) { + super(); + if (start == null && end == null) { + iStartMillis = iEndMillis = DateTimeUtils.currentTimeMillis(); + iChronology = Chronology.getISO(); + } else { + iChronology = DateTimeUtils.getInstantChronology(start); + iStartMillis = DateTimeUtils.getInstantMillis(start); + iEndMillis = DateTimeUtils.getInstantMillis(end); + checkInterval(iStartMillis, iEndMillis); + } + } + + /** + * Constructs an interval from a start instant and a duration. + * + * @param start start of this interval, null means now + * @param duration the duration of this interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + protected BaseInterval(ReadableInstant start, ReadableDuration duration) { + super(); + iChronology = DateTimeUtils.getInstantChronology(start); + iStartMillis = DateTimeUtils.getInstantMillis(start); + long durationMillis = DateTimeUtils.getDurationMillis(duration); + iEndMillis = FieldUtils.safeAdd(iStartMillis, durationMillis); + checkInterval(iStartMillis, iEndMillis); + } + + /** + * Constructs an interval from a millisecond duration and an end instant. + * + * @param duration the duration of this interval, null means zero length + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + protected BaseInterval(ReadableDuration duration, ReadableInstant end) { + super(); + iChronology = DateTimeUtils.getInstantChronology(end); + iEndMillis = DateTimeUtils.getInstantMillis(end); + long durationMillis = DateTimeUtils.getDurationMillis(duration); + iStartMillis = FieldUtils.safeAdd(iEndMillis, -durationMillis); + checkInterval(iStartMillis, iEndMillis); + } + + /** + * Constructs an interval from a start instant and a time period. + *

+ * When forming the interval, the chronology from the instant is used + * if present, otherwise the chronology of the period is used. + * + * @param start start of this interval, null means now + * @param period the period of this interval, null means zero length + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the end instant exceeds the capacity of a long + */ + protected BaseInterval(ReadableInstant start, ReadablePeriod period) { + super(); + Chronology chrono = DateTimeUtils.getInstantChronology(start); + iChronology = chrono; + iStartMillis = DateTimeUtils.getInstantMillis(start); + if (period == null) { + iEndMillis = iStartMillis; + } else { + iEndMillis = chrono.add(period, iStartMillis, 1); + } + checkInterval(iStartMillis, iEndMillis); + } + + /** + * Constructs an interval from a time period and an end instant. + *

+ * When forming the interval, the chronology from the instant is used + * if present, otherwise the chronology of the period is used. + * + * @param period the period of this interval, null means zero length + * @param end end of this interval, null means now + * @throws IllegalArgumentException if the end is before the start + * @throws ArithmeticException if the start instant exceeds the capacity of a long + */ + protected BaseInterval(ReadablePeriod period, ReadableInstant end) { + super(); + Chronology chrono = DateTimeUtils.getInstantChronology(end); + iChronology = chrono; + iEndMillis = DateTimeUtils.getInstantMillis(end); + if (period == null) { + iStartMillis = iEndMillis; + } else { + iStartMillis = chrono.add(period, iEndMillis, -1); + } + checkInterval(iStartMillis, iEndMillis); + } + + /** + * Constructs a time interval converting or copying from another object + * that describes an interval. + * + * @param interval the time interval to copy + * @param chrono the chronology to use, null means let converter decide + * @throws IllegalArgumentException if the interval is invalid + */ + protected BaseInterval(Object interval, Chronology chrono) { + super(); + IntervalConverter converter = ConverterManager.getInstance().getIntervalConverter(interval); + if (converter.isReadableInterval(interval, chrono)) { + ReadableInterval input = (ReadableInterval) interval; + iChronology = (chrono != null ? chrono : input.getChronology()); + iStartMillis = input.getStartMillis(); + iEndMillis = input.getEndMillis(); + } else if (this instanceof ReadWritableInterval) { + converter.setInto((ReadWritableInterval) this, interval, chrono); + } else { + MutableInterval mi = new MutableInterval(); + converter.setInto(mi, interval, chrono); + iChronology = mi.getChronology(); + iStartMillis = mi.getStartMillis(); + iEndMillis = mi.getEndMillis(); + } + checkInterval(iStartMillis, iEndMillis); + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology of this interval. + * + * @return the chronology + */ + public Chronology getChronology() { + return iChronology; + } + + /** + * Gets the start of this time interval which is inclusive. + * + * @return the start of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + */ + public long getStartMillis() { + return iStartMillis; + } + + /** + * Gets the end of this time interval which is exclusive. + * + * @return the end of the time interval, + * millisecond instant from 1970-01-01T00:00:00Z + */ + public long getEndMillis() { + return iEndMillis; + } + + //----------------------------------------------------------------------- + /** + * Sets this interval from two millisecond instants and a chronology. + * + * @param startInstant the start of the time interval + * @param endInstant the start of the time interval + * @param chrono the chronology, not null + * @throws IllegalArgumentException if the end is before the start + */ + protected void setInterval(long startInstant, long endInstant, Chronology chrono) { + checkInterval(startInstant, endInstant); + iStartMillis = startInstant; + iEndMillis = endInstant; + iChronology = DateTimeUtils.getChronology(chrono); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/BasePartial.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/BasePartial.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/BasePartial.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,296 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import java.io.Serializable; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadablePartial; +import org.joda.time.convert.ConverterManager; +import org.joda.time.convert.PartialConverter; + +/** + * BasePartial is an abstract implementation of ReadablePartial that stores + * data in array and Chronology fields. + *

+ * This class should generally not be used directly by API users. + * The {@link org.joda.time.ReadablePeriod} interface should be used when different + * kinds of partial objects are to be referenced. + *

+ * BasePartial subclasses may be mutable and not thread-safe. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class BasePartial + extends AbstractPartial + implements ReadablePartial, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = 2353678632973660L; + + /** The chronology in use */ + private Chronology iChronology; + /** The values of each field in this partial */ + private int[] iValues; + + //----------------------------------------------------------------------- + /** + * Constructs a partial with the current time, using ISOChronology in + * the default zone to extract the fields. + *

+ * The constructor uses the default time zone, resulting in the local time + * being initialised. Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + */ + protected BasePartial() { + this(DateTimeUtils.currentTimeMillis(), null); + } + + /** + * Constructs a partial with the current time, using the specified chronology + * and zone to extract the fields. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param chronology the chronology, null means ISOChronology in the default zone + */ + protected BasePartial(Chronology chronology) { + this(DateTimeUtils.currentTimeMillis(), chronology); + } + + /** + * Constructs a partial extracting the partial fields from the specified + * milliseconds using the ISOChronology in the default zone. + *

+ * The constructor uses the default time zone, resulting in the local time + * being initialised. Once the constructor is complete, all further calculations + * are performed without reference to a timezone (by switching to UTC). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + */ + protected BasePartial(long instant) { + this(instant, null); + } + + /** + * Constructs a partial extracting the partial fields from the specified + * milliseconds using the chronology provided. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z + * @param chronology the chronology, null means ISOChronology in the default zone + */ + protected BasePartial(long instant, Chronology chronology) { + super(); + chronology = DateTimeUtils.getChronology(chronology); + iChronology = chronology.withUTC(); + iValues = chronology.get(this, instant); + } + + /** + * Constructs a partial from an Object that represents a time, using the + * specified chronology. + *

+ * The recognised object types are defined in + * {@link org.joda.time.convert.ConverterManager ConverterManager} and + * include ReadableInstant, String, Calendar and Date. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + * + * @param instant the datetime object + * @param chronology the chronology, null means use converter + * @throws IllegalArgumentException if the date is invalid + */ + protected BasePartial(Object instant, Chronology chronology) { + super(); + PartialConverter converter = ConverterManager.getInstance().getPartialConverter(instant); + chronology = converter.getChronology(instant, chronology); + chronology = DateTimeUtils.getChronology(chronology); + iChronology = chronology.withUTC(); + iValues = converter.getPartialValues(this, instant, chronology); + } + + /** + * Constructs a partial with specified time field values and chronology. + *

+ * The constructor uses the time zone of the chronology specified. + * Once the constructor is complete, all further calculations are performed + * without reference to a timezone (by switching to UTC). + *

+ * The array of values is assigned (not cloned) to the new instance. + * + * @param values the new set of values + * @param chronology the chronology, null means ISOChronology in the default zone + * @throws IllegalArgumentException if the values are invalid + */ + protected BasePartial(int[] values, Chronology chronology) { + super(); + chronology = DateTimeUtils.getChronology(chronology); + iChronology = chronology.withUTC(); + chronology.validate(this, values); + iValues = values; + } + + /** + * Private constructor to be used by subclasses only which performs no validation. + *

+ * Data is assigned (not cloned) to the new instance. + * + * @param base the base partial + * @param values the new set of values, not cloned, null means use base + */ + protected BasePartial(BasePartial base, int[] values) { + super(); + iChronology = base.iChronology; + iValues = values; + } + + /** + * Private constructor to be used by subclasses only which performs no validation. + *

+ * Data is assigned (not cloned) to the new instance. + * This should not be used by mutable subclasses. + * + * @param base the base partial + * @param chrono the chronology to use, null means use base + */ + protected BasePartial(BasePartial base, Chronology chrono) { + super(); + iChronology = chrono.withUTC(); + iValues = base.iValues; + } + + //----------------------------------------------------------------------- + /** + * Gets the value of the field at the specifed index. + * + * @param index the index + * @return the value + * @throws IndexOutOfBoundsException if the index is invalid + */ + public int getValue(int index) { + return iValues[index]; + } + + /** + * Gets an array of the value of each of the fields that this partial supports. + *

+ * The fields are returned largest to smallest, for example Hour, Minute, Second. + * Each value corresponds to the same array index as getFields() + * + * @return the current values of each field (cloned), largest to smallest + */ + public int[] getValues() { + return (int[]) iValues.clone(); + } + + /** + * Gets the chronology of the partial which is never null. + *

+ * The {@link Chronology} is the calculation engine behind the partial and + * provides conversion and validation of the fields in a particular calendar system. + * + * @return the chronology, never null + */ + public Chronology getChronology() { + return iChronology; + } + + //----------------------------------------------------------------------- + /** + * Sets the value of the field at the specifed index. + * + * @param index the index + * @param value the value to set + * @throws IndexOutOfBoundsException if the index is invalid + */ + protected void setValue(int index, int value) { + DateTimeField field = getField(index); + iValues = field.set(this, index, iValues, value); + } + + /** + * Sets the values of all fields. + * + * @param values the array of values + */ + protected void setValues(int[] values) { + getChronology().validate(this, values); + iValues = values; + } + + //----------------------------------------------------------------------- + /** + * Converts this object to a DateTime using the current date to fill in the + * missing fields and using the default time zone. + * + * @return the DateTime instance + */ + public DateTime toDateTime() { + return toDateTime((DateTimeZone) null); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/BasePeriod.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/BasePeriod.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/BasePeriod.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,546 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.base; + +import java.io.Serializable; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.Duration; +import org.joda.time.DurationFieldType; +import org.joda.time.MutablePeriod; +import org.joda.time.PeriodType; +import org.joda.time.ReadWritablePeriod; +import org.joda.time.ReadableDuration; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadablePeriod; +import org.joda.time.convert.ConverterManager; +import org.joda.time.convert.PeriodConverter; +import org.joda.time.field.FieldUtils; + +/** + * BasePeriod is an abstract implementation of ReadablePeriod that stores + * data in a PeriodType and an int[]. + *

+ * This class should generally not be used directly by API users. + * The {@link ReadablePeriod} interface should be used when different + * kinds of period objects are to be referenced. + *

+ * BasePeriod subclasses may be mutable and not thread-safe. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class BasePeriod + extends AbstractPeriod + implements ReadablePeriod, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = -2110953284060001145L; + + /** The type of period */ + private PeriodType iType; + /** The values */ + private int[] iValues; + + //----------------------------------------------------------------------- + /** + * Creates a period from a set of field values. + * + * @param years amount of years in this period, which must be zero if unsupported + * @param months amount of months in this period, which must be zero if unsupported + * @param weeks amount of weeks in this period, which must be zero if unsupported + * @param days amount of days in this period, which must be zero if unsupported + * @param hours amount of hours in this period, which must be zero if unsupported + * @param minutes amount of minutes in this period, which must be zero if unsupported + * @param seconds amount of seconds in this period, which must be zero if unsupported + * @param millis amount of milliseconds in this period, which must be zero if unsupported + * @param type which set of fields this period supports + * @throws IllegalArgumentException if period type is invalid + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected BasePeriod(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis, + PeriodType type) { + super(); + type = checkPeriodType(type); + iType = type; + setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis); // internal method + } + + /** + * Creates a period from the given interval endpoints. + * + * @param startInstant interval start, in milliseconds + * @param endInstant interval end, in milliseconds + * @param type which set of fields this period supports, null means standard + * @param chrono the chronology to use, null means ISO default + * @throws IllegalArgumentException if period type is invalid + */ + protected BasePeriod(long startInstant, long endInstant, PeriodType type, Chronology chrono) { + super(); + type = checkPeriodType(type); + chrono = DateTimeUtils.getChronology(chrono); + iType = type; + iValues = chrono.get(this, startInstant, endInstant); + } + + /** + * Creates a period from the given interval endpoints. + * + * @param startInstant interval start, null means now + * @param endInstant interval end, null means now + * @param type which set of fields this period supports, null means standard + * @throws IllegalArgumentException if period type is invalid + */ + protected BasePeriod(ReadableInstant startInstant, ReadableInstant endInstant, PeriodType type) { + super(); + type = checkPeriodType(type); + if (startInstant == null && endInstant == null) { + iType = type; + iValues = new int[size()]; + } else { + long startMillis = DateTimeUtils.getInstantMillis(startInstant); + long endMillis = DateTimeUtils.getInstantMillis(endInstant); + Chronology chrono = DateTimeUtils.getIntervalChronology(startInstant, endInstant); + chrono = DateTimeUtils.getChronology(chrono); + iType = type; + iValues = chrono.get(this, startMillis, endMillis); + } + } + + /** + * Creates a period from the given start point and duration. + * + * @param startInstant the interval start, null means now + * @param duration the duration of the interval, null means zero-length + * @param type which set of fields this period supports, null means standard + */ + protected BasePeriod(ReadableInstant startInstant, ReadableDuration duration, PeriodType type) { + super(); + type = checkPeriodType(type); + long startMillis = DateTimeUtils.getInstantMillis(startInstant); + long durationMillis = DateTimeUtils.getDurationMillis(duration); + long endMillis = FieldUtils.safeAdd(startMillis, durationMillis); + Chronology chrono = DateTimeUtils.getInstantChronology(startInstant); + iType = type; + iValues = chrono.get(this, startMillis, endMillis); + } + + /** + * Creates a period from the given millisecond duration, which is only really + * suitable for durations less than one day. + *

+ * Only fields that are precise will be used. + * Thus the largest precise field may have a large value. + * + * @param duration the duration, in milliseconds + * @param type which set of fields this period supports, null means standard + * @param chrono the chronology to use, null means ISO default + * @throws IllegalArgumentException if period type is invalid + */ + protected BasePeriod(long duration, PeriodType type, Chronology chrono) { + super(); + type = checkPeriodType(type); + chrono = DateTimeUtils.getChronology(chrono); + iType = type; + iValues = chrono.get(this, duration); + } + + /** + * Creates a new period based on another using the {@link ConverterManager}. + * + * @param period the period to convert + * @param type which set of fields this period supports, null means use type from object + * @param chrono the chronology to use, null means ISO default + * @throws IllegalArgumentException if period is invalid + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected BasePeriod(Object period, PeriodType type, Chronology chrono) { + super(); + PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period); + type = (type == null ? converter.getPeriodType(period) : type); + type = checkPeriodType(type); + iType = type; + if (this instanceof ReadWritablePeriod) { + iValues = new int[size()]; + chrono = DateTimeUtils.getChronology(chrono); + converter.setInto((ReadWritablePeriod) this, period, chrono); + } else { + iValues = new MutablePeriod(period, type, chrono).getValues(); + } + } + + /** + * Constructor used when we trust ourselves. + * Do not expose publically. + * + * @param values the values to use, not null, not cloned + * @param type which set of fields this period supports, not null + */ + protected BasePeriod(int[] values, PeriodType type) { + super(); + iType = type; + iValues = values; + } + + //----------------------------------------------------------------------- + /** + * Validates a period type, converting nulls to a default value and + * checking the type is suitable for this instance. + * + * @param type the type to check, may be null + * @return the validated type to use, not null + * @throws IllegalArgumentException if the period type is invalid + */ + protected PeriodType checkPeriodType(PeriodType type) { + return DateTimeUtils.getPeriodType(type); + } + + //----------------------------------------------------------------------- + /** + * Gets the period type. + * + * @return the period type + */ + public PeriodType getPeriodType() { + return iType; + } + + //----------------------------------------------------------------------- + /** + * Gets the number of fields that this period supports. + * + * @return the number of fields supported + */ + public int size() { + return iType.size(); + } + + /** + * Gets the field type at the specified index. + * + * @param index the index to retrieve + * @return the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + public DurationFieldType getFieldType(int index) { + return iType.getFieldType(index); + } + + /** + * Gets the value at the specified index. + * + * @param index the index to retrieve + * @return the value of the field at the specified index + * @throws IndexOutOfBoundsException if the index is invalid + */ + public int getValue(int index) { + return iValues[index]; + } + + //----------------------------------------------------------------------- + /** + * Gets the total millisecond duration of this period relative to a start instant. + *

+ * This method adds the period to the specifed instant. + * The difference between the start instant and the result of the add is the duration + * + * @param startInstant the instant to add the period to, thus obtaining the duration + * @return the total length of the period as a duration relative to the start instant + * @throws ArithmeticException if the millis exceeds the capacity of the duration + */ + public Duration toDurationFrom(ReadableInstant startInstant) { + long startMillis = DateTimeUtils.getInstantMillis(startInstant); + Chronology chrono = DateTimeUtils.getInstantChronology(startInstant); + long endMillis = chrono.add(this, startMillis, 1); + return new Duration(startMillis, endMillis); + } + + //----------------------------------------------------------------------- + /** + * Checks whether a field type is supported, and if so adds the new value + * to the relevent index in the specified array. + * + * @param type the field type + * @param values the array to update + * @param newValue the new value to store if successful + */ + private void checkAndUpdate(DurationFieldType type, int[] values, int newValue) { + int index = indexOf(type); + if (index == -1) { + if (newValue != 0) { + throw new IllegalArgumentException( + "Period does not support field '" + type.getName() + "'"); + } + } else { + values[index] = newValue; + } + } + + //----------------------------------------------------------------------- + /** + * Sets all the fields of this period from another. + * + * @param period the period to copy from, not null + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected void setPeriod(ReadablePeriod period) { + if (period == null) { + setValues(new int[size()]); + } else { + setPeriodInternal(period); + } + } + + /** + * Private method called from constructor. + */ + private void setPeriodInternal(ReadablePeriod period) { + int[] newValues = new int[size()]; + for (int i = 0, isize = period.size(); i < isize; i++) { + DurationFieldType type = period.getFieldType(i); + int value = period.getValue(i); + checkAndUpdate(type, newValues, value); + } + iValues = newValues; + } + + /** + * Sets the eight standard the fields in one go. + * + * @param years amount of years in this period, which must be zero if unsupported + * @param months amount of months in this period, which must be zero if unsupported + * @param weeks amount of weeks in this period, which must be zero if unsupported + * @param days amount of days in this period, which must be zero if unsupported + * @param hours amount of hours in this period, which must be zero if unsupported + * @param minutes amount of minutes in this period, which must be zero if unsupported + * @param seconds amount of seconds in this period, which must be zero if unsupported + * @param millis amount of milliseconds in this period, which must be zero if unsupported + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected void setPeriod(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis) { + setPeriodInternal(years, months, weeks, days, hours, minutes, seconds, millis); + } + + /** + * Private method called from constructor. + */ + private void setPeriodInternal(int years, int months, int weeks, int days, + int hours, int minutes, int seconds, int millis) { + int[] newValues = new int[size()]; + checkAndUpdate(DurationFieldType.years(), newValues, years); + checkAndUpdate(DurationFieldType.months(), newValues, months); + checkAndUpdate(DurationFieldType.weeks(), newValues, weeks); + checkAndUpdate(DurationFieldType.days(), newValues, days); + checkAndUpdate(DurationFieldType.hours(), newValues, hours); + checkAndUpdate(DurationFieldType.minutes(), newValues, minutes); + checkAndUpdate(DurationFieldType.seconds(), newValues, seconds); + checkAndUpdate(DurationFieldType.millis(), newValues, millis); + iValues = newValues; + } + + //----------------------------------------------------------------------- + /** + * Sets the value of a field in this period. + * + * @param field the field to set + * @param value the value to set + * @throws IllegalArgumentException if field is is null or not supported. + */ + protected void setField(DurationFieldType field, int value) { + setFieldInto(iValues, field, value); + } + + /** + * Sets the value of a field in this period. + * + * @param values the array of values to update + * @param field the field to set + * @param value the value to set + * @throws IllegalArgumentException if field is null or not supported. + */ + protected void setFieldInto(int[] values, DurationFieldType field, int value) { + int index = indexOf(field); + if (index == -1) { + if (value != 0 || field == null) { + throw new IllegalArgumentException( + "Period does not support field '" + field + "'"); + } + } else { + values[index] = value; + } + } + + /** + * Adds the value of a field in this period. + * + * @param field the field to set + * @param value the value to set + * @throws IllegalArgumentException if field is is null or not supported. + */ + protected void addField(DurationFieldType field, int value) { + addFieldInto(iValues, field, value); + } + + /** + * Adds the value of a field in this period. + * + * @param values the array of values to update + * @param field the field to set + * @param value the value to set + * @throws IllegalArgumentException if field is is null or not supported. + */ + protected void addFieldInto(int[] values, DurationFieldType field, int value) { + int index = indexOf(field); + if (index == -1) { + if (value != 0 || field == null) { + throw new IllegalArgumentException( + "Period does not support field '" + field + "'"); + } + } else { + values[index] = FieldUtils.safeAdd(values[index], value); + } + } + + /** + * Merges the fields from another period. + * + * @param period the period to add from, not null + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected void mergePeriod(ReadablePeriod period) { + if (period != null) { + iValues = mergePeriodInto(getValues(), period); + } + } + + /** + * Merges the fields from another period. + * + * @param values the array of values to update + * @param period the period to add from, not null + * @return the updated values + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected int[] mergePeriodInto(int[] values, ReadablePeriod period) { + for (int i = 0, isize = period.size(); i < isize; i++) { + DurationFieldType type = period.getFieldType(i); + int value = period.getValue(i); + checkAndUpdate(type, values, value); + } + return values; + } + + /** + * Adds the fields from another period. + * + * @param period the period to add from, not null + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected void addPeriod(ReadablePeriod period) { + if (period != null) { + iValues = addPeriodInto(getValues(), period); + } + } + + /** + * Adds the fields from another period. + * + * @param values the array of values to update + * @param period the period to add from, not null + * @return the updated values + * @throws IllegalArgumentException if an unsupported field's value is non-zero + */ + protected int[] addPeriodInto(int[] values, ReadablePeriod period) { + for (int i = 0, isize = period.size(); i < isize; i++) { + DurationFieldType type = period.getFieldType(i); + int value = period.getValue(i); + if (value != 0) { + int index = indexOf(type); + if (index == -1) { + throw new IllegalArgumentException( + "Period does not support field '" + type.getName() + "'"); + } else { + values[index] = FieldUtils.safeAdd(getValue(index), value); + } + } + } + return values; + } + + //----------------------------------------------------------------------- + /** + * Sets the value of the field at the specifed index. + * + * @param index the index + * @param value the value to set + * @throws IndexOutOfBoundsException if the index is invalid + */ + protected void setValue(int index, int value) { + iValues[index] = value; + } + + /** + * Sets the values of all fields. + * + * @param values the array of values + */ + protected void setValues(int[] values) { + iValues = values; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/base/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/base/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/base/package.html 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,77 @@ + + + +org.joda.time.chrono package + + + +

+Implementation package providing abstract and base time classes. +

+

+Provides abstract implementations of the Readable* interfaces. +The Abstract* classes hold no fields and have no final methods. +They can be used by anyone wanting to implement the interface. +The Base* classes extend the Abstract* classes to provide fields for the +standard way to implement the class. +

+

+If you intend to implement a Readable* interface yourself, please consider +extending either the Abstract* or Base* class in this package. +

+ + Index: 3rdParty_sources/joda-time/org/joda/time/chrono/AssembledChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/AssembledChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/AssembledChronology.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,603 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.io.IOException; +import java.io.ObjectInputStream; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationField; + +/** + * Abstract Chronology that enables chronologies to be assembled from + * a container of fields. + *

+ * AssembledChronology is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class AssembledChronology extends BaseChronology { + + private static final long serialVersionUID = -6728465968995518215L; + + private final Chronology iBase; + private final Object iParam; + + private transient DurationField iMillis; + private transient DurationField iSeconds; + private transient DurationField iMinutes; + private transient DurationField iHours; + private transient DurationField iHalfdays; + + private transient DurationField iDays; + private transient DurationField iWeeks; + private transient DurationField iWeekyears; + private transient DurationField iMonths; + private transient DurationField iYears; + private transient DurationField iCenturies; + private transient DurationField iEras; + + private transient DateTimeField iMillisOfSecond; + private transient DateTimeField iMillisOfDay; + private transient DateTimeField iSecondOfMinute; + private transient DateTimeField iSecondOfDay; + private transient DateTimeField iMinuteOfHour; + private transient DateTimeField iMinuteOfDay; + private transient DateTimeField iHourOfDay; + private transient DateTimeField iClockhourOfDay; + private transient DateTimeField iHourOfHalfday; + private transient DateTimeField iClockhourOfHalfday; + private transient DateTimeField iHalfdayOfDay; + + private transient DateTimeField iDayOfWeek; + private transient DateTimeField iDayOfMonth; + private transient DateTimeField iDayOfYear; + private transient DateTimeField iWeekOfWeekyear; + private transient DateTimeField iWeekyear; + private transient DateTimeField iWeekyearOfCentury; + private transient DateTimeField iMonthOfYear; + private transient DateTimeField iYear; + private transient DateTimeField iYearOfEra; + private transient DateTimeField iYearOfCentury; + private transient DateTimeField iCenturyOfEra; + private transient DateTimeField iEra; + + // Bit set determines which base fields are used + // bit 1 set: hourOfDay, minuteOfHour, secondOfMinute, and millisOfSecond fields + // bit 2 set: millisOfDayField + // bit 3 set: year, monthOfYear, and dayOfMonth fields + private transient int iBaseFlags; + + /** + * Constructor calls the assemble method, enabling subclasses to define its + * supported fields. If a base chronology is supplied, the field set + * initially contains references to each base chronology field. + *

+ * Other methods in this class will delegate to the base chronology, if it + * can be determined that the base chronology will produce the same results + * as AbstractChronology. + * + * @param base optional base chronology to copy initial fields from + * @param param optional param object avalable for assemble method + */ + protected AssembledChronology(Chronology base, Object param) { + iBase = base; + iParam = param; + setFields(); + } + + public DateTimeZone getZone() { + Chronology base; + if ((base = iBase) != null) { + return base.getZone(); + } + return null; + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int millisOfDay) + throws IllegalArgumentException + { + Chronology base; + if ((base = iBase) != null && (iBaseFlags & 6) == 6) { + // Only call specialized implementation if applicable fields are the same. + return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); + } + return super.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + Chronology base; + if ((base = iBase) != null && (iBaseFlags & 5) == 5) { + // Only call specialized implementation if applicable fields are the same. + return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + return super.getDateTimeMillis(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + + public long getDateTimeMillis(long instant, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + Chronology base; + if ((base = iBase) != null && (iBaseFlags & 1) == 1) { + // Only call specialized implementation if applicable fields are the same. + return base.getDateTimeMillis + (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + return super.getDateTimeMillis + (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + + public final DurationField millis() { + return iMillis; + } + + public final DateTimeField millisOfSecond() { + return iMillisOfSecond; + } + + public final DateTimeField millisOfDay() { + return iMillisOfDay; + } + + public final DurationField seconds() { + return iSeconds; + } + + public final DateTimeField secondOfMinute() { + return iSecondOfMinute; + } + + public final DateTimeField secondOfDay() { + return iSecondOfDay; + } + + public final DurationField minutes() { + return iMinutes; + } + + public final DateTimeField minuteOfHour() { + return iMinuteOfHour; + } + + public final DateTimeField minuteOfDay() { + return iMinuteOfDay; + } + + public final DurationField hours() { + return iHours; + } + + public final DateTimeField hourOfDay() { + return iHourOfDay; + } + + public final DateTimeField clockhourOfDay() { + return iClockhourOfDay; + } + + public final DurationField halfdays() { + return iHalfdays; + } + + public final DateTimeField hourOfHalfday() { + return iHourOfHalfday; + } + + public final DateTimeField clockhourOfHalfday() { + return iClockhourOfHalfday; + } + + public final DateTimeField halfdayOfDay() { + return iHalfdayOfDay; + } + + public final DurationField days() { + return iDays; + } + + public final DateTimeField dayOfWeek() { + return iDayOfWeek; + } + + public final DateTimeField dayOfMonth() { + return iDayOfMonth; + } + + public final DateTimeField dayOfYear() { + return iDayOfYear; + } + + public final DurationField weeks() { + return iWeeks; + } + + public final DateTimeField weekOfWeekyear() { + return iWeekOfWeekyear; + } + + public final DurationField weekyears() { + return iWeekyears; + } + + public final DateTimeField weekyear() { + return iWeekyear; + } + + public final DateTimeField weekyearOfCentury() { + return iWeekyearOfCentury; + } + + public final DurationField months() { + return iMonths; + } + + public final DateTimeField monthOfYear() { + return iMonthOfYear; + } + + public final DurationField years() { + return iYears; + } + + public final DateTimeField year() { + return iYear; + } + + public final DateTimeField yearOfEra() { + return iYearOfEra; + } + + public final DateTimeField yearOfCentury() { + return iYearOfCentury; + } + + public final DurationField centuries() { + return iCenturies; + } + + public final DateTimeField centuryOfEra() { + return iCenturyOfEra; + } + + public final DurationField eras() { + return iEras; + } + + public final DateTimeField era() { + return iEra; + } + + /** + * Invoked by the constructor and after deserialization to allow subclasses + * to define all of its supported fields. All unset fields default to + * unsupported instances. + * + * @param fields container of fields + */ + protected abstract void assemble(Fields fields); + + /** + * Returns the same base chronology as passed into the constructor. + */ + protected final Chronology getBase() { + return iBase; + } + + /** + * Returns the same param object as passed into the constructor. + */ + protected final Object getParam() { + return iParam; + } + + private void setFields() { + Fields fields = new Fields(); + if (iBase != null) { + fields.copyFieldsFrom(iBase); + } + assemble(fields); + + { + DurationField f; + iMillis = (f = fields.millis) != null ? f : super.millis(); + iSeconds = (f = fields.seconds) != null ? f : super.seconds(); + iMinutes = (f = fields.minutes) != null ? f : super.minutes(); + iHours = (f = fields.hours) != null ? f : super.hours(); + iHalfdays = (f = fields.halfdays) != null ? f : super.halfdays(); + iDays = (f = fields.days) != null ? f : super.days(); + iWeeks = (f = fields.weeks) != null ? f : super.weeks(); + iWeekyears = (f = fields.weekyears) != null ? f : super.weekyears(); + iMonths = (f = fields.months) != null ? f : super.months(); + iYears = (f = fields.years) != null ? f : super.years(); + iCenturies = (f = fields.centuries) != null ? f : super.centuries(); + iEras = (f = fields.eras) != null ? f : super.eras(); + } + + { + DateTimeField f; + iMillisOfSecond = (f = fields.millisOfSecond) != null ? f : super.millisOfSecond(); + iMillisOfDay = (f = fields.millisOfDay) != null ? f : super.millisOfDay(); + iSecondOfMinute = (f = fields.secondOfMinute) != null ? f : super.secondOfMinute(); + iSecondOfDay = (f = fields.secondOfDay) != null ? f : super.secondOfDay(); + iMinuteOfHour = (f = fields.minuteOfHour) != null ? f : super.minuteOfHour(); + iMinuteOfDay = (f = fields.minuteOfDay) != null ? f : super.minuteOfDay(); + iHourOfDay = (f = fields.hourOfDay) != null ? f : super.hourOfDay(); + iClockhourOfDay = (f = fields.clockhourOfDay) != null ? f : super.clockhourOfDay(); + iHourOfHalfday = (f = fields.hourOfHalfday) != null ? f : super.hourOfHalfday(); + iClockhourOfHalfday = (f = fields.clockhourOfHalfday) != null ? f : super.clockhourOfHalfday(); + iHalfdayOfDay = (f = fields.halfdayOfDay) != null ? f : super.halfdayOfDay(); + iDayOfWeek = (f = fields.dayOfWeek) != null ? f : super.dayOfWeek(); + iDayOfMonth = (f = fields.dayOfMonth) != null ? f : super.dayOfMonth(); + iDayOfYear = (f = fields.dayOfYear) != null ? f : super.dayOfYear(); + iWeekOfWeekyear = (f = fields.weekOfWeekyear) != null ? f : super.weekOfWeekyear(); + iWeekyear = (f = fields.weekyear) != null ? f : super.weekyear(); + iWeekyearOfCentury = (f = fields.weekyearOfCentury) != null ? f : super.weekyearOfCentury(); + iMonthOfYear = (f = fields.monthOfYear) != null ? f : super.monthOfYear(); + iYear = (f = fields.year) != null ? f : super.year(); + iYearOfEra = (f = fields.yearOfEra) != null ? f : super.yearOfEra(); + iYearOfCentury = (f = fields.yearOfCentury) != null ? f : super.yearOfCentury(); + iCenturyOfEra = (f = fields.centuryOfEra) != null ? f : super.centuryOfEra(); + iEra = (f = fields.era) != null ? f : super.era(); + } + + int flags; + if (iBase == null) { + flags = 0; + } else { + flags = + ((iHourOfDay == iBase.hourOfDay() && + iMinuteOfHour == iBase.minuteOfHour() && + iSecondOfMinute == iBase.secondOfMinute() && + iMillisOfSecond == iBase.millisOfSecond() ) ? 1 : 0) | + + ((iMillisOfDay == iBase.millisOfDay()) ? 2 : 0) | + + ((iYear == iBase.year() && + iMonthOfYear == iBase.monthOfYear() && + iDayOfMonth == iBase.dayOfMonth() ) ? 4 : 0); + } + + iBaseFlags = flags; + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + setFields(); + } + + /** + * A container of fields used for assembling a chronology. + */ + public static final class Fields { + public DurationField millis; + public DurationField seconds; + public DurationField minutes; + public DurationField hours; + public DurationField halfdays; + + public DurationField days; + public DurationField weeks; + public DurationField weekyears; + public DurationField months; + public DurationField years; + public DurationField centuries; + public DurationField eras; + + public DateTimeField millisOfSecond; + public DateTimeField millisOfDay; + public DateTimeField secondOfMinute; + public DateTimeField secondOfDay; + public DateTimeField minuteOfHour; + public DateTimeField minuteOfDay; + public DateTimeField hourOfDay; + public DateTimeField clockhourOfDay; + public DateTimeField hourOfHalfday; + public DateTimeField clockhourOfHalfday; + public DateTimeField halfdayOfDay; + + public DateTimeField dayOfWeek; + public DateTimeField dayOfMonth; + public DateTimeField dayOfYear; + public DateTimeField weekOfWeekyear; + public DateTimeField weekyear; + public DateTimeField weekyearOfCentury; + public DateTimeField monthOfYear; + public DateTimeField year; + public DateTimeField yearOfEra; + public DateTimeField yearOfCentury; + public DateTimeField centuryOfEra; + public DateTimeField era; + + Fields() { + } + + /** + * Copy the supported fields from a chronology into this container. + */ + public void copyFieldsFrom(Chronology chrono) { + { + DurationField f; + if (isSupported(f = chrono.millis())) { + millis = f; + } + if (isSupported(f = chrono.seconds())) { + seconds = f; + } + if (isSupported(f = chrono.minutes())) { + minutes = f; + } + if (isSupported(f = chrono.hours())) { + hours = f; + } + if (isSupported(f = chrono.halfdays())) { + halfdays = f; + } + if (isSupported(f = chrono.days())) { + days = f; + } + if (isSupported(f = chrono.weeks())) { + weeks = f; + } + if (isSupported(f = chrono.weekyears())) { + weekyears = f; + } + if (isSupported(f = chrono.months())) { + months = f; + } + if (isSupported(f = chrono.years())) { + years = f; + } + if (isSupported(f = chrono.centuries())) { + centuries = f; + } + if (isSupported(f = chrono.eras())) { + eras = f; + } + } + + { + DateTimeField f; + if (isSupported(f = chrono.millisOfSecond())) { + millisOfSecond = f; + } + if (isSupported(f = chrono.millisOfDay())) { + millisOfDay = f; + } + if (isSupported(f = chrono.secondOfMinute())) { + secondOfMinute = f; + } + if (isSupported(f = chrono.secondOfDay())) { + secondOfDay = f; + } + if (isSupported(f = chrono.minuteOfHour())) { + minuteOfHour = f; + } + if (isSupported(f = chrono.minuteOfDay())) { + minuteOfDay = f; + } + if (isSupported(f = chrono.hourOfDay())) { + hourOfDay = f; + } + if (isSupported(f = chrono.clockhourOfDay())) { + clockhourOfDay = f; + } + if (isSupported(f = chrono.hourOfHalfday())) { + hourOfHalfday = f; + } + if (isSupported(f = chrono.clockhourOfHalfday())) { + clockhourOfHalfday = f; + } + if (isSupported(f = chrono.halfdayOfDay())) { + halfdayOfDay = f; + } + if (isSupported(f = chrono.dayOfWeek())) { + dayOfWeek = f; + } + if (isSupported(f = chrono.dayOfMonth())) { + dayOfMonth = f; + } + if (isSupported(f = chrono.dayOfYear())) { + dayOfYear = f; + } + if (isSupported(f = chrono.weekOfWeekyear())) { + weekOfWeekyear = f; + } + if (isSupported(f = chrono.weekyear())) { + weekyear = f; + } + if (isSupported(f = chrono.weekyearOfCentury())) { + weekyearOfCentury = f; + } + if (isSupported(f = chrono.monthOfYear())) { + monthOfYear = f; + } + if (isSupported(f = chrono.year())) { + year = f; + } + if (isSupported(f = chrono.yearOfEra())) { + yearOfEra = f; + } + if (isSupported(f = chrono.yearOfCentury())) { + yearOfCentury = f; + } + if (isSupported(f = chrono.centuryOfEra())) { + centuryOfEra = f; + } + if (isSupported(f = chrono.era())) { + era = f; + } + } + } + + private static boolean isSupported(DurationField field) { + return field == null ? false : field.isSupported(); + } + + private static boolean isSupported(DateTimeField field) { + return field == null ? false : field.isSupported(); + } + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/BaseChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/BaseChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/BaseChronology.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,713 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.io.Serializable; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; +import org.joda.time.ReadablePartial; +import org.joda.time.ReadablePeriod; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.UnsupportedDateTimeField; +import org.joda.time.field.UnsupportedDurationField; + +/** + * AbstractChronology provides a skeleton implementation for chronology + * classes. Many utility methods are defined, but all fields are unsupported. + *

+ * AbstractChronology is thread-safe and immutable, and all subclasses must be + * as well. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class BaseChronology + extends Chronology + implements Serializable { + + /** Serialization version. */ + private static final long serialVersionUID = -7310865996721419676L; + + /** + * Restricted constructor. + */ + protected BaseChronology() { + super(); + } + + /** + * Returns the DateTimeZone that this Chronology operates in, or null if + * unspecified. + * + * @return DateTimeZone null if unspecified + */ + public abstract DateTimeZone getZone(); + + /** + * Returns an instance of this Chronology that operates in the UTC time + * zone. Chronologies that do not operate in a time zone or are already + * UTC must return themself. + * + * @return a version of this chronology that ignores time zones + */ + public abstract Chronology withUTC(); + + /** + * Returns an instance of this Chronology that operates in any time zone. + * + * @return a version of this chronology with a specific time zone + * @param zone to use, or default if null + * @see org.joda.time.chrono.ZonedChronology + */ + public abstract Chronology withZone(DateTimeZone zone); + + /** + * Returns a datetime millisecond instant, formed from the given year, + * month, day, and millisecond values. The set of given values must refer + * to a valid datetime, or else an IllegalArgumentException is thrown. + *

+ * The default implementation calls upon separate DateTimeFields to + * determine the result. Subclasses are encouraged to provide a more + * efficient implementation. + * + * @param year year to use + * @param monthOfYear month to use + * @param dayOfMonth day of month to use + * @param millisOfDay millisecond to use + * @return millisecond instant from 1970-01-01T00:00:00Z + */ + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int millisOfDay) + throws IllegalArgumentException + { + long instant = year().set(0, year); + instant = monthOfYear().set(instant, monthOfYear); + instant = dayOfMonth().set(instant, dayOfMonth); + return millisOfDay().set(instant, millisOfDay); + } + + /** + * Returns a datetime millisecond instant, formed from the given year, + * month, day, hour, minute, second, and millisecond values. The set of + * given values must refer to a valid datetime, or else an + * IllegalArgumentException is thrown. + *

+ * The default implementation calls upon separate DateTimeFields to + * determine the result. Subclasses are encouraged to provide a more + * efficient implementation. + * + * @param year year to use + * @param monthOfYear month to use + * @param dayOfMonth day of month to use + * @param hourOfDay hour to use + * @param minuteOfHour minute to use + * @param secondOfMinute second to use + * @param millisOfSecond millisecond to use + * @return millisecond instant from 1970-01-01T00:00:00Z + */ + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + long instant = year().set(0, year); + instant = monthOfYear().set(instant, monthOfYear); + instant = dayOfMonth().set(instant, dayOfMonth); + instant = hourOfDay().set(instant, hourOfDay); + instant = minuteOfHour().set(instant, minuteOfHour); + instant = secondOfMinute().set(instant, secondOfMinute); + return millisOfSecond().set(instant, millisOfSecond); + } + + /** + * Returns a datetime millisecond instant, from from the given instant, + * hour, minute, second, and millisecond values. The set of given values + * must refer to a valid datetime, or else an IllegalArgumentException is + * thrown. + *

+ * The default implementation calls upon separate DateTimeFields to + * determine the result. Subclasses are encouraged to provide a more + * efficient implementation. + * + * @param instant instant to start from + * @param hourOfDay hour to use + * @param minuteOfHour minute to use + * @param secondOfMinute second to use + * @param millisOfSecond millisecond to use + * @return millisecond instant from 1970-01-01T00:00:00Z + */ + public long getDateTimeMillis(long instant, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + instant = hourOfDay().set(instant, hourOfDay); + instant = minuteOfHour().set(instant, minuteOfHour); + instant = secondOfMinute().set(instant, secondOfMinute); + return millisOfSecond().set(instant, millisOfSecond); + } + + //----------------------------------------------------------------------- + /** + * Validates whether the fields stored in a partial instant are valid. + *

+ * This implementation uses {@link DateTimeField#getMinimumValue(ReadablePartial, int[])} + * and {@link DateTimeField#getMaximumValue(ReadablePartial, int[])}. + * + * @param partial the partial instant to validate + * @param values the values to validate, not null + * @throws IllegalArgumentException if the instant is invalid + */ + public void validate(ReadablePartial partial, int[] values) { + // check values in standard range, catching really stupid cases like -1 + // this means that the second check will not hit trouble + int size = partial.size(); + for (int i = 0; i < size; i++) { + int value = values[i]; + DateTimeField field = partial.getField(i); + if (value < field.getMinimumValue()) { + throw new IllegalArgumentException("Value " + value + + " for " + field.getName() + " is less than minimum"); + } + if (value > field.getMaximumValue()) { + throw new IllegalArgumentException("Value " + value + + " for " + field.getName() + " is greater than maximum"); + } + } + // check values in specific range, catching really odd cases like 30th Feb + for (int i = 0; i < size; i++) { + int value = values[i]; + DateTimeField field = partial.getField(i); + if (value < field.getMinimumValue(partial, values)) { + throw new IllegalArgumentException("Value " + value + + " for " + field.getName() + " is less than minimum"); + } + if (value > field.getMaximumValue(partial, values)) { + throw new IllegalArgumentException("Value " + value + + " for " + field.getName() + " is greater than maximum"); + } + } + } + + /** + * Gets the values of a partial from an instant. + * + * @param partial the partial instant to use + * @param instant the instant to query + * @return the values of the partial extracted from the instant + */ + public int[] get(ReadablePartial partial, long instant) { + int size = partial.size(); + int[] values = new int[size]; + for (int i = 0; i < size; i++) { + values[i] = partial.getFieldType(i).getField(this).get(instant); + } + return values; + } + + /** + * Sets the partial into the instant. + * + * @param partial the partial instant to use + * @param instant the instant to update + * @return the updated instant + */ + public long set(ReadablePartial partial, long instant) { + for (int i = 0, isize = partial.size(); i < isize; i++) { + instant = partial.getFieldType(i).getField(this).set(instant, partial.getValue(i)); + } + return instant; + } + + //----------------------------------------------------------------------- + /** + * Gets the values of a period from an interval. + * + * @param period the period instant to use + * @param startInstant the start instant of an interval to query + * @param endInstant the start instant of an interval to query + * @return the values of the period extracted from the interval + */ + public int[] get(ReadablePeriod period, long startInstant, long endInstant) { + int size = period.size(); + int[] values = new int[size]; + if (startInstant != endInstant) { + for (int i = 0; i < size; i++) { + DurationField field = period.getFieldType(i).getField(this); + int value = field.getDifference(endInstant, startInstant); + startInstant = field.add(startInstant, value); + values[i] = value; + } + } + return values; + } + + /** + * Gets the values of a period from an interval. + * + * @param period the period instant to use + * @param duration the duration to query + * @return the values of the period extracted from the duration + */ + public int[] get(ReadablePeriod period, long duration) { + int size = period.size(); + int[] values = new int[size]; + if (duration != 0) { + long current = 0; + for (int i = 0; i < size; i++) { + DurationField field = period.getFieldType(i).getField(this); + if (field.isPrecise()) { + int value = field.getDifference(duration, current); + current = field.add(current, value); + values[i] = value; + } + } + } + return values; + } + + /** + * Adds the period to the instant, specifying the number of times to add. + * + * @param period the period to add, null means add nothing + * @param instant the instant to add to + * @param scalar the number of times to add + * @return the updated instant + */ + public long add(ReadablePeriod period, long instant, int scalar) { + if (scalar != 0 && period != null) { + for (int i = 0, isize = period.size(); i < isize; i++) { + long value = period.getValue(i); // use long to allow for multiplication (fits OK) + if (value != 0) { + instant = period.getFieldType(i).getField(this).add(instant, value * scalar); + } + } + } + return instant; + } + + //----------------------------------------------------------------------- + /** + * Adds the duration to the instant, specifying the number of times to add. + * + * @param instant the instant to add to + * @param duration the duration to add + * @param scalar the number of times to add + * @return the updated instant + */ + public long add(long instant, long duration, int scalar) { + if (duration == 0 || scalar == 0) { + return instant; + } + long add = FieldUtils.safeMultiply(duration, scalar); + return FieldUtils.safeAdd(instant, add); + } + + // Millis + //----------------------------------------------------------------------- + /** + * Get the millis duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField millis() { + return UnsupportedDurationField.getInstance(DurationFieldType.millis()); + } + + /** + * Get the millis of second field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField millisOfSecond() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.millisOfSecond(), millis()); + } + + /** + * Get the millis of day field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField millisOfDay() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.millisOfDay(), millis()); + } + + // Second + //----------------------------------------------------------------------- + /** + * Get the seconds duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField seconds() { + return UnsupportedDurationField.getInstance(DurationFieldType.seconds()); + } + + /** + * Get the second of minute field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField secondOfMinute() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.secondOfMinute(), seconds()); + } + + /** + * Get the second of day field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField secondOfDay() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.secondOfDay(), seconds()); + } + + // Minute + //----------------------------------------------------------------------- + /** + * Get the minutes duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField minutes() { + return UnsupportedDurationField.getInstance(DurationFieldType.minutes()); + } + + /** + * Get the minute of hour field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField minuteOfHour() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.minuteOfHour(), minutes()); + } + + /** + * Get the minute of day field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField minuteOfDay() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.minuteOfDay(), minutes()); + } + + // Hour + //----------------------------------------------------------------------- + /** + * Get the hours duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField hours() { + return UnsupportedDurationField.getInstance(DurationFieldType.hours()); + } + + /** + * Get the hour of day (0-23) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField hourOfDay() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.hourOfDay(), hours()); + } + + /** + * Get the hour of day (offset to 1-24) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField clockhourOfDay() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.clockhourOfDay(), hours()); + } + + // Halfday + //----------------------------------------------------------------------- + /** + * Get the halfdays duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField halfdays() { + return UnsupportedDurationField.getInstance(DurationFieldType.halfdays()); + } + + /** + * Get the hour of am/pm (0-11) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField hourOfHalfday() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.hourOfHalfday(), hours()); + } + + /** + * Get the hour of am/pm (offset to 1-12) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField clockhourOfHalfday() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.clockhourOfHalfday(), hours()); + } + + /** + * Get the AM(0) PM(1) field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField halfdayOfDay() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.halfdayOfDay(), halfdays()); + } + + // Day + //----------------------------------------------------------------------- + /** + * Get the days duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField days() { + return UnsupportedDurationField.getInstance(DurationFieldType.days()); + } + + /** + * Get the day of week field for this chronology. + * + *

DayOfWeek values are defined in + * {@link org.joda.time.DateTimeConstants DateTimeConstants}. + * They use the ISO definitions, where 1 is Monday and 7 is Sunday. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField dayOfWeek() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.dayOfWeek(), days()); + } + + /** + * Get the day of month field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField dayOfMonth() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.dayOfMonth(), days()); + } + + /** + * Get the day of year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField dayOfYear() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.dayOfYear(), days()); + } + + // Week + //----------------------------------------------------------------------- + /** + * Get the weeks duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField weeks() { + return UnsupportedDurationField.getInstance(DurationFieldType.weeks()); + } + + /** + * Get the week of a week based year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField weekOfWeekyear() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.weekOfWeekyear(), weeks()); + } + + // Weekyear + //----------------------------------------------------------------------- + /** + * Get the weekyears duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField weekyears() { + return UnsupportedDurationField.getInstance(DurationFieldType.weekyears()); + } + + /** + * Get the year of a week based year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField weekyear() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.weekyear(), weekyears()); + } + + /** + * Get the year of a week based year in a century field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField weekyearOfCentury() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.weekyearOfCentury(), weekyears()); + } + + // Month + //----------------------------------------------------------------------- + /** + * Get the months duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField months() { + return UnsupportedDurationField.getInstance(DurationFieldType.months()); + } + + /** + * Get the month of year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField monthOfYear() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.monthOfYear(), months()); + } + + // Year + //----------------------------------------------------------------------- + /** + * Get the years duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField years() { + return UnsupportedDurationField.getInstance(DurationFieldType.years()); + } + + /** + * Get the year field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField year() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.year(), years()); + } + + /** + * Get the year of era field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField yearOfEra() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.yearOfEra(), years()); + } + + /** + * Get the year of century field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField yearOfCentury() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.yearOfCentury(), years()); + } + + // Century + //----------------------------------------------------------------------- + /** + * Get the centuries duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField centuries() { + return UnsupportedDurationField.getInstance(DurationFieldType.centuries()); + } + + /** + * Get the century of era field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField centuryOfEra() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.centuryOfEra(), centuries()); + } + + // Era + //----------------------------------------------------------------------- + /** + * Get the eras duration field for this chronology. + * + * @return DurationField or UnsupportedDurationField if unsupported + */ + public DurationField eras() { + return UnsupportedDurationField.getInstance(DurationFieldType.eras()); + } + + /** + * Get the era field for this chronology. + * + * @return DateTimeField or UnsupportedDateTimeField if unsupported + */ + public DateTimeField era() { + return UnsupportedDateTimeField.getInstance(DateTimeFieldType.era(), eras()); + } + + //----------------------------------------------------------------------- + /** + * Gets a debugging toString. + * + * @return a debugging string + */ + public abstract String toString(); + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/BaseGJChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/BaseGJChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/BaseGJChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,857 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.Locale; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; +import org.joda.time.field.DividedDateTimeField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.MillisDurationField; +import org.joda.time.field.NonZeroDateTimeField; +import org.joda.time.field.OffsetDateTimeField; +import org.joda.time.field.PreciseDateTimeField; +import org.joda.time.field.PreciseDurationField; +import org.joda.time.field.RemainderDateTimeField; + +/** + * Abstract Chronology for implementing chronologies based on Gregorian/Julian formulae. + * Most of the utility methods required by subclasses are package-private, + * reflecting the intention that they be defined in the same package. + *

+ * AbstractGJChronology is thread-safe and immutable, and all subclasses must + * be as well. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @author Guy Allard + * @since 1.0 + */ +public abstract class BaseGJChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = 8283225332206808863L; + + static final long MILLIS_1970_TO_2000 = 946684800000L; + + // These arrays are NOT public. We trust ourselves not to alter the array. + // They use zero-based array indexes so the that valid range of months is + // automatically checked. + + private static final int[] MIN_DAYS_PER_MONTH_ARRAY = { + 31,28,31,30,31,30,31,31,30,31,30,31 + }; + + private static final int[] MAX_DAYS_PER_MONTH_ARRAY = { + 31,29,31,30,31,30,31,31,30,31,30,31 + }; + + private static final long[] MIN_TOTAL_MILLIS_BY_MONTH_ARRAY; + private static final long[] MAX_TOTAL_MILLIS_BY_MONTH_ARRAY; + + private static final DurationField cMillisField; + private static final DurationField cSecondsField; + private static final DurationField cMinutesField; + private static final DurationField cHoursField; + private static final DurationField cHalfdaysField; + private static final DurationField cDaysField; + private static final DurationField cWeeksField; + + private static final DateTimeField cMillisOfSecondField; + private static final DateTimeField cMillisOfDayField; + private static final DateTimeField cSecondOfMinuteField; + private static final DateTimeField cSecondOfDayField; + private static final DateTimeField cMinuteOfHourField; + private static final DateTimeField cMinuteOfDayField; + private static final DateTimeField cHourOfDayField; + private static final DateTimeField cHourOfHalfdayField; + private static final DateTimeField cClockhourOfDayField; + private static final DateTimeField cClockhourOfHalfdayField; + private static final DateTimeField cHalfdayOfDayField; + + static { + MIN_TOTAL_MILLIS_BY_MONTH_ARRAY = new long[12]; + MAX_TOTAL_MILLIS_BY_MONTH_ARRAY = new long[12]; + + long minSum = 0; + long maxSum = 0; + for (int i=0; i<12; i++) { + long millis = MIN_DAYS_PER_MONTH_ARRAY[i] + * (long)DateTimeConstants.MILLIS_PER_DAY; + minSum += millis; + MIN_TOTAL_MILLIS_BY_MONTH_ARRAY[i] = minSum; + + millis = MAX_DAYS_PER_MONTH_ARRAY[i] + * (long)DateTimeConstants.MILLIS_PER_DAY; + maxSum += millis; + MAX_TOTAL_MILLIS_BY_MONTH_ARRAY[i] = maxSum; + } + + cMillisField = MillisDurationField.INSTANCE; + cSecondsField = new PreciseDurationField + (DurationFieldType.seconds(), DateTimeConstants.MILLIS_PER_SECOND); + cMinutesField = new PreciseDurationField + (DurationFieldType.minutes(), DateTimeConstants.MILLIS_PER_MINUTE); + cHoursField = new PreciseDurationField + (DurationFieldType.hours(), DateTimeConstants.MILLIS_PER_HOUR); + cHalfdaysField = new PreciseDurationField + (DurationFieldType.halfdays(), DateTimeConstants.MILLIS_PER_DAY / 2); + cDaysField = new PreciseDurationField + (DurationFieldType.days(), DateTimeConstants.MILLIS_PER_DAY); + cWeeksField = new PreciseDurationField + (DurationFieldType.weeks(), DateTimeConstants.MILLIS_PER_WEEK); + + cMillisOfSecondField = new PreciseDateTimeField + (DateTimeFieldType.millisOfSecond(), cMillisField, cSecondsField); + + cMillisOfDayField = new PreciseDateTimeField + (DateTimeFieldType.millisOfDay(), cMillisField, cDaysField); + + cSecondOfMinuteField = new PreciseDateTimeField + (DateTimeFieldType.secondOfMinute(), cSecondsField, cMinutesField); + + cSecondOfDayField = new PreciseDateTimeField + (DateTimeFieldType.secondOfDay(), cSecondsField, cDaysField); + + cMinuteOfHourField = new PreciseDateTimeField + (DateTimeFieldType.minuteOfHour(), cMinutesField, cHoursField); + + cMinuteOfDayField = new PreciseDateTimeField + (DateTimeFieldType.minuteOfDay(), cMinutesField, cDaysField); + + cHourOfDayField = new PreciseDateTimeField + (DateTimeFieldType.hourOfDay(), cHoursField, cDaysField); + + cHourOfHalfdayField = new PreciseDateTimeField + (DateTimeFieldType.hourOfHalfday(), cHoursField, cHalfdaysField); + + cClockhourOfDayField = new NonZeroDateTimeField + (cHourOfDayField, DateTimeFieldType.clockhourOfDay()); + + cClockhourOfHalfdayField = new NonZeroDateTimeField + (cHourOfHalfdayField, DateTimeFieldType.clockhourOfHalfday()); + + cHalfdayOfDayField = new HalfdayField(); + } + + private transient YearInfo[] iYearInfoCache; + private transient int iYearInfoCacheMask; + + private final int iMinDaysInFirstWeek; + + BaseGJChronology(Chronology base, Object param, int minDaysInFirstWeek) { + super(base, param); + + if (minDaysInFirstWeek < 1 || minDaysInFirstWeek > 7) { + throw new IllegalArgumentException + ("Invalid min days in first week: " + minDaysInFirstWeek); + } + + iMinDaysInFirstWeek = minDaysInFirstWeek; + + Integer i; + try { + i = Integer.getInteger(getClass().getName().concat(".yearInfoCacheSize")); + } catch (SecurityException e) { + i = null; + } + + int cacheSize; + if (i == null) { + cacheSize = 1024; // (1 << 10) + } else { + cacheSize = i.intValue(); + // Ensure cache size is even power of 2. + cacheSize--; + int shift = 0; + while (cacheSize > 0) { + shift++; + cacheSize >>= 1; + } + cacheSize = 1 << shift; + } + + iYearInfoCache = new YearInfo[cacheSize]; + iYearInfoCacheMask = cacheSize - 1; + } + + public DateTimeZone getZone() { + Chronology base; + if ((base = getBase()) != null) { + return base.getZone(); + } + return DateTimeZone.UTC; + } + + public final long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int millisOfDay) + throws IllegalArgumentException + { + Chronology base; + if ((base = getBase()) != null) { + return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); + } + + FieldUtils.verifyValueBounds("millisOfDay", millisOfDay, 0, DateTimeConstants.MILLIS_PER_DAY); + return getDateMidnightMillis(year, monthOfYear, dayOfMonth) + millisOfDay; + } + + public final long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + Chronology base; + if ((base = getBase()) != null) { + return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + + FieldUtils.verifyValueBounds("hourOfDay", hourOfDay, 0, 23); + FieldUtils.verifyValueBounds("minuteOfHour", minuteOfHour, 0, 59); + FieldUtils.verifyValueBounds("secondOfMinute", secondOfMinute, 0, 59); + FieldUtils.verifyValueBounds("millisOfSecond", millisOfSecond, 0, 999); + + return getDateMidnightMillis(year, monthOfYear, dayOfMonth) + + hourOfDay * DateTimeConstants.MILLIS_PER_HOUR + + minuteOfHour * DateTimeConstants.MILLIS_PER_MINUTE + + secondOfMinute * DateTimeConstants.MILLIS_PER_SECOND + + millisOfSecond; + } + + public final int getMinimumDaysInFirstWeek() { + return iMinDaysInFirstWeek; + } + + // Output + //----------------------------------------------------------------------- + /** + * Gets a debugging toString. + * + * @return a debugging string + */ + public String toString() { + StringBuffer sb = new StringBuffer(60); + String name = getClass().getName(); + int index = name.lastIndexOf('.'); + if (index >= 0) { + name = name.substring(index + 1); + } + sb.append(name); + sb.append('['); + DateTimeZone zone = getZone(); + if (zone != null) { + sb.append(zone.getID()); + } + if (getMinimumDaysInFirstWeek() != 4) { + sb.append(",mdfw="); + sb.append(getMinimumDaysInFirstWeek()); + } + sb.append(']'); + return sb.toString(); + } + + protected void assemble(Fields fields) { + // First copy fields that are the same for all Gregorian and Julian + // chronologies. + + fields.millis = cMillisField; + fields.seconds = cSecondsField; + fields.minutes = cMinutesField; + fields.hours = cHoursField; + fields.halfdays = cHalfdaysField; + fields.days = cDaysField; + fields.weeks = cWeeksField; + + fields.millisOfSecond = cMillisOfSecondField; + fields.millisOfDay = cMillisOfDayField; + fields.secondOfMinute = cSecondOfMinuteField; + fields.secondOfDay = cSecondOfDayField; + fields.minuteOfHour = cMinuteOfHourField; + fields.minuteOfDay = cMinuteOfDayField; + fields.hourOfDay = cHourOfDayField; + fields.hourOfHalfday = cHourOfHalfdayField; + fields.clockhourOfDay = cClockhourOfDayField; + fields.clockhourOfHalfday = cClockhourOfHalfdayField; + fields.halfdayOfDay = cHalfdayOfDayField; + + // Now create fields that have unique behavior for Gregorian and Julian + // chronologies. + + fields.year = new GJYearDateTimeField(this); + fields.yearOfEra = new GJYearOfEraDateTimeField(fields.year, this); + + // Define one-based centuryOfEra and yearOfCentury. + DateTimeField field = new OffsetDateTimeField( + fields.yearOfEra, 99); + fields.centuryOfEra = new DividedDateTimeField( + field, DateTimeFieldType.centuryOfEra(), 100); + + field = new RemainderDateTimeField( + (DividedDateTimeField) fields.centuryOfEra); + fields.yearOfCentury = new OffsetDateTimeField( + field, DateTimeFieldType.yearOfCentury(), 1); + + fields.era = new GJEraDateTimeField(this); + fields.dayOfWeek = new GJDayOfWeekDateTimeField(this, fields.days); + fields.dayOfMonth = new GJDayOfMonthDateTimeField(this, fields.days); + fields.dayOfYear = new GJDayOfYearDateTimeField(this, fields.days); + fields.monthOfYear = new GJMonthOfYearDateTimeField(this); + fields.weekyear = new GJWeekyearDateTimeField(this); + fields.weekOfWeekyear = new GJWeekOfWeekyearDateTimeField(this, fields.weeks); + + field = new RemainderDateTimeField( + fields.weekyear, DateTimeFieldType.weekyearOfCentury(), 100); + fields.weekyearOfCentury = new OffsetDateTimeField( + field, DateTimeFieldType.weekyearOfCentury(), 1); + + // The remaining (imprecise) durations are available from the newly + // created datetime fields. + + fields.years = fields.year.getDurationField(); + fields.centuries = fields.centuryOfEra.getDurationField(); + fields.months = fields.monthOfYear.getDurationField(); + fields.weekyears = fields.weekyear.getDurationField(); + } + + /** + * Get the number of days in the year. + * @param year The year to use. + * @return 366 if a leap year, otherwise 365. + */ + final int getDaysInYear(int year) { + return isLeapYear(year) ? 366 : 365; + } + + final int getDaysInYearMonth(int year, int month) { + if (isLeapYear(year)) { + return MAX_DAYS_PER_MONTH_ARRAY[month - 1]; + } else { + return MIN_DAYS_PER_MONTH_ARRAY[month - 1]; + } + } + + /** + * Gets the maximum days in the specified month. + * + * @param month the month + * @return the max days + */ + final int getDaysInMonthMax(int month) { + return MAX_DAYS_PER_MONTH_ARRAY[month - 1]; + } + + /** + * Returns the total number of milliseconds elapsed in the year, by the end + * of the month. + */ + final long getTotalMillisByYearMonth(int year, int month) { + if (isLeapYear(year)) { + return MAX_TOTAL_MILLIS_BY_MONTH_ARRAY[month - 1]; + } else { + return MIN_TOTAL_MILLIS_BY_MONTH_ARRAY[month - 1]; + } + } + + /** + * Get the number of weeks in the year. + * @param year the year to use. + * @return number of weeks in the year. + */ + final int getWeeksInYear(int year) { + long firstWeekMillis1 = getFirstWeekOfYearMillis(year); + long firstWeekMillis2 = getFirstWeekOfYearMillis(year + 1); + return (int) ((firstWeekMillis2 - firstWeekMillis1) / DateTimeConstants.MILLIS_PER_WEEK); + } + + /** + * Get the millis for the first week of a year. + * @param year the year to use. + * @return millis + */ + final long getFirstWeekOfYearMillis(int year) { + long jan1millis = getYearMillis(year); + int jan1dayOfWeek = getDayOfWeek(jan1millis); + + if (jan1dayOfWeek > (8 - iMinDaysInFirstWeek)) { + // First week is end of previous year because it doesn't have enough days. + return jan1millis + (8 - jan1dayOfWeek) + * (long)DateTimeConstants.MILLIS_PER_DAY; + } else { + // First week is start of this year because it has enough days. + return jan1millis - (jan1dayOfWeek - 1) + * (long)DateTimeConstants.MILLIS_PER_DAY; + } + } + + /** + * Get the milliseconds for the start of a year. + * + * @param year The year to use. + * @return millis from 1970-01-01T00:00:00Z + */ + final long getYearMillis(int year) { + return getYearInfo(year).iFirstDayMillis; + //return calculateFirstDayOfYearMillis(year); + } + + /** + * Get the milliseconds for the start of a month. + * + * @param year The year to use. + * @param month The month to use + * @return millis from 1970-01-01T00:00:00Z + */ + final long getYearMonthMillis(int year, int month) { + long millis = getYearMillis(year); + // month + if (month > 1) { + millis += getTotalMillisByYearMonth(year, month - 1); + } + return millis; + } + + /** + * Get the milliseconds for a particular date. + * + * @param year The year to use. + * @param month The month to use + * @param dayOfMonth The day of the month to use + * @return millis from 1970-01-01T00:00:00Z + */ + final long getYearMonthDayMillis(int year, int month, int dayOfMonth) { + long millis = getYearMillis(year); + // month + if (month > 1) { + millis += getTotalMillisByYearMonth(year, month - 1); + } + // day + return millis + (dayOfMonth - 1) * (long)DateTimeConstants.MILLIS_PER_DAY; + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + */ + final int getYear(long instant) { + // Get an initial estimate of the year, and the millis value that + // represents the start of that year. Then verify estimate and fix if + // necessary. + + long unitMillis = getAverageMillisPerYear(); + long i2 = instant + getApproxMillisAtEpoch(); + if (i2 < 0) { + i2 = i2 - unitMillis + 1; + } + int year = (int) (i2 / unitMillis); + + long yearStart = getYearMillis(year); + long diff = instant - yearStart; + + if (diff < 0) { + if (diff < -DateTimeConstants.MILLIS_PER_DAY * 2L) { + // Too much error, assume operation overflowed. + return getYearOverflow(instant); + } + year--; + } else if (diff >= DateTimeConstants.MILLIS_PER_DAY * 365L) { + if (diff >= DateTimeConstants.MILLIS_PER_DAY * 367L) { + // Too much error, assume operation overflowed. + return getYearOverflow(instant); + } + // One year may need to be added to fix estimate. + long oneYear; + if (isLeapYear(year)) { + oneYear = DateTimeConstants.MILLIS_PER_DAY * 366L; + } else { + oneYear = DateTimeConstants.MILLIS_PER_DAY * 365L; + } + + yearStart += oneYear; + + if ((yearStart ^ instant) < 0) { + // Sign mismatch, operation may have overflowed. + if ((yearStart < 0 && (yearStart - oneYear) >= 0) || + (yearStart >= 0 && (yearStart - oneYear) < 0) ) { + // It overflowed. + return getYearOverflow(instant); + } + } + + if (yearStart <= instant) { + // Didn't go too far, so actually add one year. + year++; + } + } + + return year; + } + + private final int getYearOverflow(long instant) { + if (instant > 0) { + int year = getMaxYear(); + long yearStartMillis = getYearMillis(year); + if (isLeapYear(year)) { + yearStartMillis += DateTimeConstants.MILLIS_PER_DAY * 366L; + } else { + yearStartMillis += DateTimeConstants.MILLIS_PER_DAY * 365L; + } + long yearEndMillis = yearStartMillis - 1; + + if (instant <= yearEndMillis) { + return year; + } + + throw new IllegalArgumentException + ("Instant too large: " + instant + " > " + yearEndMillis); + } else { + int year = getMinYear(); + long yearStartMillis = getYearMillis(year); + if (instant >= yearStartMillis) { + return year; + } + + throw new IllegalArgumentException + ("Instant too small: " + instant + " < " + yearStartMillis); + } + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + */ + final long setYear(long instant, int year) { + int thisYear = getYear(instant); + int dayOfYear = getDayOfYear(instant, thisYear); + int millisOfDay = getMillisOfDay(instant); + + if (dayOfYear > (31 + 28)) { // after Feb 28 + if (isLeapYear(thisYear)) { + // Current date is Feb 29 or later. + if (!isLeapYear(year)) { + // Moving to a non-leap year, Feb 29 does not exist. + dayOfYear--; + } + } else { + // Current date is Mar 01 or later. + if (isLeapYear(year)) { + // Moving to a leap year, account for Feb 29. + dayOfYear++; + } + } + } + + instant = getYearMonthDayMillis(year, 1, dayOfYear); + instant += millisOfDay; + + return instant; + } + + /** + * @param millis from 1970-01-01T00:00:00Z + */ + final int getMonthOfYear(long millis) { + return getMonthOfYear(millis, getYear(millis)); + } + + /** + * @param millis from 1970-01-01T00:00:00Z + * @param year precalculated year of millis + */ + final int getMonthOfYear(long millis, int year) { + // Perform a binary search to get the month. To make it go even faster, + // compare using ints instead of longs. The number of milliseconds per + // year exceeds the limit of a 32-bit int's capacity, so divide by + // 1024. No precision is lost (except time of day) since the number of + // milliseconds per day contains 1024 as a factor. After the division, + // the instant isn't measured in milliseconds, but in units of + // (128/125)seconds. + + int i = (int)((millis - getYearMillis(year)) >> 10); + + // There are 86400000 milliseconds per day, but divided by 1024 is + // 84375. There are 84375 (128/125)seconds per day. + + return + (isLeapYear(year)) + ? ((i < 182 * 84375) + ? ((i < 91 * 84375) + ? ((i < 31 * 84375) ? 1 : (i < 60 * 84375) ? 2 : 3) + : ((i < 121 * 84375) ? 4 : (i < 152 * 84375) ? 5 : 6)) + : ((i < 274 * 84375) + ? ((i < 213 * 84375) ? 7 : (i < 244 * 84375) ? 8 : 9) + : ((i < 305 * 84375) ? 10 : (i < 335 * 84375) ? 11 : 12))) + : ((i < 181 * 84375) + ? ((i < 90 * 84375) + ? ((i < 31 * 84375) ? 1 : (i < 59 * 84375) ? 2 : 3) + : ((i < 120 * 84375) ? 4 : (i < 151 * 84375) ? 5 : 6)) + : ((i < 273 * 84375) + ? ((i < 212 * 84375) ? 7 : (i < 243 * 84375) ? 8 : 9) + : ((i < 304 * 84375) ? 10 : (i < 334 * 84375) ? 11 : 12))); + } + + /** + * @param millis from 1970-01-01T00:00:00Z + */ + final int getDayOfMonth(long millis) { + int year = getYear(millis); + int month = getMonthOfYear(millis, year); + return getDayOfMonth(millis, year, month); + } + + /** + * @param millis from 1970-01-01T00:00:00Z + * @param year precalculated year of millis + */ + final int getDayOfMonth(long millis, int year) { + int month = getMonthOfYear(millis, year); + return getDayOfMonth(millis, year, month); + } + + /** + * @param millis from 1970-01-01T00:00:00Z + * @param year precalculated year of millis + * @param month precalculated month of millis + */ + final int getDayOfMonth(long millis, int year, int month) { + long dateMillis = getYearMillis(year); + if (month > 1) { + dateMillis += getTotalMillisByYearMonth(year, month - 1); + } + return (int) ((millis - dateMillis) / DateTimeConstants.MILLIS_PER_DAY) + 1; + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + */ + final int getDayOfYear(long instant) { + return getDayOfYear(instant, getYear(instant)); + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + * @param year precalculated year of millis + */ + final int getDayOfYear(long instant, int year) { + long yearStart = getYearMillis(year); + return (int) ((instant - yearStart) / DateTimeConstants.MILLIS_PER_DAY) + 1; + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + */ + final int getWeekyear(long instant) { + int year = getYear(instant); + int week = getWeekOfWeekyear(instant, year); + if (week == 1) { + return getYear(instant + DateTimeConstants.MILLIS_PER_WEEK); + } else if (week > 51) { + return getYear(instant - (2 * DateTimeConstants.MILLIS_PER_WEEK)); + } else { + return year; + } + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + */ + final int getWeekOfWeekyear(long instant) { + return getWeekOfWeekyear(instant, getYear(instant)); + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + * @param year precalculated year of millis + */ + final int getWeekOfWeekyear(long instant, int year) { + long firstWeekMillis1 = getFirstWeekOfYearMillis(year); + if (instant < firstWeekMillis1) { + return getWeeksInYear(year - 1); + } + long firstWeekMillis2 = getFirstWeekOfYearMillis(year + 1); + if (instant >= firstWeekMillis2) { + return 1; + } + return (int) ((instant - firstWeekMillis1) / DateTimeConstants.MILLIS_PER_WEEK) + 1; + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + */ + final int getDayOfWeek(long instant) { + // 1970-01-01 is day of week 4, Thursday. + + long daysSince19700101; + if (instant >= 0) { + daysSince19700101 = instant / DateTimeConstants.MILLIS_PER_DAY; + } else { + daysSince19700101 = (instant - (DateTimeConstants.MILLIS_PER_DAY - 1)) + / DateTimeConstants.MILLIS_PER_DAY; + if (daysSince19700101 < -3) { + return 7 + (int) ((daysSince19700101 + 4) % 7); + } + } + + return 1 + (int) ((daysSince19700101 + 3) % 7); + } + + /** + * @param instant millis from 1970-01-01T00:00:00Z + */ + final int getMillisOfDay(long instant) { + if (instant >= 0) { + return (int) (instant % DateTimeConstants.MILLIS_PER_DAY); + } else { + return (DateTimeConstants.MILLIS_PER_DAY - 1) + + (int) ((instant + 1) % DateTimeConstants.MILLIS_PER_DAY); + } + } + + long getDateMidnightMillis(int year, int monthOfYear, int dayOfMonth) + throws IllegalArgumentException + { + FieldUtils.verifyValueBounds("year", year, getMinYear(), getMaxYear()); + FieldUtils.verifyValueBounds("monthOfYear", monthOfYear, 1, 12); + + boolean isLeap = isLeapYear(year); + + FieldUtils.verifyValueBounds("dayOfMonth", dayOfMonth, 1, + (isLeap ? MAX_DAYS_PER_MONTH_ARRAY : MIN_DAYS_PER_MONTH_ARRAY) + [monthOfYear - 1]); + + long instant = getYearMillis(year); + + if (monthOfYear > 1) { + instant += + (isLeap ? MAX_TOTAL_MILLIS_BY_MONTH_ARRAY : MIN_TOTAL_MILLIS_BY_MONTH_ARRAY) + [monthOfYear - 2]; + } + + if (dayOfMonth != 1) { + instant += (dayOfMonth - 1) * (long)DateTimeConstants.MILLIS_PER_DAY; + } + + return instant; + } + + abstract boolean isLeapYear(int year); + + abstract long calculateFirstDayOfYearMillis(int year); + + abstract int getMinYear(); + + abstract int getMaxYear(); + + abstract long getAverageMillisPerYear(); + + abstract long getAverageMillisPerMonth(); + + /** + * Returns a constant representing the approximate number of milliseconds + * elapsed from year 0 of this chronology. This constant must be + * defined as: + *

+     *    yearAtEpoch * averageMillisPerYear + millisOfYearAtEpoch
+     * 
+     * where epoch is 1970-01-01 (Gregorian).
+     */
+    abstract long getApproxMillisAtEpoch();
+
+    // Although accessed by multiple threads, this method doesn't need to be synchronized.
+    private YearInfo getYearInfo(int year) {
+        YearInfo[] cache = iYearInfoCache;
+        int index = year & iYearInfoCacheMask;
+        YearInfo info = cache[index];
+        if (info == null || info.iYear != year) {
+            info = new YearInfo(year, calculateFirstDayOfYearMillis(year));
+            cache[index] = info;
+        }
+        return info;
+    }
+
+    private static class HalfdayField extends PreciseDateTimeField {
+        private static final long serialVersionUID = 581601443656929254L;
+
+        HalfdayField() {
+            super(DateTimeFieldType.halfdayOfDay(), cHalfdaysField, cDaysField);
+        }
+
+        protected String getAsText(int fieldValue, Locale locale) {
+            return GJLocaleSymbols.forLocale(locale).halfdayValueToText(fieldValue);
+        }
+
+        public long set(long millis, String text, Locale locale) {
+            return set(millis, GJLocaleSymbols.forLocale(locale).halfdayTextToValue(text));
+        }
+
+        public int getMaximumTextLength(Locale locale) {
+            return GJLocaleSymbols.forLocale(locale).getHalfdayMaxTextLength();
+        }
+    }
+
+    private static class YearInfo {
+        public final int iYear;
+        public final long iFirstDayMillis;
+
+        YearInfo(int year, long firstDayMillis) {
+            iYear = year;
+            iFirstDayMillis = firstDayMillis;
+        }
+    }
+
+}
Index: 3rdParty_sources/joda-time/org/joda/time/chrono/BuddhistChronology.java
===================================================================
RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/BuddhistChronology.java,v
diff -u
--- /dev/null	1 Jan 1970 00:00:00 -0000
+++ 3rdParty_sources/joda-time/org/joda/time/chrono/BuddhistChronology.java	17 Aug 2012 14:54:58 -0000	1.1
@@ -0,0 +1,239 @@
+/*
+ * Joda Software License, Version 1.0
+ *
+ *
+ * Copyright (c) 2001-2004 Stephen Colebourne.  
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer. 
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * 3. The end-user documentation included with the redistribution,
+ *    if any, must include the following acknowledgment:  
+ *       "This product includes software developed by the
+ *        Joda project (http://www.joda.org/)."
+ *    Alternately, this acknowledgment may appear in the software itself,
+ *    if and wherever such third-party acknowledgments normally appear.
+ *
+ * 4. The name "Joda" must not be used to endorse or promote products
+ *    derived from this software without prior written permission. For
+ *    written permission, please contact licence@joda.org.
+ *
+ * 5. Products derived from this software may not be called "Joda",
+ *    nor may "Joda" appear in their name, without prior written
+ *    permission of the Joda project.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED.  IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
+ * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Joda project and was originally 
+ * created by Stephen Colebourne . For more
+ * information on the Joda project, please see .
+ */
+package org.joda.time.chrono;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.joda.time.Chronology;
+import org.joda.time.DateTime;
+import org.joda.time.DateTimeConstants;
+import org.joda.time.DateTimeField;
+import org.joda.time.DateTimeFieldType;
+import org.joda.time.DateTimeZone;
+import org.joda.time.field.DividedDateTimeField;
+import org.joda.time.field.OffsetDateTimeField;
+import org.joda.time.field.RemainderDateTimeField;
+
+/**
+ * Implements the Buddhist calendar system, which is similar to Gregorian/Julian,
+ * except with the year offset by 543.
+ * 

+ * The Buddhist calendar differs from the Gregorian/Julian calendar only + * in the year. This class is compatable with the BuddhistCalendar class + * supplied by Sun. + *

+ * BuddhistChronology is thread-safe and immutable. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public final class BuddhistChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -3474595157769370126L; + + /** + * Constant value for 'Buddhist Era', equivalent to the value returned + * for AD/CE. + */ + public static final int BE = DateTimeConstants.CE; + + /** Number of years difference in calendars. */ + private static final int BUDDHIST_OFFSET = 543; + + /** Cache of zone to chronology */ + private static final Map cCache = new HashMap(); + + /** UTC instance of the chronology */ + private static final BuddhistChronology INSTANCE_UTC = getInstance(DateTimeZone.UTC); + + /** + * Standard instance of a Buddhist Chronology, that matches + * Sun's BuddhistCalendar class. This means that it follows the + * GregorianJulian calendar rules with a cutover date. + *

+ * The time zone of the returned instance is UTC. + */ + public static BuddhistChronology getInstanceUTC() { + return INSTANCE_UTC; + } + + /** + * Standard instance of a Buddhist Chronology, that matches + * Sun's BuddhistCalendar class. This means that it follows the + * GregorianJulian calendar rules with a cutover date. + */ + public static BuddhistChronology getInstance() { + return getInstance(DateTimeZone.getDefault()); + } + + /** + * Standard instance of a Buddhist Chronology, that matches + * Sun's BuddhistCalendar class. This means that it follows the + * GregorianJulian calendar rules with a cutover date. + * + * @param zone the time zone to use, null is default + */ + public static synchronized BuddhistChronology getInstance(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + BuddhistChronology chrono = (BuddhistChronology) cCache.get(zone); + if (chrono == null) { + // First create without a lower limit. + chrono = new BuddhistChronology(GJChronology.getInstance(zone, null), null); + // Impose lower limit and make another BuddhistChronology. + DateTime lowerLimit = new DateTime(1, 1, 1, 0, 0, 0, 0, chrono); + chrono = new BuddhistChronology(LimitChronology.getInstance(chrono, lowerLimit, null), ""); + cCache.put(zone, chrono); + } + return chrono; + } + + // Constructors and instance variables + //----------------------------------------------------------------------- + + /** + * Restricted constructor. + * + * @param param if non-null, then don't change the field set + */ + private BuddhistChronology(Chronology base, Object param) { + super(base, param); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + Chronology base = getBase(); + return base == null ? getInstanceUTC() : getInstance(base.getZone()); + } + + // Conversion + //----------------------------------------------------------------------- + /** + * Gets the Chronology in the UTC time zone. + * + * @return the chronology in UTC + */ + public Chronology withUTC() { + return INSTANCE_UTC; + } + + /** + * Gets the Chronology in a specific time zone. + * + * @param zone the zone to get the chronology in, null is default + * @return the chronology + */ + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getZone()) { + return this; + } + return getInstance(zone); + } + + // Output + //----------------------------------------------------------------------- + /** + * Gets a debugging toString. + * + * @return a debugging string + */ + public String toString() { + String str = "BuddhistChronology"; + DateTimeZone zone = getZone(); + if (zone != null) { + str = str + '[' + zone.getID() + ']'; + } + return str; + } + + protected void assemble(Fields fields) { + if (getParam() == null) { + DateTimeField field = fields.year; + fields.year = new OffsetDateTimeField(field, BUDDHIST_OFFSET); + + field = fields.yearOfEra; + fields.yearOfEra = new OffsetDateTimeField( + fields.year, DateTimeFieldType.yearOfEra(), BUDDHIST_OFFSET); + + field = fields.weekyear; + fields.weekyear = new OffsetDateTimeField(field, BUDDHIST_OFFSET); + + field = new OffsetDateTimeField(fields.yearOfEra, 99); + fields.centuryOfEra = new DividedDateTimeField( + field, DateTimeFieldType.centuryOfEra(), 100); + + field = new RemainderDateTimeField( + (DividedDateTimeField) fields.centuryOfEra); + fields.yearOfCentury = new OffsetDateTimeField( + field, DateTimeFieldType.yearOfCentury(), 1); + + field = new RemainderDateTimeField( + fields.weekyear, DateTimeFieldType.weekyearOfCentury(), 100); + fields.weekyearOfCentury = new OffsetDateTimeField( + field, DateTimeFieldType.weekyearOfCentury(), 1); + + fields.era = BuddhistEraDateTimeField.INSTANCE; + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/BuddhistEraDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/BuddhistEraDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/BuddhistEraDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,179 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.Locale; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; +import org.joda.time.field.BaseDateTimeField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.UnsupportedDurationField; + +/** + * Provides time calculations for the buddhist era component of time. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +final class BuddhistEraDateTimeField extends BaseDateTimeField { + + /** Serialization version */ + private static final long serialVersionUID = -9175876774456816364L; + + /** + * Singleton instance + */ + static final DateTimeField INSTANCE = new BuddhistEraDateTimeField(); + + /** + * Restricted constructor + */ + private BuddhistEraDateTimeField() { + super(DateTimeFieldType.era()); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return INSTANCE; + } + + public boolean isLenient() { + return false; + } + + /** + * Get the Era component of the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the era extracted from the input. + */ + public int get(long instant) { + return BuddhistChronology.BE; + } + + /** + * Set the Era component of the specified time instant. + * + * @param instant the time instant in millis to update. + * @param era the era (BuddhistChronology.BE) to update the time to. + * @return the updated time instant. + * @throws IllegalArgumentException if era is invalid. + */ + public long set(long instant, int era) { + FieldUtils.verifyValueBounds(this, era, getMinimumValue(), getMaximumValue()); + + return instant; + } + + /** + * @see org.joda.time.DateTimeField#set(long, String, Locale) + */ + public long set(long instant, String text, Locale locale) { + if ("BE".equals(text) == false) { + throw new IllegalArgumentException("Invalid era text: " + text); + } + return instant; + } + + public long roundFloor(long instant) { + return Long.MIN_VALUE; + } + + public long roundCeiling(long instant) { + return Long.MAX_VALUE; + } + + public long roundHalfFloor(long instant) { + return Long.MIN_VALUE; + } + + public long roundHalfCeiling(long instant) { + return Long.MIN_VALUE; + } + + public long roundHalfEven(long instant) { + return Long.MIN_VALUE; + } + + public DurationField getDurationField() { + return UnsupportedDurationField.getInstance(DurationFieldType.eras()); + } + + public DurationField getRangeDurationField() { + return null; + } + + public int getMinimumValue() { + return BuddhistChronology.BE; + } + + public int getMaximumValue() { + return BuddhistChronology.BE; + } + + protected String getAsText(int fieldValue, Locale locale) { + return "BE"; + } + + public int getMaximumTextLength(Locale locale) { + return 2; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/CopticChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/CopticChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/CopticChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,328 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.HashMap; +import java.util.Map; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.PreciseDurationField; + +/** + * Implements the Coptic calendar system, which defines every fourth year as + * leap, much like the Julian calendar. The year is broken down into 12 months, + * each 30 days in length. An extra period at the end of the year is either 5 + * or 6 days in length. In this implementation, it is considered a 13th month. + *

+ * Year 1 in the Coptic calendar began on August 29, 284 CE (Julian), thus + * Coptic years do not begin at the same time as Julian years. This chronology + * is not proleptic, as it does not allow dates before the first Coptic year. + *

+ * CopticChronology is thread-safe and immutable. + * + * @see Wikipedia + * @see JulianChronology + * + * @author Brian S O'Neill + * @since 1.0 + */ +public final class CopticChronology extends BaseGJChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -5972804258688333942L; + + /** + * Constant value for 'Anno Martyrum' or 'Era of the Martyrs', equivalent + * to the value returned for AD/CE. + */ + public static final int AM = DateTimeConstants.CE; + + private static final long MILLIS_PER_YEAR = + (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY); + + private static final long MILLIS_PER_MONTH = + (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY / 12); + + private static final DurationField cMonthsField; + + /** Singleton instance of a UTC CopticChronology */ + private static final CopticChronology INSTANCE_UTC; + + /** Cache of zone to chronology arrays */ + private static final Map cCache = new HashMap(); + + static { + cMonthsField = new PreciseDurationField + (DurationFieldType.months(), 30L * DateTimeConstants.MILLIS_PER_DAY); + INSTANCE_UTC = getInstance(DateTimeZone.UTC); + } + + /** + * Gets an instance of the CopticChronology. + * The time zone of the returned instance is UTC. + * + * @return a singleton UTC instance of the chronology + */ + public static CopticChronology getInstanceUTC() { + return INSTANCE_UTC; + } + + /** + * Gets an instance of the CopticChronology in the default time zone. + * + * @return a chronology in the default time zone + */ + public static CopticChronology getInstance() { + return getInstance(DateTimeZone.getDefault(), 4); + } + + /** + * Gets an instance of the CopticChronology in the given time zone. + * + * @param zone the time zone to get the chronology in, null is default + * @return a chronology in the specified time zone + */ + public static CopticChronology getInstance(DateTimeZone zone) { + return getInstance(zone, 4); + } + + /** + * Gets an instance of the CopticChronology in the given time zone. + * + * @param zone the time zone to get the chronology in, null is default + * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 + * @return a chronology in the specified time zone + */ + public static CopticChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + CopticChronology chrono; + synchronized (cCache) { + CopticChronology[] chronos = (CopticChronology[]) cCache.get(zone); + if (chronos == null) { + chronos = new CopticChronology[7]; + cCache.put(zone, chronos); + } + try { + chrono = chronos[minDaysInFirstWeek - 1]; + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException + ("Invalid min days in first week: " + minDaysInFirstWeek); + } + if (chrono == null) { + if (zone == DateTimeZone.UTC) { + // First create without a lower limit. + chrono = new CopticChronology(null, null, minDaysInFirstWeek); + // Impose lower limit and make another CopticChronology. + DateTime lowerLimit = new DateTime(1, 1, 1, 0, 0, 0, 0, chrono); + chrono = new CopticChronology + (LimitChronology.getInstance(chrono, lowerLimit, null), + null, minDaysInFirstWeek); + } else { + chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); + chrono = new CopticChronology + (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); + } + chronos[minDaysInFirstWeek - 1] = chrono; + } + } + return chrono; + } + + // Constructors and instance variables + //----------------------------------------------------------------------- + + /** + * Restricted constructor + */ + CopticChronology(Chronology base, Object param, int minDaysInFirstWeek) { + super(base, param, minDaysInFirstWeek); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + Chronology base = getBase(); + return base == null ? getInstanceUTC() : getInstance(base.getZone()); + } + + // Conversion + //----------------------------------------------------------------------- + /** + * Gets the Chronology in the UTC time zone. + * + * @return the chronology in UTC + */ + public Chronology withUTC() { + return INSTANCE_UTC; + } + + /** + * Gets the Chronology in a specific time zone. + * + * @param zone the zone to get the chronology in, null is default + * @return the chronology + */ + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getZone()) { + return this; + } + return getInstance(zone); + } + + long getDateMidnightMillis(int year, int monthOfYear, int dayOfMonth) + throws IllegalArgumentException + { + FieldUtils.verifyValueBounds("year", year, getMinYear(), getMaxYear()); + FieldUtils.verifyValueBounds("monthOfYear", monthOfYear, 1, 13); + + int dayLimit = (monthOfYear != 13) ? 30 : (isLeapYear(year) ? 6 : 5); + FieldUtils.verifyValueBounds("dayOfMonth", dayOfMonth, 1, dayLimit); + + long instant = getYearMillis(year); + + if (monthOfYear > 1) { + instant += (monthOfYear - 1) * 30L * DateTimeConstants.MILLIS_PER_DAY; + } + + if (dayOfMonth != 1) { + instant += (dayOfMonth - 1) * (long)DateTimeConstants.MILLIS_PER_DAY; + } + + return instant; + } + + boolean isLeapYear(int year) { + return (year & 3) == 3; + } + + long calculateFirstDayOfYearMillis(int year) { + // Java epoch is 1970-01-01 Gregorian which is 1686-04-23 Coptic. + // Calculate relative to the nearest leap year and account for the + // difference later. + + int relativeYear = year - 1687; + int leapYears; + if (relativeYear <= 0) { + // Add 3 before shifting right since /4 and >>2 behave differently + // on negative numbers. + leapYears = (relativeYear + 3) >> 2; + } else { + leapYears = relativeYear >> 2; + // For post 1687 an adjustment is needed as jan1st is before leap day + if (!isLeapYear(year)) { + leapYears++; + } + } + + long millis = (relativeYear * 365L + leapYears) + * (long)DateTimeConstants.MILLIS_PER_DAY; + + // Adjust to account for difference between 1687-01-01 and 1686-04-23. + + return millis + (365L - 112) * DateTimeConstants.MILLIS_PER_DAY; + } + + int getMinYear() { + // The lowest year that can be fully supported. + return -292269337; + } + + int getMaxYear() { + // The highest year that can be fully supported. + return 292271022; + } + + long getAverageMillisPerYear() { + return MILLIS_PER_YEAR; + } + + long getAverageMillisPerMonth() { + return MILLIS_PER_MONTH; + } + + long getApproxMillisAtEpoch() { + return 1686L * MILLIS_PER_YEAR + 112L * DateTimeConstants.MILLIS_PER_DAY; + } + + protected void assemble(Fields fields) { + if (getBase() == null) { + super.assemble(fields); + + fields.year = new CopticYearDateTimeField(this); + fields.years = fields.year.getDurationField(); + + // Coptic, like Julian, has no year zero. + fields.year = new JulianChronology.NoYearZeroField(this, fields.year); + fields.weekyear = new JulianChronology.NoWeekyearZeroField(this, fields.weekyear); + + fields.era = CopticEraDateTimeField.INSTANCE; + fields.months = cMonthsField; + fields.monthOfYear = new CopticMonthOfYearDateTimeField(this, cMonthsField); + fields.dayOfMonth = new CopticDayOfMonthDateTimeField(this, fields.days); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/CopticDayOfMonthDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/CopticDayOfMonthDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/CopticDayOfMonthDateTimeField.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,149 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; +import org.joda.time.field.PreciseDurationDateTimeField; + +/** + * Provides time calculations for the day of the month component of time. + * + * @author Brian S O'Neill + * @since 1.0 + */ +final class CopticDayOfMonthDateTimeField extends PreciseDurationDateTimeField { + + private static final long serialVersionUID = -5441610762799659434L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor. + */ + CopticDayOfMonthDateTimeField(BaseGJChronology chronology, DurationField days) { + super(DateTimeFieldType.dayOfMonth(), days); + iChronology = chronology; + } + + public int get(long instant) { + return (iChronology.getDayOfYear(instant) - 1) % 30 + 1; + } + + public DurationField getRangeDurationField() { + return iChronology.months(); + } + + public int getMinimumValue() { + return 1; + } + + public int getMaximumValue() { + return 30; + } + + public int getMaximumValue(long instant) { + if (((iChronology.getDayOfYear(instant) - 1) / 30) < 12) { + return 30; + } + return iChronology.isLeapYear(iChronology.getYear(instant)) ? 6 : 5; + } + + public int getMaximumValue(ReadablePartial partial) { + if (partial.isSupported(DateTimeFieldType.monthOfYear())) { + // find month + int month = partial.get(DateTimeFieldType.monthOfYear()); + if (month <= 12) { + return 30; + } + // 13th month, so check year + if (partial.isSupported(DateTimeFieldType.year())) { + int year = partial.get(DateTimeFieldType.year()); + return iChronology.isLeapYear(year) ? 6 : 5; + } + return 6; + } + return 30; + } + + public int getMaximumValue(ReadablePartial partial, int[] values) { + int size = partial.size(); + for (int i = 0; i < size; i++) { + // find month + if (partial.getFieldType(i) == DateTimeFieldType.monthOfYear()) { + int month = values[i]; + if (month <= 12) { + return 30; + } + // 13th month, so check year + for (int j = 0; j < size; j++) { + if (partial.getFieldType(j) == DateTimeFieldType.year()) { + int year = values[j]; + return iChronology.isLeapYear(year) ? 6 : 5; + } + } + return 6; + } + } + return 30; + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.dayOfMonth(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/CopticEraDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/CopticEraDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/CopticEraDateTimeField.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,178 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.Locale; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; +import org.joda.time.field.BaseDateTimeField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.UnsupportedDurationField; + +/** + * Provides time calculations for the coptic era component of time. + * + * @author Brian S O'Neill + * @since 1.0 + */ +final class CopticEraDateTimeField extends BaseDateTimeField { + + /** Serialization version */ + private static final long serialVersionUID = 4090856468123006167L; + + /** + * Singleton instance + */ + static final DateTimeField INSTANCE = new CopticEraDateTimeField(); + + /** + * Restricted constructor + */ + private CopticEraDateTimeField() { + super(DateTimeFieldType.era()); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return INSTANCE; + } + + public boolean isLenient() { + return false; + } + + /** + * Get the Era component of the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the era extracted from the input. + */ + public int get(long instant) { + return CopticChronology.AM; + } + + /** + * Set the Era component of the specified time instant. + * + * @param instant the time instant in millis to update. + * @param era the era (CopticChronology.AM) to update the time to. + * @return the updated time instant. + * @throws IllegalArgumentException if era is invalid. + */ + public long set(long instant, int era) { + FieldUtils.verifyValueBounds(this, era, getMinimumValue(), getMaximumValue()); + + return instant; + } + + /** + * @see org.joda.time.DateTimeField#set(long, String, Locale) + */ + public long set(long instant, String text, Locale locale) { + if ("AM".equals(text) == false) { + throw new IllegalArgumentException("Invalid era text: " + text); + } + return instant; + } + + public long roundFloor(long instant) { + return Long.MIN_VALUE; + } + + public long roundCeiling(long instant) { + return Long.MAX_VALUE; + } + + public long roundHalfFloor(long instant) { + return Long.MIN_VALUE; + } + + public long roundHalfCeiling(long instant) { + return Long.MIN_VALUE; + } + + public long roundHalfEven(long instant) { + return Long.MIN_VALUE; + } + + public DurationField getDurationField() { + return UnsupportedDurationField.getInstance(DurationFieldType.eras()); + } + + public DurationField getRangeDurationField() { + return null; + } + + public int getMinimumValue() { + return CopticChronology.AM; + } + + public int getMaximumValue() { + return CopticChronology.AM; + } + + protected String getAsText(int fieldValue, Locale locale) { + return "AM"; + } + + public int getMaximumTextLength(Locale locale) { + return 2; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/CopticMonthOfYearDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/CopticMonthOfYearDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/CopticMonthOfYearDateTimeField.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,127 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.field.PreciseDurationDateTimeField; + +/** + * + * + * @author Brian S O'Neill + */ +final class CopticMonthOfYearDateTimeField extends PreciseDurationDateTimeField { + + private static final long serialVersionUID = 7741038885247700323L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor. + */ + CopticMonthOfYearDateTimeField(BaseGJChronology chronology, DurationField months) { + super(DateTimeFieldType.monthOfYear(), months); + iChronology = chronology; + } + + public int get(long instant) { + return (iChronology.getDayOfYear(instant) - 1) / 30 + 1; + } + + public long set(long instant, int value) { + instant = super.set(instant, value); + if (value == 13) { + int day = iChronology.getDayOfYear(instant); + if (day < 30) { + // Move back a few days to the end of the 13th "month". + instant -= (long)DateTimeConstants.MILLIS_PER_DAY * day; + } + } + return instant; + } + + public DurationField getRangeDurationField() { + return iChronology.years(); + } + + public boolean isLeap(long instant) { + return get(instant) > 12 && iChronology.isLeapYear(iChronology.getYear(instant)); + } + + public int getLeapAmount(long instant) { + return isLeap(instant) ? 1 : 0; + } + + public DurationField getLeapDurationField() { + return iChronology.days(); + } + + public int getMinimumValue() { + return 1; + } + + public int getMaximumValue() { + return 13; + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.monthOfYear(); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/CopticYearDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/CopticYearDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/CopticYearDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,205 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.ImpreciseDateTimeField; + +/** + * + * @author Brian S O'Neill + * @since 1.0 + */ +final class CopticYearDateTimeField extends ImpreciseDateTimeField { + + private static final long serialVersionUID = 8990199361773280783L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor + */ + CopticYearDateTimeField(BaseGJChronology chronology) { + super(DateTimeFieldType.year(), chronology.getAverageMillisPerYear()); + iChronology = chronology; + } + + public boolean isLenient() { + return false; + } + + public int get(long instant) { + return iChronology.getYear(instant); + } + + public long add(long instant, int years) { + if (years == 0) { + return instant; + } + return set(instant, get(instant) + years); + } + + public long add(long instant, long years) { + return add(instant, FieldUtils.safeToInt(years)); + } + + public long addWrapField(long instant, int years) { + if (years == 0) { + return instant; + } + // Return newly calculated millis value + int thisYear = iChronology.getYear(instant); + int wrappedYear = FieldUtils.getWrappedValue + (thisYear, years, iChronology.getMinYear(), iChronology.getMaxYear()); + return set(instant, wrappedYear); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + if (minuendInstant < subtrahendInstant) { + return -getDifference(subtrahendInstant, minuendInstant); + } + + int minuendYear = get(minuendInstant); + int subtrahendYear = get(subtrahendInstant); + + // Inlined remainder method to avoid duplicate calls to get. + long minuendRem = minuendInstant - iChronology.getYearMillis(minuendYear); + long subtrahendRem = subtrahendInstant - iChronology.getYearMillis(subtrahendYear); + + int difference = minuendYear - subtrahendYear; + if (minuendRem < subtrahendRem) { + difference--; + } + return difference; + } + + public long set(long instant, int year) { + FieldUtils.verifyValueBounds + (this, year, iChronology.getMinYear(), iChronology.getMaxYear()); + + BaseGJChronology chrono = iChronology; + + int thisYear = chrono.getYear(instant); + int dayOfYear = chrono.getDayOfYear(instant, thisYear); + int millisOfDay = chrono.getMillisOfDay(instant); + + if (dayOfYear > 365) { + // Current year is leap, and day is leap. + if (!chrono.isLeapYear(year)) { + // Moving to a non-leap year, leap day doesn't exist. + dayOfYear--; + } + } + + instant = chrono.getYearMonthDayMillis(year, 1, dayOfYear); + instant += millisOfDay; + + return instant; + } + + public DurationField getRangeDurationField() { + return null; + } + + public boolean isLeap(long instant) { + return iChronology.isLeapYear(get(instant)); + } + + public int getLeapAmount(long instant) { + if (iChronology.isLeapYear(get(instant))) { + return 1; + } else { + return 0; + } + } + + public DurationField getLeapDurationField() { + return iChronology.days(); + } + + public int getMinimumValue() { + return iChronology.getMinYear(); + } + + public int getMaximumValue() { + return iChronology.getMaxYear(); + } + + public long roundFloor(long instant) { + return iChronology.getYearMillis(get(instant)); + } + + public long roundCeiling(long instant) { + int year = get(instant); + long yearStartMillis = iChronology.getYearMillis(year); + if (instant != yearStartMillis) { + // Bump up to start of next year. + instant = iChronology.getYearMillis(year + 1); + } + return instant; + } + + public long remainder(long instant) { + return instant - roundFloor(instant); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.year(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/GJChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,1043 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationField; +import org.joda.time.Instant; +import org.joda.time.ReadableInstant; +import org.joda.time.field.BaseDateTimeField; +import org.joda.time.field.DecoratedDurationField; +import org.joda.time.format.DateTimePrinter; +import org.joda.time.format.ISODateTimeFormat; + +/** + * Implements the Gregorian/Julian calendar system which is the calendar system + * used in most of the world. Wherever possible, it is recommended to use the + * {@link ISOChronology} instead. + *

+ * The Gregorian calendar replaced the Julian calendar, and the point in time + * when this chronology switches can be controlled using the second parameter + * of the getInstance method. By default this cutover is set to the date the + * Gregorian calendar was first instituted, October 15, 1582. + *

+ * Before this date, this chronology uses the proleptic Julian calendar + * (proleptic means extending indefinitely). The Julian calendar has leap years + * every four years, whereas the Gregorian has special rules for 100 and 400 + * years. A meaningful result will thus be obtained for all input values. + * However before 8 CE, Julian leap years were irregular, and before 45 BCE + * there was no Julian calendar. + *

+ * This chronology differs from + * {@link java.util.GregorianCalendar GregorianCalendar} in that years + * in BCE are returned correctly. Thus year 1 BCE is returned as -1 instead of 1. + * The yearOfEra field produces results compatible with GregorianCalendar. + *

+ * The Julian calendar does not have a year zero, and so year -1 is followed by + * year 1. If the Gregorian cutover date is specified at or before year -1 + * (Julian), year zero is defined. In other words, the proleptic Gregorian + * chronology used by this class has a year zero. + *

+ * To create a pure proleptic Julian chronology, use {@link JulianChronology}, + * and to create a pure proleptic Gregorian chronology, use + * {@link GregorianChronology}. + *

+ * GJChronology is thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public final class GJChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -2545574827706931671L; + + /** + * Convert a datetime from one chronology to another. + */ + private static long convertByYear(long instant, Chronology from, Chronology to) { + return to.getDateTimeMillis + (from.year().get(instant), + from.monthOfYear().get(instant), + from.dayOfMonth().get(instant), + from.millisOfDay().get(instant)); + } + + /** + * Convert a datetime from one chronology to another. + */ + private static long convertByWeekyear(final long instant, Chronology from, Chronology to) { + long newInstant; + newInstant = to.weekyear().set(0, from.weekyear().get(instant)); + newInstant = to.weekOfWeekyear().set(newInstant, from.weekOfWeekyear().get(instant)); + newInstant = to.dayOfWeek().set(newInstant, from.dayOfWeek().get(instant)); + newInstant = to.millisOfDay().set(newInstant, from.millisOfDay().get(instant)); + return newInstant; + } + + /** + * The default GregorianJulian cutover point. + */ + static final Instant DEFAULT_CUTOVER = new Instant(-12219292800000L); + + /** Cache of zone to chronology list */ + private static final Map cCache = new HashMap(); + + /** + * Factory method returns instances of the default GJ cutover + * chronology. This uses a cutover date of October 15, 1582 (Gregorian) + * 00:00:00 UTC. For this value, October 4, 1582 (Julian) is followed by + * October 15, 1582 (Gregorian). + * + *

The first day of the week is designated to be + * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, + * and the minimum days in the first week of the year is 4. + * + *

The time zone of the returned instance is UTC. + */ + public static GJChronology getInstanceUTC() { + return getInstance(DateTimeZone.UTC, DEFAULT_CUTOVER, 4); + } + + /** + * Factory method returns instances of the default GJ cutover + * chronology. This uses a cutover date of October 15, 1582 (Gregorian) + * 00:00:00 UTC. For this value, October 4, 1582 (Julian) is followed by + * October 15, 1582 (Gregorian). + * + *

The first day of the week is designated to be + * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, + * and the minimum days in the first week of the year is 4. + * + *

The returned chronology is in the default time zone. + */ + public static GJChronology getInstance() { + return getInstance(DateTimeZone.getDefault(), DEFAULT_CUTOVER, 4); + } + + /** + * Factory method returns instances of the GJ cutover chronology. This uses + * a cutover date of October 15, 1582 (Gregorian) 00:00:00 UTC. For this + * value, October 4, 1582 (Julian) is followed by October 15, 1582 + * (Gregorian). + * + *

The first day of the week is designated to be + * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, + * and the minimum days in the first week of the year is 4. + * + * @param zone the time zone to use, null is default + */ + public static GJChronology getInstance(DateTimeZone zone) { + return getInstance(zone, DEFAULT_CUTOVER, 4); + } + + /** + * Factory method returns instances of the GJ cutover chronology. Any + * cutover date may be specified. + * + *

The first day of the week is designated to be + * {@link org.joda.time.DateTimeConstants#MONDAY Monday}, + * and the minimum days in the first week of the year is 4. + * + * @param zone the time zone to use, null is default + * @param gregorianCutover the cutover to use, null means default + */ + public static GJChronology getInstance( + DateTimeZone zone, + ReadableInstant gregorianCutover) { + + return getInstance(zone, gregorianCutover, 4); + } + + /** + * Factory method returns instances of the GJ cutover chronology. Any + * cutover date may be specified. + * + * @param zone the time zone to use, null is default + * @param gregorianCutover the cutover to use, null means default + * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 + */ + public static synchronized GJChronology getInstance( + DateTimeZone zone, + ReadableInstant gregorianCutover, + int minDaysInFirstWeek) { + + zone = DateTimeUtils.getZone(zone); + Instant cutoverInstant; + if (gregorianCutover == null) { + cutoverInstant = DEFAULT_CUTOVER; + } else { + cutoverInstant = gregorianCutover.toInstant(); + } + + GJChronology chrono; + + ArrayList chronos = (ArrayList)cCache.get(zone); + if (chronos == null) { + chronos = new ArrayList(2); + cCache.put(zone, chronos); + } else { + for (int i=chronos.size(); --i>=0; ) { + chrono = (GJChronology)chronos.get(i); + if (minDaysInFirstWeek == chrono.getMinimumDaysInFirstWeek() && + cutoverInstant.equals(chrono.getGregorianCutover())) { + + return chrono; + } + } + } + + if (zone == DateTimeZone.UTC) { + chrono = new GJChronology + (JulianChronology.getInstance(zone, minDaysInFirstWeek), + GregorianChronology.getInstance(zone, minDaysInFirstWeek), + cutoverInstant); + } else { + chrono = getInstance(DateTimeZone.UTC, cutoverInstant, minDaysInFirstWeek); + chrono = new GJChronology + (ZonedChronology.getInstance(chrono, zone), + chrono.iJulianChronology, + chrono.iGregorianChronology, + chrono.iCutoverInstant); + } + + chronos.add(chrono); + + return chrono; + } + + /** + * Factory method returns instances of the GJ cutover chronology. Any + * cutover date may be specified. + * + * @param zone the time zone to use, null is default + * @param gregorianCutover the cutover to use + * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 + */ + public static GJChronology getInstance( + DateTimeZone zone, + long gregorianCutover, + int minDaysInFirstWeek) { + + Instant cutoverInstant; + if (gregorianCutover == DEFAULT_CUTOVER.getMillis()) { + cutoverInstant = null; + } else { + cutoverInstant = new Instant(gregorianCutover); + } + return getInstance(zone, cutoverInstant, minDaysInFirstWeek); + } + + //----------------------------------------------------------------------- + private JulianChronology iJulianChronology; + private GregorianChronology iGregorianChronology; + private Instant iCutoverInstant; + + private long iCutoverMillis; + private long iGapDuration; + + /** + * @param julian chronology used before the cutover instant + * @param gregorian chronology used at and after the cutover instant + * @param cutoverInstant instant when the gregorian chronology began + */ + private GJChronology(JulianChronology julian, + GregorianChronology gregorian, + Instant cutoverInstant) { + super(null, new Object[] {julian, gregorian, cutoverInstant}); + } + + /** + * Called when applying a time zone. + */ + private GJChronology(Chronology base, + JulianChronology julian, + GregorianChronology gregorian, + Instant cutoverInstant) { + super(base, new Object[] {julian, gregorian, cutoverInstant}); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return getInstance(getZone(), iCutoverInstant, getMinimumDaysInFirstWeek()); + } + + public DateTimeZone getZone() { + Chronology base; + if ((base = getBase()) != null) { + return base.getZone(); + } + return DateTimeZone.UTC; + } + + // Conversion + //----------------------------------------------------------------------- + /** + * Gets the Chronology in the UTC time zone. + * + * @return the chronology in UTC + */ + public Chronology withUTC() { + return withZone(DateTimeZone.UTC); + } + + /** + * Gets the Chronology in a specific time zone. + * + * @param zone the zone to get the chronology in, null is default + * @return the chronology + */ + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getZone()) { + return this; + } + return getInstance(zone, iCutoverInstant, getMinimumDaysInFirstWeek()); + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int millisOfDay) + throws IllegalArgumentException + { + Chronology base; + if ((base = getBase()) != null) { + return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); + } + + // Assume date is Gregorian. + long instant = iGregorianChronology.getDateTimeMillis + (year, monthOfYear, dayOfMonth, millisOfDay); + if (instant < iCutoverMillis) { + // Maybe it's Julian. + instant = iJulianChronology.getDateTimeMillis + (year, monthOfYear, dayOfMonth, millisOfDay); + if (instant >= iCutoverMillis) { + // Okay, it's in the illegal cutover gap. + throw new IllegalArgumentException("Specified date does not exist"); + } + } + return instant; + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + Chronology base; + if ((base = getBase()) != null) { + return base.getDateTimeMillis + (year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + } + + // Assume date is Gregorian. + long instant = iGregorianChronology.getDateTimeMillis + (year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + if (instant < iCutoverMillis) { + // Maybe it's Julian. + instant = iJulianChronology.getDateTimeMillis + (year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + if (instant >= iCutoverMillis) { + // Okay, it's in the illegal cutover gap. + throw new IllegalArgumentException("Specified date does not exist"); + } + } + return instant; + } + + /** + * Gets the cutover instant between Gregorian and Julian chronologies. + * @return the cutover instant + */ + public Instant getGregorianCutover() { + return iCutoverInstant; + } + + /** + * Gets the minimum days needed for a week to be the first week in a year. + * + * @return the minimum days + */ + public int getMinimumDaysInFirstWeek() { + return iGregorianChronology.getMinimumDaysInFirstWeek(); + } + + // Output + //----------------------------------------------------------------------- + /** + * Gets a debugging toString. + * + * @return a debugging string + */ + public String toString() { + StringBuffer sb = new StringBuffer(60); + sb.append("GJChronology"); + sb.append('['); + sb.append(getZone().getID()); + + if (iCutoverMillis != DEFAULT_CUTOVER.getMillis()) { + sb.append(",cutover="); + DateTimePrinter printer; + if (withUTC().dayOfYear().remainder(iCutoverMillis) == 0) { + printer = ISODateTimeFormat.getInstance().date(); + } else { + printer = ISODateTimeFormat.getInstance().dateTime(); + } + printer.printTo(sb, iCutoverMillis, withUTC()); + } + + if (getMinimumDaysInFirstWeek() != 4) { + sb.append(",mdfw="); + sb.append(getMinimumDaysInFirstWeek()); + } + sb.append(']'); + + return sb.toString(); + } + + protected void assemble(Fields fields) { + Object[] params = (Object[])getParam(); + + JulianChronology julian = (JulianChronology)params[0]; + GregorianChronology gregorian = (GregorianChronology)params[1]; + Instant cutoverInstant = (Instant)params[2]; + iCutoverMillis = cutoverInstant.getMillis(); + + iJulianChronology = julian; + iGregorianChronology = gregorian; + iCutoverInstant = cutoverInstant; + + if (getBase() != null) { + return; + } + + if (julian.getMinimumDaysInFirstWeek() != gregorian.getMinimumDaysInFirstWeek()) { + throw new IllegalArgumentException(); + } + + // Compute difference between the chronologies at the cutover instant + iGapDuration = iCutoverMillis - julianToGregorianByYear(iCutoverMillis); + + // Begin field definitions. + + // First just copy all the Gregorian fields and then override those + // that need special attention. + fields.copyFieldsFrom(gregorian); + + // Assuming cutover is at midnight, all time of day fields can be + // gregorian since they are unaffected by cutover. + + // Verify assumption. + if (gregorian.millisOfDay().get(iCutoverMillis) == 0) { + // Cutover is sometime in the day, so cutover fields are required + // for time of day. + + fields.millisOfSecond = new CutoverField(julian.millisOfSecond(), fields.millisOfSecond, iCutoverMillis); + fields.millisOfDay = new CutoverField(julian.millisOfDay(), fields.millisOfDay, iCutoverMillis); + fields.secondOfMinute = new CutoverField(julian.secondOfMinute(), fields.secondOfMinute, iCutoverMillis); + fields.secondOfDay = new CutoverField(julian.secondOfDay(), fields.secondOfDay, iCutoverMillis); + fields.minuteOfHour = new CutoverField(julian.minuteOfHour(), fields.minuteOfHour, iCutoverMillis); + fields.minuteOfDay = new CutoverField(julian.minuteOfDay(), fields.minuteOfDay, iCutoverMillis); + fields.hourOfDay = new CutoverField(julian.hourOfDay(), fields.hourOfDay, iCutoverMillis); + fields.hourOfHalfday = new CutoverField(julian.hourOfHalfday(), fields.hourOfHalfday, iCutoverMillis); + fields.clockhourOfDay = new CutoverField(julian.clockhourOfDay(), fields.clockhourOfDay, iCutoverMillis); + fields.clockhourOfHalfday = new CutoverField(julian.clockhourOfHalfday(), + fields.clockhourOfHalfday, iCutoverMillis); + fields.halfdayOfDay = new CutoverField(julian.halfdayOfDay(), fields.halfdayOfDay, iCutoverMillis); + } + + // These fields just require basic cutover support. + { + fields.era = new CutoverField(julian.era(), fields.era, iCutoverMillis); + fields.dayOfMonth = new CutoverField(julian.dayOfMonth(), fields.dayOfMonth, iCutoverMillis); + } + + // DayOfYear and weekOfWeekyear require special handling since cutover + // year has fewer days and weeks. Extend the cutover to the start of + // the next year or weekyear. This keeps the sequence unbroken during + // the cutover year. + + { + long cutover = gregorian.year().roundCeiling(iCutoverMillis); + fields.dayOfYear = new CutoverField( + julian.dayOfYear(), fields.dayOfYear, cutover); + } + + { + long cutover = gregorian.weekyear().roundCeiling(iCutoverMillis); + fields.weekOfWeekyear = new CutoverField( + julian.weekOfWeekyear(), fields.weekOfWeekyear, cutover, true); + } + + // These fields are special because they have imprecise durations. The + // family of addition methods need special attention. Override affected + // duration fields as well. + { + fields.year = new ImpreciseCutoverField( + julian.year(), fields.year, iCutoverMillis); + fields.years = fields.year.getDurationField(); + fields.yearOfEra = new ImpreciseCutoverField( + julian.yearOfEra(), fields.yearOfEra, fields.years, iCutoverMillis); + fields.yearOfCentury = new ImpreciseCutoverField( + julian.yearOfCentury(), fields.yearOfCentury, fields.years, iCutoverMillis); + + fields.centuryOfEra = new ImpreciseCutoverField( + julian.centuryOfEra(), fields.centuryOfEra, iCutoverMillis); + fields.centuries = fields.centuryOfEra.getDurationField(); + + fields.monthOfYear = new ImpreciseCutoverField( + julian.monthOfYear(), fields.monthOfYear, iCutoverMillis); + fields.months = fields.monthOfYear.getDurationField(); + + fields.weekyear = new ImpreciseCutoverField( + julian.weekyear(), fields.weekyear, null, iCutoverMillis, true); + fields.weekyearOfCentury = new ImpreciseCutoverField( + julian.weekyearOfCentury(), fields.weekyearOfCentury, fields.weekyears, iCutoverMillis); + fields.weekyears = fields.weekyear.getDurationField(); + } + } + + long julianToGregorianByYear(long instant) { + return convertByYear(instant, iJulianChronology, iGregorianChronology); + } + + long gregorianToJulianByYear(long instant) { + return convertByYear(instant, iGregorianChronology, iJulianChronology); + } + + long julianToGregorianByWeekyear(long instant) { + return convertByWeekyear(instant, iJulianChronology, iGregorianChronology); + } + + long gregorianToJulianByWeekyear(long instant) { + return convertByWeekyear(instant, iGregorianChronology, iJulianChronology); + } + + //----------------------------------------------------------------------- + /** + * This basic cutover field adjusts calls to 'get' and 'set' methods, and + * assumes that calls to add and addWrapField are unaffected by the cutover. + */ + private class CutoverField extends BaseDateTimeField { + private static final long serialVersionUID = 3528501219481026402L; + + final DateTimeField iJulianField; + final DateTimeField iGregorianField; + final long iCutover; + final boolean iConvertByWeekyear; + + protected DurationField iDurationField; + + /** + * @param julianField field from the chronology used before the cutover instant + * @param gregorianField field from the chronology used at and after the cutover + * @param cutoverMillis the millis of the cutover + */ + CutoverField(DateTimeField julianField, DateTimeField gregorianField, long cutoverMillis) { + this(julianField, gregorianField, cutoverMillis, false); + } + + /** + * @param julianField field from the chronology used before the cutover instant + * @param gregorianField field from the chronology used at and after the cutover + * @param cutoverMillis the millis of the cutover + * @param convertByWeekyear + */ + CutoverField(DateTimeField julianField, DateTimeField gregorianField, + long cutoverMillis, boolean convertByWeekyear) { + super(gregorianField.getType()); + iJulianField = julianField; + iGregorianField = gregorianField; + iCutover = cutoverMillis; + iConvertByWeekyear = convertByWeekyear; + // Although average length of Julian and Gregorian years differ, + // use the Gregorian duration field because it is more accurate. + iDurationField = gregorianField.getDurationField(); + } + + public boolean isLenient() { + return false; + } + + public int get(long instant) { + if (instant >= iCutover) { + return iGregorianField.get(instant); + } else { + return iJulianField.get(instant); + } + } + + public String getAsText(long instant, Locale locale) { + if (instant >= iCutover) { + return iGregorianField.getAsText(instant, locale); + } else { + return iJulianField.getAsText(instant, locale); + } + } + + public String getAsShortText(long instant, Locale locale) { + if (instant >= iCutover) { + return iGregorianField.getAsShortText(instant, locale); + } else { + return iJulianField.getAsShortText(instant, locale); + } + } + + public long add(long instant, int value) { + return iGregorianField.add(instant, value); + } + + public long add(long instant, long value) { + return iGregorianField.add(instant, value); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return iGregorianField.getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + public long set(long instant, int value) { + if (instant >= iCutover) { + instant = iGregorianField.set(instant, value); + if (instant < iCutover) { + // Only adjust if gap fully crossed. + if (instant + iGapDuration < iCutover) { + instant = gregorianToJulian(instant); + } + // Verify that new value stuck. + if (get(instant) != value) { + throw new IllegalArgumentException + ("Illegal value for " + iGregorianField.getName() + ": " + value); + } + } + } else { + instant = iJulianField.set(instant, value); + if (instant >= iCutover) { + // Only adjust if gap fully crossed. + if (instant - iGapDuration >= iCutover) { + instant = julianToGregorian(instant); + } + // Verify that new value stuck. + if (get(instant) != value) { + throw new IllegalArgumentException + ("Illegal value for " + iJulianField.getName() + ": " + value); + } + } + } + return instant; + } + + public long set(long instant, String text, Locale locale) { + if (instant >= iCutover) { + instant = iGregorianField.set(instant, text, locale); + if (instant < iCutover) { + // Only adjust if gap fully crossed. + if (instant + iGapDuration < iCutover) { + instant = gregorianToJulian(instant); + } + // Cannot verify that new value stuck because set may be lenient. + } + } else { + instant = iJulianField.set(instant, text, locale); + if (instant >= iCutover) { + // Only adjust if gap fully crossed. + if (instant - iGapDuration >= iCutover) { + instant = julianToGregorian(instant); + } + // Cannot verify that new value stuck because set may be lenient. + } + } + return instant; + } + + public DurationField getDurationField() { + return iDurationField; + } + + public DurationField getRangeDurationField() { + DurationField rangeField = iGregorianField.getRangeDurationField(); + if (rangeField == null) { + rangeField = iJulianField.getRangeDurationField(); + } + return rangeField; + } + + public boolean isLeap(long instant) { + if (instant >= iCutover) { + return iGregorianField.isLeap(instant); + } else { + return iJulianField.isLeap(instant); + } + } + + public int getLeapAmount(long instant) { + if (instant >= iCutover) { + return iGregorianField.getLeapAmount(instant); + } else { + return iJulianField.getLeapAmount(instant); + } + } + + public DurationField getLeapDurationField() { + return iGregorianField.getLeapDurationField(); + } + + + public int getMinimumValue() { + // For all precise fields, the Julian and Gregorian limits are + // identical. Choose Julian to tighten up the year limits. + return iJulianField.getMinimumValue(); + } + + public int getMinimumValue(long instant) { + if (instant < iCutover) { + return iJulianField.getMinimumValue(instant); + } + + int min = iGregorianField.getMinimumValue(instant); + + // Because the cutover may reduce the length of this field, verify + // the minimum by setting it. + instant = iGregorianField.set(instant, min); + if (instant < iCutover) { + min = iGregorianField.get(iCutover); + } + + return min; + } + + public int getMaximumValue() { + // For all precise fields, the Julian and Gregorian limits are + // identical. + return iGregorianField.getMaximumValue(); + } + + public int getMaximumValue(long instant) { + if (instant >= iCutover) { + return iGregorianField.getMaximumValue(instant); + } + + int max = iJulianField.getMaximumValue(instant); + + // Because the cutover may reduce the length of this field, verify + // the maximum by setting it. + instant = iJulianField.set(instant, max); + if (instant >= iCutover) { + max = iJulianField.get(iJulianField.add(iCutover, -1)); + } + + return max; + } + + public long roundFloor(long instant) { + if (instant >= iCutover) { + instant = iGregorianField.roundFloor(instant); + if (instant < iCutover) { + // Only adjust if gap fully crossed. + if (instant + iGapDuration < iCutover) { + instant = gregorianToJulian(instant); + } + } + } else { + instant = iJulianField.roundFloor(instant); + } + return instant; + } + + public long roundCeiling(long instant) { + if (instant >= iCutover) { + instant = iGregorianField.roundCeiling(instant); + } else { + instant = iJulianField.roundCeiling(instant); + if (instant >= iCutover) { + // Only adjust if gap fully crossed. + if (instant - iGapDuration >= iCutover) { + instant = julianToGregorian(instant); + } + } + } + return instant; + } + + public int getMaximumTextLength(Locale locale) { + return Math.max(iJulianField.getMaximumTextLength(locale), + iGregorianField.getMaximumTextLength(locale)); + } + + public int getMaximumShortTextLength(Locale locale) { + return Math.max(iJulianField.getMaximumShortTextLength(locale), + iGregorianField.getMaximumShortTextLength(locale)); + } + + protected long julianToGregorian(long instant) { + if (iConvertByWeekyear) { + return julianToGregorianByWeekyear(instant); + } else { + return julianToGregorianByYear(instant); + } + } + + protected long gregorianToJulian(long instant) { + if (iConvertByWeekyear) { + return gregorianToJulianByWeekyear(instant); + } else { + return gregorianToJulianByYear(instant); + } + } + } + + //----------------------------------------------------------------------- + /** + * Cutover field for variable length fields. These fields internally call + * set whenever add is called. As a result, the same correction applied to + * set must be applied to add and addWrapField. Knowing when to use this + * field requires specific knowledge of how the GJ fields are implemented. + */ + private final class ImpreciseCutoverField extends CutoverField { + private static final long serialVersionUID = 3410248757173576441L; + + /** + * Creates a duration field that links back to this. + */ + ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, long cutoverMillis) { + this(julianField, gregorianField, null, cutoverMillis, false); + } + + /** + * Uses a shared duration field rather than creating a new one. + * + * @param durationField shared duration field + */ + ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, + DurationField durationField, long cutoverMillis) + { + this(julianField, gregorianField, durationField, cutoverMillis, false); + } + + /** + * Uses a shared duration field rather than creating a new one. + * + * @param durationField shared duration field + */ + ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, + DurationField durationField, + long cutoverMillis, boolean convertByWeekyear) + { + super(julianField, gregorianField, cutoverMillis, convertByWeekyear); + if (durationField == null) { + durationField = new LinkedDurationField(iDurationField, this); + } + iDurationField = durationField; + } + + public long add(long instant, int value) { + if (instant >= iCutover) { + instant = iGregorianField.add(instant, value); + if (instant < iCutover) { + // Only adjust if gap fully crossed. + if (instant + iGapDuration < iCutover) { + instant = gregorianToJulian(instant); + } + } + } else { + instant = iJulianField.add(instant, value); + if (instant >= iCutover) { + // Only adjust if gap fully crossed. + if (instant - iGapDuration >= iCutover) { + instant = julianToGregorian(instant); + } + } + } + return instant; + } + + public long add(long instant, long value) { + if (instant >= iCutover) { + instant = iGregorianField.add(instant, value); + if (instant < iCutover) { + // Only adjust if gap fully crossed. + if (instant + iGapDuration < iCutover) { + instant = gregorianToJulian(instant); + } + } + } else { + instant = iJulianField.add(instant, value); + if (instant >= iCutover) { + // Only adjust if gap fully crossed. + if (instant - iGapDuration >= iCutover) { + instant = julianToGregorian(instant); + } + } + } + return instant; + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + if (minuendInstant >= iCutover) { + if (subtrahendInstant >= iCutover) { + return iGregorianField.getDifference(minuendInstant, subtrahendInstant); + } + // Remember, the add is being reversed. Since subtrahend is + // Julian, convert minuend to Julian to match. + minuendInstant = gregorianToJulian(minuendInstant); + return iJulianField.getDifference(minuendInstant, subtrahendInstant); + } else { + if (subtrahendInstant < iCutover) { + return iJulianField.getDifference(minuendInstant, subtrahendInstant); + } + // Remember, the add is being reversed. Since subtrahend is + // Gregorian, convert minuend to Gregorian to match. + minuendInstant = julianToGregorian(minuendInstant); + return iGregorianField.getDifference(minuendInstant, subtrahendInstant); + } + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + if (minuendInstant >= iCutover) { + if (subtrahendInstant >= iCutover) { + return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + // Remember, the add is being reversed. Since subtrahend is + // Julian, convert minuend to Julian to match. + minuendInstant = gregorianToJulian(minuendInstant); + return iJulianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } else { + if (subtrahendInstant < iCutover) { + return iJulianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + // Remember, the add is being reversed. Since subtrahend is + // Gregorian, convert minuend to Gregorian to match. + minuendInstant = julianToGregorian(minuendInstant); + return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + } + + // Since the imprecise fields have durations longer than the gap + // duration, keep these methods simple. The inherited implementations + // produce incorrect results. + // + // Degenerate case: If this field is a month, and the cutover is set + // far into the future, then the gap duration may be so large as to + // reduce the number of months in a year. If the missing month(s) are + // at the beginning or end of the year, then the minimum and maximum + // values are not 1 and 12. I don't expect this case to ever occur. + + public int getMinimumValue(long instant) { + if (instant >= iCutover) { + return iGregorianField.getMinimumValue(instant); + } else { + return iJulianField.getMinimumValue(instant); + } + } + + public int getMaximumValue(long instant) { + if (instant >= iCutover) { + return iGregorianField.getMaximumValue(instant); + } else { + return iJulianField.getMaximumValue(instant); + } + } + } + + //----------------------------------------------------------------------- + /** + * Links the duration back to a ImpreciseCutoverField. + */ + private static class LinkedDurationField extends DecoratedDurationField { + private static final long serialVersionUID = 4097975388007713084L; + + private final ImpreciseCutoverField iField; + + LinkedDurationField(DurationField durationField, ImpreciseCutoverField dateTimeField) { + super(durationField, durationField.getType()); + iField = dateTimeField; + } + + public long add(long instant, int value) { + return iField.add(instant, value); + } + + public long add(long instant, long value) { + return iField.add(instant, value); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return iField.getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJDayOfMonthDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/GJDayOfMonthDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJDayOfMonthDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,150 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; +import org.joda.time.field.PreciseDurationDateTimeField; + +/** + * Provides time calculations for the day of the month component of time. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +final class GJDayOfMonthDateTimeField extends PreciseDurationDateTimeField { + + private static final long serialVersionUID = -4677223814028011723L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor. + */ + GJDayOfMonthDateTimeField(BaseGJChronology chronology, DurationField days) { + super(DateTimeFieldType.dayOfMonth(), days); + iChronology = chronology; + } + + /** + * Get the day of the month component of the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the day of the month extracted from the input. + */ + public int get(long instant) { + return iChronology.getDayOfMonth(instant); + } + + public DurationField getRangeDurationField() { + return iChronology.months(); + } + + public int getMinimumValue() { + return 1; + } + + public int getMaximumValue() { + return 31; + } + + public int getMaximumValue(long instant) { + int thisYear = iChronology.getYear(instant); + int thisMonth = iChronology.getMonthOfYear(instant, thisYear); + return iChronology.getDaysInYearMonth(thisYear, thisMonth); + } + + public int getMaximumValue(ReadablePartial partial) { + if (partial.isSupported(DateTimeFieldType.monthOfYear())) { + int month = partial.get(DateTimeFieldType.monthOfYear()); + if (partial.isSupported(DateTimeFieldType.year())) { + int year = partial.get(DateTimeFieldType.year()); + return iChronology.getDaysInYearMonth(year, month); + } + return iChronology.getDaysInMonthMax(month); + } + return 31; + } + + public int getMaximumValue(ReadablePartial partial, int[] values) { + int size = partial.size(); + for (int i = 0; i < size; i++) { + if (partial.getFieldType(i) == DateTimeFieldType.monthOfYear()) { + int month = values[i]; + for (int j = 0; j < size; j++) { + if (partial.getFieldType(j) == DateTimeFieldType.year()) { + int year = values[j]; + return iChronology.getDaysInYearMonth(year, month); + } + } + return iChronology.getDaysInMonthMax(month); + } + } + return 31; + } + + protected int getMaximumValueForSet(long instant, int value) { + return value > 28 ? getMaximumValue(instant) : 28; + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.dayOfMonth(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJDayOfWeekDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/GJDayOfWeekDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJDayOfWeekDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,179 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.Locale; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.field.PreciseDurationDateTimeField; + +/** + * GJDayOfWeekDateTimeField provides time calculations for the + * day of the week component of time. + * + * @since 1.0 + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + */ +final class GJDayOfWeekDateTimeField extends PreciseDurationDateTimeField { + + /** Serialization version */ + private static final long serialVersionUID = -3857947176719041436L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor. + */ + GJDayOfWeekDateTimeField(BaseGJChronology chronology, DurationField days) { + super(DateTimeFieldType.dayOfWeek(), days); + iChronology = chronology; + } + + /** + * Get the value of the specified time instant. + * + * @param instant the time instant in millis to query + * @return the day of the week extracted from the input + */ + public int get(long instant) { + return iChronology.getDayOfWeek(instant); + } + + /** + * Get the textual value of the specified time instant. + * + * @param fieldValue the field value to query + * @param locale the locale to use + * @return the day of the week, such as 'Monday' + */ + protected String getAsText(int fieldValue, Locale locale) { + return GJLocaleSymbols.forLocale(locale).dayOfWeekValueToText(fieldValue); + } + + /** + * Get the abbreviated textual value of the specified time instant. + * + * @param fieldValue the field value to query + * @param locale the locale to use + * @return the day of the week, such as 'Mon' + */ + protected String getAsShortText(int fieldValue, Locale locale) { + return GJLocaleSymbols.forLocale(locale).dayOfWeekValueToShortText(fieldValue); + } + + /** + * Convert the specified text and locale into a value. + * + * @param text the text to convert + * @param locale the locale to convert using + * @return the value extracted from the text + * @throws IllegalArgumentException if the text is invalid + */ + protected int convertText(String text, Locale locale) { + return GJLocaleSymbols.forLocale(locale).dayOfWeekTextToValue(text); + } + + public DurationField getRangeDurationField() { + return iChronology.weeks(); + } + + /** + * Get the minimum value that this field can have. + * + * @return the field's minimum value + */ + public int getMinimumValue() { + return DateTimeConstants.MONDAY; + } + + /** + * Get the maximum value that this field can have. + * + * @return the field's maximum value + */ + public int getMaximumValue() { + return DateTimeConstants.SUNDAY; + } + + /** + * Get the maximum length of the text returned by this field. + * + * @param locale the locale to use + * @return the maximum textual length + */ + public int getMaximumTextLength(Locale locale) { + return GJLocaleSymbols.forLocale(locale).getDayOfWeekMaxTextLength(); + } + + /** + * Get the maximum length of the abbreviated text returned by this field. + * + * @param locale the locale to use + * @return the maximum abbreviated textual length + */ + public int getMaximumShortTextLength(Locale locale) { + return GJLocaleSymbols.forLocale(locale).getDayOfWeekMaxShortTextLength(); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.dayOfWeek(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJDayOfYearDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/GJDayOfYearDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJDayOfYearDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,139 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; +import org.joda.time.field.PreciseDurationDateTimeField; + +/** + * Provides time calculations for the day of the year component of time. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +final class GJDayOfYearDateTimeField extends PreciseDurationDateTimeField { + + private static final long serialVersionUID = -6821236822336841037L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor + */ + GJDayOfYearDateTimeField(BaseGJChronology chronology, DurationField days) { + super(DateTimeFieldType.dayOfYear(), days); + iChronology = chronology; + } + + /** + * Get the day of the year component of the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the day of the year extracted from the input. + */ + public int get(long instant) { + return iChronology.getDayOfYear(instant); + } + + public DurationField getRangeDurationField() { + return iChronology.years(); + } + + public int getMinimumValue() { + return 1; + } + + public int getMaximumValue() { + return 366; + } + + public int getMaximumValue(long instant) { + int year = iChronology.getYear(instant); + return iChronology.getDaysInYear(year); + } + + public int getMaximumValue(ReadablePartial partial) { + if (partial.isSupported(DateTimeFieldType.year())) { + int year = partial.get(DateTimeFieldType.year()); + return iChronology.getDaysInYear(year); + } + return 366; + } + + public int getMaximumValue(ReadablePartial partial, int[] values) { + int size = partial.size(); + for (int i = 0; i < size; i++) { + if (partial.getFieldType(i) == DateTimeFieldType.year()) { + int year = values[i]; + return iChronology.getDaysInYear(year); + } + } + return 366; + } + + protected int getMaximumValueForSet(long instant, int value) { + return value > 365 ? getMaximumValue(instant) : 365; + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.dayOfYear(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJEraDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/GJEraDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJEraDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,191 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.Locale; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; +import org.joda.time.field.BaseDateTimeField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.UnsupportedDurationField; + +/** + * Provides time calculations for the era component of time. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @version 1.0 + * @since 1.0 + */ +final class GJEraDateTimeField extends BaseDateTimeField { + + /** Serialization version */ + private static final long serialVersionUID = 4240986525305515528L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor + */ + GJEraDateTimeField(BaseGJChronology chronology) { + super(DateTimeFieldType.era()); + iChronology = chronology; + } + + public boolean isLenient() { + return false; + } + + /** + * Get the Era component of the specified time instant. + * + * @param instant the time instant in millis to query. + */ + public int get(long instant) { + if (iChronology.getYear(instant) <= 0) { + return DateTimeConstants.BCE; + } else { + return DateTimeConstants.CE; + } + } + + protected String getAsText(int fieldValue, Locale locale) { + return GJLocaleSymbols.forLocale(locale).eraValueToText(fieldValue); + } + + /** + * Set the Era component of the specified time instant. + * + * @param instant the time instant in millis to update. + * @param era the era to update the time to. + * @return the updated time instant. + * @throws IllegalArgumentException if era is invalid. + */ + public long set(long instant, int era) { + FieldUtils.verifyValueBounds(this, era, DateTimeConstants.BCE, DateTimeConstants.CE); + + int oldEra = get(instant); + if (oldEra != era) { + int year = iChronology.getYear(instant); + return iChronology.setYear(instant, -year); + } else { + return instant; + } + } + + public long set(long instant, String text, Locale locale) { + return set(instant, GJLocaleSymbols.forLocale(locale).eraTextToValue(text)); + } + + public long roundFloor(long instant) { + if (get(instant) == DateTimeConstants.CE) { + return iChronology.setYear(0, 1); + } else { + return Long.MIN_VALUE; + } + } + + public long roundCeiling(long instant) { + if (get(instant) == DateTimeConstants.BCE) { + return iChronology.setYear(0, 1); + } else { + return Long.MAX_VALUE; + } + } + + public long roundHalfFloor(long instant) { + // In reality, the era is infinite, so there is no halfway point. + return roundFloor(instant); + } + + public long roundHalfCeiling(long instant) { + // In reality, the era is infinite, so there is no halfway point. + return roundFloor(instant); + } + + public long roundHalfEven(long instant) { + // In reality, the era is infinite, so there is no halfway point. + return roundFloor(instant); + } + + public DurationField getDurationField() { + return UnsupportedDurationField.getInstance(DurationFieldType.eras()); + } + + public DurationField getRangeDurationField() { + return null; + } + + public int getMinimumValue() { + return DateTimeConstants.BCE; + } + + public int getMaximumValue() { + return DateTimeConstants.CE; + } + + public int getMaximumTextLength(Locale locale) { + return GJLocaleSymbols.forLocale(locale).getEraMaxTextLength(); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.era(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJLocaleSymbols.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/GJLocaleSymbols.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJLocaleSymbols.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,275 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.lang.ref.WeakReference; +import java.text.DateFormatSymbols; +import java.util.WeakHashMap; +import java.util.Locale; + +/** + * Utility class used by a few of the GJDateTimeFields. + * + * @author Brian S O'Neill + */ +class GJLocaleSymbols { + private static final int FAST_CACHE_SIZE = 64; + + private static final GJLocaleSymbols[] cFastCache = new GJLocaleSymbols[FAST_CACHE_SIZE]; + + private static WeakHashMap cCache = new WeakHashMap(); + + public static GJLocaleSymbols forLocale(Locale locale) { + int index = System.identityHashCode(locale) & (FAST_CACHE_SIZE - 1); + GJLocaleSymbols symbols = cFastCache[index]; + if (symbols != null && symbols.iLocale.get() == locale) { + return symbols; + } + synchronized (cCache) { + symbols = (GJLocaleSymbols) cCache.get(locale); + if (symbols == null) { + symbols = new GJLocaleSymbols(locale); + cCache.put(locale, symbols); + } + } + cFastCache[index] = symbols; + return symbols; + } + + private static String[] realignMonths(String[] months) { + String[] a = new String[13]; + for (int i=1; i<13; i++) { + a[i] = months[i - 1]; + } + return a; + } + + private static String[] realignDaysOfWeek(String[] daysOfWeek) { + String[] a = new String[8]; + for (int i=1; i<8; i++) { + a[i] = daysOfWeek[(i < 7) ? i + 1 : 1]; + } + return a; + } + + private static int maxLength(String[] a) { + int max = 0; + for (int i=a.length; --i>=0; ) { + String s = a[i]; + if (s != null) { + int len = s.length(); + if (len > max) { + max = len; + } + } + } + return max; + } + + private final WeakReference iLocale; + + private final String[] iEras; + private final String[] iDaysOfWeek; + private final String[] iShortDaysOfWeek; + private final String[] iMonths; + private final String[] iShortMonths; + private final String[] iHalfday; + + private final int iMaxEraLength; + private final int iMaxDayOfWeekLength; + private final int iMaxShortDayOfWeekLength; + private final int iMaxMonthLength; + private final int iMaxShortMonthLength; + private final int iMaxHalfdayLength; + + private GJLocaleSymbols(Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + + iLocale = new WeakReference(locale); + + DateFormatSymbols dfs = new DateFormatSymbols(locale); + + iEras = dfs.getEras(); + iDaysOfWeek = realignDaysOfWeek(dfs.getWeekdays()); + iShortDaysOfWeek = realignDaysOfWeek(dfs.getShortWeekdays()); + iMonths = realignMonths(dfs.getMonths()); + iShortMonths = realignMonths(dfs.getShortMonths()); + iHalfday = dfs.getAmPmStrings(); + + iMaxEraLength = maxLength(iEras); + iMaxDayOfWeekLength = maxLength(iDaysOfWeek); + iMaxShortDayOfWeekLength = maxLength(iShortDaysOfWeek); + iMaxMonthLength = maxLength(iMonths); + iMaxShortMonthLength = maxLength(iShortMonths); + iMaxHalfdayLength = maxLength(iHalfday); + } + + public String eraValueToText(int value) { + return iEras[value]; + } + + public int eraTextToValue(String text) { + String[] eras = iEras; + for (int i=eras.length; --i>=0; ) { + if (eras[i].equalsIgnoreCase(text)) { + return i; + } + } + throw new IllegalArgumentException("Illegal era text: " + text); + } + + public int getEraMaxTextLength() { + return iMaxEraLength; + } + + public String monthOfYearValueToText(int value) { + return iMonths[value]; + } + + public String monthOfYearValueToShortText(int value) { + return iShortMonths[value]; + } + + public int monthOfYearTextToValue(String text) { + String[] months = iMonths; + for (int i=months.length; --i>=1; ) { + if (months[i].equalsIgnoreCase(text)) { + return i; + } + } + months = iShortMonths; + for (int i=months.length; --i>=1; ) { + if (months[i].equalsIgnoreCase(text)) { + return i; + } + } + try { + int month = Integer.parseInt(text); + if (month >= 1 && month <= 12) { + return month; + } + } catch (NumberFormatException ex) { + // ignore + } + throw new IllegalArgumentException("Illegal monthOfYear text: " + text); + } + + public int getMonthMaxTextLength() { + return iMaxMonthLength; + } + + public int getMonthMaxShortTextLength() { + return iMaxShortMonthLength; + } + + public String dayOfWeekValueToText(int value) { + return iDaysOfWeek[value]; + } + + public String dayOfWeekValueToShortText(int value) { + return iShortDaysOfWeek[value]; + } + + public int dayOfWeekTextToValue(String text) { + String[] daysOfWeek = iDaysOfWeek; + for (int i=daysOfWeek.length; --i>=1; ) { + if (daysOfWeek[i].equalsIgnoreCase(text)) { + return i; + } + } + daysOfWeek = iShortDaysOfWeek; + for (int i=daysOfWeek.length; --i>=1; ) { + if (daysOfWeek[i].equalsIgnoreCase(text)) { + return i; + } + } + try { + int day = Integer.parseInt(text); + if (day >= 1 && day <= 7) { + return day; + } + } catch (NumberFormatException ex) { + // ignore + } + throw new IllegalArgumentException("Illegal dayOfWeek text: " + text); + } + + public int getDayOfWeekMaxTextLength() { + return iMaxDayOfWeekLength; + } + + public int getDayOfWeekMaxShortTextLength() { + return iMaxShortDayOfWeekLength; + } + + public String halfdayValueToText(int value) { + return iHalfday[value]; + } + + public int halfdayTextToValue(String text) { + String[] halfday = iHalfday; + for (int i = halfday.length; --i>=0; ) { + if (halfday[i].equalsIgnoreCase(text)) { + return i; + } + } + throw new IllegalArgumentException("Illegal halfday text: " + text); + } + + public int getHalfdayMaxTextLength() { + return iMaxHalfdayLength; + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJMonthOfYearDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/GJMonthOfYearDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJMonthOfYearDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,389 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.Locale; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.ImpreciseDateTimeField; + +/** + * Provides time calculations for the month of the year component of time. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @version 1.0 + * @since 1.0 + */ +final class GJMonthOfYearDateTimeField extends ImpreciseDateTimeField { + + /** Serialization version */ + private static final long serialVersionUID = -4748157875845286249L; + + private static final int MIN = DateTimeConstants.JANUARY; + private static final int MAX = DateTimeConstants.DECEMBER; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor + */ + GJMonthOfYearDateTimeField(BaseGJChronology chronology) { + super(DateTimeFieldType.monthOfYear(), chronology.getAverageMillisPerMonth()); + iChronology = chronology; + } + + public boolean isLenient() { + return false; + } + + /** + * Get the Month component of the specified time instant. + * + * @see org.joda.time.DateTimeField#get(long) + * @see org.joda.time.ReadableDateTime#getMonthOfYear() + * @param instant the time instant in millis to query. + * @return the month extracted from the input. + */ + public int get(long instant) { + return iChronology.getMonthOfYear(instant); + } + + protected String getAsText(int fieldValue, Locale locale) { + return GJLocaleSymbols.forLocale(locale).monthOfYearValueToText(fieldValue); + } + + protected String getAsShortText(int fieldValue, Locale locale) { + return GJLocaleSymbols.forLocale(locale).monthOfYearValueToShortText(fieldValue); + } + + /** + * Add the specified month to the specified time instant. + * The amount added may be negative.

+ * If the new month has less total days than the specified + * day of the month, this value is coerced to the nearest + * sane value. e.g.

+ * 07-31 - (1 month) = 06-30

+ * 03-31 - (1 month) = 02-28 or 02-29 depending

+ * + * @see org.joda.time.DateTimeField#add + * @see org.joda.time.ReadWritableDateTime#addMonths(int) + * @param instant the time instant in millis to update. + * @param months the months to add (can be negative). + * @return the updated time instant. + */ + public long add(long instant, int months) { + if (months == 0) { + return instant; // the easy case + } + // + // Save time part first. + // + long timePart = iChronology.getMillisOfDay(instant); + // + // + // Get this year and month. + // + int thisYear = iChronology.getYear(instant); + int thisMonth = iChronology.getMonthOfYear(instant, thisYear); + // ---------------------------------------------------------- + // + // Do not refactor without careful consideration. + // Order of calculation is important. + // + int yearToUse; + // Initially, monthToUse is zero-based + int monthToUse = thisMonth - 1 + months; + if (monthToUse >= 0) { + yearToUse = thisYear + (monthToUse / MAX); + monthToUse = (monthToUse % MAX) + 1; + } else { + yearToUse = thisYear + (monthToUse / MAX) - 1; + monthToUse = Math.abs(monthToUse); + int remMonthToUse = monthToUse % MAX; + // Take care of the boundary condition + if (remMonthToUse == 0) { + remMonthToUse = MAX; + } + monthToUse = MAX - remMonthToUse + 1; + // Take care of the boundary condition + if (monthToUse == 1) { + yearToUse += 1; + } + } + // End of do not refactor. + // ---------------------------------------------------------- + + // + // Quietly force DOM to nearest sane value. + // + int dayToUse = iChronology.getDayOfMonth(instant, thisYear, thisMonth); + int maxDay = iChronology.getDaysInYearMonth(yearToUse, monthToUse); + if (dayToUse > maxDay) { + dayToUse = maxDay; + } + // + // get proper date part, and return result + // + long datePart = + iChronology.getYearMonthDayMillis(yearToUse, monthToUse, dayToUse); + return datePart + timePart; + } + + public long add(long instant, long months) { + int i_months = (int)months; + if (i_months == months) { + return add(instant, i_months); + } + + // Copied from add(long, int) and modified slightly: + + long timePart = iChronology.getMillisOfDay(instant); + + int thisYear = iChronology.getYear(instant); + int thisMonth = iChronology.getMonthOfYear(instant, thisYear); + + long yearToUse; + long monthToUse = thisMonth - 1 + months; + if (monthToUse >= 0) { + yearToUse = thisYear + (monthToUse / MAX); + monthToUse = (monthToUse % MAX) + 1; + } else { + yearToUse = thisYear + (monthToUse / MAX) - 1; + monthToUse = Math.abs(monthToUse); + int remMonthToUse = (int)(monthToUse % MAX); + if (remMonthToUse == 0) { + remMonthToUse = MAX; + } + monthToUse = MAX - remMonthToUse + 1; + if (monthToUse == 1) { + yearToUse += 1; + } + } + + if (yearToUse < iChronology.getMinYear() || + yearToUse > iChronology.getMaxYear()) { + + throw new IllegalArgumentException + ("Magnitude of add amount is too large: " + months); + } + + int i_yearToUse = (int)yearToUse; + int i_monthToUse = (int)monthToUse; + + int dayToUse = iChronology.getDayOfMonth(instant, thisYear, thisMonth); + int maxDay = iChronology.getDaysInYearMonth(i_yearToUse, i_monthToUse); + if (dayToUse > maxDay) { + dayToUse = maxDay; + } + + long datePart = + iChronology.getYearMonthDayMillis(i_yearToUse, i_monthToUse, dayToUse); + return datePart + timePart; + } + + /** + * Add to the Month component of the specified time instant + * wrapping around within that component if necessary. + * + * @see org.joda.time.DateTimeField#addWrapField + * @param instant the time instant in millis to update. + * @param months the months to add (can be negative). + * @return the updated time instant. + */ + public long addWrapField(long instant, int months) { + return set(instant, FieldUtils.getWrappedValue(get(instant), months, MIN, MAX)); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + if (minuendInstant < subtrahendInstant) { + return -getDifference(subtrahendInstant, minuendInstant); + } + + int minuendYear = iChronology.getYear(minuendInstant); + int minuendMonth = iChronology.getMonthOfYear(minuendInstant, minuendYear); + int subtrahendYear = iChronology.getYear(subtrahendInstant); + int subtrahendMonth = iChronology.getMonthOfYear(subtrahendInstant, subtrahendYear); + + long difference = (minuendYear - subtrahendYear) * 12L + minuendMonth - subtrahendMonth; + + // Before adjusting for remainder, account for special case of add + // where the day-of-month is forced to the nearest sane value. + int minuendDom = iChronology.getDayOfMonth + (minuendInstant, minuendYear, minuendMonth); + if (minuendDom == iChronology.getDaysInYearMonth(minuendYear, minuendMonth)) { + // Last day of the minuend month... + int subtrahendDom = iChronology.getDayOfMonth + (subtrahendInstant, subtrahendYear, subtrahendMonth); + if (subtrahendDom > minuendDom) { + // ...and day of subtrahend month is larger. + // Note: This works fine, but it ideally shouldn't invoke other + // fields from within a field. + subtrahendInstant = iChronology.dayOfMonth().set(subtrahendInstant, minuendDom); + } + } + + // Inlined remainder method to avoid duplicate calls. + long minuendRem = minuendInstant + - iChronology.getYearMonthMillis(minuendYear, minuendMonth); + long subtrahendRem = subtrahendInstant + - iChronology.getYearMonthMillis(subtrahendYear, subtrahendMonth); + + if (minuendRem < subtrahendRem) { + difference--; + } + + return difference; + } + + /** + * Set the Month component of the specified time instant.

+ * If the new month has less total days than the specified + * day of the month, this value is coerced to the nearest + * sane value. e.g.

+ * 07-31 to month 6 = 06-30

+ * 03-31 to month 2 = 02-28 or 02-29 depending

+ * + * @param instant the time instant in millis to update. + * @param month the month (1,12) to update the time to. + * @return the updated time instant. + * @throws IllegalArgumentException if month is invalid + */ + public long set(long instant, int month) { + FieldUtils.verifyValueBounds(this, month, MIN, MAX); + // + int thisYear = iChronology.getYear(instant); + // + int thisDom = iChronology.getDayOfMonth(instant, thisYear); + int maxDom = iChronology.getDaysInYearMonth(thisYear, month); + if (thisDom > maxDom) { + // Quietly force DOM to nearest sane value. + thisDom = maxDom; + } + // Return newly calculated millis value + return iChronology.getYearMonthDayMillis(thisYear, month, thisDom) + + iChronology.getMillisOfDay(instant); + } + + /** + * Convert the specified text and locale into a value. + * + * @param text the text to convert + * @param locale the locale to convert using + * @return the value extracted from the text + * @throws IllegalArgumentException if the text is invalid + */ + protected int convertText(String text, Locale locale) { + return GJLocaleSymbols.forLocale(locale).monthOfYearTextToValue(text); + } + + public DurationField getRangeDurationField() { + return iChronology.years(); + } + + public boolean isLeap(long instant) { + int thisYear = iChronology.getYear(instant); + int thisMonth = iChronology.getMonthOfYear(instant, thisYear); + if (thisMonth != 2) { + return false; + } else { + return 29 == iChronology.getDaysInYearMonth(thisYear, thisMonth); + } + } + + public int getLeapAmount(long instant) { + return isLeap(instant) ? 1 : 0; + } + + public DurationField getLeapDurationField() { + return iChronology.days(); + } + + public int getMinimumValue() { + return MIN; + } + + public int getMaximumValue() { + return MAX; + } + + public int getMaximumTextLength(Locale locale) { + return GJLocaleSymbols.forLocale(locale).getMonthMaxTextLength(); + } + + public int getMaximumShortTextLength(Locale locale) { + return GJLocaleSymbols.forLocale(locale).getMonthMaxShortTextLength(); + } + + public long roundFloor(long instant) { + int year = iChronology.getYear(instant); + int month = iChronology.getMonthOfYear(instant, year); + return iChronology.getYearMonthMillis(year, month); + } + + public long remainder(long instant) { + return instant - roundFloor(instant); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.monthOfYear(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJWeekOfWeekyearDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/GJWeekOfWeekyearDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJWeekOfWeekyearDateTimeField.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,159 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; +import org.joda.time.field.PreciseDurationDateTimeField; + +/** + * Provides time calculations for the week of a week based year component of time. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @version 1.0 + * @since 1.0 + */ +final class GJWeekOfWeekyearDateTimeField extends PreciseDurationDateTimeField { + + private static final long serialVersionUID = -1587436826395135328L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor + */ + GJWeekOfWeekyearDateTimeField(BaseGJChronology chronology, DurationField weeks) { + super(DateTimeFieldType.weekOfWeekyear(), weeks); + iChronology = chronology; + } + + /** + * Get the week of a week based year component of the specified time instant. + * + * @see org.joda.time.DateTimeField#get(long) + * @param instant the time instant in millis to query. + * @return the week of the year extracted from the input. + */ + public int get(long instant) { + return iChronology.getWeekOfWeekyear(instant); + } + + public DurationField getRangeDurationField() { + return iChronology.weekyears(); + } + + // 1970-01-01 is day of week 4, Thursday. The rounding methods need to + // apply a corrective alignment since weeks begin on day of week 1, Monday. + + public long roundFloor(long instant) { + return super.roundFloor(instant + 3 * DateTimeConstants.MILLIS_PER_DAY) + - 3 * DateTimeConstants.MILLIS_PER_DAY; + } + + public long roundCeiling(long instant) { + return super.roundCeiling(instant + 3 * DateTimeConstants.MILLIS_PER_DAY) + - 3 * DateTimeConstants.MILLIS_PER_DAY; + } + + public long remainder(long instant) { + return super.remainder(instant + 3 * DateTimeConstants.MILLIS_PER_DAY); + } + + public int getMinimumValue() { + return 1; + } + + public int getMaximumValue() { + return 53; + } + + public int getMaximumValue(long instant) { + int weekyear = iChronology.getWeekyear(instant); + return iChronology.getWeeksInYear(weekyear); + } + + public int getMaximumValue(ReadablePartial partial) { + if (partial.isSupported(DateTimeFieldType.weekyear())) { + int weekyear = partial.get(DateTimeFieldType.weekyear()); + return iChronology.getWeeksInYear(weekyear); + } + return 53; + } + + public int getMaximumValue(ReadablePartial partial, int[] values) { + int size = partial.size(); + for (int i = 0; i < size; i++) { + if (partial.getFieldType(i) == DateTimeFieldType.weekyear()) { + int weekyear = values[i]; + return iChronology.getWeeksInYear(weekyear); + } + } + return 53; + } + + protected int getMaximumValueForSet(long instant, int value) { + return value > 52 ? getMaximumValue(instant) : 52; + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.weekOfWeekyear(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJWeekyearDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/GJWeekyearDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJWeekyearDateTimeField.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,292 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.ImpreciseDateTimeField; + +/** + * Provides time calculations for the week of the weekyear component of time. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @version 1.0 + * @since 1.0 + * @see org.joda.time.DateTimeField + */ +final class GJWeekyearDateTimeField extends ImpreciseDateTimeField { + + private static final long serialVersionUID = 6215066916806820644L; + + private static final long WEEK_53 = (53L - 1) * DateTimeConstants.MILLIS_PER_WEEK; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor + */ + GJWeekyearDateTimeField(BaseGJChronology chronology) { + super(DateTimeFieldType.weekyear(), chronology.getAverageMillisPerYear()); + iChronology = chronology; + } + + public boolean isLenient() { + return false; + } + + /** + * Get the Year of a week based year component of the specified time instant. + * + * @see org.joda.time.DateTimeField#get + * @param instant the time instant in millis to query. + * @return the year extracted from the input. + */ + public int get(long instant) { + return iChronology.getWeekyear(instant); + } + + /** + * Add the specified years to the specified time instant. + * + * @see org.joda.time.DateTimeField#add + * @param instant the time instant in millis to update. + * @param years the years to add (can be negative). + * @return the updated time instant. + */ + public long add(long instant, int years) { + if (years == 0) { + return instant; + } + return set(instant, get(instant) + years); + } + + public long add(long instant, long value) { + return add(instant, FieldUtils.safeToInt(value)); + } + + /** + * Add to the year component of the specified time instant + * wrapping around within that component if necessary. + * + * @see org.joda.time.DateTimeField#addWrapField + * @param instant the time instant in millis to update. + * @param years the years to add (can be negative). + * @return the updated time instant. + */ + public long addWrapField(long instant, int years) { + return add(instant, years); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + if (minuendInstant < subtrahendInstant) { + return -getDifference(subtrahendInstant, minuendInstant); + } + + int minuendWeekyear = get(minuendInstant); + int subtrahendWeekyear = get(subtrahendInstant); + + long minuendRem = remainder(minuendInstant); + long subtrahendRem = remainder(subtrahendInstant); + + // Balance leap weekyear differences on remainders. + if (subtrahendRem >= WEEK_53 && iChronology.getWeeksInYear(minuendWeekyear) <= 52) { + subtrahendRem -= DateTimeConstants.MILLIS_PER_WEEK; + } + + int difference = minuendWeekyear - subtrahendWeekyear; + if (minuendRem < subtrahendRem) { + difference--; + } + return difference; + } + + /** + * Set the Year of a week based year component of the specified time instant. + * + * @see org.joda.time.DateTimeField#set + * @param instant the time instant in millis to update. + * @param year the year (-9999,9999) to set the date to. + * @return the updated DateTime. + * @throws IllegalArgumentException if year is invalid. + */ + public long set(long instant, int year) { + FieldUtils.verifyValueBounds(this, Math.abs(year), + iChronology.getMinYear(), iChronology.getMaxYear()); + // + // Do nothing if no real change is requested. + // + int thisWeekyear = get( instant ); + if ( thisWeekyear == year ) { + return instant; + } + // + // Calculate the DayOfWeek (to be preserved). + // + int thisDow = iChronology.getDayOfWeek(instant); + // + // Calculate the maximum weeks in the target year. + // + int weeksInFromYear = iChronology.getWeeksInYear( thisWeekyear ); + int weeksInToYear = iChronology.getWeeksInYear( year ); + int maxOutWeeks = (weeksInToYear < weeksInFromYear) ? + weeksInToYear : weeksInFromYear; + // + // Get the current week of the year. This will be preserved in + // the output unless it is greater than the maximum possible + // for the target weekyear. In that case it is adjusted + // to the maximum possible. + // + int setToWeek = iChronology.getWeekOfWeekyear(instant); + if ( setToWeek > maxOutWeeks ) { + setToWeek = maxOutWeeks; + } + // + // Get a wroking copy of the current date-time. + // This can be a convenience for debugging. + // + long workInstant = instant; // Get a copy + // + // Attempt to get close to the proper weekyear. + // Note - we cannot currently call ourself, so we just call + // set for the year. This at least gets us close. + // + workInstant = iChronology.setYear( workInstant, year ); + // + // Calculate the weekyear number for the get close to value + // (which might not be equal to the year just set). + // + int workWoyYear = get( workInstant ); + + // + // At most we are off by one year, which can be "fixed" by + // adding/subtracting a week. + // + if ( workWoyYear < year ) { + workInstant += DateTimeConstants.MILLIS_PER_WEEK; + } else if ( workWoyYear > year ) { + workInstant -= DateTimeConstants.MILLIS_PER_WEEK; + } + // + // Set the proper week in the current weekyear. + // + + // BEGIN: possible set WeekOfWeekyear logic. + int currentWoyWeek = iChronology.getWeekOfWeekyear(workInstant); + // No range check required (we already know it is OK). + workInstant = workInstant + (setToWeek - currentWoyWeek) + * (long)DateTimeConstants.MILLIS_PER_WEEK; + // END: possible set WeekOfWeekyear logic. + + // + // Reset DayOfWeek to previous value. + // + // Note: This works fine, but it ideally shouldn't invoke other + // fields from within a field. + workInstant = iChronology.dayOfWeek().set( workInstant, thisDow ); + // + // Return result. + // + return workInstant; + } + + public DurationField getRangeDurationField() { + return null; + } + + public boolean isLeap(long instant) { + return iChronology.getWeeksInYear(iChronology.getWeekyear(instant)) > 52; + } + + public int getLeapAmount(long instant) { + return iChronology.getWeeksInYear(iChronology.getWeekyear(instant)) - 52; + } + + public DurationField getLeapDurationField() { + return iChronology.weeks(); + } + + public int getMinimumValue() { + return iChronology.getMinYear(); + } + + public int getMaximumValue() { + return iChronology.getMaxYear(); + } + + public long roundFloor(long instant) { + // Note: This works fine, but it ideally shouldn't invoke other + // fields from within a field. + instant = iChronology.weekOfWeekyear().roundFloor(instant); + int wow = iChronology.getWeekOfWeekyear(instant); + if (wow > 1) { + instant -= ((long) DateTimeConstants.MILLIS_PER_WEEK) * (wow - 1); + } + return instant; + } + + public long remainder(long instant) { + return instant - roundFloor(instant); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.weekyear(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJYearDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/Attic/GJYearDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJYearDateTimeField.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,236 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.field.FieldUtils; +import org.joda.time.field.ImpreciseDateTimeField; + +/** + * Provides time calculations for the year component of time. + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +final class GJYearDateTimeField extends ImpreciseDateTimeField { + + private static final long serialVersionUID = -679076949530018869L; + + private static final long FEB_29 = (31L + 29 - 1) * DateTimeConstants.MILLIS_PER_DAY; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor + */ + GJYearDateTimeField(BaseGJChronology chronology) { + super(DateTimeFieldType.year(), chronology.getAverageMillisPerYear()); + iChronology = chronology; + } + + public boolean isLenient() { + return false; + } + + /** + * Get the Year component of the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the year extracted from the input. + */ + public int get(long instant) { + return iChronology.getYear(instant); + } + + /** + * Add the specified year to the specified time instant. + * The amount added may be negative. + * + * @param instant the time instant in millis to update. + * @param years the years to add (can be negative). + * @return the updated time instant. + */ + public long add(long instant, int years) { + if (years == 0) { + return instant; + } + int thisYear = get(instant); + int newYear = thisYear + years; + return set(instant, newYear); + } + + public long add(long instant, long years) { + return add(instant, FieldUtils.safeToInt(years)); + } + + /** + * Add to the Year component of the specified time instant + * wrapping around within that component if necessary. + * + * @param instant the time instant in millis to update. + * @param years the years to add (can be negative). + * @return the updated time instant. + */ + public long addWrapField(long instant, int years) { + if (years == 0) { + return instant; + } + // Return newly calculated millis value + int thisYear = iChronology.getYear(instant); + int wrappedYear = FieldUtils.getWrappedValue + (thisYear, years, iChronology.getMinYear(), iChronology.getMaxYear()); + return set(instant, wrappedYear); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + if (minuendInstant < subtrahendInstant) { + return -getDifference(subtrahendInstant, minuendInstant); + } + + int minuendYear = get(minuendInstant); + int subtrahendYear = get(subtrahendInstant); + + // Inlined remainder method to avoid duplicate calls to get. + long minuendRem = minuendInstant - iChronology.getYearMillis(minuendYear); + long subtrahendRem = subtrahendInstant - iChronology.getYearMillis(subtrahendYear); + + // Balance leap year differences on remainders. + if (subtrahendRem >= FEB_29) { + if (iChronology.isLeapYear(subtrahendYear)) { + if (!iChronology.isLeapYear(minuendYear)) { + subtrahendRem -= DateTimeConstants.MILLIS_PER_DAY; + } + } else if (minuendRem >= FEB_29 && iChronology.isLeapYear(minuendYear)) { + minuendRem -= DateTimeConstants.MILLIS_PER_DAY; + } + } + + int difference = minuendYear - subtrahendYear; + if (minuendRem < subtrahendRem) { + difference--; + } + return difference; + } + + /** + * Set the Year component of the specified time instant. + * + * @param instant the time instant in millis to update. + * @param year the year (-292269055,292278994) to update the time to. + * @return the updated time instant. + * @throws IllegalArgumentException if year is invalid. + */ + public long set(long instant, int year) { + FieldUtils.verifyValueBounds + (this, year, iChronology.getMinYear(), iChronology.getMaxYear()); + return iChronology.setYear(instant, year); + } + + public DurationField getRangeDurationField() { + return null; + } + + public boolean isLeap(long instant) { + return iChronology.isLeapYear(get(instant)); + } + + public int getLeapAmount(long instant) { + if (iChronology.isLeapYear(get(instant))) { + return 1; + } else { + return 0; + } + } + + public DurationField getLeapDurationField() { + return iChronology.days(); + } + + public int getMinimumValue() { + return iChronology.getMinYear(); + } + + public int getMaximumValue() { + return iChronology.getMaxYear(); + } + + public long roundFloor(long instant) { + return iChronology.getYearMillis(get(instant)); + } + + public long roundCeiling(long instant) { + int year = get(instant); + long yearStartMillis = iChronology.getYearMillis(year); + if (instant != yearStartMillis) { + // Bump up to start of next year. + instant = iChronology.getYearMillis(year + 1); + } + return instant; + } + + public long remainder(long instant) { + return instant - roundFloor(instant); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.year(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GJYearOfEraDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/GJYearOfEraDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GJYearOfEraDateTimeField.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,155 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.ReadablePartial; +import org.joda.time.field.DecoratedDateTimeField; +import org.joda.time.field.FieldUtils; + +/** + * Provides time calculations for the year of era component of time. + * + * @author Brian S O'Neill + */ +final class GJYearOfEraDateTimeField extends DecoratedDateTimeField { + + private static final long serialVersionUID = -5961050944769862059L; + + private final BaseGJChronology iChronology; + + /** + * Restricted constructor. + */ + GJYearOfEraDateTimeField(DateTimeField yearField, BaseGJChronology chronology) { + super(yearField, DateTimeFieldType.yearOfEra()); + iChronology = chronology; + } + + public int get(long instant) { + int year = getWrappedField().get(instant); + if (year <= 0) { + year = 1 - year; + } + return year; + } + + public long add(long instant, int years) { + return getWrappedField().add(instant, years); + } + + public long add(long instant, long years) { + return getWrappedField().add(instant, years); + } + + public long addWrapField(long instant, int years) { + return getWrappedField().addWrapField(instant, years); + } + + public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int years) { + return getWrappedField().addWrapField(instant, fieldIndex, values, years); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + /** + * Set the year component of the specified time instant. + * + * @param instant the time instant in millis to update. + * @param year the year (0,292278994) to update the time to. + * @return the updated time instant. + * @throws IllegalArgumentException if year is invalid. + */ + public long set(long instant, int year) { + FieldUtils.verifyValueBounds(this, year, 1, getMaximumValue()); + if (iChronology.getYear(instant) <= 0) { + year = 1 - year; + } + return super.set(instant, year); + } + + public int getMinimumValue() { + return 1; + } + + public int getMaximumValue() { + return getWrappedField().getMaximumValue(); + } + + public long roundFloor(long instant) { + return getWrappedField().roundFloor(instant); + } + + public long roundCeiling(long instant) { + return getWrappedField().roundCeiling(instant); + } + + public long remainder(long instant) { + return getWrappedField().remainder(instant); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return iChronology.yearOfEra(); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/GregorianChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/GregorianChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/GregorianChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,279 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.HashMap; +import java.util.Map; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeZone; + +/** + * Implements a pure proleptic Gregorian calendar system, which defines every + * fourth year as leap, unless the year is divisible by 100 and not by 400. + * This improves upon the Julian calendar leap year rule. + *

+ * Although the Gregorian calendar did not exist before 1582 CE, this + * chronology assumes it did, thus it is proleptic. This implementation also + * fixes the start of the year at January 1, and defines the year zero. + *

+ * GregorianChronology is thread-safe and immutable. + * + * @see Wikipedia + * @see JulianChronology + * @see GJChronology + * + * @author Guy Allard + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public final class GregorianChronology extends BaseGJChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -861407383323710522L; + + private static final long MILLIS_PER_YEAR = + (long) (365.2425 * DateTimeConstants.MILLIS_PER_DAY); + + private static final long MILLIS_PER_MONTH = + (long) (365.2425 * DateTimeConstants.MILLIS_PER_DAY / 12); + + /** Singleton instance of a UTC GregorianChronology */ + private static final GregorianChronology INSTANCE_UTC; + + /** Cache of zone to chronology arrays */ + private static final Map cCache = new HashMap(); + + static { + INSTANCE_UTC = getInstance(DateTimeZone.UTC); + } + + /** + * Gets an instance of the GregorianChronology. + * The time zone of the returned instance is UTC. + * + * @return a singleton UTC instance of the chronology + */ + public static GregorianChronology getInstanceUTC() { + return INSTANCE_UTC; + } + + /** + * Gets an instance of the GregorianChronology in the default time zone. + * + * @return a chronology in the default time zone + */ + public static GregorianChronology getInstance() { + return getInstance(DateTimeZone.getDefault(), 4); + } + + /** + * Gets an instance of the GregorianChronology in the given time zone. + * + * @param zone the time zone to get the chronology in, null is default + * @return a chronology in the specified time zone + */ + public static GregorianChronology getInstance(DateTimeZone zone) { + return getInstance(zone, 4); + } + + /** + * Gets an instance of the GregorianChronology in the given time zone. + * + * @param zone the time zone to get the chronology in, null is default + * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 + * @return a chronology in the specified time zone + */ + public static GregorianChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + GregorianChronology chrono; + synchronized (cCache) { + GregorianChronology[] chronos = (GregorianChronology[]) cCache.get(zone); + if (chronos == null) { + chronos = new GregorianChronology[7]; + cCache.put(zone, chronos); + } + try { + chrono = chronos[minDaysInFirstWeek - 1]; + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException + ("Invalid min days in first week: " + minDaysInFirstWeek); + } + if (chrono == null) { + if (zone == DateTimeZone.UTC) { + chrono = new GregorianChronology(null, null, minDaysInFirstWeek); + } else { + chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); + chrono = new GregorianChronology + (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); + } + chronos[minDaysInFirstWeek - 1] = chrono; + } + } + return chrono; + } + + // Constructors and instance variables + //----------------------------------------------------------------------- + + /** + * Restricted constructor + */ + private GregorianChronology(Chronology base, Object param, int minDaysInFirstWeek) { + super(base, param, minDaysInFirstWeek); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + Chronology base = getBase(); + return base == null ? getInstanceUTC() : getInstance(base.getZone()); + } + + // Conversion + //----------------------------------------------------------------------- + /** + * Gets the Chronology in the UTC time zone. + * + * @return the chronology in UTC + */ + public Chronology withUTC() { + return INSTANCE_UTC; + } + + /** + * Gets the Chronology in a specific time zone. + * + * @param zone the zone to get the chronology in, null is default + * @return the chronology + */ + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getZone()) { + return this; + } + return getInstance(zone); + } + + protected void assemble(Fields fields) { + if (getBase() == null) { + super.assemble(fields); + } + } + + boolean isLeapYear(int year) { + return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0); + } + + long calculateFirstDayOfYearMillis(int year) { + // Calculate relative to 2000 as that is on a 400 year boundary + // and that makes the sum easier + int relativeYear = year - 2000; + // Initial value is just temporary. + int leapYears = relativeYear / 100; + if (relativeYear <= 0) { + // Add 3 before shifting right since /4 and >>2 behave differently + // on negative numbers. When the expression is written as + // (relativeYear / 4) - (relativeYear / 100) + (relativeYear / 400), + // it works for both positive and negative values, except this optimization + // eliminates two divisions. + leapYears = ((relativeYear + 3) >> 2) - leapYears + ((leapYears + 3) >> 2); + } else { + leapYears = (relativeYear >> 2) - leapYears + (leapYears >> 2); + // For post 2000 an adjustment is needed as jan1st is before leap day + if (!isLeapYear(year)) { + leapYears++; + } + } + + long millis = (relativeYear * 365L + leapYears) + * (long)DateTimeConstants.MILLIS_PER_DAY; + + // Previous line was reduced from this to eliminate a multiplication. + // millis = ((relativeYear - leapYears) * 365L + leapYears * 366) * MILLIS_PER_DAY; + // (x - y)*c + y*(c + 1) => x*c - y*c + y*c + y => x*c + y + + return millis + MILLIS_1970_TO_2000; + } + + int getMinYear() { + // The lowest year that can be fully supported. + return -292275054; + } + + int getMaxYear() { + // The highest year that can be fully supported. + return 292277023; + } + + long getAverageMillisPerYear() { + return MILLIS_PER_YEAR; + } + + long getAverageMillisPerMonth() { + return MILLIS_PER_MONTH; + } + + long getApproxMillisAtEpoch() { + return 1970L * MILLIS_PER_YEAR; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/ISOChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/ISOChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/ISOChronology.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,252 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeZone; +import org.joda.time.field.DividedDateTimeField; +import org.joda.time.field.RemainderDateTimeField; + +/** + * Implements a chronology that follows the rules of the ISO8601 standard, + * which is compatible with Gregorian for all modern dates. + * When ISO does not define a field, but it can be determined (such as AM/PM) + * it is included. + *

+ * With the exception of century related fields, ISOChronology is exactly the + * same as {@link GregorianChronology}. In this chronology, centuries and year + * of century are zero based. For all years, the century is determined by + * dropping the last two digits of the year, ignoring sign. The year of century + * is the value of the last two year digits. + *

+ * ISOChronology is thread-safe and immutable. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public final class ISOChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -6212696554273812441L; + + /** Singleton instance of a UTC ISOChronology */ + private static final ISOChronology INSTANCE_UTC; + + private static final int FAST_CACHE_SIZE = 64; + + /** Fast cache of zone to chronology */ + private static final ISOChronology[] cFastCache; + + /** Cache of zone to chronology */ + private static final Map cCache = new HashMap(); + static { + cFastCache = new ISOChronology[FAST_CACHE_SIZE]; + INSTANCE_UTC = new ISOChronology(GregorianChronology.getInstanceUTC()); + cCache.put(DateTimeZone.UTC, INSTANCE_UTC); + } + + /** + * Gets an instance of the ISOChronology. + * The time zone of the returned instance is UTC. + * + * @return a singleton UTC instance of the chronology + */ + public static ISOChronology getInstanceUTC() { + return INSTANCE_UTC; + } + + /** + * Gets an instance of the ISOChronology in the default time zone. + * + * @return a chronology in the default time zone + */ + public static ISOChronology getInstance() { + return getInstance(DateTimeZone.getDefault()); + } + + /** + * Gets an instance of the ISOChronology in the given time zone. + * + * @param zone the time zone to get the chronology in, null is default + * @return a chronology in the specified time zone + */ + public static ISOChronology getInstance(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + int index = System.identityHashCode(zone) & (FAST_CACHE_SIZE - 1); + ISOChronology chrono = cFastCache[index]; + if (chrono != null && chrono.getZone() == zone) { + return chrono; + } + synchronized (cCache) { + chrono = (ISOChronology) cCache.get(zone); + if (chrono == null) { + chrono = new ISOChronology(ZonedChronology.getInstance(INSTANCE_UTC, zone)); + cCache.put(zone, chrono); + } + } + cFastCache[index] = chrono; + return chrono; + } + + // Constructors and instance variables + //----------------------------------------------------------------------- + + /** + * Restricted constructor + */ + private ISOChronology(Chronology base) { + super(base, null); + } + + // Conversion + //----------------------------------------------------------------------- + /** + * Gets the Chronology in the UTC time zone. + * + * @return the chronology in UTC + */ + public Chronology withUTC() { + return INSTANCE_UTC; + } + + /** + * Gets the Chronology in a specific time zone. + * + * @param zone the zone to get the chronology in, null is default + * @return the chronology + */ + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getZone()) { + return this; + } + return getInstance(zone); + } + + // Output + //----------------------------------------------------------------------- + /** + * Gets a debugging toString. + * + * @return a debugging string + */ + public String toString() { + String str = "ISOChronology"; + DateTimeZone zone = getZone(); + if (zone != null) { + str = str + '[' + zone.getID() + ']'; + } + return str; + } + + protected void assemble(Fields fields) { + if (getBase().getZone() == DateTimeZone.UTC) { + // Use zero based century and year of century. + fields.centuryOfEra = new DividedDateTimeField( + ISOYearOfEraDateTimeField.INSTANCE, DateTimeFieldType.centuryOfEra(), 100); + fields.yearOfCentury = new RemainderDateTimeField( + (DividedDateTimeField) fields.centuryOfEra, DateTimeFieldType.yearOfCentury()); + fields.weekyearOfCentury = new RemainderDateTimeField( + (DividedDateTimeField) fields.centuryOfEra, DateTimeFieldType.weekyearOfCentury()); + + fields.centuries = fields.centuryOfEra.getDurationField(); + } + } + + /** + * Serialize ISOChronology instances using a small stub. This reduces the + * serialized size, and deserialized instances come from the cache. + */ + private Object writeReplace() { + return new Stub(getZone()); + } + + private static final class Stub implements Serializable { + private static final long serialVersionUID = -6212696554273812441L; + + private transient DateTimeZone iZone; + + Stub(DateTimeZone zone) { + iZone = zone; + } + + private Object readResolve() { + return ISOChronology.getInstance(iZone); + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeObject(iZone); + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + iZone = (DateTimeZone)in.readObject(); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/ISOYearOfEraDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/ISOYearOfEraDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/ISOYearOfEraDateTimeField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,149 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.ReadablePartial; +import org.joda.time.field.DecoratedDateTimeField; +import org.joda.time.field.FieldUtils; + +/** + * This field is not publicy exposed by ISOChronology, but rather it is used to + * build the yearOfCentury and centuryOfEra fields. It merely drops the sign of + * the year. + * + * @author Brian S O'Neill + * @see GJYearOfEraDateTimeField + */ +class ISOYearOfEraDateTimeField extends DecoratedDateTimeField { + + private static final long serialVersionUID = 7037524068969447317L; + + /** + * Singleton instance + */ + static final DateTimeField INSTANCE = new ISOYearOfEraDateTimeField(); + + /** + * Restricted constructor. + */ + private ISOYearOfEraDateTimeField() { + super(GregorianChronology.getInstanceUTC().year(), DateTimeFieldType.yearOfEra()); + } + + public int get(long instant) { + int year = getWrappedField().get(instant); + return year < 0 ? -year : year; + } + + public long add(long instant, int years) { + return getWrappedField().add(instant, years); + } + + public long add(long instant, long years) { + return getWrappedField().add(instant, years); + } + + public long addWrapField(long instant, int years) { + return getWrappedField().addWrapField(instant, years); + } + + public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int years) { + return getWrappedField().addWrapField(instant, fieldIndex, values, years); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + public long set(long instant, int year) { + FieldUtils.verifyValueBounds(this, year, 0, getMaximumValue()); + if (getWrappedField().get(instant) < 0) { + year = -year; + } + return super.set(instant, year); + } + + public int getMinimumValue() { + return 0; + } + + public int getMaximumValue() { + return getWrappedField().getMaximumValue(); + } + + public long roundFloor(long instant) { + return getWrappedField().roundFloor(instant); + } + + public long roundCeiling(long instant) { + return getWrappedField().roundCeiling(instant); + } + + public long remainder(long instant) { + return getWrappedField().remainder(instant); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + return INSTANCE; + } +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/JulianChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/JulianChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/JulianChronology.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,352 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.HashMap; +import java.util.Map; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeZone; +import org.joda.time.field.DelegatedDateTimeField; +import org.joda.time.field.FieldUtils; + +/** + * Implements a pure proleptic Julian calendar system, which defines every + * fourth year as leap. This implementation follows the leap year rule + * strictly, even for dates before 8 CE, where leap years were actually + * irregular. In the Julian calendar, year zero does not exist: 1 BCE is + * followed by 1 CE. + *

+ * Although the Julian calendar did not exist before 45 BCE, this chronology + * assumes it did, thus it is proleptic. This implementation also fixes the + * start of the year at January 1. + *

+ * JulianChronology is thread-safe and immutable. + * + * @see Wikipedia + * @see GregorianChronology + * @see GJChronology + * + * @author Guy Allard + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public final class JulianChronology extends BaseGJChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -8731039522547897247L; + + private static final long MILLIS_PER_YEAR = + (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY); + + private static final long MILLIS_PER_MONTH = + (long) (365.25 * DateTimeConstants.MILLIS_PER_DAY / 12); + + /** Singleton instance of a UTC JulianChronology */ + private static final JulianChronology INSTANCE_UTC; + + /** Cache of zone to chronology arrays */ + private static final Map cCache = new HashMap(); + + static { + INSTANCE_UTC = getInstance(DateTimeZone.UTC); + } + + static int adjustYearForSet(int year) { + if (year <= 0) { + if (year == 0) { + throw new IllegalArgumentException("Invalid year: " + year); + } + year++; + } + return year; + } + + /** + * Gets an instance of the JulianChronology. + * The time zone of the returned instance is UTC. + * + * @return a singleton UTC instance of the chronology + */ + public static JulianChronology getInstanceUTC() { + return INSTANCE_UTC; + } + + /** + * Gets an instance of the JulianChronology in the default time zone. + * + * @return a chronology in the default time zone + */ + public static JulianChronology getInstance() { + return getInstance(DateTimeZone.getDefault(), 4); + } + + /** + * Gets an instance of the JulianChronology in the given time zone. + * + * @param zone the time zone to get the chronology in, null is default + * @return a chronology in the specified time zone + */ + public static JulianChronology getInstance(DateTimeZone zone) { + return getInstance(zone, 4); + } + + /** + * Gets an instance of the JulianChronology in the given time zone. + * + * @param zone the time zone to get the chronology in, null is default + * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 + * @return a chronology in the specified time zone + */ + public static JulianChronology getInstance(DateTimeZone zone, int minDaysInFirstWeek) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + JulianChronology chrono; + synchronized (cCache) { + JulianChronology[] chronos = (JulianChronology[]) cCache.get(zone); + if (chronos == null) { + chronos = new JulianChronology[7]; + cCache.put(zone, chronos); + } + try { + chrono = chronos[minDaysInFirstWeek - 1]; + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException + ("Invalid min days in first week: " + minDaysInFirstWeek); + } + if (chrono == null) { + if (zone == DateTimeZone.UTC) { + chrono = new JulianChronology(null, null, minDaysInFirstWeek); + } else { + chrono = getInstance(DateTimeZone.UTC, minDaysInFirstWeek); + chrono = new JulianChronology + (ZonedChronology.getInstance(chrono, zone), null, minDaysInFirstWeek); + } + chronos[minDaysInFirstWeek - 1] = chrono; + } + } + return chrono; + } + + // Constructors and instance variables + //----------------------------------------------------------------------- + + /** + * Restricted constructor + */ + JulianChronology(Chronology base, Object param, int minDaysInFirstWeek) { + super(base, param, minDaysInFirstWeek); + } + + /** + * Serialization singleton + */ + private Object readResolve() { + Chronology base = getBase(); + return base == null ? getInstanceUTC() : getInstance(base.getZone()); + } + + // Conversion + //----------------------------------------------------------------------- + /** + * Gets the Chronology in the UTC time zone. + * + * @return the chronology in UTC + */ + public Chronology withUTC() { + return INSTANCE_UTC; + } + + /** + * Gets the Chronology in a specific time zone. + * + * @param zone the zone to get the chronology in, null is default + * @return the chronology + */ + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getZone()) { + return this; + } + return getInstance(zone); + } + + long getDateMidnightMillis(int year, int monthOfYear, int dayOfMonth) + throws IllegalArgumentException + { + return super.getDateMidnightMillis(adjustYearForSet(year), monthOfYear, dayOfMonth); + } + + boolean isLeapYear(int year) { + return (year & 3) == 0; + } + + long calculateFirstDayOfYearMillis(int year) { + // Java epoch is 1970-01-01 Gregorian which is 1969-12-19 Julian. + // Calculate relative to the nearest leap year and account for the + // difference later. + + int relativeYear = year - 1968; + int leapYears; + if (relativeYear <= 0) { + // Add 3 before shifting right since /4 and >>2 behave differently + // on negative numbers. + leapYears = (relativeYear + 3) >> 2; + } else { + leapYears = relativeYear >> 2; + // For post 1968 an adjustment is needed as jan1st is before leap day + if (!isLeapYear(year)) { + leapYears++; + } + } + + long millis = (relativeYear * 365L + leapYears) + * (long)DateTimeConstants.MILLIS_PER_DAY; + + // Adjust to account for difference between 1968-01-01 and 1969-12-19. + + return millis - (366L + 352) * DateTimeConstants.MILLIS_PER_DAY; + } + + int getMinYear() { + // The lowest year that can be fully supported. + return -292269054; + } + + int getMaxYear() { + // The highest year that can be fully supported. + return 292271022; + } + + long getAverageMillisPerYear() { + return MILLIS_PER_YEAR; + } + + long getAverageMillisPerMonth() { + return MILLIS_PER_MONTH; + } + + long getApproxMillisAtEpoch() { + return 1969L * MILLIS_PER_YEAR + 352L * DateTimeConstants.MILLIS_PER_DAY; + } + + protected void assemble(Fields fields) { + if (getBase() == null) { + super.assemble(fields); + // Julian chronology has no year zero. + fields.year = new NoYearZeroField(this, fields.year); + fields.weekyear = new NoWeekyearZeroField(this, fields.weekyear); + } + } + + static class NoYearZeroField extends DelegatedDateTimeField { + private static final long serialVersionUID = -8869148464118507846L; + + final BaseGJChronology iChronology; + private transient int iMinYear; + + NoYearZeroField(BaseGJChronology chronology, DateTimeField field) { + super(field); + iChronology = chronology; + int min = super.getMinimumValue(); + if (min < 0) { + iMinYear = min - 1; + } else if (min == 0) { + iMinYear = 1; + } else { + iMinYear = min; + } + } + + public int get(long millis) { + int year = super.get(millis); + if (year <= 0) { + year--; + } + return year; + } + + public long set(long millis, int year) { + FieldUtils.verifyValueBounds(this, year, iMinYear, getMaximumValue()); + return super.set(millis, adjustYearForSet(year)); + } + + public int getMinimumValue() { + return iMinYear; + } + + private Object readResolve() { + return iChronology.year(); + } + } + + static class NoWeekyearZeroField extends NoYearZeroField { + private static final long serialVersionUID = -5013429014495501104L; + + NoWeekyearZeroField(BaseGJChronology chronology, DateTimeField field) { + super(chronology, field); + } + + private Object readResolve() { + return iChronology.weekyear(); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/LenientChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/LenientChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/LenientChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,159 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeZone; +import org.joda.time.field.LenientDateTimeField; + +/** + * Wraps another Chronology, ensuring all the fields are lenient. + *

+ * LenientChronology is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + * @see LenientDateTimeField + * @see StrictChronology + */ +public final class LenientChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -3148237568046877177L; + + /** + * Create a LenientChronology for any chronology. + * + * @param base the chronology to wrap + * @throws IllegalArgumentException if chronology is null + */ + public static LenientChronology getInstance(Chronology base) { + if (base == null) { + throw new IllegalArgumentException("Must supply a chronology"); + } + return new LenientChronology(base); + } + + private transient Chronology iWithUTC; + + /** + * Create a LenientChronology for any chronology. + * + * @param base the chronology to wrap + */ + private LenientChronology(Chronology base) { + super(base, null); + } + + public Chronology withUTC() { + if (iWithUTC == null) { + if (getZone() == DateTimeZone.UTC) { + iWithUTC = this; + } else { + iWithUTC = LenientChronology.getInstance(getBase().withUTC()); + } + } + return iWithUTC; + } + + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == DateTimeZone.UTC) { + return withUTC(); + } + if (zone == getZone()) { + return this; + } + return LenientChronology.getInstance(getBase().withZone(zone)); + } + + protected void assemble(Fields fields) { + fields.year = convertField(fields.year); + fields.yearOfEra = convertField(fields.yearOfEra); + fields.yearOfCentury = convertField(fields.yearOfCentury); + fields.centuryOfEra = convertField(fields.centuryOfEra); + fields.era = convertField(fields.era); + fields.dayOfWeek = convertField(fields.dayOfWeek); + fields.dayOfMonth = convertField(fields.dayOfMonth); + fields.dayOfYear = convertField(fields.dayOfYear); + fields.monthOfYear = convertField(fields.monthOfYear); + fields.weekOfWeekyear = convertField(fields.weekOfWeekyear); + fields.weekyear = convertField(fields.weekyear); + fields.weekyearOfCentury = convertField(fields.weekyearOfCentury); + + fields.millisOfSecond = convertField(fields.millisOfSecond); + fields.millisOfDay = convertField(fields.millisOfDay); + fields.secondOfMinute = convertField(fields.secondOfMinute); + fields.secondOfDay = convertField(fields.secondOfDay); + fields.minuteOfHour = convertField(fields.minuteOfHour); + fields.minuteOfDay = convertField(fields.minuteOfDay); + fields.hourOfDay = convertField(fields.hourOfDay); + fields.hourOfHalfday = convertField(fields.hourOfHalfday); + fields.clockhourOfDay = convertField(fields.clockhourOfDay); + fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday); + fields.halfdayOfDay = convertField(fields.halfdayOfDay); + } + + private static final DateTimeField convertField(DateTimeField field) { + return LenientDateTimeField.getInstance(field); + } + + public String toString() { + return "LenientChronology[" + getBase().toString() + ']'; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/LimitChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/LimitChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/LimitChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,598 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.HashMap; +import java.util.Locale; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationField; +import org.joda.time.MutableDateTime; +import org.joda.time.ReadableDateTime; +import org.joda.time.field.DecoratedDateTimeField; +import org.joda.time.field.DecoratedDurationField; +import org.joda.time.format.DateTimePrinter; +import org.joda.time.format.ISODateTimeFormat; + +/** + * Wraps another Chronology to impose limits on the range of instants that + * the fields within a Chronology may support. The limits are applied to both + * DateTimeFields and DurationFields. + *

+ * Methods in DateTimeField and DurationField throw an IllegalArgumentException + * whenever given an input instant that is outside the limits or when an + * attempt is made to move an instant outside the limits. + *

+ * LimitChronology is thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public final class LimitChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = 7670866536893052522L; + + /** + * Wraps another chronology, with datetime limits. When withUTC or + * withZone is called, the returned LimitChronology instance has + * the same limits, except they are time zone adjusted. + * + * @param base base chronology to wrap + * @param lowerLimit inclusive lower limit, or null if none + * @param upperLimit exclusive upper limit, or null if none + * @throws IllegalArgumentException if chronology is null or limits are invalid + */ + public static LimitChronology getInstance(Chronology base, + ReadableDateTime lowerLimit, + ReadableDateTime upperLimit) { + if (base == null) { + throw new IllegalArgumentException("Must supply a chronology"); + } + + lowerLimit = lowerLimit == null ? null : lowerLimit.toDateTime(); + upperLimit = upperLimit == null ? null : upperLimit.toDateTime(); + + if (lowerLimit != null && upperLimit != null) { + if (!lowerLimit.isBefore(upperLimit)) { + throw new IllegalArgumentException + ("The lower limit must be come before than the upper limit"); + } + } + + return new LimitChronology(base, (DateTime)lowerLimit, (DateTime)upperLimit); + } + + final DateTime iLowerLimit; + final DateTime iUpperLimit; + + private transient LimitChronology iWithUTC; + + /** + * Wraps another chronology, with datetime limits. When withUTC or + * withZone is called, the returned LimitChronology instance has + * the same limits, except they are time zone adjusted. + * + * @param lowerLimit inclusive lower limit, or null if none + * @param upperLimit exclusive upper limit, or null if none + */ + private LimitChronology(Chronology base, + DateTime lowerLimit, DateTime upperLimit) { + super(base, null); + // These can be set after assembly. + iLowerLimit = lowerLimit; + iUpperLimit = upperLimit; + } + + /** + * Returns the inclusive lower limit instant. + * + * @return lower limit + */ + public DateTime getLowerLimit() { + return iLowerLimit; + } + + /** + * Returns the inclusive upper limit instant. + * + * @return upper limit + */ + public DateTime getUpperLimit() { + return iUpperLimit; + } + + /** + * If this LimitChronology is already UTC, then this is + * returned. Otherwise, a new instance is returned, with the limits + * adjusted to the new time zone. + */ + public Chronology withUTC() { + return withZone(DateTimeZone.UTC); + } + + /** + * If this LimitChronology has the same time zone as the one given, then + * this is returned. Otherwise, a new instance is returned, with the limits + * adjusted to the new time zone. + */ + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getZone()) { + return this; + } + + if (zone == DateTimeZone.UTC && iWithUTC != null) { + return iWithUTC; + } + + DateTime lowerLimit = iLowerLimit; + if (lowerLimit != null) { + MutableDateTime mdt = lowerLimit.toMutableDateTime(); + mdt.setZoneRetainFields(zone); + lowerLimit = mdt.toDateTime(); + } + + DateTime upperLimit = iUpperLimit; + if (upperLimit != null) { + MutableDateTime mdt = upperLimit.toMutableDateTime(); + mdt.setZoneRetainFields(zone); + upperLimit = mdt.toDateTime(); + } + + LimitChronology chrono = getInstance + (getBase().withZone(zone), lowerLimit, upperLimit); + + if (zone == DateTimeZone.UTC) { + iWithUTC = chrono; + } + + return chrono; + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int millisOfDay) + throws IllegalArgumentException + { + long instant = getBase().getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); + checkLimits(instant, "resulting"); + return instant; + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + long instant = getBase().getDateTimeMillis + (year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + checkLimits(instant, "resulting"); + return instant; + } + + public long getDateTimeMillis(long instant, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + checkLimits(instant, null); + instant = getBase().getDateTimeMillis + (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); + checkLimits(instant, "resulting"); + return instant; + } + + protected void assemble(Fields fields) { + // Keep a local cache of converted fields so as not to create redundant + // objects. + HashMap converted = new HashMap(); + + // Convert duration fields... + + fields.eras = convertField(fields.eras, converted); + fields.centuries = convertField(fields.centuries, converted); + fields.years = convertField(fields.years, converted); + fields.months = convertField(fields.months, converted); + fields.weekyears = convertField(fields.weekyears, converted); + fields.weeks = convertField(fields.weeks, converted); + fields.days = convertField(fields.days, converted); + + fields.halfdays = convertField(fields.halfdays, converted); + fields.hours = convertField(fields.hours, converted); + fields.minutes = convertField(fields.minutes, converted); + fields.seconds = convertField(fields.seconds, converted); + fields.millis = convertField(fields.millis, converted); + + // Convert datetime fields... + + fields.year = convertField(fields.year, converted); + fields.yearOfEra = convertField(fields.yearOfEra, converted); + fields.yearOfCentury = convertField(fields.yearOfCentury, converted); + fields.centuryOfEra = convertField(fields.centuryOfEra, converted); + fields.era = convertField(fields.era, converted); + fields.dayOfWeek = convertField(fields.dayOfWeek, converted); + fields.dayOfMonth = convertField(fields.dayOfMonth, converted); + fields.dayOfYear = convertField(fields.dayOfYear, converted); + fields.monthOfYear = convertField(fields.monthOfYear, converted); + fields.weekOfWeekyear = convertField(fields.weekOfWeekyear, converted); + fields.weekyear = convertField(fields.weekyear, converted); + fields.weekyearOfCentury = convertField(fields.weekyearOfCentury, converted); + + fields.millisOfSecond = convertField(fields.millisOfSecond, converted); + fields.millisOfDay = convertField(fields.millisOfDay, converted); + fields.secondOfMinute = convertField(fields.secondOfMinute, converted); + fields.secondOfDay = convertField(fields.secondOfDay, converted); + fields.minuteOfHour = convertField(fields.minuteOfHour, converted); + fields.minuteOfDay = convertField(fields.minuteOfDay, converted); + fields.hourOfDay = convertField(fields.hourOfDay, converted); + fields.hourOfHalfday = convertField(fields.hourOfHalfday, converted); + fields.clockhourOfDay = convertField(fields.clockhourOfDay, converted); + fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday, converted); + fields.halfdayOfDay = convertField(fields.halfdayOfDay, converted); + } + + private DurationField convertField(DurationField field, HashMap converted) { + if (field == null || !field.isSupported()) { + return field; + } + if (converted.containsKey(field)) { + return (DurationField)converted.get(field); + } + LimitDurationField limitField = new LimitDurationField(field); + converted.put(field, limitField); + return limitField; + } + + private DateTimeField convertField(DateTimeField field, HashMap converted) { + if (field == null || !field.isSupported()) { + return field; + } + if (converted.containsKey(field)) { + return (DateTimeField)converted.get(field); + } + LimitDateTimeField limitField = + new LimitDateTimeField(field, + convertField(field.getDurationField(), converted), + convertField(field.getRangeDurationField(), converted), + convertField(field.getLeapDurationField(), converted)); + converted.put(field, limitField); + return limitField; + } + + public String toString() { + return getBase().toString(); + } + + void checkLimits(long instant, String desc) { + DateTime limit; + if ((limit = iLowerLimit) != null && instant < limit.getMillis()) { + throw new LimitException(desc, true); + } + if ((limit = iUpperLimit) != null && instant >= limit.getMillis()) { + throw new LimitException(desc, false); + } + } + + /** + * Extends IllegalArgumentException such that the exception message is not + * generated unless it is actually requested. + */ + private class LimitException extends IllegalArgumentException { + private static final long serialVersionUID = -5924689995607498581L; + + private final boolean iIsLow; + + LimitException(String desc, boolean isLow) { + super(desc); + iIsLow = isLow; + } + + public String getMessage() { + StringBuffer buf = new StringBuffer(85); + buf.append("The"); + String desc = super.getMessage(); + if (desc != null) { + buf.append(' '); + buf.append(desc); + } + buf.append(" instant is "); + + DateTimePrinter p = ISODateTimeFormat.getInstance().dateTime(); + + if (iIsLow) { + buf.append("below the supported minimum of "); + p.printTo(buf, getLowerLimit().getMillis(), getBase()); + } else { + buf.append("above the supported maximum of "); + p.printTo(buf, getUpperLimit().getMillis(), getBase()); + } + + buf.append(" ("); + buf.append(getBase()); + buf.append(')'); + + return buf.toString(); + } + + public String toString() { + return "IllegalArgumentException: " + getMessage(); + } + } + + private class LimitDurationField extends DecoratedDurationField { + private static final long serialVersionUID = 8049297699408782284L; + + LimitDurationField(DurationField field) { + super(field, field.getType()); + } + + public int getValue(long duration, long instant) { + checkLimits(instant, null); + return getWrappedField().getValue(duration, instant); + } + + public long getValueAsLong(long duration, long instant) { + checkLimits(instant, null); + return getWrappedField().getValueAsLong(duration, instant); + } + + public long getMillis(int value, long instant) { + checkLimits(instant, null); + return getWrappedField().getMillis(value, instant); + } + + public long getMillis(long value, long instant) { + checkLimits(instant, null); + return getWrappedField().getMillis(value, instant); + } + + public long add(long instant, int amount) { + checkLimits(instant, null); + long result = getWrappedField().add(instant, amount); + checkLimits(result, "resulting"); + return result; + } + + public long add(long instant, long amount) { + checkLimits(instant, null); + long result = getWrappedField().add(instant, amount); + checkLimits(result, "resulting"); + return result; + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + checkLimits(minuendInstant, "minuend"); + checkLimits(subtrahendInstant, "subtrahend"); + return getWrappedField().getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + checkLimits(minuendInstant, "minuend"); + checkLimits(subtrahendInstant, "subtrahend"); + return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + } + + private class LimitDateTimeField extends DecoratedDateTimeField { + private static final long serialVersionUID = -2435306746995699312L; + + private final DurationField iDurationField; + private final DurationField iRangeDurationField; + private final DurationField iLeapDurationField; + + LimitDateTimeField(DateTimeField field, + DurationField durationField, + DurationField rangeDurationField, + DurationField leapDurationField) { + super(field, field.getType()); + iDurationField = durationField; + iRangeDurationField = rangeDurationField; + iLeapDurationField = leapDurationField; + } + + public int get(long instant) { + checkLimits(instant, null); + return getWrappedField().get(instant); + } + + public String getAsText(long instant, Locale locale) { + checkLimits(instant, null); + return getWrappedField().getAsText(instant, locale); + } + + public String getAsShortText(long instant, Locale locale) { + checkLimits(instant, null); + return getWrappedField().getAsShortText(instant, locale); + } + + public long add(long instant, int amount) { + checkLimits(instant, null); + long result = getWrappedField().add(instant, amount); + checkLimits(result, "resulting"); + return result; + } + + public long add(long instant, long amount) { + checkLimits(instant, null); + long result = getWrappedField().add(instant, amount); + checkLimits(result, "resulting"); + return result; + } + + public long addWrapField(long instant, int amount) { + checkLimits(instant, null); + long result = getWrappedField().addWrapField(instant, amount); + checkLimits(result, "resulting"); + return result; + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + checkLimits(minuendInstant, "minuend"); + checkLimits(subtrahendInstant, "subtrahend"); + return getWrappedField().getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + checkLimits(minuendInstant, "minuend"); + checkLimits(subtrahendInstant, "subtrahend"); + return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + public long set(long instant, int value) { + checkLimits(instant, null); + long result = getWrappedField().set(instant, value); + checkLimits(result, "resulting"); + return result; + } + + public long set(long instant, String text, Locale locale) { + checkLimits(instant, null); + long result = getWrappedField().set(instant, text, locale); + checkLimits(result, "resulting"); + return result; + } + + public final DurationField getDurationField() { + return iDurationField; + } + + public final DurationField getRangeDurationField() { + return iRangeDurationField; + } + + public boolean isLeap(long instant) { + checkLimits(instant, null); + return getWrappedField().isLeap(instant); + } + + public int getLeapAmount(long instant) { + checkLimits(instant, null); + return getWrappedField().getLeapAmount(instant); + } + + public final DurationField getLeapDurationField() { + return iLeapDurationField; + } + + public long roundFloor(long instant) { + checkLimits(instant, null); + long result = getWrappedField().roundFloor(instant); + checkLimits(result, "resulting"); + return result; + } + + public long roundCeiling(long instant) { + checkLimits(instant, null); + long result = getWrappedField().roundCeiling(instant); + checkLimits(result, "resulting"); + return result; + } + + public long roundHalfFloor(long instant) { + checkLimits(instant, null); + long result = getWrappedField().roundHalfFloor(instant); + checkLimits(result, "resulting"); + return result; + } + + public long roundHalfCeiling(long instant) { + checkLimits(instant, null); + long result = getWrappedField().roundHalfCeiling(instant); + checkLimits(result, "resulting"); + return result; + } + + public long roundHalfEven(long instant) { + checkLimits(instant, null); + long result = getWrappedField().roundHalfEven(instant); + checkLimits(result, "resulting"); + return result; + } + + public long remainder(long instant) { + checkLimits(instant, null); + long result = getWrappedField().remainder(instant); + checkLimits(result, "resulting"); + return result; + } + + public int getMinimumValue(long instant) { + checkLimits(instant, null); + return getWrappedField().getMinimumValue(instant); + } + + public int getMaximumValue(long instant) { + checkLimits(instant, null); + return getWrappedField().getMaximumValue(instant); + } + + public int getMaximumTextLength(Locale locale) { + return getWrappedField().getMaximumTextLength(locale); + } + + public int getMaximumShortTextLength(Locale locale) { + return getWrappedField().getMaximumShortTextLength(locale); + } + + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/StrictChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/StrictChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/StrictChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,159 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeZone; +import org.joda.time.field.StrictDateTimeField; + +/** + * Wraps another Chronology, ensuring all the fields are strict. + *

+ * StrictChronology is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + * @see StrictDateTimeField + * @see LenientChronology + */ +public final class StrictChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = 6633006628097111960L; + + /** + * Create a StrictChronology for any chronology. + * + * @param base the chronology to wrap + * @throws IllegalArgumentException if chronology is null + */ + public static StrictChronology getInstance(Chronology base) { + if (base == null) { + throw new IllegalArgumentException("Must supply a chronology"); + } + return new StrictChronology(base); + } + + private transient Chronology iWithUTC; + + /** + * Create a StrictChronology for any chronology. + * + * @param base the chronology to wrap + */ + private StrictChronology(Chronology base) { + super(base, null); + } + + public Chronology withUTC() { + if (iWithUTC == null) { + if (getZone() == DateTimeZone.UTC) { + iWithUTC = this; + } else { + iWithUTC = StrictChronology.getInstance(getBase().withUTC()); + } + } + return iWithUTC; + } + + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == DateTimeZone.UTC) { + return withUTC(); + } + if (zone == getZone()) { + return this; + } + return StrictChronology.getInstance(getBase().withZone(zone)); + } + + protected void assemble(Fields fields) { + fields.year = convertField(fields.year); + fields.yearOfEra = convertField(fields.yearOfEra); + fields.yearOfCentury = convertField(fields.yearOfCentury); + fields.centuryOfEra = convertField(fields.centuryOfEra); + fields.era = convertField(fields.era); + fields.dayOfWeek = convertField(fields.dayOfWeek); + fields.dayOfMonth = convertField(fields.dayOfMonth); + fields.dayOfYear = convertField(fields.dayOfYear); + fields.monthOfYear = convertField(fields.monthOfYear); + fields.weekOfWeekyear = convertField(fields.weekOfWeekyear); + fields.weekyear = convertField(fields.weekyear); + fields.weekyearOfCentury = convertField(fields.weekyearOfCentury); + + fields.millisOfSecond = convertField(fields.millisOfSecond); + fields.millisOfDay = convertField(fields.millisOfDay); + fields.secondOfMinute = convertField(fields.secondOfMinute); + fields.secondOfDay = convertField(fields.secondOfDay); + fields.minuteOfHour = convertField(fields.minuteOfHour); + fields.minuteOfDay = convertField(fields.minuteOfDay); + fields.hourOfDay = convertField(fields.hourOfDay); + fields.hourOfHalfday = convertField(fields.hourOfHalfday); + fields.clockhourOfDay = convertField(fields.clockhourOfDay); + fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday); + fields.halfdayOfDay = convertField(fields.halfdayOfDay); + } + + private static final DateTimeField convertField(DateTimeField field) { + return StrictDateTimeField.getInstance(field); + } + + public String toString() { + return "StrictChronology[" + getBase().toString() + ']'; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/ZonedChronology.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/ZonedChronology.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/ZonedChronology.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,505 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.chrono; + +import java.util.HashMap; +import java.util.Locale; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationField; +import org.joda.time.field.BaseDateTimeField; +import org.joda.time.field.BaseDurationField; + +/** + * Wraps another Chronology to add support for time zones. + *

+ * ZonedChronology is thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public final class ZonedChronology extends AssembledChronology { + + /** Serialization lock */ + private static final long serialVersionUID = -1079258847191166848L; + + /** + * Create a ZonedChronology for any chronology, overriding any time zone it + * may already have. + * + * @param base base chronology to wrap + * @param zone the time zone + * @throws IllegalArgumentException if chronology or time zone is null + */ + public static ZonedChronology getInstance(Chronology base, DateTimeZone zone) { + if (base == null) { + throw new IllegalArgumentException("Must supply a chronology"); + } + base = base.withUTC(); + if (base == null) { + throw new IllegalArgumentException("UTC chronology must not be null"); + } + if (zone == null) { + throw new IllegalArgumentException("DateTimeZone must not be null"); + } + return new ZonedChronology(base, zone); + } + + static boolean useTimeArithmetic(DurationField field) { + // Use time of day arithmetic rules for unit durations less than + // typical time zone offsets. + return field != null && field.getUnitMillis() < DateTimeConstants.MILLIS_PER_HOUR * 12; + } + + /** + * Restricted constructor + * + * @param base base chronology to wrap + * @param zone the time zone + */ + private ZonedChronology(Chronology base, DateTimeZone zone) { + super(base, zone); + } + + public DateTimeZone getZone() { + return (DateTimeZone)getParam(); + } + + public Chronology withUTC() { + return getBase(); + } + + public Chronology withZone(DateTimeZone zone) { + if (zone == null) { + zone = DateTimeZone.getDefault(); + } + if (zone == getParam()) { + return this; + } + if (zone == DateTimeZone.UTC) { + return getBase(); + } + return new ZonedChronology(getBase(), zone); + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int millisOfDay) + throws IllegalArgumentException + { + return localToUTC(getBase().getDateTimeMillis + (year, monthOfYear, dayOfMonth, millisOfDay)); + } + + public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + return localToUTC(getBase().getDateTimeMillis + (year, monthOfYear, dayOfMonth, + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond)); + } + + public long getDateTimeMillis(long instant, + int hourOfDay, int minuteOfHour, + int secondOfMinute, int millisOfSecond) + throws IllegalArgumentException + { + return localToUTC(getBase().getDateTimeMillis + (instant + getZone().getOffset(instant), + hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond)); + } + + /** + * @param instant instant from 1970-01-01T00:00:00 local time + * @return instant from 1970-01-01T00:00:00Z + */ + private long localToUTC(long instant) { + DateTimeZone zone = getZone(); + int offset = zone.getOffsetFromLocal(instant); + instant -= offset; + if (offset != zone.getOffset(instant)) { + throw new IllegalArgumentException + ("Illegal instant due to time zone offset transition"); + } + return instant; + } + + protected void assemble(Fields fields) { + // Keep a local cache of converted fields so as not to create redundant + // objects. + HashMap converted = new HashMap(); + + // Convert duration fields... + + fields.eras = convertField(fields.eras, converted); + fields.centuries = convertField(fields.centuries, converted); + fields.years = convertField(fields.years, converted); + fields.months = convertField(fields.months, converted); + fields.weekyears = convertField(fields.weekyears, converted); + fields.weeks = convertField(fields.weeks, converted); + fields.days = convertField(fields.days, converted); + + fields.halfdays = convertField(fields.halfdays, converted); + fields.hours = convertField(fields.hours, converted); + fields.minutes = convertField(fields.minutes, converted); + fields.seconds = convertField(fields.seconds, converted); + fields.millis = convertField(fields.millis, converted); + + // Convert datetime fields... + + fields.year = convertField(fields.year, converted); + fields.yearOfEra = convertField(fields.yearOfEra, converted); + fields.yearOfCentury = convertField(fields.yearOfCentury, converted); + fields.centuryOfEra = convertField(fields.centuryOfEra, converted); + fields.era = convertField(fields.era, converted); + fields.dayOfWeek = convertField(fields.dayOfWeek, converted); + fields.dayOfMonth = convertField(fields.dayOfMonth, converted); + fields.dayOfYear = convertField(fields.dayOfYear, converted); + fields.monthOfYear = convertField(fields.monthOfYear, converted); + fields.weekOfWeekyear = convertField(fields.weekOfWeekyear, converted); + fields.weekyear = convertField(fields.weekyear, converted); + fields.weekyearOfCentury = convertField(fields.weekyearOfCentury, converted); + + fields.millisOfSecond = convertField(fields.millisOfSecond, converted); + fields.millisOfDay = convertField(fields.millisOfDay, converted); + fields.secondOfMinute = convertField(fields.secondOfMinute, converted); + fields.secondOfDay = convertField(fields.secondOfDay, converted); + fields.minuteOfHour = convertField(fields.minuteOfHour, converted); + fields.minuteOfDay = convertField(fields.minuteOfDay, converted); + fields.hourOfDay = convertField(fields.hourOfDay, converted); + fields.hourOfHalfday = convertField(fields.hourOfHalfday, converted); + fields.clockhourOfDay = convertField(fields.clockhourOfDay, converted); + fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfday, converted); + fields.halfdayOfDay = convertField(fields.halfdayOfDay, converted); + } + + private DurationField convertField(DurationField field, HashMap converted) { + if (field == null || !field.isSupported()) { + return field; + } + if (converted.containsKey(field)) { + return (DurationField)converted.get(field); + } + ZonedDurationField zonedField = new ZonedDurationField(field, getZone()); + converted.put(field, zonedField); + return zonedField; + } + + private DateTimeField convertField(DateTimeField field, HashMap converted) { + if (field == null || !field.isSupported()) { + return field; + } + if (converted.containsKey(field)) { + return (DateTimeField)converted.get(field); + } + ZonedDateTimeField zonedField = + new ZonedDateTimeField(field, getZone(), + convertField(field.getDurationField(), converted), + convertField(field.getRangeDurationField(), converted), + convertField(field.getLeapDurationField(), converted)); + converted.put(field, zonedField); + return zonedField; + } + + public String toString() { + return "ZonedChronology[" + getBase() + ", " + getZone().getID() + ']'; + } + + /* + * Because time durations are typically smaller than time zone offsets, the + * arithmetic methods subtract the original offset. This produces a more + * expected behavior when crossing time zone offset transitions. For dates, + * the new offset is subtracted off. This behavior, if applied to time + * fields, can nullify or reverse an add when crossing a transition. + */ + + static class ZonedDurationField extends BaseDurationField { + private static final long serialVersionUID = -485345310999208286L; + + final DurationField iField; + final boolean iTimeField; + final DateTimeZone iZone; + + ZonedDurationField(DurationField field, DateTimeZone zone) { + super(field.getType()); + if (!field.isSupported()) { + throw new IllegalArgumentException(); + } + iField = field; + iTimeField = useTimeArithmetic(field); + this.iZone = zone; + } + + public boolean isPrecise() { + return iTimeField ? iField.isPrecise() : iZone.isFixed(); + } + + public long getUnitMillis() { + return iField.getUnitMillis(); + } + + public int getValue(long duration, long instant) { + return iField.getValue(duration, instant + this.iZone.getOffset(instant)); + } + + public long getValueAsLong(long duration, long instant) { + return iField.getValueAsLong(duration, instant + this.iZone.getOffset(instant)); + } + + public long getMillis(int value, long instant) { + return iField.getMillis(value, instant + this.iZone.getOffset(instant)); + } + + public long getMillis(long value, long instant) { + return iField.getMillis(value, instant + this.iZone.getOffset(instant)); + } + + public long add(long instant, int value) { + int offset = this.iZone.getOffset(instant); + instant = iField.add(instant + offset, value); + return instant - (iTimeField ? offset : this.iZone.getOffsetFromLocal(instant)); + } + + public long add(long instant, long value) { + int offset = this.iZone.getOffset(instant); + instant = iField.add(instant + offset, value); + return instant - (iTimeField ? offset : this.iZone.getOffsetFromLocal(instant)); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + int offset = this.iZone.getOffset(subtrahendInstant); + return iField.getDifference + (minuendInstant + (iTimeField ? offset : this.iZone.getOffset(minuendInstant)), + subtrahendInstant + offset); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + int offset = this.iZone.getOffset(subtrahendInstant); + return iField.getDifferenceAsLong + (minuendInstant + (iTimeField ? offset : this.iZone.getOffset(minuendInstant)), + subtrahendInstant + offset); + } + } + + /** + * A DateTimeField that decorates another to add timezone behaviour. + *

+ * This class converts passed in instants to local wall time, and vice + * versa on output. + */ + static final class ZonedDateTimeField extends BaseDateTimeField { + private static final long serialVersionUID = -3968986277775529794L; + + final DateTimeField iField; + final DateTimeZone iZone; + final DurationField iDurationField; + final boolean iTimeField; + final DurationField iRangeDurationField; + final DurationField iLeapDurationField; + + ZonedDateTimeField(DateTimeField field, + DateTimeZone zone, + DurationField durationField, + DurationField rangeDurationField, + DurationField leapDurationField) { + super(field.getType()); + if (!field.isSupported()) { + throw new IllegalArgumentException(); + } + iField = field; + this.iZone = zone; + iDurationField = durationField; + iTimeField = useTimeArithmetic(durationField); + iRangeDurationField = rangeDurationField; + iLeapDurationField = leapDurationField; + } + + public boolean isLenient() { + return iField.isLenient(); + } + + public int get(long instant) { + return iField.get(instant + this.iZone.getOffset(instant)); + } + + public String getAsText(long instant, Locale locale) { + return iField.getAsText(instant + this.iZone.getOffset(instant), locale); + } + + public String getAsShortText(long instant, Locale locale) { + return iField.getAsShortText(instant + this.iZone.getOffset(instant), locale); + } + + public long add(long instant, int value) { + int offset = this.iZone.getOffset(instant); + instant = iField.add(instant + offset, value); + return instant - (iTimeField ? offset : this.iZone.getOffsetFromLocal(instant)); + } + + public long add(long instant, long value) { + int offset = this.iZone.getOffset(instant); + instant = iField.add(instant + offset, value); + return instant - (iTimeField ? offset : this.iZone.getOffsetFromLocal(instant)); + } + + public long addWrapField(long instant, int value) { + int offset = this.iZone.getOffset(instant); + instant = iField.addWrapField(instant + offset, value); + return instant - (iTimeField ? offset : this.iZone.getOffsetFromLocal(instant)); + } + + public long set(long instant, int value) { + long offset = this.iZone.getOffset(instant); + + instant = iField.set(instant + offset, value); + long offsetFromLocal = this.iZone.getOffsetFromLocal(instant); + instant -= offsetFromLocal; + + if (offset != offsetFromLocal) { + if (get(instant) != value) { + throw new IllegalArgumentException + ("Illegal value for " + iField.getName() + ": " + value); + } + } + + return instant; + } + + public long set(long instant, String text, Locale locale) { + instant = iField.set(instant + this.iZone.getOffset(instant), text, locale); + // Cannot verify that new value stuck because set may be lenient. + return instant - this.iZone.getOffsetFromLocal(instant); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + int offset = this.iZone.getOffset(subtrahendInstant); + return iField.getDifference + (minuendInstant + (iTimeField ? offset : this.iZone.getOffset(minuendInstant)), + subtrahendInstant + offset); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + int offset = this.iZone.getOffset(subtrahendInstant); + return iField.getDifferenceAsLong + (minuendInstant + (iTimeField ? offset : this.iZone.getOffset(minuendInstant)), + subtrahendInstant + offset); + } + + public final DurationField getDurationField() { + return iDurationField; + } + + public final DurationField getRangeDurationField() { + return iRangeDurationField; + } + + public boolean isLeap(long instant) { + return iField.isLeap(instant + this.iZone.getOffset(instant)); + } + + public int getLeapAmount(long instant) { + return iField.getLeapAmount(instant + this.iZone.getOffset(instant)); + } + + public final DurationField getLeapDurationField() { + return iLeapDurationField; + } + + public long roundFloor(long instant) { + int offset = this.iZone.getOffset(instant); + instant = iField.roundFloor(instant + offset); + return instant - (iTimeField ? offset : this.iZone.getOffsetFromLocal(instant)); + } + + public long roundCeiling(long instant) { + int offset = this.iZone.getOffset(instant); + instant = iField.roundCeiling(instant + offset); + return instant - (iTimeField ? offset : this.iZone.getOffsetFromLocal(instant)); + } + + public long remainder(long instant) { + return iField.remainder(instant + this.iZone.getOffset(instant)); + } + + public int getMinimumValue() { + return iField.getMinimumValue(); + } + + public int getMinimumValue(long instant) { + return iField.getMinimumValue(instant + this.iZone.getOffset(instant)); + } + + public int getMaximumValue() { + return iField.getMaximumValue(); + } + + public int getMaximumValue(long instant) { + return iField.getMaximumValue(instant + this.iZone.getOffset(instant)); + } + + public int getMaximumTextLength(Locale locale) { + return iField.getMaximumTextLength(locale); + } + + public int getMaximumShortTextLength(Locale locale) { + return iField.getMaximumShortTextLength(locale); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/chrono/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/chrono/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/chrono/package.html 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,72 @@ + + + +org.joda.time.chrono package + + + +

+Implementation package providing the Chronology implementaions. +

+

+This package contains all of the chronology implementations within the library. +It also contains all of the specialised field implementations. +Most applications will create chronologies using the static factory methods on +the Chronology class itself in the main package. +

+ + Index: 3rdParty_sources/joda-time/org/joda/time/convert/AbstractConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/AbstractConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/AbstractConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,173 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.PeriodType; +import org.joda.time.ReadablePartial; + +/** + * AbstractConverter simplifies the process of implementing a converter. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class AbstractConverter implements Converter { + + /** + * Restricted constructor. + */ + protected AbstractConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Extracts the millis from an object of this convertor's type. + *

+ * This implementation returns the current time. + * + * @param object the object to convert + * @param chrono the chronology to use, which is always non-null + * @return the millisecond value + */ + public long getInstantMillis(Object object, Chronology chrono) { + return DateTimeUtils.currentTimeMillis(); + } + + //----------------------------------------------------------------------- + /** + * Extracts the chronology from an object of this convertor's type + * where the time zone is specified. + *

+ * This implementation returns the ISO chronology. + * + * @param object the object to convert + * @param zone the specified zone to use, null means default zone + * @return the chronology, never null + */ + public Chronology getChronology(Object object, DateTimeZone zone) { + return Chronology.getISO(zone); + } + + /** + * Extracts the chronology from an object of this convertor's type + * where the chronology is specified. + *

+ * This implementation returns the chronology specified, or the + * ISO chronology in the default zone if null passed in. + * + * @param object the object to convert + * @param chrono the chronology to use, null means ISO default + * @return the chronology, never null + */ + public Chronology getChronology(Object object, Chronology chrono) { + return DateTimeUtils.getChronology(chrono); + } + + //----------------------------------------------------------------------- + /** + * Extracts the values of the partial from an object of this converter's type. + * The chrono parameter is a hint to the converter, should it require a + * chronology to aid in conversion. + * + * @param fieldSource a partial that provides access to the fields. + * This partial may be incomplete and only getFieldType(int) should be used + * @param object the object to convert + * @param chrono the chronology to use, which is the non-null result of getChronology() + * @return the array of field values that match the + */ + public int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono) { + long instant = getInstantMillis(object, chrono); + return chrono.get(fieldSource, instant); + } + + //----------------------------------------------------------------------- + /** + * Selects a suitable period type for the given object. + * + * @param object the object to examine + * @return the period type, never null + */ + public PeriodType getPeriodType(Object object) { + return PeriodType.standard(); + } + + //----------------------------------------------------------------------- + /** + * Checks if the input is a ReadableInterval. + *

+ * If it is, then the calling code should cast and copy the fields directly. + * + * @param object the object to convert + * @param chrono the chronology to use, may be null + * @return true if the input is a ReadableInterval + */ + public boolean isReadableInterval(Object object, Chronology chrono) { + return false; + } + + //----------------------------------------------------------------------- + /** + * Gets a debugging string version of this converter. + * + * @return a debugging string + */ + public String toString() { + return "Converter[" + (getSupportedType() == null ? "null" : getSupportedType().getName()) + "]"; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/CalendarConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/CalendarConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/CalendarConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,169 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import java.util.Calendar; +import java.util.GregorianCalendar; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeZone; +import org.joda.time.chrono.BuddhistChronology; +import org.joda.time.chrono.GJChronology; + +/** + * CalendarConverter converts a java util Calendar to an instant or partial. + * The Calendar is converted to milliseconds and the chronology that best + * matches the calendar. + * + * @author Stephen Colebourne + * @since 1.0 + */ +final class CalendarConverter extends AbstractConverter + implements InstantConverter, PartialConverter { + + /** + * Singleton instance. + */ + static final CalendarConverter INSTANCE = new CalendarConverter(); + + /** + * Restricted constructor. + */ + protected CalendarConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology. + *

+ * If a chronology is specified then it is used. + * Otherwise, it is the GJChronology if a GregorianCalendar is used, + * BuddhistChronology if a BuddhistCalendar is used or ISOChronology otherwise. + * The time zone is extracted from the calendar if possible, default used if not. + * + * @param object the Calendar to convert, must not be null + * @param chrono the chronology to use, null means use Calendar + * @return the chronology, never null + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public Chronology getChronology(Object object, Chronology chrono) { + if (chrono != null) { + return chrono; + } + Calendar cal = (Calendar) object; + DateTimeZone zone = null; + try { + zone = DateTimeZone.getInstance(cal.getTimeZone()); + + } catch (IllegalArgumentException ex) { + zone = DateTimeZone.getDefault(); + } + return getChronology(cal, zone); + } + + /** + * Gets the chronology, which is the GJChronology if a GregorianCalendar is used, + * BuddhistChronology if a BuddhistCalendar is used or ISOChronology otherwise. + * The time zone specified is used in preference to that on the calendar. + * + * @param object the Calendar to convert, must not be null + * @param zone the specified zone to use, null means default zone + * @return the chronology, never null + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public Chronology getChronology(Object object, DateTimeZone zone) { + if (object.getClass().getName().endsWith(".BuddhistCalendar")) { + return BuddhistChronology.getInstance(zone); + } else if (object instanceof GregorianCalendar) { + GregorianCalendar gc = (GregorianCalendar) object; + long cutover = gc.getGregorianChange().getTime(); + if (cutover == Long.MIN_VALUE) { + return Chronology.getGregorian(zone); + } else if (cutover == Long.MAX_VALUE) { + return Chronology.getJulian(zone); + } else { + return GJChronology.getInstance(zone, cutover, 4); + } + } else { + return Chronology.getISO(zone); + } + } + + /** + * Gets the millis, which is the Calendar millis value. + * + * @param object the Calendar to convert, must not be null + * @param chrono the chronology result from getChronology, non-null + * @return the millisecond value + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public long getInstantMillis(Object object, Chronology chrono) { + return ((Calendar) object).getTime().getTime(); + } + + //----------------------------------------------------------------------- + /** + * Returns Calendar.class. + * + * @return Calendar.class + */ + public Class getSupportedType() { + return Calendar.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/Converter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/Converter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/Converter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +/** + * Basic converter interface for specifying what object type can be converted. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public interface Converter { + /** + * Returns the object type that this converter supports, which may + * specified by a class, superclass, abstract class, interface, or null. + * + * @return the object type that this converter supports + */ + Class getSupportedType(); +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/ConverterManager.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/ConverterManager.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/ConverterManager.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,635 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.JodaTimePermission; + +/** + * ConverterManager controls the date and time converters. + *

+ * This class enables additional conversion classes to be added via + * {@link #addInstantConverter(InstantConverter)}, which may replace an + * existing converter. Similar methods exist for duration, time period and + * interval converters. + *

+ * This class is threadsafe, so adding/removing converters can be done at any + * time. Updating the set of convertors is relatively expensive, and so should + * not be performed often. + *

+ * The default instant converters are: + *

    + *
  • ReadableInstant + *
  • String + *
  • Calendar + *
  • Date + *
  • Long (milliseconds) + *
  • null (now) + *
+ * + * The default partial converters are: + *
    + *
  • ReadablePartial + *
  • ReadableInstant + *
  • String + *
  • Calendar + *
  • Date + *
  • Long (milliseconds) + *
  • null (now) + *
+ * + * The default duration converters are: + *
    + *
  • ReadableDuration + *
  • ReadableInterval + *
  • String + *
  • Long (milliseconds) + *
  • null (zero ms) + *
+ * + * The default time period converters are: + *
    + *
  • ReadablePeriod + *
  • ReadableInterval + *
  • String + *
  • null (zero) + *
+ * + * The default interval converters are: + *
    + *
  • ReadableInterval + *
  • String + *
  • null (zero-length from now to now) + *
+ * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public final class ConverterManager { + + /** + * Singleton instance, lazily loaded to avoid class loading. + */ + private static ConverterManager INSTANCE; + + public static ConverterManager getInstance() { + if (INSTANCE == null) { + INSTANCE = new ConverterManager(); + } + return INSTANCE; + } + + private ConverterSet iInstantConverters; + private ConverterSet iPartialConverters; + private ConverterSet iDurationConverters; + private ConverterSet iPeriodConverters; + private ConverterSet iIntervalConverters; + + /** + * Restricted constructor. + */ + protected ConverterManager() { + super(); + + iInstantConverters = new ConverterSet(new Converter[] { + ReadableInstantConverter.INSTANCE, + StringConverter.INSTANCE, + CalendarConverter.INSTANCE, + DateConverter.INSTANCE, + LongConverter.INSTANCE, + NullConverter.INSTANCE, + }); + + iPartialConverters = new ConverterSet(new Converter[] { + ReadablePartialConverter.INSTANCE, + ReadableInstantConverter.INSTANCE, + StringConverter.INSTANCE, + CalendarConverter.INSTANCE, + DateConverter.INSTANCE, + LongConverter.INSTANCE, + NullConverter.INSTANCE, + }); + + iDurationConverters = new ConverterSet(new Converter[] { + ReadableDurationConverter.INSTANCE, + ReadableIntervalConverter.INSTANCE, + StringConverter.INSTANCE, + LongConverter.INSTANCE, + NullConverter.INSTANCE, + }); + + iPeriodConverters = new ConverterSet(new Converter[] { + ReadableDurationConverter.INSTANCE, + ReadablePeriodConverter.INSTANCE, + ReadableIntervalConverter.INSTANCE, + StringConverter.INSTANCE, + NullConverter.INSTANCE, + }); + + iIntervalConverters = new ConverterSet(new Converter[] { + ReadableIntervalConverter.INSTANCE, + StringConverter.INSTANCE, + NullConverter.INSTANCE, + }); + } + + //----------------------------------------------------------------------- + /** + * Gets the best converter for the object specified. + * + * @param object the object to convert + * @return the converter to use + * @throws IllegalArgumentException if no suitable converter + * @throws IllegalStateException if multiple converters match the type + * equally well + */ + public InstantConverter getInstantConverter(Object object) { + InstantConverter converter = + (InstantConverter)iInstantConverters.select(object == null ? null : object.getClass()); + if (converter != null) { + return converter; + } + throw new IllegalArgumentException("No instant converter found for type: " + + (object == null ? "null" : object.getClass().getName())); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of the set of converters. + * + * @return the converters, a copy of the real data, never null + */ + public InstantConverter[] getInstantConverters() { + ConverterSet set = iInstantConverters; + InstantConverter[] converters = new InstantConverter[set.size()]; + set.copyInto(converters); + return converters; + } + + /** + * Adds a converter to the set of converters. If a matching converter is + * already in the set, the given converter replaces it. If the converter is + * exactly the same as one already in the set, no changes are made. + *

+ * The order in which converters are added is not relevent. The best + * converter is selected by examining the object hierarchy. + * + * @param converter the converter to add, null ignored + * @return replaced converter, or null + */ + public InstantConverter addInstantConverter(InstantConverter converter) + throws SecurityException { + + checkAlterInstantConverters(); + if (converter == null) { + return null; + } + InstantConverter[] removed = new InstantConverter[1]; + iInstantConverters = iInstantConverters.add(converter, removed); + return removed[0]; + } + + /** + * Removes a converter from the set of converters. If the converter was + * not in the set, no changes are made. + * + * @param converter the converter to remove, null ignored + * @return replaced converter, or null + */ + public InstantConverter removeInstantConverter(InstantConverter converter) + throws SecurityException { + + checkAlterInstantConverters(); + if (converter == null) { + return null; + } + InstantConverter[] removed = new InstantConverter[1]; + iInstantConverters = iInstantConverters.remove(converter, removed); + return removed[0]; + } + + /** + * Checks whether the user has permission 'ConverterManager.alterInstantConverters'. + * + * @throws SecurityException if the user does not have the permission + */ + private void checkAlterInstantConverters() throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("ConverterManager.alterInstantConverters")); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the best converter for the object specified. + * + * @param object the object to convert + * @return the converter to use + * @throws IllegalArgumentException if no suitable converter + * @throws IllegalStateException if multiple converters match the type + * equally well + */ + public PartialConverter getPartialConverter(Object object) { + PartialConverter converter = + (PartialConverter)iPartialConverters.select(object == null ? null : object.getClass()); + if (converter != null) { + return converter; + } + throw new IllegalArgumentException("No partial converter found for type: " + + (object == null ? "null" : object.getClass().getName())); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of the set of converters. + * + * @return the converters, a copy of the real data, never null + */ + public PartialConverter[] getPartialConverters() { + ConverterSet set = iPartialConverters; + PartialConverter[] converters = new PartialConverter[set.size()]; + set.copyInto(converters); + return converters; + } + + /** + * Adds a converter to the set of converters. If a matching converter is + * already in the set, the given converter replaces it. If the converter is + * exactly the same as one already in the set, no changes are made. + *

+ * The order in which converters are added is not relevent. The best + * converter is selected by examining the object hierarchy. + * + * @param converter the converter to add, null ignored + * @return replaced converter, or null + */ + public PartialConverter addPartialConverter(PartialConverter converter) + throws SecurityException { + + checkAlterPartialConverters(); + if (converter == null) { + return null; + } + PartialConverter[] removed = new PartialConverter[1]; + iPartialConverters = iPartialConverters.add(converter, removed); + return removed[0]; + } + + /** + * Removes a converter from the set of converters. If the converter was + * not in the set, no changes are made. + * + * @param converter the converter to remove, null ignored + * @return replaced converter, or null + */ + public PartialConverter removePartialConverter(PartialConverter converter) + throws SecurityException { + + checkAlterPartialConverters(); + if (converter == null) { + return null; + } + PartialConverter[] removed = new PartialConverter[1]; + iPartialConverters = iPartialConverters.remove(converter, removed); + return removed[0]; + } + + /** + * Checks whether the user has permission 'ConverterManager.alterPartialConverters'. + * + * @throws SecurityException if the user does not have the permission + */ + private void checkAlterPartialConverters() throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("ConverterManager.alterPartialConverters")); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the best converter for the object specified. + * + * @param object the object to convert + * @return the converter to use + * @throws IllegalArgumentException if no suitable converter + * @throws IllegalStateException if multiple converters match the type + * equally well + */ + public DurationConverter getDurationConverter(Object object) { + DurationConverter converter = + (DurationConverter)iDurationConverters.select(object == null ? null : object.getClass()); + if (converter != null) { + return converter; + } + throw new IllegalArgumentException("No duration converter found for type: " + + (object == null ? "null" : object.getClass().getName())); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of the list of converters. + * + * @return the converters, a copy of the real data, never null + */ + public DurationConverter[] getDurationConverters() { + ConverterSet set = iDurationConverters; + DurationConverter[] converters = new DurationConverter[set.size()]; + set.copyInto(converters); + return converters; + } + + /** + * Adds a converter to the set of converters. If a matching converter is + * already in the set, the given converter replaces it. If the converter is + * exactly the same as one already in the set, no changes are made. + *

+ * The order in which converters are added is not relevent. The best + * converter is selected by examining the object hierarchy. + * + * @param converter the converter to add, null ignored + * @return replaced converter, or null + */ + public DurationConverter addDurationConverter(DurationConverter converter) + throws SecurityException { + + checkAlterDurationConverters(); + if (converter == null) { + return null; + } + DurationConverter[] removed = new DurationConverter[1]; + iDurationConverters = iDurationConverters.add(converter, removed); + return removed[0]; + } + + /** + * Removes a converter from the set of converters. If the converter was + * not in the set, no changes are made. + * + * @param converter the converter to remove, null ignored + * @return replaced converter, or null + */ + public DurationConverter removeDurationConverter(DurationConverter converter) + throws SecurityException { + + checkAlterDurationConverters(); + if (converter == null) { + return null; + } + DurationConverter[] removed = new DurationConverter[1]; + iDurationConverters = iDurationConverters.remove(converter, removed); + return removed[0]; + } + + /** + * Checks whether the user has permission 'ConverterManager.alterDurationConverters'. + * + * @throws SecurityException if the user does not have the permission + */ + private void checkAlterDurationConverters() throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("ConverterManager.alterDurationConverters")); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the best converter for the object specified. + * + * @param object the object to convert + * @return the converter to use + * @throws IllegalArgumentException if no suitable converter + * @throws IllegalStateException if multiple converters match the type + * equally well + */ + public PeriodConverter getPeriodConverter(Object object) { + PeriodConverter converter = + (PeriodConverter)iPeriodConverters.select(object == null ? null : object.getClass()); + if (converter != null) { + return converter; + } + throw new IllegalArgumentException("No period converter found for type: " + + (object == null ? "null" : object.getClass().getName())); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of the list of converters. + * + * @return the converters, a copy of the real data, never null + */ + public PeriodConverter[] getPeriodConverters() { + ConverterSet set = iPeriodConverters; + PeriodConverter[] converters = new PeriodConverter[set.size()]; + set.copyInto(converters); + return converters; + } + + /** + * Adds a converter to the set of converters. If a matching converter is + * already in the set, the given converter replaces it. If the converter is + * exactly the same as one already in the set, no changes are made. + *

+ * The order in which converters are added is not relevent. The best + * converter is selected by examining the object hierarchy. + * + * @param converter the converter to add, null ignored + * @return replaced converter, or null + */ + public PeriodConverter addPeriodConverter(PeriodConverter converter) + throws SecurityException { + + checkAlterPeriodConverters(); + if (converter == null) { + return null; + } + PeriodConverter[] removed = new PeriodConverter[1]; + iPeriodConverters = iPeriodConverters.add(converter, removed); + return removed[0]; + } + + /** + * Removes a converter from the set of converters. If the converter was + * not in the set, no changes are made. + * + * @param converter the converter to remove, null ignored + * @return replaced converter, or null + */ + public PeriodConverter removePeriodConverter(PeriodConverter converter) + throws SecurityException { + + checkAlterPeriodConverters(); + if (converter == null) { + return null; + } + PeriodConverter[] removed = new PeriodConverter[1]; + iPeriodConverters = iPeriodConverters.remove(converter, removed); + return removed[0]; + } + + /** + * Checks whether the user has permission 'ConverterManager.alterPeriodConverters'. + * + * @throws SecurityException if the user does not have the permission + */ + private void checkAlterPeriodConverters() throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("ConverterManager.alterPeriodConverters")); + } + } + + //----------------------------------------------------------------------- + /** + * Gets the best converter for the object specified. + * + * @param object the object to convert + * @return the converter to use + * @throws IllegalArgumentException if no suitable converter + * @throws IllegalStateException if multiple converters match the type + * equally well + */ + public IntervalConverter getIntervalConverter(Object object) { + IntervalConverter converter = + (IntervalConverter)iIntervalConverters.select(object == null ? null : object.getClass()); + if (converter != null) { + return converter; + } + throw new IllegalArgumentException("No interval converter found for type: " + + (object == null ? "null" : object.getClass().getName())); + } + + //----------------------------------------------------------------------- + /** + * Gets a copy of the list of converters. + * + * @return the converters, a copy of the real data, never null + */ + public IntervalConverter[] getIntervalConverters() { + ConverterSet set = iIntervalConverters; + IntervalConverter[] converters = new IntervalConverter[set.size()]; + set.copyInto(converters); + return converters; + } + + /** + * Adds a converter to the set of converters. If a matching converter is + * already in the set, the given converter replaces it. If the converter is + * exactly the same as one already in the set, no changes are made. + *

+ * The order in which converters are added is not relevent. The best + * converter is selected by examining the object hierarchy. + * + * @param converter the converter to add, null ignored + * @return replaced converter, or null + */ + public IntervalConverter addIntervalConverter(IntervalConverter converter) + throws SecurityException { + + checkAlterIntervalConverters(); + if (converter == null) { + return null; + } + IntervalConverter[] removed = new IntervalConverter[1]; + iIntervalConverters = iIntervalConverters.add(converter, removed); + return removed[0]; + } + + /** + * Removes a converter from the set of converters. If the converter was + * not in the set, no changes are made. + * + * @param converter the converter to remove, null ignored + * @return replaced converter, or null + */ + public IntervalConverter removeIntervalConverter(IntervalConverter converter) + throws SecurityException { + + checkAlterIntervalConverters(); + if (converter == null) { + return null; + } + IntervalConverter[] removed = new IntervalConverter[1]; + iIntervalConverters = iIntervalConverters.remove(converter, removed); + return removed[0]; + } + + /** + * Checks whether the user has permission 'ConverterManager.alterIntervalConverters'. + * + * @throws SecurityException if the user does not have the permission + */ + private void checkAlterIntervalConverters() throws SecurityException { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(new JodaTimePermission("ConverterManager.alterIntervalConverters")); + } + } + + //----------------------------------------------------------------------- + /** + * Gets a debug representation of the object. + */ + public String toString() { + return "ConverterManager[" + + iInstantConverters.size() + " instant," + + iPartialConverters.size() + " partial," + + iDurationConverters.size() + " duration," + + iPeriodConverters.size() + " period," + + iIntervalConverters.size() + " interval]"; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/ConverterSet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/ConverterSet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/ConverterSet.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,366 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +/** + * A set of converters, which allows exact converters to be quickly + * selected. This class is threadsafe because it is (essentially) immutable. + * + * @author Brian S O'Neill + * @since 1.0 + */ +class ConverterSet { + private final Converter[] iConverters; + + // A simple immutable hashtable: closed hashing, linear probing, sized + // power of 2, at least one null slot. + private Entry[] iSelectEntries; + + ConverterSet(Converter[] converters) { + // Since this is a package private constructor, we trust ourselves not + // to alter the array outside this class. + iConverters = converters; + iSelectEntries = new Entry[1 << 4]; // 16 + } + + /** + * Returns the closest matching converter for the given type, or null if + * none found. + * + * @param type type to select, which may be null + * @throws IllegalStateException if multiple converters match the type + * equally well + */ + Converter select(Class type) throws IllegalStateException { + // Check the hashtable first. + Entry[] entries = iSelectEntries; + int length = entries.length; + int index = type == null ? 0 : type.hashCode() & (length - 1); + + Entry e; + // This loop depends on there being at least one null slot. + while ((e = entries[index]) != null) { + if (e.iType == type) { + return e.iConverter; + } + if (++index >= length) { + index = 0; + } + } + + // Not found in the hashtable, so do actual work. + + Converter converter = selectSlow(this, type); + e = new Entry(type, converter); + + // Save the entry for future selects. This class must be threadsafe, + // but there is no synchronization. Since the hashtable is being used + // as a cache, it is okay to destroy existing entries. This isn't + // likely to occur unless there is a high amount of concurrency. As + // time goes on, cache updates will occur less often, and the cache + // will fill with all the necessary entries. + + // Do all updates on a copy: slots in iSelectEntries must not be + // updated by multiple threads as this can allow all null slots to be + // consumed. + entries = (Entry[])entries.clone(); + + // Add new entry. + entries[index] = e; + + // Verify that at least one null slot exists! + for (int i=0; i= newLength) { + index = 0; + } + } + newEntries[index] = e; + } + + // Swap in new hashtable. + iSelectEntries = newEntries; + return converter; + } + + /** + * Returns the amount of converters in the set. + */ + int size() { + return iConverters.length; + } + + /** + * Copies all the converters in the set to the given array. + */ + void copyInto(Converter[] converters) { + System.arraycopy(iConverters, 0, converters, 0, iConverters.length); + } + + /** + * Returns a copy of this set, with the given converter added. If a + * matching converter is already in the set, the given converter replaces + * it. If the converter is exactly the same as one already in the set, the + * original set is returned. + * + * @param converter converter to add, must not be null + * @param removed if not null, element 0 is set to the removed converter + * @throws NullPointerException if converter is null + */ + ConverterSet add(Converter converter, Converter[] removed) { + Converter[] converters = iConverters; + int length = converters.length; + + for (int i=0; i= length) { + throw new IndexOutOfBoundsException(); + } + + if (removed != null) { + removed[0] = converters[index]; + } + + Converter[] copy = new Converter[length - 1]; + + int j = 0; + for (int i=0; i=0; ) { + converter = converters[i]; + Class supportedType = converter.getSupportedType(); + + if (supportedType == type) { + // Exact match. + return converter; + } + + if (supportedType == null || (type != null && !supportedType.isAssignableFrom(type))) { + // Eliminate the impossible. + set = set.remove(i, null); + converters = set.iConverters; + length = converters.length; + } + } + + // Haven't found exact match, so check what remains in the set. + + if (type == null || length == 0) { + return null; + } + if (length == 1) { + // Found the one best match. + return converters[0]; + } + + // At this point, there exist multiple potential converters. + + // Eliminate supertypes. + for (int i=length; --i>=0; ) { + converter = converters[i]; + Class supportedType = converter.getSupportedType(); + for (int j=length; --j>=0; ) { + if (j != i && converters[j].getSupportedType().isAssignableFrom(supportedType)) { + // Eliminate supertype. + set = set.remove(j, null); + converters = set.iConverters; + length = converters.length; + i = length - 1; + } + } + } + + // Check what remains in the set. + + if (length == 1) { + // Found the one best match. + return converters[0]; + } + + // Class c implements a, b {} + // Converters exist only for a and b. Which is better? Neither. + + StringBuffer msg = new StringBuffer(); + msg.append("Unable to find best converter for type \""); + msg.append(type.getName()); + msg.append("\" from remaining set: "); + for (int i=0; i. For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import java.util.Date; + +import org.joda.time.Chronology; + +/** + * DateConverter converts a java util Date to an instant or partial. + * The Date is converted to milliseconds in the ISO chronology. + * + * @author Stephen Colebourne + * @since 1.0 + */ +final class DateConverter extends AbstractConverter + implements InstantConverter, PartialConverter { + + /** + * Singleton instance. + */ + static final DateConverter INSTANCE = new DateConverter(); + + /** + * Restricted constructor. + */ + protected DateConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the millis, which is the Date millis value. + * + * @param object the Date to convert, must not be null + * @param chrono the non-null result of getChronology + * @return the millisecond value + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public long getInstantMillis(Object object, Chronology chrono) { + return ((Date) object).getTime(); + } + + //----------------------------------------------------------------------- + /** + * Returns Date.class. + * + * @return Date.class + */ + public Class getSupportedType() { + return Date.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/DurationConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/DurationConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/DurationConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +/** + * DurationConverter defines how an object is converted to a millisecond duration. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public interface DurationConverter extends Converter { + + /** + * Extracts the millis from an object of this convertor's type. + * + * @param object the object to convert, must not be null + * @return the millisecond duration + * @throws ClassCastException if the object is invalid + */ + long getDurationMillis(Object object); + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/InstantConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/InstantConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/InstantConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,109 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeZone; + +/** + * InstantConverter defines how an object is converted to milliseconds/chronology. + *

+ * The two methods in this interface must be called in order, as the + * getInstantMillis method relies on the result of the + * getChronology method being passed in. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public interface InstantConverter extends Converter { + + /** + * Extracts the chronology from an object of this converter's type + * where the time zone is specified. + * + * @param object the object to convert + * @param zone the specified zone to use, null means default zone + * @return the chronology, never null + * @throws ClassCastException if the object is invalid + */ + Chronology getChronology(Object object, DateTimeZone zone); + + /** + * Extracts the chronology from an object of this converter's type + * where the chronology may be specified. + *

+ * If the chronology is non-null it should be used. If it is null, then the + * object should be queried, and if it has no chronology then ISO default is used. + * + * @param object the object to convert + * @param chrono the chronology to use, null means use object + * @return the chronology, never null + * @throws ClassCastException if the object is invalid + */ + Chronology getChronology(Object object, Chronology chrono); + + //----------------------------------------------------------------------- + /** + * Extracts the millis from an object of this converter's type. + *

+ * The chronology passed in is the result of the call to getChronology. + * + * @param object the object to convert + * @param chrono the chronology to use, which is the non-null result of getChronology() + * @return the millisecond instant + * @throws ClassCastException if the object is invalid + */ + long getInstantMillis(Object object, Chronology chrono); + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/IntervalConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/IntervalConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/IntervalConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.ReadWritableInterval; + +/** + * IntervalConverter defines how an object is converted to an interval. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public interface IntervalConverter extends Converter { + + /** + * Checks if the input is a ReadableInterval. + *

+ * If it is, then the calling code should cast and copy the fields directly. + * + * @param object the object to convert, must not be null + * @param chrono the chronology to use, may be null + * @return true if the input is a ReadableInterval + * @throws ClassCastException if the object is invalid + */ + boolean isReadableInterval(Object object, Chronology chrono); + + /** + * Extracts interval endpoint values from an object of this converter's + * type, and sets them into the given ReadWritableInterval. + * + * @param writableInterval interval to get modified, not null + * @param object the object to convert, must not be null + * @param chrono the chronology to use, may be null + * @throws ClassCastException if the object is invalid + */ + void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono); + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/LongConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/LongConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/LongConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,118 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; + +/** + * LongConverter converts a Long to an instant, partial or duration. + * The Long value represents milliseconds in the ISO chronology. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +class LongConverter extends AbstractConverter + implements InstantConverter, PartialConverter, DurationConverter { + + /** + * Singleton instance. + */ + static final LongConverter INSTANCE = new LongConverter(); + + /** + * Restricted constructor. + */ + protected LongConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the millisecond instant, which is the Long value. + * + * @param object the Long to convert, must not be null + * @param chrono the chronology to use, which is always non-null + * @return the millisecond value + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public long getInstantMillis(Object object, Chronology chrono) { + return ((Long) object).longValue(); + } + + //----------------------------------------------------------------------- + /** + * Gets the millisecond duration, which is the Long value. + * + * @param object the Long to convert, must not be null + * @return the millisecond duration + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public long getDurationMillis(Object object) { + return ((Long) object).longValue(); + } + + //----------------------------------------------------------------------- + /** + * Returns Long.class. + * + * @return Long.class + */ + public Class getSupportedType() { + return Long.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/NullConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/NullConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/NullConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,136 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.Period; +import org.joda.time.ReadWritableInterval; +import org.joda.time.ReadWritablePeriod; + +/** + * NullConverter converts null to an instant, partial, duration, period + * or interval. Null means now for instant/partial, zero for duration/period + * and from now to now for interval. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +class NullConverter extends AbstractConverter + implements InstantConverter, PartialConverter, DurationConverter, PeriodConverter, IntervalConverter { + + /** + * Singleton instance. + */ + static final NullConverter INSTANCE = new NullConverter(); + + /** + * Restricted constructor. + */ + protected NullConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the millisecond duration, which is zero. + * + * @param object the object to convert, which is null + * @return the millisecond duration + */ + public long getDurationMillis(Object object) { + return 0L; + } + + //----------------------------------------------------------------------- + /** + * Sets the given ReadWritableDuration to zero milliseconds. + * + * @param duration duration to get modified + * @param object the object to convert, which is null + * @param chrono the chronology to use + * @throws NullPointerException if the duration is null + */ + public void setInto(ReadWritablePeriod duration, Object object, Chronology chrono) { + duration.setPeriod((Period) null); + } + + //----------------------------------------------------------------------- + /** + * Extracts interval endpoint values from an object of this converter's + * type, and sets them into the given ReadWritableInterval. + * + * @param writableInterval interval to get modified, not null + * @param object the object to convert, which is null + * @param chrono the chronology to use, may be null + * @throws NullPointerException if the interval is null + */ + public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) { + writableInterval.setChronology(chrono); + long now = DateTimeUtils.currentTimeMillis(); + writableInterval.setInterval(now, now); + } + + //----------------------------------------------------------------------- + /** + * Returns null. + * + * @return null + */ + public Class getSupportedType() { + return null; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/PartialConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/PartialConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/PartialConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.ReadablePartial; + +/** + * PartialConverter defines how an object is converted to a ReadablePartial. + *

+ * The two methods in this interface must be called in order, as the + * getPartialValues method relies on the result of the + * getChronology method being passed in. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public interface PartialConverter extends Converter { + + /** + * Extracts the chronology from an object of this converter's type + * where the chronology is specified. + * + * @param object the object to convert + * @param chrono the chronology to use, null usually means ISO + * @return the chronology, not converted to UTC/local time zone, must be non-null valid + * @throws ClassCastException if the object is invalid + */ + Chronology getChronology(Object object, Chronology chrono); + + /** + * Extracts the values of the partial from an object of this converter's type. + * The chrono parameter is a hint to the converter, should it require a + * chronology to aid in conversion. + * + * @param fieldSource a partial that provides access to the fields. + * This partial may be incomplete and only getFieldType(int) should be used + * @param object the object to convert + * @param chrono the chronology to use, which is the non-null result of getChronology() + * @return the array of field values that match the fieldSource, must be non-null valid + * @throws ClassCastException if the object is invalid + */ + int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono); + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/PeriodConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/PeriodConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/PeriodConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.PeriodType; +import org.joda.time.ReadWritablePeriod; + +/** + * PeriodConverter defines how an object is converted to a time period. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public interface PeriodConverter extends Converter { + + /** + * Extracts duration values from an object of this converter's type, and + * sets them into the given ReadWritableDuration. + * + * @param period the period to modify + * @param object the object to convert, must not be null + * @param chrono the chronology to use, must not be null + * @throws ClassCastException if the object is invalid + */ + void setInto(ReadWritablePeriod period, Object object, Chronology chrono); + + /** + * Selects a suitable period type for the given object. + * + * @param object the object to examine, must not be null + * @return the period type, never null + * @throws ClassCastException if the object is invalid + */ + PeriodType getPeriodType(Object object); + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/ReadableDurationConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/ReadableDurationConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/ReadableDurationConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.ReadWritablePeriod; +import org.joda.time.ReadableDuration; + +/** + * ReadableDurationConverter extracts milliseconds and chronology from a ReadableDuration. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +class ReadableDurationConverter extends AbstractConverter + implements DurationConverter, PeriodConverter { + + /** + * Singleton instance. + */ + static final ReadableDurationConverter INSTANCE = new ReadableDurationConverter(); + + /** + * Restricted constructor. + */ + protected ReadableDurationConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Extracts the millis from an object of this convertor's type. + * + * @param object the object to convert, must not be null + * @return the millisecond value + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + * @throws IllegalArgumentException if the object is invalid + */ + public long getDurationMillis(Object object) { + return ((ReadableDuration) object).getMillis(); + } + + //----------------------------------------------------------------------- + /** + * Extracts duration values from an object of this converter's type, and + * sets them into the given ReadWritableDuration. + * + * @param writablePeriod period to get modified + * @param object the object to convert, must not be null + * @param chrono the chronology to use, must not be null + * @throws NullPointerException if the duration or object is null + * @throws ClassCastException if the object is an invalid type + * @throws IllegalArgumentException if the object is invalid + */ + public void setInto(ReadWritablePeriod writablePeriod, Object object, Chronology chrono) { + ReadableDuration dur = (ReadableDuration) object; + chrono = DateTimeUtils.getChronology(chrono); + long duration = dur.getMillis(); + int[] values = chrono.get(writablePeriod, duration); + for (int i = 0; i < values.length; i++) { + writablePeriod.setValue(i, values[i]); + } + } + + //----------------------------------------------------------------------- + /** + * Returns ReadableDuration.class. + * + * @return ReadableDuration.class + */ + public Class getSupportedType() { + return ReadableDuration.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/ReadableInstantConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/ReadableInstantConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/ReadableInstantConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,151 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadableInstant; +import org.joda.time.chrono.ISOChronology; + +/** + * ReadableInstantConverter extracts milliseconds and chronology from a ReadableInstant. + * + * @author Stephen Colebourne + * @since 1.0 + */ +class ReadableInstantConverter extends AbstractConverter + implements InstantConverter, PartialConverter { + + /** + * Singleton instance. + */ + static final ReadableInstantConverter INSTANCE = new ReadableInstantConverter(); + + /** + * Restricted constructor. + */ + protected ReadableInstantConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology, which is taken from the ReadableInstant. + * If the chronology on the instant is null, the ISOChronology in the + * specified time zone is used. + * If the chronology on the instant is not in the specified zone, it is + * adapted. + * + * @param object the ReadableInstant to convert, must not be null + * @param zone the specified zone to use, null means default zone + * @return the chronology, never null + */ + public Chronology getChronology(Object object, DateTimeZone zone) { + Chronology chrono = ((ReadableInstant) object).getChronology(); + if (chrono == null) { + return ISOChronology.getInstance(zone); + } + DateTimeZone chronoZone = chrono.getZone(); + if (chronoZone != zone) { + chrono = chrono.withZone(zone); + if (chrono == null) { + return ISOChronology.getInstance(zone); + } + } + return chrono; + } + + /** + * Gets the chronology, which is taken from the ReadableInstant. + *

+ * If the passed in chronology is non-null, it is used. + * Otherwise the chronology from the instant is used. + * + * @param object the ReadableInstant to convert, must not be null + * @param chrono the chronology to use, null means use that from object + * @return the chronology, never null + */ + public Chronology getChronology(Object object, Chronology chrono) { + if (chrono == null) { + chrono = ((ReadableInstant) object).getChronology(); + chrono = DateTimeUtils.getChronology(chrono); + } + return chrono; + } + + /** + * Extracts the millis from an object of this convertor's type. + * + * @param object the ReadableInstant to convert, must not be null + * @param chrono the non-null result of getChronology + * @return the millisecond value + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public long getInstantMillis(Object object, Chronology chrono) { + return ((ReadableInstant) object).getMillis(); + } + + //----------------------------------------------------------------------- + /** + * Returns ReadableInstant.class. + * + * @return ReadableInstant.class + */ + public Class getSupportedType() { + return ReadableInstant.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/ReadableIntervalConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/ReadableIntervalConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/ReadableIntervalConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,154 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.ReadWritableInterval; +import org.joda.time.ReadWritablePeriod; +import org.joda.time.ReadableInterval; + +/** + * Converts intervals into durations of any requested period type. + * + * @author Brian S O'Neill + * @since 1.0 + */ +class ReadableIntervalConverter extends AbstractConverter + implements IntervalConverter, DurationConverter, PeriodConverter { + + /** + * Singleton instance. + */ + static final ReadableIntervalConverter INSTANCE = new ReadableIntervalConverter(); + + /** + * Restricted constructor. + */ + protected ReadableIntervalConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the millisecond length of the interval. + * + * @param object the interval + */ + public long getDurationMillis(Object object) { + return (((ReadableInterval) object)).toDurationMillis(); + } + + //----------------------------------------------------------------------- + /** + * Sets the values of the mutable duration from the specified interval. + * + * @param writablePeriod the period to modify + * @param object the interval to set from + * @param chrono the chronology to use + */ + public void setInto(ReadWritablePeriod writablePeriod, Object object, Chronology chrono) { + ReadableInterval interval = (ReadableInterval) object; + chrono = (chrono != null ? chrono : DateTimeUtils.getIntervalChronology(interval)); + long start = interval.getStartMillis(); + long end = interval.getEndMillis(); + int[] values = chrono.get(writablePeriod, start, end); + for (int i = 0; i < values.length; i++) { + writablePeriod.setValue(i, values[i]); + } + } + + //----------------------------------------------------------------------- + /** + * Checks if the input is a ReadableInterval. + *

+ * If it is, then the calling code should cast and copy the fields directly. + * + * @param object the object to convert, must not be null + * @param chrono the chronology to use, may be null + * @return true if the input is a ReadableInterval + * @throws ClassCastException if the object is invalid + */ + public boolean isReadableInterval(Object object, Chronology chrono) { + return true; + } + + /** + * Extracts interval endpoint values from an object of this converter's + * type, and sets them into the given ReadWritableInterval. + * + * @param writableInterval interval to get modified, not null + * @param object the object to convert, must not be null + * @param chrono the chronology to use, may be null + * @throws ClassCastException if the object is invalid + */ + public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) { + ReadableInterval input = (ReadableInterval) object; + writableInterval.setInterval(input); + if (chrono != null) { + writableInterval.setChronology(chrono); + } else { + writableInterval.setChronology(input.getChronology()); + } + } + + //----------------------------------------------------------------------- + /** + * Returns ReadableInterval.class. + */ + public Class getSupportedType() { + return ReadableInterval.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/ReadablePartialConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/ReadablePartialConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/ReadablePartialConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,151 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadablePartial; + +/** + * ReadablePartialConverter extracts partial fields and chronology from a ReadablePartial. + * + * @author Stephen Colebourne + * @since 1.0 + */ +class ReadablePartialConverter extends AbstractConverter + implements PartialConverter { + + /** + * Singleton instance. + */ + static final ReadablePartialConverter INSTANCE = new ReadablePartialConverter(); + + /** + * Restricted constructor. + */ + protected ReadablePartialConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology, which is taken from the ReadablePartial. + * + * @param object the ReadablePartial to convert, must not be null + * @param zone the specified zone to use, null means default zone + * @return the chronology, never null + */ + public Chronology getChronology(Object object, DateTimeZone zone) { + return getChronology(object, (Chronology) null).withZone(zone); + } + + /** + * Gets the chronology, which is taken from the ReadableInstant. + *

+ * If the passed in chronology is non-null, it is used. + * Otherwise the chronology from the instant is used. + * + * @param object the ReadablePartial to convert, must not be null + * @param chrono the chronology to use, null means use that from object + * @return the chronology, never null + */ + public Chronology getChronology(Object object, Chronology chrono) { + if (chrono == null) { + chrono = ((ReadablePartial) object).getChronology(); + chrono = DateTimeUtils.getChronology(chrono); + } + return chrono; + } + + /** + * Extracts the values of the partial from an object of this converter's type. + * The chrono parameter is a hint to the converter, should it require a + * chronology to aid in conversion. + * + * @param fieldSource a partial that provides access to the fields. + * This partial may be incomplete and only getFieldType(int) should be used + * @param object the object to convert + * @param chrono the chronology to use, which is the non-null result of getChronology() + * @return the array of field values that match the fieldSource, must be non-null valid + * @throws ClassCastException if the object is invalid + */ + public int[] getPartialValues(ReadablePartial fieldSource, Object object, Chronology chrono) { + ReadablePartial input = (ReadablePartial) object; + int size = fieldSource.size(); + if (input.size() != size) { + throw new IllegalArgumentException("Partial field type lists are different"); + } + int[] values = new int[size]; + for (int i = 0; i < size; i++) { + if (fieldSource.getFieldType(i) != input.getFieldType(i)) { + throw new IllegalArgumentException("Partial field type lists are different"); + } + values[i] = input.getValue(i); + } + chrono.validate(fieldSource, values); + return values; + } + + //----------------------------------------------------------------------- + /** + * Returns ReadableInstant.class. + * + * @return ReadableInstant.class + */ + public Class getSupportedType() { + return ReadablePartial.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/ReadablePeriodConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/ReadablePeriodConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/ReadablePeriodConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,122 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.PeriodType; +import org.joda.time.ReadWritablePeriod; +import org.joda.time.ReadablePeriod; + +/** + * ReadablePeriodConverter extracts milliseconds and chronology from a ReadablePeriod. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +class ReadablePeriodConverter extends AbstractConverter + implements PeriodConverter { + + /** + * Singleton instance. + */ + static final ReadablePeriodConverter INSTANCE = new ReadablePeriodConverter(); + + /** + * Restricted constructor. + */ + protected ReadablePeriodConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Extracts duration values from an object of this converter's type, and + * sets them into the given ReadWritablePeriod. + * + * @param duration duration to get modified + * @param object the object to convert, must not be null + * @param chrono the chronology to use + * @throws NullPointerException if the duration or object is null + * @throws ClassCastException if the object is an invalid type + * @throws IllegalArgumentException if the object is invalid + */ + public void setInto(ReadWritablePeriod duration, Object object, Chronology chrono) { + duration.setPeriod((ReadablePeriod) object); + } + + /** + * Selects a suitable period type for the given object. + * + * @param object the object to examine, must not be null + * @return the period type from the readable duration + * @throws NullPointerException if the object is null + * @throws ClassCastException if the object is an invalid type + */ + public PeriodType getPeriodType(Object object) { + ReadablePeriod period = (ReadablePeriod) object; + return period.getPeriodType(); + } + + //----------------------------------------------------------------------- + /** + * Returns ReadablePeriod class. + * + * @return ReadablePeriod.class + */ + public Class getSupportedType() { + return ReadablePeriod.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/StringConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/StringConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/StringConverter.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,258 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.convert; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.Period; +import org.joda.time.ReadWritableInterval; +import org.joda.time.ReadWritablePeriod; +import org.joda.time.field.FieldUtils; +import org.joda.time.format.DateTimeParser; +import org.joda.time.format.ISODateTimeFormat; +import org.joda.time.format.ISOPeriodFormat; +import org.joda.time.format.PeriodFormatter; +import org.joda.time.format.PeriodParser; + +/** + * StringConverter converts from a String to an instant, partial, + * duration, period or interval.. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +class StringConverter extends AbstractConverter + implements InstantConverter, PartialConverter, DurationConverter, PeriodConverter, IntervalConverter { + + /** + * Singleton instance. + */ + static final StringConverter INSTANCE = new StringConverter(); + + /** + * Restricted constructor. + */ + protected StringConverter() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the millis, which is the ISO parsed string value. + * + * @param object the String to convert, must not be null + * @param chrono the chronology to use, non-null result of getChronology + * @return the millisecond value + * @throws IllegalArgumentException if the value if invalid + */ + public long getInstantMillis(Object object, Chronology chrono) { + String str = (String) object; + DateTimeParser p = ISODateTimeFormat.getInstance().dateTimeParser(); + return p.parseMillis(str, chrono); + } + + //----------------------------------------------------------------------- + /** + * Gets the duration of the string using the standard type. + * This matches the toString() method of ReadableDuration. + * + * @param object the String to convert, must not be null + * @throws ClassCastException if the object is invalid + */ + public long getDurationMillis(Object object) { + // parse here because duration could be bigger than the int supported + // by the period parser + String original = (String) object; + String str = original; + int len = str.length(); + if (len >= 4 && + (str.charAt(0) == 'P' || str.charAt(0) == 'p') && + (str.charAt(1) == 'T' || str.charAt(1) == 't') && + (str.charAt(len - 1) == 'S' || str.charAt(len - 1) == 's')) { + // ok + } else { + throw new IllegalArgumentException("Invalid format: \"" + original + '"'); + } + str = str.substring(2, len - 1); + int dot = -1; + for (int i = 0; i < str.length(); i++) { + if ((str.charAt(i) >= '0' && str.charAt(i) <= '9') || + (i == 0 && str.charAt(0) == '-')) { + // ok + } else if (i > 0 && str.charAt(i) == '.' && dot == -1) { + // ok + dot = i; + } else { + throw new IllegalArgumentException("Invalid format: \"" + original + '"'); + } + } + long millis = 0, seconds = 0; + if (dot > 0) { + seconds = Long.parseLong(str.substring(0, dot)); + str = str.substring(dot + 1); + if (str.length() != 3) { + str = (str + "000").substring(0, 3); + } + millis = Integer.parseInt(str); + } else { + seconds = Long.parseLong(str); + } + if (seconds < 0) { + return FieldUtils.safeAdd(FieldUtils.safeMultiply(seconds, 1000), -millis); + } else { + return FieldUtils.safeAdd(FieldUtils.safeMultiply(seconds, 1000), millis); + } + } + + //----------------------------------------------------------------------- + /** + * Extracts duration values from an object of this converter's type, and + * sets them into the given ReadWritableDuration. + * + * @param period period to get modified + * @param object the String to convert, must not be null + * @param chrono the chronology to use + * @return the millisecond duration + * @throws ClassCastException if the object is invalid + */ + public void setInto(ReadWritablePeriod period, Object object, Chronology chrono) { + String str = (String) object; + PeriodParser parser = ISOPeriodFormat.getInstance().standard(); + period.clear(); + int pos = parser.parseInto(period, str, 0); + if (pos < str.length()) { + if (pos < 0) { + // Parse again to get a better exception thrown. + parser.parseMutablePeriod(period.getPeriodType(), str); + } + throw new IllegalArgumentException("Invalid format: \"" + str + '"'); + } + } + + //----------------------------------------------------------------------- + /** + * Sets the value of the mutable interval from the string. + * + * @param writableInterval the interval to set + * @param object the String to convert, must not be null + * @param chrono the chronology to use, may be null + */ + public void setInto(ReadWritableInterval writableInterval, Object object, Chronology chrono) { + String str = (String) object; + + int separator = str.indexOf('/'); + if (separator < 0) { + throw new IllegalArgumentException("Format requires a '/' separator: " + str); + } + + String leftStr = str.substring(0, separator); + if (leftStr.length() <= 0) { + throw new IllegalArgumentException("Format invalid: " + str); + } + String rightStr = str.substring(separator + 1); + if (rightStr.length() <= 0) { + throw new IllegalArgumentException("Format invalid: " + str); + } + + DateTimeParser dateTimeParser = ISODateTimeFormat.getInstance().dateTimeParser(); + PeriodFormatter periodParser = ISOPeriodFormat.getInstance().standard(); + long startInstant = 0, endInstant = 0; + Period period = null; + Chronology parsedChrono = null; + + // before slash + char c = leftStr.charAt(0); + if (c == 'P' || c == 'p') { + period = periodParser.parsePeriod(getPeriodType(leftStr), leftStr); + } else { + DateTime start = dateTimeParser.parseDateTime(leftStr, chrono); + startInstant = start.getMillis(); + parsedChrono = start.getChronology(); + } + + // after slash + c = rightStr.charAt(0); + if (c == 'P' || c == 'p') { + if (period != null) { + throw new IllegalArgumentException("Interval composed of two durations: " + str); + } + period = periodParser.parsePeriod(getPeriodType(rightStr), rightStr); + chrono = (chrono != null ? chrono : parsedChrono); + endInstant = chrono.add(period, startInstant, 1); + } else { + DateTime end = dateTimeParser.parseDateTime(rightStr, chrono); + endInstant = end.getMillis(); + parsedChrono = (parsedChrono != null ? parsedChrono : end.getChronology()); + chrono = (chrono != null ? chrono : parsedChrono); + if (period != null) { + startInstant = chrono.add(period, endInstant, -1); + } + } + + writableInterval.setInterval(startInstant, endInstant); + writableInterval.setChronology(chrono); + } + + //----------------------------------------------------------------------- + /** + * Returns String.class. + * + * @return String.class + */ + public Class getSupportedType() { + return String.class; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/convert/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/convert/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/convert/package.html 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,71 @@ + + + +org.joda.time.convert package + + + +

+Implementation package providing conversion between date and time objects. +

+

+Provides support for converting objects into instants and durations. Converters +are used internally by many of the standard classes, like DateTime. Most +applications have no need to use these classes directly. +

+ + Index: 3rdParty_sources/joda-time/org/joda/time/field/AbstractPartialFieldProperty.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/AbstractPartialFieldProperty.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/AbstractPartialFieldProperty.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,345 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.util.Locale; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeUtils; +import org.joda.time.DurationField; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadablePartial; + +/** + * AbstractPartialFieldProperty is a base class for binding a + * ReadablePartial to a DateTimeField. + *

+ * It allows the date and time manipulation code to be field based yet + * still easy to use. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class AbstractPartialFieldProperty { + + /** + * Constructor. + */ + protected AbstractPartialFieldProperty() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the field being used. + * + * @return the field + */ + public abstract DateTimeField getField(); + + /** + * Gets the field type being used. + * + * @return the field type + */ + public DateTimeFieldType getFieldType() { + return getField().getType(); + } + + /** + * Gets the name of the field. + * + * @return the field name + */ + public String getName() { + return getField().getName(); + } + + /** + * Gets the partial instant being used. + * + * @return the partial instant + */ + public abstract ReadablePartial getReadablePartial(); + + //----------------------------------------------------------------------- + /** + * Gets a value from the partial instant. + * + * @return the current value + */ + public abstract int get(); + + /** + * Gets a text value from the partial instant. + * + * @param locale optional locale to use for selecting a text symbol + * @return the current text value + * @see DateTimeField#getAsText + */ + public String getAsText(Locale locale) { + return getField().getAsText(getReadablePartial(), get(), locale); + } + + /** + * Gets a text value from the partial instant. + * + * @return the current text value + * @see DateTimeField#getAsText + */ + public String getAsText() { + return getAsText(null); + } + + /** + * Gets a short text value from the partial instant. + * + * @param locale optional locale to use for selecting a text symbol + * @return the current text value + * @see DateTimeField#getAsShortText + */ + public String getAsShortText(Locale locale) { + return getField().getAsShortText(getReadablePartial(), get(), locale); + } + + /** + * Gets a short text value from the partial instant. + * + * @return the current text value + * @see DateTimeField#getAsShortText + */ + public String getAsShortText() { + return getAsShortText(null); + } + + //----------------------------------------------------------------------- + /** + * Returns the duration per unit value of this field. For example, if this + * field represents "hour of day", then the duration is an hour. + * + * @return the duration of this field, or UnsupportedDurationField + */ + public DurationField getDurationField() { + return getField().getDurationField(); + } + + /** + * Returns the range duration of this field. For example, if this field + * represents "hour of day", then the range duration is a day. + * + * @return the range duration of this field, or null if field has no range + */ + public DurationField getRangeDurationField() { + return getField().getRangeDurationField(); + } + + //----------------------------------------------------------------------- + /** + * Gets the minimum value for the field ignoring the current time. + * + * @return the minimum value + * @see DateTimeField#getMinimumValue + */ + public int getMinimumValueOverall() { + return getField().getMinimumValue(); + } + + /** + * Gets the minimum value for this field given the current field values. + * + * @return the minimum value + * @see DateTimeField#getMinimumValue + */ + public int getMinimumValue() { + return getField().getMinimumValue(getReadablePartial()); + } + + /** + * Gets the maximum value for the field ignoring the current time. + * + * @return the maximum value + * @see DateTimeField#getMaximumValue + */ + public int getMaximumValueOverall() { + return getField().getMaximumValue(); + } + + /** + * Gets the maximum value for this field given the current field values. + * + * @return the maximum value + * @see DateTimeField#getMaximumValue + */ + public int getMaximumValue() { + return getField().getMaximumValue(getReadablePartial()); + } + + //----------------------------------------------------------------------- + /** + * Gets the maximum text length for the field. + * + * @param locale optional locale to use for selecting a text symbol + * @return the maximum length + * @see DateTimeField#getMaximumTextLength + */ + public int getMaximumTextLength(Locale locale) { + return getField().getMaximumTextLength(locale); + } + + /** + * Gets the maximum short text length for the field. + * + * @param locale optional locale to use for selecting a text symbol + * @return the maximum length + * @see DateTimeField#getMaximumShortTextLength + */ + public int getMaximumShortTextLength(Locale locale) { + return getField().getMaximumShortTextLength(locale); + } + + //----------------------------------------------------------------------- + /** + * Compare this field to the same field on another instant. + *

+ * The comparison is based on the value of the same field type, irrespective + * of any difference in chronology. Thus, if this property represents the + * hourOfDay field, then the hourOfDay field of the other instant will be queried + * whether in the same chronology or not. + * + * @param instant the instant to compare to + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws IllegalArgumentException if the instant is null or the instant + * doesn't support the field of this property + */ + public int compareTo(ReadableInstant instant) { + if (instant == null) { + throw new IllegalArgumentException("The instant must not be null"); + } + int thisValue = get(); + Chronology chrono = DateTimeUtils.getChronology(instant.getChronology()); + int otherValue = getFieldType().getField(chrono).get(instant.getMillis()); + if (thisValue < otherValue) { + return -1; + } else if (thisValue > otherValue) { + return 1; + } else { + return 0; + } + } + + /** + * Compare this field to the same field on another partial instant. + *

+ * The comparison is based on the value of the same field type, irrespective + * of any difference in chronology. Thus, if this property represents the + * hourOfDay field, then the hourOfDay field of the other partial will be queried + * whether in the same chronology or not. + * + * @param partial the partial to compare to + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws IllegalArgumentException if the instant is null + * @throws IllegalArgumentException if the field of this property cannot be queried + * on the specified instant + */ + public int compareTo(ReadablePartial partial) { + if (partial == null) { + throw new IllegalArgumentException("The instant must not be null"); + } + int thisValue = get(); + int otherValue = partial.get(getFieldType()); + if (thisValue < otherValue) { + return -1; + } else if (thisValue > otherValue) { + return 1; + } else { + return 0; + } + } + + //----------------------------------------------------------------------- + /** + * Compares this property to another. + * + * @param object the object to compare to + * @return true if equal + */ + public boolean equals(Object object) { + if (this == object) { + return true; + } + if (object instanceof AbstractPartialFieldProperty) { + AbstractPartialFieldProperty other = (AbstractPartialFieldProperty) object; + if (get() == other.get() && + getFieldType() == other.getFieldType() && + getReadablePartial().getChronology() == other.getReadablePartial().getChronology()) { + return true; + } + } + return false; + } + + //----------------------------------------------------------------------- + /** + * Output a debugging string. + * + * @return debugging string + */ + public String toString() { + return "Property[" + getName() + "]"; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/AbstractReadableInstantFieldProperty.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/AbstractReadableInstantFieldProperty.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/AbstractReadableInstantFieldProperty.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,428 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.io.Serializable; +import java.util.Locale; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeUtils; +import org.joda.time.DurationField; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadablePartial; + +/** + * AbstractReadableInstantFieldProperty is a base class for binding a + * ReadableInstant to a DateTimeField. + *

+ * It allows the date and time manipulation code to be field based yet + * still easy to use. + *

+ * AbstractReadableInstantFieldProperty itself is thread-safe and immutable, + * but the ReadableInstant being operated on may be mutable and not + * thread-safe. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class AbstractReadableInstantFieldProperty implements Serializable { + + /** Serialization version. */ + private static final long serialVersionUID = 1971226328211649661L; + + /** + * Constructor. + */ + public AbstractReadableInstantFieldProperty() { + super(); + } + + //----------------------------------------------------------------------- + /** + * Gets the field being used. + * + * @return the field + */ + public abstract DateTimeField getField(); + + /** + * Gets the field type being used. + * + * @return the field type + */ + public DateTimeFieldType getFieldType() { + return getField().getType(); + } + + /** + * Gets the name of the field. + * + * @return the field name + */ + public String getName() { + return getField().getName(); + } + + /** + * Gets the instant being used. + * + * @return the instant + */ + public abstract ReadableInstant getReadableInstant(); + + //----------------------------------------------------------------------- + /** + * Gets a value from the instant. + * + * @return the current value + * @see DateTimeField#get + */ + public int get() { + return getField().get(getReadableInstant().getMillis()); + } + + /** + * Gets a text value from the instant. + * + * @param locale optional locale to use for selecting a text symbol + * @return the current text value + * @see DateTimeField#getAsText + */ + public String getAsText(Locale locale) { + return getField().getAsText(getReadableInstant().getMillis(), locale); + } + + /** + * Gets a text value from the instant. + * + * @return the current text value + * @see DateTimeField#getAsText + */ + public final String getAsText() { + return getAsText(null); + } + + /** + * Gets a short text value from the instant. + * + * @param locale optional locale to use for selecting a text symbol + * @return the current text value + * @see DateTimeField#getAsShortText + */ + public String getAsShortText(Locale locale) { + return getField().getAsShortText(getReadableInstant().getMillis(), locale); + } + + /** + * Gets a short text value from the instant. + * + * @return the current text value + * @see DateTimeField#getAsShortText + */ + public final String getAsShortText() { + return getAsShortText(null); + } + + //----------------------------------------------------------------------- + /** + * Returns the difference between this field property instant and the one + * passed in, in the units of this field. The sign of the difference + * matches that of compareTo. In other words, this field property's instant + * is the minuend. + * + * @param instant the subtrahend, null means now + * @return the difference in the units of this field + * @see DateTimeField#getDifference + */ + public int getDifference(ReadableInstant instant) { + if (instant == null) { + return getField().getDifference(getReadableInstant().getMillis(), DateTimeUtils.currentTimeMillis()); + } + return getField().getDifference(getReadableInstant().getMillis(), instant.getMillis()); + } + + /** + * Returns the difference between this field property instant and the one + * passed in, in the units of this field. The sign of the difference + * matches that of compareTo. In other words, this field property's instant + * is the minuend. + * + * @param instant the subtrahend, null means now + * @return the difference in the units of this field + * @see DateTimeField#getDifference + */ + public long getDifferenceAsLong(ReadableInstant instant) { + if (instant == null) { + return getField().getDifferenceAsLong(getReadableInstant().getMillis(), DateTimeUtils.currentTimeMillis()); + } + return getField().getDifferenceAsLong(getReadableInstant().getMillis(), instant.getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Returns the duration per unit value of this field. For example, if this + * field represents "hour of day", then the duration is an hour. + * + * @return the duration of this field, or UnsupportedDurationField + */ + public DurationField getDurationField() { + return getField().getDurationField(); + } + + /** + * Returns the range duration of this field. For example, if this field + * represents "hour of day", then the range duration is a day. + * + * @return the range duration of this field, or null if field has no range + */ + public DurationField getRangeDurationField() { + return getField().getRangeDurationField(); + } + + /** + * Gets whether this field is leap. + * + * @return true if a leap field + * @see DateTimeField#isLeap + */ + public boolean isLeap() { + return getField().isLeap(getReadableInstant().getMillis()); + } + + /** + * Gets the amount by which this field is leap. + * + * @return the amount by which the field is leap + * @see DateTimeField#getLeapAmount + */ + public int getLeapAmount() { + return getField().getLeapAmount(getReadableInstant().getMillis()); + } + + /** + * If this field were to leap, then it would be in units described by the + * returned duration. If this field doesn't ever leap, null is returned. + */ + public DurationField getLeapDurationField() { + return getField().getLeapDurationField(); + } + + //----------------------------------------------------------------------- + /** + * Gets the minimum value for the field ignoring the current time. + * + * @return the minimum value + * @see DateTimeField#getMinimumValue + */ + public int getMinimumValueOverall() { + return getField().getMinimumValue(); + } + + /** + * Gets the minimum value for the field. + * + * @return the minimum value + * @see DateTimeField#getMinimumValue + */ + public int getMinimumValue() { + return getField().getMinimumValue(getReadableInstant().getMillis()); + } + + /** + * Gets the maximum value for the field ignoring the current time. + * + * @return the maximum value + * @see DateTimeField#getMaximumValue + */ + public int getMaximumValueOverall() { + return getField().getMaximumValue(); + } + + /** + * Gets the maximum value for the field. + * + * @return the maximum value + * @see DateTimeField#getMaximumValue + */ + public int getMaximumValue() { + return getField().getMaximumValue(getReadableInstant().getMillis()); + } + + /** + * Gets the maximum text length for the field. + * + * @param locale optional locale to use for selecting a text symbol + * @return the maximum length + * @see DateTimeField#getMaximumTextLength + */ + public int getMaximumTextLength(Locale locale) { + return getField().getMaximumTextLength(locale); + } + + /** + * Gets the maximum short text length for the field. + * + * @param locale optional locale to use for selecting a text symbol + * @return the maximum length + * @see DateTimeField#getMaximumShortTextLength + */ + public int getMaximumShortTextLength(Locale locale) { + return getField().getMaximumShortTextLength(locale); + } + + + /** + * Returns the fractional duration milliseconds of this field. + * + * @see DateTimeField#remainder + * @return remainder duration, in milliseconds + */ + public long remainder() { + return getField().remainder(getReadableInstant().getMillis()); + } + + //----------------------------------------------------------------------- + /** + * Compare this field to the same field on another instant. + *

+ * The comparison is based on the value of the same field type, irrespective + * of any difference in chronology. Thus, if this property represents the + * hourOfDay field, then the hourOfDay field of the other instant will be queried + * whether in the same chronology or not. + * + * @param instant the instant to compare to + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws IllegalArgumentException if the instant is null + */ + public int compareTo(ReadableInstant instant) { + if (instant == null) { + throw new IllegalArgumentException("The instant must not be null"); + } + int thisValue = get(); + Chronology chrono = DateTimeUtils.getChronology(instant.getChronology()); + int otherValue = getFieldType().getField(chrono).get(instant.getMillis()); + if (thisValue < otherValue) { + return -1; + } else if (thisValue > otherValue) { + return 1; + } else { + return 0; + } + } + + /** + * Compare this field to the same field on another partial instant. + *

+ * The comparison is based on the value of the same field type, irrespective + * of any difference in chronology. Thus, if this property represents the + * hourOfDay field, then the hourOfDay field of the other partial will be queried + * whether in the same chronology or not. + * + * @param partial the partial to compare to + * @return negative value if this is less, 0 if equal, or positive value if greater + * @throws IllegalArgumentException if the instant is null + * @throws IllegalArgumentException if the field of this property cannot be queried + * on the specified instant + */ + public int compareTo(ReadablePartial partial) { + if (partial == null) { + throw new IllegalArgumentException("The instant must not be null"); + } + int thisValue = get(); + int otherValue = partial.get(getFieldType()); + if (thisValue < otherValue) { + return -1; + } else if (thisValue > otherValue) { + return 1; + } else { + return 0; + } + } + + //----------------------------------------------------------------------- + /** + * Compares this property to another. + * + * @param object the object to compare to + * @return true if equal + */ + public boolean equals(Object object) { + if (this == object) { + return true; + } + if (object instanceof AbstractReadableInstantFieldProperty) { + AbstractReadableInstantFieldProperty other = (AbstractReadableInstantFieldProperty) object; + if (get() == other.get() && + getFieldType() == other.getFieldType() && + getReadableInstant().getChronology() == other.getReadableInstant().getChronology()) { + return true; + } + } + return false; + } + + //----------------------------------------------------------------------- + /** + * Output a debugging string. + * + * @return debugging string + */ + public String toString() { + return "Property[" + getName() + "]"; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/BaseDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/BaseDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/BaseDateTimeField.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,958 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.util.Locale; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; + +/** + * BaseDateTimeField provides the common behaviour for DateTimeField + * implementations. + *

+ * This class should generally not be used directly by API users. The + * DateTimeField class should be used when different kinds of DateTimeField + * objects are to be referenced. + *

+ * BaseDateTimeField is thread-safe and immutable, and its subclasses must + * be as well. + * + * @author Brian S O'Neill + * @since 1.0 + * @see DecoratedDateTimeField + */ +public abstract class BaseDateTimeField extends DateTimeField { + + /** The field type. */ + private final DateTimeFieldType iType; + + /** + * Constructor. + */ + protected BaseDateTimeField(DateTimeFieldType type) { + super(); + if (type == null) { + throw new IllegalArgumentException("The type must not be null"); + } + iType = type; + } + + public final DateTimeFieldType getType() { + return iType; + } + + public final String getName() { + return iType.getName(); + } + + /** + * @return true always + */ + public final boolean isSupported() { + return true; + } + + // Main access API + //------------------------------------------------------------------------ + /** + * Get the value of this field from the milliseconds. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the value of the field, in the units of the field + */ + public abstract int get(long instant); + + //----------------------------------------------------------------------- + /** + * Get the human-readable, text value of this field from the milliseconds. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation returns getAsText(get(instant), locale). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @param locale the locale to use for selecting a text symbol, null means default + * @return the text value of the field + */ + public String getAsText(long instant, Locale locale) { + return getAsText(get(instant), locale); + } + + /** + * Get the human-readable, text value of this field from the milliseconds. + *

+ * The default implementation calls {@link #getAsText(long, Locale)}. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the text value of the field + */ + public final String getAsText(long instant) { + return getAsText(instant, null); + } + + /** + * Get the human-readable, text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation returns getAsText(fieldValue, locale). + * + * @param partial the partial instant to query + * @param fieldValue the field value of this field, provided for performance + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public String getAsText(ReadablePartial partial, int fieldValue, Locale locale) { + return getAsText(fieldValue, locale); + } + + /** + * Get the human-readable, text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation calls {@link ReadablePartial#get(DateTimeFieldType)} + * and {@link #getAsText(ReadablePartial, int, Locale)}. + * + * @param partial the partial instant to query + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public final String getAsText(ReadablePartial partial, Locale locale) { + return getAsText(partial, partial.get(getType()), locale); + } + + /** + * Get the human-readable, text value of this field from the field value. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation returns Integer.toString(get(instant)). + *

+ * Note: subclasses that override this method should also override + * getMaximumTextLength. + * + * @param fieldValue the numeric value to convert to text + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + protected String getAsText(int fieldValue, Locale locale) { + return Integer.toString(fieldValue); + } + + //----------------------------------------------------------------------- + /** + * Get the human-readable, short text value of this field from the milliseconds. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation returns getAsShortText(get(instant), locale). + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @param locale the locale to use for selecting a text symbol, null means default + * @return the text value of the field + */ + public String getAsShortText(long instant, Locale locale) { + return getAsShortText(get(instant), locale); + } + + /** + * Get the human-readable, short text value of this field from the milliseconds. + *

+ * The default implementation calls {@link #getAsShortText(long, Locale)}. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the text value of the field + */ + public final String getAsShortText(long instant) { + return getAsShortText(instant, null); + } + + /** + * Get the human-readable, short text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation returns getAsShortText(fieldValue, locale). + * + * @param partial the partial instant to query + * @param fieldValue the field value of this field, provided for performance + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale) { + return getAsShortText(fieldValue, locale); + } + + /** + * Get the human-readable, short text value of this field from a partial instant. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation calls {@link ReadablePartial#get(DateTimeFieldType)} + * and {@link #getAsText(ReadablePartial, int, Locale)}. + * + * @param partial the partial instant to query + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + public final String getAsShortText(ReadablePartial partial, Locale locale) { + return getAsShortText(partial, partial.get(getType()), locale); + } + + /** + * Get the human-readable, short text value of this field from the field value. + * If the specified locale is null, the default locale is used. + *

+ * The default implementation returns getAsText(fieldValue, locale). + *

+ * Note: subclasses that override this method should also override + * getMaximumShortTextLength. + * + * @param fieldValue the numeric value to convert to text + * @param locale the locale to use for selecting a text symbol, null for default + * @return the text value of the field + */ + protected String getAsShortText(int fieldValue, Locale locale) { + return getAsText(fieldValue, locale); + } + + //----------------------------------------------------------------------- + /** + * Adds a value (which may be negative) to the instant value, + * overflowing into larger fields if necessary. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field, larger fields will increase as required. + * Smaller fields should be unaffected, except where the result would be + * an invalid value for a smaller field. In this case the smaller field is + * adjusted to be in range. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 add six months is 2001-02-20
+ * 2000-08-20 add twenty months is 2002-04-20
+ * 2000-08-20 add minus nine months is 1999-11-20
+ * 2001-01-31 add one month is 2001-02-28
+ * 2001-01-31 add two months is 2001-03-31
+ * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the value to add, in the units of the field + * @return the updated milliseconds + */ + public long add(long instant, int value) { + return getDurationField().add(instant, value); + } + + /** + * Adds a value (which may be negative) to the instant value, + * overflowing into larger fields if necessary. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the long value to add, in the units of the field + * @return the updated milliseconds + * @throws IllegalArgumentException if value is too large + * @see #add(long,int) + */ + public long add(long instant, long value) { + return getDurationField().add(instant, value); + } + + /** + * Adds a value (which may be negative) to the partial instant, + * throwing an exception if the maximum size of the instant is reached. + *

+ * The value will be added to this field, overflowing into larger fields + * if necessary. Smaller fields should be unaffected, except where the + * result would be an invalid value for a smaller field. In this case the + * smaller field is adjusted to be in range. + *

+ * Partial instants only contain some fields. This may result in a maximum + * possible value, such as TimeOfDay being limited to 23:59:59:999. If this + * limit is breached by the add an exception is thrown. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 add six months is 2000-02-20
+ * 2000-08-20 add twenty months is 2000-04-20
+ * 2000-08-20 add minus nine months is 2000-11-20
+ * 2001-01-31 add one month is 2001-02-28
+ * 2001-01-31 add two months is 2001-03-31
+ * + * @param instant the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values of the partial instant which should be updated + * @param valueToAdd the value to add, in the units of the field + * @return the passed in values + * @throws IllegalArgumentException if the value is invalid or the maximum instant is reached + */ + public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { + if (valueToAdd == 0) { + return values; + } + // there are more efficient algorithms than this (especially for time only fields) + // trouble is when dealing with days and months, so we use this technique of + // adding/removing one from the larger field at a time + DateTimeField nextField = null; + + while (valueToAdd > 0) { + int max = getMaximumValue(instant, values); + long proposed = values[fieldIndex] + valueToAdd; + if (proposed <= max) { + values[fieldIndex] = (int) proposed; + break; + } + if (nextField == null) { + if (fieldIndex == 0) { + throw new IllegalArgumentException("Maximum value exceeded for add"); + } + nextField = instant.getField(fieldIndex - 1); + // test only works if this field is UTC (ie. local) + if (getRangeDurationField() != nextField.getDurationField()) { + throw new IllegalArgumentException("Fields invalid for add"); + } + } + valueToAdd -= (max + 1) - values[fieldIndex]; + values = nextField.add(instant, fieldIndex - 1, values, 1); + values[fieldIndex] = getMinimumValue(instant, values); + } + while (valueToAdd < 0) { + int min = getMinimumValue(instant, values); + long proposed = values[fieldIndex] + valueToAdd; + if (proposed >= min) { + values[fieldIndex] = (int) proposed; + break; + } + if (nextField == null) { + if (fieldIndex == 0) { + throw new IllegalArgumentException("Maximum value exceeded for add"); + } + nextField = instant.getField(fieldIndex - 1); + if (getRangeDurationField() != nextField.getDurationField()) { + throw new IllegalArgumentException("Fields invalid for add"); + } + } + valueToAdd -= (min - 1) - values[fieldIndex]; + values = nextField.add(instant, fieldIndex - 1, values, -1); + values[fieldIndex] = getMaximumValue(instant, values); + } + + return set(instant, fieldIndex, values, values[fieldIndex]); // adjusts smaller fields + } + + /** + * Adds a value (which may be negative) to the instant value, + * wrapping within this field. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it wraps. Larger fields are always + * unaffected. Smaller fields should be unaffected, except where the + * result would be an invalid value for a smaller field. In this case the + * smaller field is adjusted to be in range. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 addWrapField six months is 2000-02-20
+ * 2000-08-20 addWrapField twenty months is 2000-04-20
+ * 2000-08-20 addWrapField minus nine months is 2000-11-20
+ * 2001-01-31 addWrapField one month is 2001-02-28
+ * 2001-01-31 addWrapField two months is 2001-03-31
+ *

+ * The default implementation internally calls set. Subclasses are + * encouraged to provide a more efficient implementation. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param value the value to add, in the units of the field + * @return the updated milliseconds + */ + public long addWrapField(long instant, int value) { + int current = get(instant); + int wrapped = FieldUtils.getWrappedValue + (current, value, getMinimumValue(instant), getMaximumValue(instant)); + return set(instant, wrapped); + } + + /** + * Adds a value (which may be negative) to the partial instant, + * wrapping within this field. + *

+ * The value will be added to this field. If the value is too large to be + * added solely to this field then it wraps. Larger fields are always + * unaffected. Smaller fields should be unaffected, except where the + * result would be an invalid value for a smaller field. In this case the + * smaller field is adjusted to be in range. + *

+ * For example, in the ISO chronology:
+ * 2000-08-20 addWrapField six months is 2000-02-20
+ * 2000-08-20 addWrapField twenty months is 2000-04-20
+ * 2000-08-20 addWrapField minus nine months is 2000-11-20
+ * 2001-01-31 addWrapField one month is 2001-02-28
+ * 2001-01-31 addWrapField two months is 2001-03-31
+ *

+ * The default implementation internally calls set. Subclasses are + * encouraged to provide a more efficient implementation. + * + * @param instant the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values of the partial instant which should be updated + * @param valueToAdd the value to add, in the units of the field + * @return the passed in values + * @throws IllegalArgumentException if the value is invalid + */ + public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { + int current = values[fieldIndex]; + int wrapped = FieldUtils.getWrappedValue + (current, valueToAdd, getMinimumValue(instant), getMaximumValue(instant)); + return set(instant, fieldIndex, values, wrapped); // adjusts smaller fields + } + + //----------------------------------------------------------------------- + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *

+     * long instant = ...
+     * int v = ...
+     * int age = getDifference(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public int getDifference(long minuendInstant, long subtrahendInstant) { + return getDurationField().getDifference(minuendInstant, subtrahendInstant); + } + + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *
+     * long instant = ...
+     * long v = ...
+     * long age = getDifferenceAsLong(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return getDurationField().getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + /** + * Sets a value in the milliseconds supplied. + *

+ * The value of this field will be set. + * If the value is invalid, an exception if thrown. + *

+ * If setting this field would make other fields invalid, then those fields + * may be changed. For example if the current date is the 31st January, and + * the month is set to February, the day would be invalid. Instead, the day + * would be changed to the closest value - the 28th/29th February as appropriate. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param value the value to set, in the units of the field + * @return the updated milliseconds + * @throws IllegalArgumentException if the value is invalid + */ + public abstract long set(long instant, int value); + + /** + * Sets a value using the specified partial instant. + *

+ * The value of this field (specified by the index) will be set. + * If the value is invalid, an exception if thrown. + *

+ * If setting this field would make other fields invalid, then those fields + * may be changed. For example if the current date is the 31st January, and + * the month is set to February, the day would be invalid. Instead, the day + * would be changed to the closest value - the 28th/29th February as appropriate. + * + * @param partial the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values to update + * @param newValue the value to set, in the units of the field + * @return the updated values + * @throws IllegalArgumentException if the value is invalid + */ + public int[] set(ReadablePartial partial, int fieldIndex, int[] values, int newValue) { + FieldUtils.verifyValueBounds(this, newValue, getMinimumValue(partial, values), getMaximumValue(partial, values)); + values[fieldIndex] = newValue; + + // may need to adjust smaller fields + for (int i = fieldIndex + 1; i < partial.size(); i++) { + DateTimeField field = partial.getField(i); + if (values[i] > field.getMaximumValue(partial, values)) { + values[i] = field.getMaximumValue(partial, values); + } + if (values[i] < field.getMinimumValue(partial, values)) { + values[i] = field.getMinimumValue(partial, values); + } + } + return values; + } + + /** + * Sets a value in the milliseconds supplied from a human-readable, text value. + * If the specified locale is null, the default locale is used. + *

+ * This implementation uses {@link #convertText(String, Locale)} and + * {@link #set(long, int)}. + *

+ * Note: subclasses that override this method should also override + * getAsText. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param text the text value to set + * @param locale the locale to use for selecting a text symbol, null for default + * @return the updated milliseconds + * @throws IllegalArgumentException if the text value is invalid + */ + public long set(long instant, String text, Locale locale) { + int value = convertText(text, locale); + return set(instant, value); + } + + /** + * Sets a value in the milliseconds supplied from a human-readable, text value. + *

+ * This implementation uses {@link #set(long, String, Locale)}. + *

+ * Note: subclasses that override this method should also override getAsText. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param text the text value to set + * @return the updated milliseconds + * @throws IllegalArgumentException if the text value is invalid + */ + public final long set(long instant, String text) { + return set(instant, text, null); + } + + /** + * Sets a value in the milliseconds supplied from a human-readable, text value. + * If the specified locale is null, the default locale is used. + *

+ * This implementation uses {@link #convertText(String, Locale)} and + * {@link #set(ReadablePartial, int, int[], int)}. + * + * @param instant the partial instant + * @param fieldIndex the index of this field in the instant + * @param values the values of the partial instant which should be updated + * @param text the text value to set + * @param locale the locale to use for selecting a text symbol, null for default + * @return the passed in values + * @throws IllegalArgumentException if the text value is invalid + */ + public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale) { + int value = convertText(text, locale); + return set(instant, fieldIndex, values, value); + } + + /** + * Convert the specified text and locale into a value. + * + * @param text the text to convert + * @param locale the locale to convert using + * @return the value extracted from the text + * @throws IllegalArgumentException if the text is invalid + */ + protected int convertText(String text, Locale locale) { + try { + return Integer.parseInt(text); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Invalid " + getName() + " text: " + text); + } + } + + // Extra information API + //------------------------------------------------------------------------ + /** + * Returns the duration per unit value of this field. For example, if this + * field represents "hour of day", then the unit duration is an hour. + * + * @return the duration of this field, or UnsupportedDurationField if field + * has no duration + */ + public abstract DurationField getDurationField(); + + /** + * Returns the range duration of this field. For example, if this field + * represents "hour of day", then the range duration is a day. + * + * @return the range duration of this field, or null if field has no range + */ + public abstract DurationField getRangeDurationField(); + + /** + * Returns whether this field is 'leap' for the specified instant. + *

+ * For example, a leap year would return true, a non leap year would return + * false. + *

+ * This implementation returns false. + * + * @return true if the field is 'leap' + */ + public boolean isLeap(long instant) { + return false; + } + + /** + * Gets the amount by which this field is 'leap' for the specified instant. + *

+ * For example, a leap year would return one, a non leap year would return + * zero. + *

+ * This implementation returns zero. + */ + public int getLeapAmount(long instant) { + return 0; + } + + /** + * If this field were to leap, then it would be in units described by the + * returned duration. If this field doesn't ever leap, null is returned. + *

+ * This implementation returns null. + */ + public DurationField getLeapDurationField() { + return null; + } + + /** + * Get the minimum allowable value for this field. + * + * @return the minimum valid value for this field, in the units of the + * field + */ + public abstract int getMinimumValue(); + + /** + * Get the minimum value for this field evaluated at the specified time. + *

+ * This implementation returns the same as {@link #getMinimumValue()}. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the minimum value for this field, in the units of the field + */ + public int getMinimumValue(long instant) { + return getMinimumValue(); + } + + /** + * Get the minimum value for this field evaluated at the specified instant. + *

+ * This implementation returns the same as {@link #getMinimumValue()}. + * + * @param instant the partial instant to query + * @return the minimum value for this field, in the units of the field + */ + public int getMinimumValue(ReadablePartial instant) { + return getMinimumValue(); + } + + /** + * Get the minimum value for this field using the partial instant and + * the specified values. + *

+ * This implementation returns the same as {@link #getMinimumValue(ReadablePartial)}. + * + * @param instant the partial instant to query + * @param values the values to use + * @return the minimum value for this field, in the units of the field + */ + public int getMinimumValue(ReadablePartial instant, int[] values) { + return getMinimumValue(instant); + } + + /** + * Get the maximum allowable value for this field. + * + * @return the maximum valid value for this field, in the units of the + * field + */ + public abstract int getMaximumValue(); + + /** + * Get the maximum value for this field evaluated at the specified time. + *

+ * This implementation returns the same as {@link #getMaximumValue()}. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the maximum value for this field, in the units of the field + */ + public int getMaximumValue(long instant) { + return getMaximumValue(); + } + + /** + * Get the maximum value for this field evaluated at the specified instant. + *

+ * This implementation returns the same as {@link #getMaximumValue()}. + * + * @param instant the partial instant to query + * @return the maximum value for this field, in the units of the field + */ + public int getMaximumValue(ReadablePartial instant) { + return getMaximumValue(); + } + + /** + * Get the maximum value for this field using the partial instant and + * the specified values. + *

+ * This implementation returns the same as {@link #getMaximumValue(ReadablePartial)}. + * + * @param instant the partial instant to query + * @param values the values to use + * @return the maximum value for this field, in the units of the field + */ + public int getMaximumValue(ReadablePartial instant, int[] values) { + return getMaximumValue(instant); + } + + /** + * Get the maximum text value for this field. The default implementation + * returns the equivalent of Integer.toString(getMaximumValue()).length(). + * + * @param locale the locale to use for selecting a text symbol + * @return the maximum text length + */ + public int getMaximumTextLength(Locale locale) { + int max = getMaximumValue(); + if (max >= 0) { + if (max < 10) { + return 1; + } else if (max < 100) { + return 2; + } else if (max < 1000) { + return 3; + } + } + return Integer.toString(max).length(); + } + + /** + * Get the maximum short text value for this field. The default + * implementation returns getMaximumTextLength(). + * + * @param locale the locale to use for selecting a text symbol + * @return the maximum short text length + */ + public int getMaximumShortTextLength(Locale locale) { + return getMaximumTextLength(locale); + } + + // Calculation API + //------------------------------------------------------------------------ + /** + * Round to the lowest whole unit of this field. After rounding, the value + * of this field and all fields of a higher magnitude are retained. The + * fractional millis that cannot be expressed in whole increments of this + * field are set to minimum. + *

+ * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the + * lowest whole hour is 2002-11-02T23:00:00.000. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public abstract long roundFloor(long instant); + + /** + * Round to the highest whole unit of this field. The value of this field + * and all fields of a higher magnitude may be incremented in order to + * achieve this result. The fractional millis that cannot be expressed in + * whole increments of this field are set to minimum. + *

+ * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the + * highest whole hour is 2002-11-03T00:00:00.000. + *

+ * The default implementation calls roundFloor, and if the instant is + * modified as a result, adds one field unit. Subclasses are encouraged to + * provide a more efficient implementation. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public long roundCeiling(long instant) { + long newInstant = roundFloor(instant); + if (newInstant != instant) { + instant = add(newInstant, 1); + } + return instant; + } + + /** + * Round to the nearest whole unit of this field. If the given millisecond + * value is closer to the floor or is exactly halfway, this function + * behaves like roundFloor. If the millisecond value is closer to the + * ceiling, this function behaves like roundCeiling. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public long roundHalfFloor(long instant) { + long floor = roundFloor(instant); + long ceiling = roundCeiling(instant); + + long diffFromFloor = instant - floor; + long diffToCeiling = ceiling - instant; + + if (diffFromFloor <= diffToCeiling) { + // Closer to the floor, or halfway - round floor + return floor; + } else { + return ceiling; + } + } + + /** + * Round to the nearest whole unit of this field. If the given millisecond + * value is closer to the floor, this function behaves like roundFloor. If + * the millisecond value is closer to the ceiling or is exactly halfway, + * this function behaves like roundCeiling. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public long roundHalfCeiling(long instant) { + long floor = roundFloor(instant); + long ceiling = roundCeiling(instant); + + long diffFromFloor = instant - floor; + long diffToCeiling = ceiling - instant; + + if (diffToCeiling <= diffFromFloor) { + // Closer to the ceiling, or halfway - round ceiling + return ceiling; + } else { + return floor; + } + } + + /** + * Round to the nearest whole unit of this field. If the given millisecond + * value is closer to the floor, this function behaves like roundFloor. If + * the millisecond value is closer to the ceiling, this function behaves + * like roundCeiling. + *

+ * If the millisecond value is exactly halfway between the floor and + * ceiling, the ceiling is chosen over the floor only if it makes this + * field's value even. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to round + * @return rounded milliseconds + */ + public long roundHalfEven(long instant) { + long floor = roundFloor(instant); + long ceiling = roundCeiling(instant); + + long diffFromFloor = instant - floor; + long diffToCeiling = ceiling - instant; + + if (diffFromFloor < diffToCeiling) { + // Closer to the floor - round floor + return floor; + } else if (diffToCeiling < diffFromFloor) { + // Closer to the ceiling - round ceiling + return ceiling; + } else { + // Round to the instant that makes this field even. If both values + // make this field even (unlikely), favor the ceiling. + if ((get(ceiling) & 1) == 0) { + return ceiling; + } + return floor; + } + } + + /** + * Returns the fractional duration milliseconds of this field. In other + * words, calling remainder returns the duration that roundFloor would + * subtract. + *

+ * For example, on a datetime of 2002-11-02T23:34:56.789, the remainder by + * hour is 34 minutes and 56.789 seconds. + *

+ * The default implementation computes + * instant - roundFloor(instant). Subclasses are encouraged to + * provide a more efficient implementation. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to get the + * remainder + * @return remainder duration, in milliseconds + */ + public long remainder(long instant) { + return instant - roundFloor(instant); + } + + /** + * Get a suitable debug string. + * + * @return debug string + */ + public String toString() { + return "DateTimeField[" + getName() + ']'; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/BaseDurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/BaseDurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/BaseDurationField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,205 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.io.Serializable; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; + +/** + * BaseDurationField provides the common behaviour for DurationField + * implementations. + *

+ * This class should generally not be used directly by API users. The + * DurationField class should be used when different kinds of DurationField + * objects are to be referenced. + *

+ * BaseDurationField is thread-safe and immutable, and its subclasses must + * be as well. + * + * @author Brian S O'Neill + * @see DecoratedDurationField + */ +public abstract class BaseDurationField extends DurationField implements Serializable { + + /** Serialization lock. */ + private static final long serialVersionUID = -2554245107589433218L; + + /** A desriptive name for the field. */ + private final DurationFieldType iType; + + protected BaseDurationField(DurationFieldType type) { + super(); + if (type == null) { + throw new IllegalArgumentException("The type must not be null"); + } + iType = type; + } + + public final DurationFieldType getType() { + return iType; + } + + public final String getName() { + return iType.getName(); + } + + /** + * @return true always + */ + public final boolean isSupported() { + return true; + } + + //------------------------------------------------------------------------ + /** + * Get the value of this field from the milliseconds, which is approximate + * if this field is imprecise. + * + * @param duration the milliseconds to query, which may be negative + * @return the value of the field, in the units of the field, which may be + * negative + */ + public int getValue(long duration) { + return FieldUtils.safeToInt(getValueAsLong(duration)); + } + + /** + * Get the value of this field from the milliseconds, which is approximate + * if this field is imprecise. + * + * @param duration the milliseconds to query, which may be negative + * @return the value of the field, in the units of the field, which may be + * negative + */ + public long getValueAsLong(long duration) { + return duration / getUnitMillis(); + } + + /** + * Get the value of this field from the milliseconds relative to an + * instant. + * + *

If the milliseconds is positive, then the instant is treated as a + * "start instant". If negative, the instant is treated as an "end + * instant". + * + *

The default implementation returns + * Utils.safeToInt(getAsLong(millisDuration, instant)). + * + * @param duration the milliseconds to query, which may be negative + * @param instant the start instant to calculate relative to + * @return the value of the field, in the units of the field, which may be + * negative + */ + public int getValue(long duration, long instant) { + return FieldUtils.safeToInt(getValueAsLong(duration, instant)); + } + + /** + * Get the millisecond duration of this field from its value, which is + * approximate if this field is imprecise. + * + * @param value the value of the field, which may be negative + * @return the milliseconds that the field represents, which may be + * negative + */ + public long getMillis(int value) { + return value * getUnitMillis(); // safe + } + + /** + * Get the millisecond duration of this field from its value, which is + * approximate if this field is imprecise. + * + * @param value the value of the field, which may be negative + * @return the milliseconds that the field represents, which may be + * negative + */ + public long getMillis(long value) { + return FieldUtils.safeMultiply(value, getUnitMillis()); + } + + // Calculation API + //------------------------------------------------------------------------ + public int getDifference(long minuendInstant, long subtrahendInstant) { + return FieldUtils.safeToInt(getDifferenceAsLong(minuendInstant, subtrahendInstant)); + } + + //------------------------------------------------------------------------ + public int compareTo(Object durationField) { + DurationField otherField = (DurationField) durationField; + long otherMillis = otherField.getUnitMillis(); + long thisMillis = getUnitMillis(); + // cannot do (thisMillis - otherMillis) as can overflow + if (thisMillis == otherMillis) { + return 0; + } + if (thisMillis < otherMillis) { + return -1; + } else { + return 1; + } + } + + /** + * Get a suitable debug string. + * + * @return debug string + */ + public String toString() { + return "DurationField[" + getName() + ']'; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/DecoratedDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/DecoratedDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/DecoratedDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,143 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; + +/** + * DecoratedDateTimeField extends {@link BaseDateTimeField}, + * implementing only the minimum required set of methods. These implemented + * methods delegate to a wrapped field. + *

+ * This design allows new DateTimeField types to be defined that piggyback on + * top of another, inheriting all the safe method implementations from + * BaseDateTimeField. Should any method require pure delegation to the + * wrapped field, simply override and use the provided getWrappedField method. + *

+ * DecoratedDateTimeField is thread-safe and immutable, and its subclasses must + * be as well. + * + * @author Brian S O'Neill + * @since 1.0 + * @see DelegatedDateTimeField + */ +public abstract class DecoratedDateTimeField extends BaseDateTimeField { + + /** Serialization version */ + private static final long serialVersionUID = 203115783733757597L; + + /** The DateTimeField being wrapped */ + private final DateTimeField iField; + + /** + * Constructor. + * + * @param field the field being decorated + * @param type allow type to be overridden + */ + protected DecoratedDateTimeField(DateTimeField field, DateTimeFieldType type) { + super(type); + if (field == null) { + throw new IllegalArgumentException("The field must not be null"); + } + if (!field.isSupported()) { + throw new IllegalArgumentException("The field must be supported"); + } + iField = field; + } + + /** + * Gets the wrapped date time field. + * + * @return the wrapped DateTimeField + */ + public final DateTimeField getWrappedField() { + return iField; + } + + public boolean isLenient() { + return iField.isLenient(); + } + + public int get(long instant) { + return iField.get(instant); + } + + public long set(long instant, int value) { + return iField.set(instant, value); + } + + public DurationField getDurationField() { + return iField.getDurationField(); + } + + public DurationField getRangeDurationField() { + return iField.getRangeDurationField(); + } + + public int getMinimumValue() { + return iField.getMinimumValue(); + } + + public int getMaximumValue() { + return iField.getMaximumValue(); + } + + public long roundFloor(long instant) { + return iField.roundFloor(instant); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/DecoratedDurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/DecoratedDurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/DecoratedDurationField.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,141 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; + +/** + * DecoratedDurationField extends {@link BaseDurationField}, + * implementing only the minimum required set of methods. These implemented + * methods delegate to a wrapped field. + *

+ * This design allows new DurationField types to be defined that piggyback on + * top of another, inheriting all the safe method implementations from + * BaseDurationField. Should any method require pure delegation to the + * wrapped field, simply override and use the provided getWrappedField method. + *

+ * DecoratedDurationField is thread-safe and immutable, and its subclasses must + * be as well. + * + * @author Brian S O'Neill + * @see DelegatedDurationField + */ +public class DecoratedDurationField extends BaseDurationField { + + private static final long serialVersionUID = 8019982251647420015L; + + /** The DurationField being wrapped */ + private final DurationField iField; + + /** + * Constructor. + * + * @param field the base field + * @param type the type to actually use + */ + public DecoratedDurationField(DurationField field, DurationFieldType type) { + super(type); + if (field == null) { + throw new IllegalArgumentException("The field must not be null"); + } + if (!field.isSupported()) { + throw new IllegalArgumentException("The field must be supported"); + } + iField = field; + } + + //----------------------------------------------------------------------- + /** + * Gets the wrapped duration field. + * + * @return the wrapped DurationField + */ + public final DurationField getWrappedField() { + return iField; + } + + public boolean isPrecise() { + return iField.isPrecise(); + } + + public long getValueAsLong(long duration, long instant) { + return iField.getValueAsLong(duration, instant); + } + + public long getMillis(int value, long instant) { + return iField.getMillis(value, instant); + } + + public long getMillis(long value, long instant) { + return iField.getMillis(value, instant); + } + + public long add(long instant, int value) { + return iField.add(instant, value); + } + + public long add(long instant, long value) { + return iField.add(instant, value); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + public long getUnitMillis() { + return iField.getUnitMillis(); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/DelegatedDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/DelegatedDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/DelegatedDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,305 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.io.Serializable; +import java.util.Locale; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; + +/** + * DelegatedDateTimeField delegates each method call to the + * date time field it wraps. + *

+ * DelegatedDateTimeField is thread-safe and immutable, and its subclasses must + * be as well. + * + * @author Brian S O'Neill + * @since 1.0 + * @see DecoratedDateTimeField + */ +public class DelegatedDateTimeField extends DateTimeField implements Serializable { + + /** Serialization version */ + private static final long serialVersionUID = -4730164440214502503L; + + /** The DateTimeField being wrapped */ + private final DateTimeField iField; + /** The override field type */ + private final DateTimeFieldType iType; + + /** + * Constructor. + * + * @param field the field being decorated + */ + protected DelegatedDateTimeField(DateTimeField field) { + this(field, null); + } + + /** + * Constructor. + * + * @param field the field being decorated + * @param type the field type override + */ + protected DelegatedDateTimeField(DateTimeField field, DateTimeFieldType type) { + super(); + if (field == null) { + throw new IllegalArgumentException("The field must not be null"); + } + iField = field; + iType = (type == null ? field.getType() : type); + } + + /** + * Gets the wrapped date time field. + * + * @return the wrapped DateTimeField + */ + public final DateTimeField getWrappedField() { + return iField; + } + + public DateTimeFieldType getType() { + return iType; + } + + public String getName() { + return iType.getName(); + } + + public boolean isSupported() { + return iField.isSupported(); + } + + public boolean isLenient() { + return iField.isLenient(); + } + + public int get(long instant) { + return iField.get(instant); + } + + public String getAsText(long instant, Locale locale) { + return iField.getAsText(instant, locale); + } + + public String getAsText(long instant) { + return iField.getAsText(instant); + } + + public String getAsText(ReadablePartial partial, int fieldValue, Locale locale) { + return iField.getAsText(partial, fieldValue, locale); + } + + public String getAsText(ReadablePartial partial, Locale locale) { + return iField.getAsText(partial, locale); + } + + public String getAsShortText(long instant, Locale locale) { + return iField.getAsShortText(instant, locale); + } + + public String getAsShortText(long instant) { + return iField.getAsShortText(instant); + } + + public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale) { + return iField.getAsShortText(partial, fieldValue, locale); + } + + public String getAsShortText(ReadablePartial partial, Locale locale) { + return iField.getAsShortText(partial, locale); + } + + public long add(long instant, int value) { + return iField.add(instant, value); + } + + public long add(long instant, long value) { + return iField.add(instant, value); + } + + public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { + return iField.add(instant, fieldIndex, values, valueToAdd); + } + + public long addWrapField(long instant, int value) { + return iField.addWrapField(instant, value); + } + + public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { + return iField.addWrapField(instant, fieldIndex, values, valueToAdd); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return iField.getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + public long set(long instant, int value) { + return iField.set(instant, value); + } + + public long set(long instant, String text, Locale locale) { + return iField.set(instant, text, locale); + } + + public long set(long instant, String text) { + return iField.set(instant, text); + } + + public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue) { + return iField.set(instant, fieldIndex, values, newValue); + } + + public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale) { + return iField.set(instant, fieldIndex, values, text, locale); + } + + public DurationField getDurationField() { + return iField.getDurationField(); + } + + public DurationField getRangeDurationField() { + return iField.getRangeDurationField(); + } + + public boolean isLeap(long instant) { + return iField.isLeap(instant); + } + + public int getLeapAmount(long instant) { + return iField.getLeapAmount(instant); + } + + public DurationField getLeapDurationField() { + return iField.getLeapDurationField(); + } + + public int getMinimumValue() { + return iField.getMinimumValue(); + } + + public int getMinimumValue(long instant) { + return iField.getMinimumValue(instant); + } + + public int getMinimumValue(ReadablePartial instant) { + return iField.getMinimumValue(instant); + } + + public int getMinimumValue(ReadablePartial instant, int[] values) { + return iField.getMinimumValue(instant, values); + } + + public int getMaximumValue() { + return iField.getMaximumValue(); + } + + public int getMaximumValue(long instant) { + return iField.getMaximumValue(instant); + } + + public int getMaximumValue(ReadablePartial instant) { + return iField.getMaximumValue(instant); + } + + public int getMaximumValue(ReadablePartial instant, int[] values) { + return iField.getMaximumValue(instant, values); + } + + public int getMaximumTextLength(Locale locale) { + return iField.getMaximumTextLength(locale); + } + + public int getMaximumShortTextLength(Locale locale) { + return iField.getMaximumShortTextLength(locale); + } + + public long roundFloor(long instant) { + return iField.roundFloor(instant); + } + + public long roundCeiling(long instant) { + return iField.roundCeiling(instant); + } + + public long roundHalfFloor(long instant) { + return iField.roundHalfFloor(instant); + } + + public long roundHalfCeiling(long instant) { + return iField.roundHalfCeiling(instant); + } + + public long roundHalfEven(long instant) { + return iField.roundHalfEven(instant); + } + + public long remainder(long instant) { + return iField.remainder(instant); + } + + public String toString() { + return ("DateTimeField[" + getName() + ']'); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/DelegatedDurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/DelegatedDurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/DelegatedDurationField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,194 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.io.Serializable; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; + +/** + * DelegatedDurationField delegates each method call to the + * duration field it wraps. + *

+ * DelegatedDurationField is thread-safe and immutable, and its subclasses must + * be as well. + * + * @author Brian S O'Neill + * @see DecoratedDurationField + */ +public class DelegatedDurationField extends DurationField implements Serializable { + + /** Serialization lock. */ + private static final long serialVersionUID = -5576443481242007829L; + + /** The DurationField being wrapped */ + private final DurationField iField; + /** The field type */ + private final DurationFieldType iType; + + /** + * Constructor. + * + * @param field the base field + */ + protected DelegatedDurationField(DurationField field) { + this(field, null); + } + + /** + * Constructor. + * + * @param field the base field + * @param type the field type to use + */ + protected DelegatedDurationField(DurationField field, DurationFieldType type) { + super(); + if (field == null) { + throw new IllegalArgumentException("The field must not be null"); + } + iField = field; + iType = (type == null ? field.getType() : type); + } + + //----------------------------------------------------------------------- + /** + * Gets the wrapped duration field. + * + * @return the wrapped DurationField + */ + public final DurationField getWrappedField() { + return iField; + } + + public DurationFieldType getType() { + return iType; + } + + public String getName() { + return iType.getName(); + } + + /** + * Returns true if this field is supported. + */ + public boolean isSupported() { + return iField.isSupported(); + } + + public boolean isPrecise() { + return iField.isPrecise(); + } + + public int getValue(long duration) { + return iField.getValue(duration); + } + + public long getValueAsLong(long duration) { + return iField.getValueAsLong(duration); + } + + public int getValue(long duration, long instant) { + return iField.getValue(duration, instant); + } + + public long getValueAsLong(long duration, long instant) { + return iField.getValueAsLong(duration, instant); + } + + public long getMillis(int value) { + return iField.getMillis(value); + } + + public long getMillis(long value) { + return iField.getMillis(value); + } + + public long getMillis(int value, long instant) { + return iField.getMillis(value, instant); + } + + public long getMillis(long value, long instant) { + return iField.getMillis(value, instant); + } + + public long add(long instant, int value) { + return iField.add(instant, value); + } + + public long add(long instant, long value) { + return iField.add(instant, value); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return iField.getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + public long getUnitMillis() { + return iField.getUnitMillis(); + } + + public int compareTo(Object durationField) { + return iField.compareTo(durationField); + } + + public String toString() { + return (iType == null) ? iField.toString() : + ("DurationField[" + iType + ']'); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/DividedDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/DividedDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/DividedDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,267 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; + +/** + * Divides a DateTimeField such that the retrieved values are reduced by a + * fixed divisor. The field's unit duration is scaled accordingly, but the + * range duration is unchanged. + *

+ * DividedDateTimeField is thread-safe and immutable. + * + * @see RemainderDateTimeField + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public class DividedDateTimeField extends DecoratedDateTimeField { + + private static final long serialVersionUID = 8318475124230605365L; + + // Shared with RemainderDateTimeField. + final int iDivisor; + final DurationField iDurationField; + + private final int iMin; + private final int iMax; + + /** + * Constructor. + * + * @param field the field to wrap, like "year()". + * @param type the field type this field will actually use + * @param divisor divisor, such as 100 years in a century + * @throws IllegalArgumentException if divisor is less than two + */ + public DividedDateTimeField(DateTimeField field, + DateTimeFieldType type, int divisor) { + super(field, type); + + if (divisor < 2) { + throw new IllegalArgumentException("The divisor must be at least 2"); + } + + DurationField unitField = field.getDurationField(); + if (unitField == null) { + iDurationField = null; + } else { + iDurationField = new ScaledDurationField( + unitField, type.getDurationType(), divisor); + } + + iDivisor = divisor; + + int i = field.getMinimumValue(); + int min = (i >= 0) ? i / divisor : ((i + 1) / divisor - 1); + + int j = field.getMaximumValue(); + int max = (j >= 0) ? j / divisor : ((j + 1) / divisor - 1); + + iMin = min; + iMax = max; + } + + /** + * Construct a DividedDateTimeField that compliments the given + * RemainderDateTimeField. + * + * @param remainderField complimentary remainder field, like "yearOfCentury()". + * @param type the field type this field will actually use + */ + public DividedDateTimeField(RemainderDateTimeField remainderField, DateTimeFieldType type) { + super(remainderField.getWrappedField(), type); + int divisor = iDivisor = remainderField.iDivisor; + iDurationField = remainderField.iRangeField; + + DateTimeField field = getWrappedField(); + int i = field.getMinimumValue(); + int min = (i >= 0) ? i / divisor : ((i + 1) / divisor - 1); + + int j = field.getMaximumValue(); + int max = (j >= 0) ? j / divisor : ((j + 1) / divisor - 1); + + iMin = min; + iMax = max; + } + + /** + * Get the amount of scaled units from the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the amount of scaled units extracted from the input. + */ + public int get(long instant) { + int value = getWrappedField().get(instant); + if (value >= 0) { + return value / iDivisor; + } else { + return ((value + 1) / iDivisor) - 1; + } + } + + /** + * Add the specified amount of scaled units to the specified time + * instant. The amount added may be negative. + * + * @param instant the time instant in millis to update. + * @param amount the amount of scaled units to add (can be negative). + * @return the updated time instant. + */ + public long add(long instant, int amount) { + return getWrappedField().add(instant, amount * iDivisor); + } + + /** + * Add the specified amount of scaled units to the specified time + * instant. The amount added may be negative. + * + * @param instant the time instant in millis to update. + * @param amount the amount of scaled units to add (can be negative). + * @return the updated time instant. + */ + public long add(long instant, long amount) { + return getWrappedField().add(instant, amount * iDivisor); + } + + /** + * Add to the scaled component of the specified time instant, + * wrapping around within that component if necessary. + * + * @param instant the time instant in millis to update. + * @param amount the amount of scaled units to add (can be negative). + * @return the updated time instant. + */ + public long addWrapField(long instant, int amount) { + return set(instant, FieldUtils.getWrappedValue(get(instant), amount, iMin, iMax)); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifference(minuendInstant, subtrahendInstant) / iDivisor; + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant) / iDivisor; + } + + /** + * Set the specified amount of scaled units to the specified time instant. + * + * @param instant the time instant in millis to update. + * @param value value of scaled units to set. + * @return the updated time instant. + * @throws IllegalArgumentException if value is too large or too small. + */ + public long set(long instant, int value) { + FieldUtils.verifyValueBounds(this, value, iMin, iMax); + int remainder = getRemainder(getWrappedField().get(instant)); + return getWrappedField().set(instant, value * iDivisor + remainder); + } + + /** + * Returns a scaled version of the wrapped field's unit duration field. + */ + public DurationField getDurationField() { + return iDurationField; + } + + /** + * Get the minimum value for the field. + * + * @return the minimum value + */ + public int getMinimumValue() { + return iMin; + } + + /** + * Get the maximum value for the field. + * + * @return the maximum value + */ + public int getMaximumValue() { + return iMax; + } + + public long roundFloor(long instant) { + DateTimeField field = getWrappedField(); + return field.roundFloor(field.set(instant, get(instant) * iDivisor)); + } + + public long remainder(long instant) { + return set(instant, get(getWrappedField().remainder(instant))); + } + + /** + * Returns the divisor applied, in the field's units. + * + * @return the divisor + */ + public int getDivisor() { + return iDivisor; + } + + private int getRemainder(int value) { + if (value >= 0) { + return value % iDivisor; + } else { + return (iDivisor - 1) + ((value + 1) % iDivisor); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/FieldUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/FieldUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/FieldUtils.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,269 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; + +/** + * General utilities that don't fit elsewhere. + *

+ * FieldUtils is thread-safe and immutable. + * + * @author Stephen Colebourne + * @since 1.0 + */ +public class FieldUtils { + + /** + * Restricted constructor. + */ + private FieldUtils() { + super(); + } + + //------------------------------------------------------------------------ + /** + * Add two values throwing an exception if overflow occurs. + * + * @param val1 the first value + * @param val2 the second value + * @return the new total + */ + public static int safeAdd(int val1, int val2) { + long total = ((long) val1) + ((long) val2); + if (total < Integer.MIN_VALUE || total > Integer.MAX_VALUE) { + throw new ArithmeticException("The calculation caused an overflow: " + val1 +" + " + val2); + } + return (int) total; + } + + /** + * Add two values throwing an exception if overflow occurs. + * + * @param val1 the first value + * @param val2 the second value + * @return the new total + */ + public static long safeAdd(long val1, long val2) { + long total = val1 + val2; + if (val1 > 0 && val2 > 0 && total < 0) { + throw new ArithmeticException("The calculation caused an overflow: " + val1 +" + " + val2); + } + if (val1 < 0 && val2 < 0 && total > 0) { + throw new ArithmeticException("The calculation caused an overflow: " + val1 +" + " + val2); + } + return total; + } + + /** + * Subtracts two values throwing an exception if overflow occurs. + * + * @param val1 the first value, to be taken away from + * @param val2 the second value, the amount to take away + * @return the new total + */ + public static long safeSubtract(long val1, long val2) { + if (val2 == Long.MIN_VALUE) { + if (val1 <= 0L) { + return (val1 - val2); + } + throw new ArithmeticException("The calculation caused an overflow: " + val1 +" - " + val2); + } + return safeAdd(val1, -val2); + } + + /** + * Multiply two values throwing an exception if overflow occurs. + * + * @param val1 the first value + * @param val2 the second value + * @return the new total + */ + public static long safeMultiply(long val1, long val2) { + if (val1 == 0 || val2 == 0) { + return 0L; + } + long total = val1 * val2; + if (total / val2 != val1) { + throw new ArithmeticException("The calculation caused an overflow: " + val1 +" * " + val2); + } + return total; + } + + /** + * Casts to an int throwing an exception if overflow occurs. + * + * @param value the value + * @return the value as an int + */ + public static int safeToInt(long value) { + if (Integer.MIN_VALUE <= value && value <= Integer.MAX_VALUE) { + return (int) value; + } + throw new ArithmeticException("Value cannot fit in an int: " + value); + } + + /** + * Multiply two values to return an int throwing an exception if overflow occurs. + * + * @param val1 the first value + * @param val2 the second value + * @return the new total + */ + public static int safeMultiplyToInt(long val1, long val2) { + long val = FieldUtils.safeMultiply(val1, val2); + return FieldUtils.safeToInt(val); + } + + /** + * Verify that input values are within specified bounds. + * + * @param value the value to check + * @param lowerBound the lower bound allowed for value + * @param upperBound the upper bound allowed for value + * @throws IllegalArgumentException if value is not in the specified bounds + */ + public static void verifyValueBounds(DateTimeField field, + int value, int lowerBound, int upperBound) { + if ((value < lowerBound) || (value > upperBound)) { + throw new IllegalArgumentException( + "Value " + + value + + " for " + + field.getName() + + " must be in the range [" + + lowerBound + + ',' + + upperBound + + ']'); + } + } + + /** + * Verify that input values are within specified bounds. + * + * @param value the value to check + * @param lowerBound the lower bound allowed for value + * @param upperBound the upper bound allowed for value + * @throws IllegalArgumentException if value is not in the specified bounds + */ + public static void verifyValueBounds(String fieldName, + int value, int lowerBound, int upperBound) { + if ((value < lowerBound) || (value > upperBound)) { + throw new IllegalArgumentException( + "Value " + + value + + " for " + + fieldName + + " must be in the range [" + + lowerBound + + ',' + + upperBound + + ']'); + } + } + + /** + * Utility method used by addWrapField implementations to ensure the new + * value lies within the field's legal value range. + * + * @param currentValue the current value of the data, which may lie outside + * the wrapped value range + * @param wrapValue the value to add to current value before + * wrapping. This may be negative. + * @param minValue the wrap range minimum value. + * @param maxValue the wrap range maximum value. This must be + * greater than minValue (checked by the method). + * @return the wrapped value + * @throws IllegalArgumentException if minValue is greater + * than or equal to maxValue + */ + public static int getWrappedValue(int currentValue, int wrapValue, + int minValue, int maxValue) { + return getWrappedValue(currentValue + wrapValue, minValue, maxValue); + } + + /** + * Utility method that ensures the given value lies within the field's + * legal value range. + * + * @param value the value to fit into the wrapped value range + * @param minValue the wrap range minimum value. + * @param maxValue the wrap range maximum value. This must be + * greater than minValue (checked by the method). + * @return the wrapped value + * @throws IllegalArgumentException if minValue is greater + * than or equal to maxValue + */ + public static int getWrappedValue(int value, int minValue, int maxValue) { + if (minValue >= maxValue) { + throw new IllegalArgumentException("MIN > MAX"); + } + + int wrapRange = maxValue - minValue + 1; + value -= minValue; + + if (value >= 0) { + return (value % wrapRange) + minValue; + } + + int remByRange = (-value) % wrapRange; + + if (remByRange == 0) { + return 0 + minValue; + } + return (wrapRange - remByRange) + minValue; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/ImpreciseDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/ImpreciseDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/ImpreciseDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,237 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; + +/** + * Abstract datetime field class that defines its own DurationField, which + * delegates back into this ImpreciseDateTimeField. + *

+ * This DateTimeField is useful for defining DateTimeFields that are composed + * of imprecise durations. If both duration fields are precise, then a + * {@link PreciseDateTimeField} should be used instead. + *

+ * When defining imprecise DateTimeFields where a matching DurationField is + * already available, just extend BaseDateTimeField directly so as not to + * create redundant DurationField instances. + *

+ * ImpreciseDateTimeField is thread-safe and immutable, and its subclasses must + * be as well. + * + * @author Brian S O'Neill + * @see PreciseDateTimeField + */ +public abstract class ImpreciseDateTimeField extends BaseDateTimeField { + + private static final long serialVersionUID = 7190739608550251860L; + + final long iUnitMillis; + private final DurationField iDurationField; + + /** + * Constructor. + * + * @param type the field type + * @param unitMillis the average duration unit milliseconds + */ + public ImpreciseDateTimeField(DateTimeFieldType type, long unitMillis) { + super(type); + iUnitMillis = unitMillis; + iDurationField = new LinkedDurationField(type.getDurationType()); + } + + public abstract int get(long instant); + + public abstract long set(long instant, int value); + + public abstract long add(long instant, int value); + + public abstract long add(long instant, long value); + + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *

+     * long instant = ...
+     * int v = ...
+     * int age = getDifference(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + *

+ * The default implementation call getDifferenceAsLong and converts the + * return value to an int. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public int getDifference(long minuendInstant, long subtrahendInstant) { + return FieldUtils.safeToInt(getDifferenceAsLong(minuendInstant, subtrahendInstant)); + } + + /** + * Computes the difference between two instants, as measured in the units + * of this field. Any fractional units are dropped from the result. Calling + * getDifference reverses the effect of calling add. In the following code: + * + *

+     * long instant = ...
+     * long v = ...
+     * long age = getDifferenceAsLong(add(instant, v), instant);
+     * 
+ * + * The value 'age' is the same as the value 'v'. + *

+ * The default implementation performs a guess-and-check algorithm using + * getDurationField().getUnitMillis() and the add() method. Subclasses are + * encouraged to provide a more efficient implementation. + * + * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract from + * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to + * subtract off the minuend + * @return the difference in the units of this field + */ + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + if (minuendInstant < subtrahendInstant) { + return -getDifferenceAsLong(subtrahendInstant, minuendInstant); + } + + long difference = (minuendInstant - subtrahendInstant) / iUnitMillis; + if (add(subtrahendInstant, difference) < minuendInstant) { + do { + difference++; + } while (add(subtrahendInstant, difference) <= minuendInstant); + difference--; + } else if (add(subtrahendInstant, difference) > minuendInstant) { + do { + difference--; + } while (add(subtrahendInstant, difference) > minuendInstant); + } + return difference; + } + + public final DurationField getDurationField() { + return iDurationField; + } + + public abstract DurationField getRangeDurationField(); + + public abstract long roundFloor(long instant); + + protected final long getDurationUnitMillis() { + return iUnitMillis; + } + + private final class LinkedDurationField extends BaseDurationField { + private static final long serialVersionUID = -203813474600094134L; + + LinkedDurationField(DurationFieldType type) { + super(type); + } + + public boolean isPrecise() { + return false; + } + + public long getUnitMillis() { + return iUnitMillis; + } + + public int getValue(long duration, long instant) { + return ImpreciseDateTimeField.this + .getDifference(instant + duration, instant); + } + + public long getValueAsLong(long duration, long instant) { + return ImpreciseDateTimeField.this + .getDifferenceAsLong(instant + duration, instant); + } + + public long getMillis(int value, long instant) { + return ImpreciseDateTimeField.this.add(instant, value) - instant; + } + + public long getMillis(long value, long instant) { + return ImpreciseDateTimeField.this.add(instant, value) - instant; + } + + public long add(long instant, int value) { + return ImpreciseDateTimeField.this.add(instant, value); + } + + public long add(long instant, long value) { + return ImpreciseDateTimeField.this.add(instant, value); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return ImpreciseDateTimeField.this + .getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return ImpreciseDateTimeField.this + .getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/LenientDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/LenientDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/LenientDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; + +/** + * Converts a strict DateTimeField into a lenient one. By being lenient, the + * set method accepts out of bounds values, performing an addition instead. + *

+ * LenientDateTimeField is thread-safe and immutable. + * + * @author Brian S O'Neill + * @see org.joda.time.chrono.LenientChronology + * @see StrictDateTimeField + */ +public class LenientDateTimeField extends DelegatedDateTimeField { + + private static final long serialVersionUID = 8714085824173290599L; + + /** + * Returns a lenient version of the given field. If it is already lenient, + * then it is returned as-is. Otherwise, a new LenientDateTimeField is + * returned. + */ + public static DateTimeField getInstance(DateTimeField field) { + if (field == null) { + return null; + } + if (field instanceof StrictDateTimeField) { + field = ((StrictDateTimeField)field).getWrappedField(); + } + if (field.isLenient()) { + return field; + } + return new LenientDateTimeField(field); + } + + protected LenientDateTimeField(DateTimeField field) { + super(field); + } + + public final boolean isLenient() { + return true; + } + + /** + * Set values which may be out of bounds. If the value is out of bounds, + * the instant is first set to the minimum allowed value, and then the + * difference is added. + */ + public long set(long instant, int value) { + int min = getMinimumValue(instant); + if (value >= min && value < getMaximumValue(instant)) { + return super.set(instant, value); + } + return add(super.set(instant, min), value - min); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/field/MillisDurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/MillisDurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/MillisDurationField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,201 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.io.Serializable; + +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; + +/** + * Duration field class representing a field with a fixed unit length of one + * millisecond. + *

+ * MillisDurationField is thread-safe and immutable. + * + * @author Brian S O'Neill + */ +public final class MillisDurationField extends DurationField implements Serializable { + + /** Serialization lock. */ + private static final long serialVersionUID = 2656707858124633367L; + + /** Singleton instance. */ + public static final DurationField INSTANCE = new MillisDurationField(); + + /** + * Restricted constructor. + */ + private MillisDurationField() { + super(); + } + + //------------------------------------------------------------------------ + public DurationFieldType getType() { + return DurationFieldType.millis(); + } + + public String getName() { + return "millis"; + } + + /** + * Returns true as this field is supported. + * + * @return true always + */ + public boolean isSupported() { + return true; + } + + /** + * Returns true as this field is precise. + * + * @return true always + */ + public final boolean isPrecise() { + return true; + } + + /** + * Returns the amount of milliseconds per unit value of this field. + * + * @return one always + */ + public final long getUnitMillis() { + return 1; + } + + //------------------------------------------------------------------------ + public int getValue(long duration) { + return FieldUtils.safeToInt(duration); + } + + public long getValueAsLong(long duration) { + return duration; + } + + public int getValue(long duration, long instant) { + return FieldUtils.safeToInt(duration); + } + + public long getValueAsLong(long duration, long instant) { + return duration; + } + + public long getMillis(int value) { + return value; + } + + public long getMillis(long value) { + return value; + } + + public long getMillis(int value, long instant) { + return value; + } + + public long getMillis(long value, long instant) { + return value; + } + + public long add(long instant, int value) { + return FieldUtils.safeAdd(instant, value); + } + + public long add(long instant, long value) { + return FieldUtils.safeAdd(instant, value); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return FieldUtils.safeToInt(FieldUtils.safeSubtract(minuendInstant, subtrahendInstant)); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return FieldUtils.safeSubtract(minuendInstant, subtrahendInstant); + } + + //------------------------------------------------------------------------ + public int compareTo(Object durationField) { + DurationField otherField = (DurationField) durationField; + long otherMillis = otherField.getUnitMillis(); + long thisMillis = getUnitMillis(); + // cannot do (thisMillis - otherMillis) as can overflow + if (thisMillis == otherMillis) { + return 0; + } + if (thisMillis < otherMillis) { + return -1; + } else { + return 1; + } + } + + /** + * Get a suitable debug string. + * + * @return debug string + */ + public String toString() { + return "DurationField[millis]"; + } + + /** + * Deserialize to the singleton. + */ + private Object readResolve() { + return INSTANCE; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/NonZeroDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/Attic/NonZeroDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/NonZeroDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,242 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; + +/** + * Wraps another field such that zero values are replaced with one more than + * it's maximum. This is particularly useful for implementing an clockhourOfDay + * field, where the midnight value of 0 is replaced with 24. + *

+ * NonZeroDateTimeField is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public final class NonZeroDateTimeField extends DecoratedDateTimeField { + + private static final long serialVersionUID = 961749798233026866L; + + /** + * Constructor. + * + * @param field the base field + * @param type the field type this field will actually use + * @throws IllegalArgumentException if wrapped field's minimum value is not zero + */ + public NonZeroDateTimeField(DateTimeField field, DateTimeFieldType type) { + super(field, type); + if (field.getMinimumValue() != 0) { + throw new IllegalArgumentException("Wrapped field's minumum value must be zero"); + } + } + + public int get(long instant) { + int value = getWrappedField().get(instant); + if (value == 0) { + value = getMaximumValue(); + } + return value; + } + + public long add(long instant, int value) { + return getWrappedField().add(instant, value); + } + + public long add(long instant, long value) { + return getWrappedField().add(instant, value); + } + + public long addWrapField(long instant, int value) { + return getWrappedField().addWrapField(instant, value); + } + + public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { + return getWrappedField().addWrapField(instant, fieldIndex, values, valueToAdd); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifference(minuendInstant, subtrahendInstant); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + public long set(long instant, int value) { + int max = getMaximumValue(); + FieldUtils.verifyValueBounds(this, value, 1, max); + if (value == max) { + value = 0; + } + return getWrappedField().set(instant, value); + } + + public boolean isLeap(long instant) { + return getWrappedField().isLeap(instant); + } + + public int getLeapAmount(long instant) { + return getWrappedField().getLeapAmount(instant); + } + + public DurationField getLeapDurationField() { + return getWrappedField().getLeapDurationField(); + } + + /** + * Always returns 1. + * + * @return the minimum value of 1 + */ + public int getMinimumValue() { + return 1; + } + + /** + * Always returns 1. + * + * @return the minimum value of 1 + */ + public int getMinimumValue(long instant) { + return 1; + } + + /** + * Always returns 1. + * + * @return the minimum value of 1 + */ + public int getMinimumValue(ReadablePartial instant) { + return 1; + } + + /** + * Always returns 1. + * + * @return the minimum value of 1 + */ + public int getMinimumValue(ReadablePartial instant, int[] values) { + return 1; + } + + /** + * Get the maximum value for the field, which is one more than the wrapped + * field's maximum value. + * + * @return the maximum value + */ + public int getMaximumValue() { + return getWrappedField().getMaximumValue() + 1; + } + + /** + * Get the maximum value for the field, which is one more than the wrapped + * field's maximum value. + * + * @return the maximum value + */ + public int getMaximumValue(long instant) { + return getWrappedField().getMaximumValue(instant) + 1; + } + + /** + * Get the maximum value for the field, which is one more than the wrapped + * field's maximum value. + * + * @return the maximum value + */ + public int getMaximumValue(ReadablePartial instant) { + return getWrappedField().getMaximumValue(instant) + 1; + } + + /** + * Get the maximum value for the field, which is one more than the wrapped + * field's maximum value. + * + * @return the maximum value + */ + public int getMaximumValue(ReadablePartial instant, int[] values) { + return getWrappedField().getMaximumValue(instant, values) + 1; + } + + public long roundFloor(long instant) { + return getWrappedField().roundFloor(instant); + } + + public long roundCeiling(long instant) { + return getWrappedField().roundCeiling(instant); + } + + public long roundHalfFloor(long instant) { + return getWrappedField().roundHalfFloor(instant); + } + + public long roundHalfCeiling(long instant) { + return getWrappedField().roundHalfCeiling(instant); + } + + public long roundHalfEven(long instant) { + return getWrappedField().roundHalfEven(instant); + } + + public long remainder(long instant) { + return getWrappedField().remainder(instant); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/OffsetDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/OffsetDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/OffsetDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,256 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; + +/** + * Generic offset adjusting datetime field. + *

+ * OffsetDateTimeField is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public class OffsetDateTimeField extends DecoratedDateTimeField { + private static final long serialVersionUID = 3145790132623583142L; + + private final int iOffset; + + private final int iMin; + private final int iMax; + + /** + * Constructor. + * + * @param field the field to wrap, like "year()". + * @param offset offset to add to field values + * @throws IllegalArgumentException if offset is zero + */ + public OffsetDateTimeField(DateTimeField field, int offset) { + this(field, (field == null ? null : field.getType()), offset, Integer.MIN_VALUE, Integer.MAX_VALUE); + } + + /** + * Constructor. + * + * @param field the field to wrap, like "year()". + * @param type the field type this field actually uses + * @param offset offset to add to field values + * @throws IllegalArgumentException if offset is zero + */ + public OffsetDateTimeField(DateTimeField field, DateTimeFieldType type, int offset) { + this(field, type, offset, Integer.MIN_VALUE, Integer.MAX_VALUE); + } + + /** + * Constructor. + * + * @param field the field to wrap, like "year()". + * @param type the field type this field actually uses + * @param offset offset to add to field values + * @param minValue minimum allowed value + * @param maxValue maximum allowed value + * @throws IllegalArgumentException if offset is zero + */ + public OffsetDateTimeField(DateTimeField field, DateTimeFieldType type, int offset, + int minValue, int maxValue) { + super(field, type); + + if (offset == 0) { + throw new IllegalArgumentException("The offset cannot be zero"); + } + + iOffset = offset; + + if (minValue < (field.getMinimumValue() + offset)) { + iMin = field.getMinimumValue() + offset; + } else { + iMin = minValue; + } + if (maxValue > (field.getMaximumValue() + offset)) { + iMax = field.getMaximumValue() + offset; + } else { + iMax = maxValue; + } + } + + /** + * Get the amount of offset units from the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the amount of units extracted from the input. + */ + public int get(long instant) { + return super.get(instant) + iOffset; + } + + /** + * Add the specified amount of offset units to the specified time + * instant. The amount added may be negative. + * + * @param instant the time instant in millis to update. + * @param amount the amount of units to add (can be negative). + * @return the updated time instant. + */ + public long add(long instant, int amount) { + instant = super.add(instant, amount); + FieldUtils.verifyValueBounds(this, get(instant), iMin, iMax); + return instant; + } + + /** + * Add the specified amount of offset units to the specified time + * instant. The amount added may be negative. + * + * @param instant the time instant in millis to update. + * @param amount the amount of units to add (can be negative). + * @return the updated time instant. + */ + public long add(long instant, long amount) { + instant = super.add(instant, amount); + FieldUtils.verifyValueBounds(this, get(instant), iMin, iMax); + return instant; + } + + /** + * Add to the offset component of the specified time instant, + * wrapping around within that component if necessary. + * + * @param instant the time instant in millis to update. + * @param amount the amount of units to add (can be negative). + * @return the updated time instant. + */ + public long addWrapField(long instant, int amount) { + return set(instant, FieldUtils.getWrappedValue(get(instant), amount, iMin, iMax)); + } + + /** + * Set the specified amount of offset units to the specified time instant. + * + * @param instant the time instant in millis to update. + * @param value value of units to set. + * @return the updated time instant. + * @throws IllegalArgumentException if value is too large or too small. + */ + public long set(long instant, int value) { + FieldUtils.verifyValueBounds(this, value, iMin, iMax); + return super.set(instant, value - iOffset); + } + + public boolean isLeap(long instant) { + return getWrappedField().isLeap(instant); + } + + public int getLeapAmount(long instant) { + return getWrappedField().getLeapAmount(instant); + } + + public DurationField getLeapDurationField() { + return getWrappedField().getLeapDurationField(); + } + + /** + * Get the minimum value for the field. + * + * @return the minimum value + */ + public int getMinimumValue() { + return iMin; + } + + /** + * Get the maximum value for the field. + * + * @return the maximum value + */ + public int getMaximumValue() { + return iMax; + } + + public long roundFloor(long instant) { + return getWrappedField().roundFloor(instant); + } + + public long roundCeiling(long instant) { + return getWrappedField().roundCeiling(instant); + } + + public long roundHalfFloor(long instant) { + return getWrappedField().roundHalfFloor(instant); + } + + public long roundHalfCeiling(long instant) { + return getWrappedField().roundHalfCeiling(instant); + } + + public long roundHalfEven(long instant) { + return getWrappedField().roundHalfEven(instant); + } + + public long remainder(long instant) { + return getWrappedField().remainder(instant); + } + + /** + * Returns the offset added to the field values. + * + * @return the offset + */ + public int getOffset() { + return iOffset; + } +} Index: 3rdParty_sources/joda-time/org/joda/time/field/PreciseDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/PreciseDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/PreciseDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,184 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; + +/** + * Precise datetime field, composed of two precise duration fields. + *

+ * This DateTimeField is useful for defining DateTimeFields that are composed + * of precise durations, like time of day fields. If either duration field is + * imprecise, then an {@link ImpreciseDateTimeField} may be used instead. + *

+ * PreciseDateTimeField is thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + * @see ImpreciseDateTimeField + */ +public class PreciseDateTimeField extends PreciseDurationDateTimeField { + + private static final long serialVersionUID = -5586801265774496376L; + + /** The maximum range in the correct units */ + private final int iRange; + + private final DurationField iRangeField; + + /** + * Constructor. + * + * @param type the field type this field uses + * @param unit precise unit duration, like "seconds()". + * @param range precise range duration, preferably a multiple of the unit, + * like "minutes()". + * @throws IllegalArgumentException if either duration field is imprecise + * @throws IllegalArgumentException if unit milliseconds is less than one + * or effective value range is less than two. + */ + public PreciseDateTimeField(DateTimeFieldType type, + DurationField unit, DurationField range) { + super(type, unit); + + if (!range.isPrecise()) { + throw new IllegalArgumentException("Range duration field must be precise"); + } + + long rangeMillis = range.getUnitMillis(); + iRange = (int)(rangeMillis / getUnitMillis()); + if (iRange < 2) { + throw new IllegalArgumentException("The effective range must be at least 2"); + } + + iRangeField = range; + } + + /** + * Get the amount of fractional units from the specified time instant. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to query + * @return the amount of fractional units extracted from the input. + */ + public int get(long instant) { + if (instant >= 0) { + return (int) ((instant / getUnitMillis()) % iRange); + } else { + return iRange - 1 + (int) (((instant + 1) / getUnitMillis()) % iRange); + } + } + + /** + * Add to the component of the specified time instant, wrapping around + * within that component if necessary. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to + * @param amount the amount of units to add (can be negative). + * @return the updated time instant. + */ + public long addWrapField(long instant, int amount) { + int thisValue = get(instant); + int wrappedValue = FieldUtils.getWrappedValue + (thisValue, amount, getMinimumValue(), getMaximumValue()); + // copy code from set() to avoid repeat call to get() + return instant + (wrappedValue - thisValue) * getUnitMillis(); + } + + /** + * Set the specified amount of units to the specified time instant. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param value value of units to set. + * @return the updated time instant. + * @throws IllegalArgumentException if value is too large or too small. + */ + public long set(long instant, int value) { + FieldUtils.verifyValueBounds(this, value, getMinimumValue(), getMaximumValue()); + return instant + (value - get(instant)) * iUnitMillis; + } + + /** + * Returns the range duration of this field. For example, if this field + * represents "minute of hour", then the range duration field is an hours. + * + * @return the range duration of this field, or null if field has no range + */ + public DurationField getRangeDurationField() { + return iRangeField; + } + + /** + * Get the maximum value for the field. + * + * @return the maximum value + */ + public int getMaximumValue() { + return iRange - 1; + } + + /** + * Returns the range of the field in the field's units. + *

+ * For example, 60 for seconds per minute. The field is allowed values + * from 0 to range - 1. + * + * @return unit range + */ + public int getRange() { + return iRange; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/PreciseDurationDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/PreciseDurationDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/PreciseDurationDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,203 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; + +/** + * Precise datetime field, which has a precise unit duration field. + *

+ * PreciseDurationDateTimeField is thread-safe and immutable, and its + * subclasses must be as well. + * + * @author Brian S O'Neill + */ +public abstract class PreciseDurationDateTimeField extends BaseDateTimeField { + + private static final long serialVersionUID = 5004523158306266035L; + + /** The fractional unit in millis */ + final long iUnitMillis; + + private final DurationField iUnitField; + + /** + * Constructor. + * + * @param type the field type + * @param unit precise unit duration, like "days()". + * @throws IllegalArgumentException if duration field is imprecise + * @throws IllegalArgumentException if unit milliseconds is less than one + */ + public PreciseDurationDateTimeField(DateTimeFieldType type, DurationField unit) { + super(type); + + if (!unit.isPrecise()) { + throw new IllegalArgumentException("Unit duration field must be precise"); + } + + iUnitMillis = unit.getUnitMillis(); + if (iUnitMillis < 1) { + throw new IllegalArgumentException("The unit milliseconds must be at least 1"); + } + + iUnitField = unit; + } + + /** + * Returns false by default. + */ + public boolean isLenient() { + return false; + } + + /** + * Set the specified amount of units to the specified time instant. + * + * @param instant the milliseconds from 1970-01-01T00:00:00Z to set in + * @param value value of units to set. + * @return the updated time instant. + * @throws IllegalArgumentException if value is too large or too small. + */ + public long set(long instant, int value) { + FieldUtils.verifyValueBounds(this, value, getMinimumValue(), + getMaximumValueForSet(instant, value)); + return instant + (value - get(instant)) * iUnitMillis; + } + + /** + * This method assumes that this field is properly rounded on + * 1970-01-01T00:00:00. If the rounding alignment differs, override this + * method as follows: + *

+     * return super.roundFloor(instant + ALIGNMENT_MILLIS) - ALIGNMENT_MILLIS;
+     * 
+ */ + public long roundFloor(long instant) { + if (instant >= 0) { + return instant - instant % iUnitMillis; + } else { + instant += 1; + return instant - instant % iUnitMillis - iUnitMillis; + } + } + + /** + * This method assumes that this field is properly rounded on + * 1970-01-01T00:00:00. If the rounding alignment differs, override this + * method as follows: + *
+     * return super.roundCeiling(instant + ALIGNMENT_MILLIS) - ALIGNMENT_MILLIS;
+     * 
+ */ + public long roundCeiling(long instant) { + if (instant > 0) { + instant -= 1; + return instant - instant % iUnitMillis + iUnitMillis; + } else { + return instant - instant % iUnitMillis; + } + } + + /** + * This method assumes that this field is properly rounded on + * 1970-01-01T00:00:00. If the rounding alignment differs, override this + * method as follows: + *
+     * return super.remainder(instant + ALIGNMENT_MILLIS);
+     * 
+ */ + public long remainder(long instant) { + if (instant >= 0) { + return instant % iUnitMillis; + } else { + return (instant + 1) % iUnitMillis + iUnitMillis - 1; + } + } + + /** + * Returns the duration per unit value of this field. For example, if this + * field represents "minute of hour", then the duration field is minutes. + * + * @return the duration of this field, or UnsupportedDurationField if field + * has no duration + */ + public DurationField getDurationField() { + return iUnitField; + } + + /** + * Get the minimum value for the field. + * + * @return the minimum value + */ + public int getMinimumValue() { + return 0; + } + + public final long getUnitMillis() { + return iUnitMillis; + } + + /** + * Called by the set method to get the maximum allowed value. By default, + * returns getMaximumValue(instant). Override to provide a faster + * implementation. + */ + protected int getMaximumValueForSet(long instant, int value) { + return getMaximumValue(instant); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/PreciseDurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/PreciseDurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/PreciseDurationField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,186 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DurationFieldType; + +/** + * Duration field class representing a field with a fixed unit length. + *

+ * PreciseDurationField is thread-safe and immutable. + * + * @author Stephen Colebourne + * @author Brian S O'Neill + * @since 1.0 + */ +public class PreciseDurationField extends BaseDurationField { + + private static final long serialVersionUID = -8346152187724495365L; + + /** The size of the unit */ + private final long iUnitMillis; + + /** + * Constructor. + * + * @param type the field type + * @param unitMillis the unit milliseconds + */ + public PreciseDurationField(DurationFieldType type, long unitMillis) { + super(type); + iUnitMillis = unitMillis; + } + + //------------------------------------------------------------------------ + /** + * This field is precise. + * + * @return true always + */ + public final boolean isPrecise() { + return true; + } + + /** + * Returns the amount of milliseconds per unit value of this field. + * + * @return the unit size of this field, in milliseconds + */ + public final long getUnitMillis() { + return iUnitMillis; + } + + //------------------------------------------------------------------------ + /** + * Get the value of this field from the milliseconds. + * + * @param duration the milliseconds to query, which may be negative + * @param instant ignored + * @return the value of the field, in the units of the field, which may be + * negative + */ + public long getValueAsLong(long duration, long instant) { + return duration / iUnitMillis; // safe + } + + /** + * Get the millisecond duration of this field from its value. + * + * @param value the value of the field, which may be negative + * @param instant ignored + * @return the milliseconds that the field represents, which may be + * negative + */ + public long getMillis(int value, long instant) { + return value * iUnitMillis; // safe + } + + /** + * Get the millisecond duration of this field from its value. + * + * @param value the value of the field, which may be negative + * @param instant ignored + * @return the milliseconds that the field represents, which may be + * negative + */ + public long getMillis(long value, long instant) { + return FieldUtils.safeMultiply(value, iUnitMillis); + } + + public long add(long instant, int value) { + long addition = value * iUnitMillis; // safe + return FieldUtils.safeAdd(instant, addition); + } + + public long add(long instant, long value) { + long addition = FieldUtils.safeMultiply(value, iUnitMillis); + return FieldUtils.safeAdd(instant, addition); + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + long difference = FieldUtils.safeSubtract(minuendInstant, subtrahendInstant); + return difference / iUnitMillis; + } + + //----------------------------------------------------------------------- + /** + * Compares this duration field to another. + * Two fields are equal if of the same type and duration. + * + * @param obj the object to compare to + * @return if equal + */ + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj instanceof PreciseDurationField) { + PreciseDurationField other = (PreciseDurationField) obj; + return (getType() == other.getType()) && (iUnitMillis == other.iUnitMillis); + } + return false; + } + + /** + * Gets a hash code for this instance. + * + * @return a suitable hashcode + */ + public int hashCode() { + long millis = iUnitMillis; + int hash = (int) (millis ^ (millis >>> 32)); + hash += getType().hashCode(); + return hash; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/RemainderDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/RemainderDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/RemainderDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,240 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; + +/** + * Counterpart remainder datetime field to {@link DividedDateTimeField}. The + * field's unit duration is unchanged, but the range duration is scaled + * accordingly. + *

+ * RemainderDateTimeField is thread-safe and immutable. + * + * @see DividedDateTimeField + * + * @author Brian S O'Neill + * @since 1.0 + */ +public class RemainderDateTimeField extends DecoratedDateTimeField { + + private static final long serialVersionUID = 5708241235177666790L; + + // Shared with DividedDateTimeField. + final int iDivisor; + final DurationField iRangeField; + + /** + * Constructor. + * + * @param field the field to wrap, like "year()". + * @param type the field type this field actually uses + * @param divisor divisor, such as 100 years in a century + * @throws IllegalArgumentException if divisor is less than two + */ + public RemainderDateTimeField(DateTimeField field, + DateTimeFieldType type, int divisor) { + super(field, type); + + if (divisor < 2) { + throw new IllegalArgumentException("The divisor must be at least 2"); + } + + DurationField rangeField = field.getDurationField(); + if (rangeField == null) { + iRangeField = null; + } else { + iRangeField = new ScaledDurationField( + rangeField, type.getRangeDurationType(), divisor); + } + + iDivisor = divisor; + } + + /** + * Construct a RemainderDateTimeField that compliments the given + * DividedDateTimeField. + * + * @param dividedField complimentary divided field, like "century()". + */ + public RemainderDateTimeField(DividedDateTimeField dividedField) { + this(dividedField, dividedField.getType()); + } + + /** + * Construct a RemainderDateTimeField that compliments the given + * DividedDateTimeField. + * + * @param dividedField complimentary divided field, like "century()". + * @param type the field type this field actually uses + */ + public RemainderDateTimeField(DividedDateTimeField dividedField, DateTimeFieldType type) { + super(dividedField.getWrappedField(), type); + iDivisor = dividedField.iDivisor; + iRangeField = dividedField.iDurationField; + } + + //----------------------------------------------------------------------- + /** + * Get the remainder from the specified time instant. + * + * @param instant the time instant in millis to query. + * @return the remainder extracted from the input. + */ + public int get(long instant) { + int value = getWrappedField().get(instant); + if (value >= 0) { + return value % iDivisor; + } else { + return (iDivisor - 1) + ((value + 1) % iDivisor); + } + } + + /** + * Add the specified amount to the specified time instant, wrapping around + * within the remainder range if necessary. The amount added may be + * negative. + * + * @param instant the time instant in millis to update. + * @param amount the amount to add (can be negative). + * @return the updated time instant. + */ + public long addWrapField(long instant, int amount) { + return set(instant, FieldUtils.getWrappedValue(get(instant), amount, 0, iDivisor - 1)); + } + + /** + * Set the specified amount of remainder units to the specified time instant. + * + * @param instant the time instant in millis to update. + * @param value value of remainder units to set. + * @return the updated time instant. + * @throws IllegalArgumentException if value is too large or too small. + */ + public long set(long instant, int value) { + FieldUtils.verifyValueBounds(this, value, 0, iDivisor - 1); + int divided = getDivided(getWrappedField().get(instant)); + return getWrappedField().set(instant, divided * iDivisor + value); + } + + /** + * Returns a scaled version of the wrapped field's unit duration field. + */ + public DurationField getRangeDurationField() { + return iRangeField; + } + + /** + * Get the minimum value for the field, which is always zero. + * + * @return the minimum value of zero. + */ + public int getMinimumValue() { + return 0; + } + + /** + * Get the maximum value for the field, which is always one less than the + * divisor. + * + * @return the maximum value + */ + public int getMaximumValue() { + return iDivisor - 1; + } + + public long roundFloor(long instant) { + return getWrappedField().roundFloor(instant); + } + + public long roundCeiling(long instant) { + return getWrappedField().roundCeiling(instant); + } + + public long roundHalfFloor(long instant) { + return getWrappedField().roundHalfFloor(instant); + } + + public long roundHalfCeiling(long instant) { + return getWrappedField().roundHalfCeiling(instant); + } + + public long roundHalfEven(long instant) { + return getWrappedField().roundHalfEven(instant); + } + + public long remainder(long instant) { + return getWrappedField().remainder(instant); + } + + /** + * Returns the divisor applied, in the field's units. + * + * @return the divisor + */ + public int getDivisor() { + return iDivisor; + } + + private int getDivided(int value) { + if (value >= 0) { + return value / iDivisor; + } else { + return ((value + 1) / iDivisor) - 1; + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/ScaledDurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/ScaledDurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/ScaledDurationField.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,191 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; + +/** + * Scales a DurationField such that it's unit millis becomes larger in + * magnitude. + *

+ * ScaledDurationField is thread-safe and immutable. + * + * @see PreciseDurationField + * + * @author Brian S O'Neill + */ +public class ScaledDurationField extends DecoratedDurationField { + + private static final long serialVersionUID = -3205227092378684157L; + + private final int iScalar; + + /** + * Constructor + * + * @param field the field to wrap, like "year()". + * @param type the type this field will actually use + * @param scalar scalar, such as 100 years in a century + * @throws IllegalArgumentException if scalar is zero or one. + */ + public ScaledDurationField(DurationField field, DurationFieldType type, int scalar) { + super(field, type); + if (scalar == 0 || scalar == 1) { + throw new IllegalArgumentException("The scalar must not be 0 or 1"); + } + iScalar = scalar; + } + + public int getValue(long duration) { + return getWrappedField().getValue(duration) / iScalar; + } + + public long getValueAsLong(long duration) { + return getWrappedField().getValueAsLong(duration) / iScalar; + } + + public int getValue(long duration, long instant) { + return getWrappedField().getValue(duration, instant) / iScalar; + } + + public long getValueAsLong(long duration, long instant) { + return getWrappedField().getValueAsLong(duration, instant) / iScalar; + } + + public long getMillis(int value) { + long scaled = ((long) value) * ((long) iScalar); + return getWrappedField().getMillis(scaled); + } + + public long getMillis(long value) { + long scaled = FieldUtils.safeMultiply(value, iScalar); + return getWrappedField().getMillis(scaled); + } + + public long getMillis(int value, long instant) { + long scaled = ((long) value) * ((long) iScalar); + return getWrappedField().getMillis(scaled, instant); + } + + public long getMillis(long value, long instant) { + long scaled = FieldUtils.safeMultiply(value, iScalar); + return getWrappedField().getMillis(scaled, instant); + } + + public long add(long instant, int value) { + long scaled = ((long) value) * ((long) iScalar); + return getWrappedField().add(instant, scaled); + } + + public long add(long instant, long value) { + long scaled = FieldUtils.safeMultiply(value, iScalar); + return getWrappedField().add(instant, scaled); + } + + public int getDifference(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifference(minuendInstant, subtrahendInstant) / iScalar; + } + + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return getWrappedField().getDifferenceAsLong(minuendInstant, subtrahendInstant) / iScalar; + } + + public long getUnitMillis() { + return getWrappedField().getUnitMillis() * iScalar; + } + + //----------------------------------------------------------------------- + /** + * Returns the scalar applied, in the field's units. + * + * @return the scalar + */ + public int getScalar() { + return iScalar; + } + + /** + * Compares this duration field to another. + * Two fields are equal if of the same type and duration. + * + * @param obj the object to compare to + * @return if equal + */ + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj instanceof ScaledDurationField) { + ScaledDurationField other = (ScaledDurationField) obj; + return (getWrappedField().equals(other.getWrappedField())) && + (getType() == other.getType()) && + (iScalar == other.iScalar); + } + return false; + } + + /** + * Gets a hash code for this instance. + * + * @return a suitable hashcode + */ + public int hashCode() { + long scalar = iScalar; + int hash = (int) (scalar ^ (scalar >>> 32)); + hash += getType().hashCode(); + hash += getWrappedField().hashCode(); + return hash; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/StrictDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/StrictDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/StrictDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import org.joda.time.DateTimeField; + +/** + * Converts a lenient DateTimeField into a strict one. By being strict, the set + * throws an IllegalArgumentException if the value is out of bounds. + *

+ * StrictDateTimeField is thread-safe and immutable. + * + * @author Brian S O'Neill + * @see org.joda.time.chrono.StrictChronology + * @see LenientDateTimeField + */ +public class StrictDateTimeField extends DelegatedDateTimeField { + + private static final long serialVersionUID = 3154803964207950910L; + + /** + * Returns a strict version of the given field. If it is already strict, + * then it is returned as-is. Otherwise, a new StrictDateTimeField is + * returned. + */ + public static DateTimeField getInstance(DateTimeField field) { + if (field == null) { + return null; + } + if (field instanceof LenientDateTimeField) { + field = ((LenientDateTimeField)field).getWrappedField(); + } + if (!field.isLenient()) { + return field; + } + return new StrictDateTimeField(field); + } + + protected StrictDateTimeField(DateTimeField field) { + super(field); + } + + public final boolean isLenient() { + return false; + } + + /** + * Does a bounds check before setting the value. + * + * @throws IllegalArgumentException if the value is invalid + */ + public long set(long instant, int value) { + FieldUtils.verifyValueBounds + (this, value, getMinimumValue(instant), getMaximumValue(instant)); + return super.set(instant, value); + } +} Index: 3rdParty_sources/joda-time/org/joda/time/field/UnsupportedDateTimeField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/UnsupportedDateTimeField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/UnsupportedDateTimeField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,557 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Locale; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DurationField; +import org.joda.time.ReadablePartial; + +/** + * A placeholder implementation to use when a datetime field is not supported. + *

+ * UnsupportedDateTimeField is thread-safe and immutable. + * + * @author Brian S O'Neill + */ +public final class UnsupportedDateTimeField extends DateTimeField implements Serializable { + + /** Serialilzation version */ + private static final long serialVersionUID = -1934618396111902255L; + + /** The cache of unsupported datetime field instances */ + private static HashMap cCache; + + /** + * Gets an instance of UnsupportedDateTimeField for a specific named field. + * Names should be of standard format, such as 'monthOfYear' or 'hourOfDay'. + * The returned instance is cached. + * + * @param type the type to obtain + * @return the instance + * @throws IllegalArgumentException if durationField is null + */ + public static synchronized UnsupportedDateTimeField getInstance( + DateTimeFieldType type, DurationField durationField) { + + UnsupportedDateTimeField field; + if (cCache == null) { + cCache = new HashMap(7); + field = null; + } else { + field = (UnsupportedDateTimeField)cCache.get(type); + if (field != null && field.getDurationField() != durationField) { + field = null; + } + } + if (field == null) { + field = new UnsupportedDateTimeField(type, durationField); + cCache.put(type, field); + } + return field; + } + + /** The field type */ + private final DateTimeFieldType iType; + /** The duration of the datetime field */ + private final DurationField iDurationField; + + /** + * Constructor. + * + * @param type the field type + * @param durationField the duration to use + */ + private UnsupportedDateTimeField(DateTimeFieldType type, DurationField durationField) { + if (type == null || durationField == null) { + throw new IllegalArgumentException(); + } + iType = type; + iDurationField = durationField; + } + + //----------------------------------------------------------------------- + // Design note: Simple accessors return a suitable value, but methods + // intended to perform calculations throw an UnsupportedOperationException. + + public DateTimeFieldType getType() { + return iType; + } + + public String getName() { + return iType.getName(); + } + + /** + * This field is not supported. + * + * @return false always + */ + public boolean isSupported() { + return false; + } + + /** + * This field is not lenient. + * + * @return false always + */ + public boolean isLenient() { + return false; + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int get(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsText(long instant, Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsText(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsText(ReadablePartial partial, int fieldValue, Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsText(ReadablePartial partial, Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsShortText(long instant, Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsShortText(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsShortText(ReadablePartial partial, int fieldValue, Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public String getAsShortText(ReadablePartial partial, Locale locale) { + throw unsupported(); + } + + /** + * Delegates to the duration field. + * + * @throws UnsupportedOperationException if the duration is unsupported + */ + public long add(long instant, int value) { + return getDurationField().add(instant, value); + } + + /** + * Delegates to the duration field. + * + * @throws UnsupportedOperationException if the duration is unsupported + */ + public long add(long instant, long value) { + return getDurationField().add(instant, value); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int[] add(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long addWrapField(long instant, int value) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int[] addWrapField(ReadablePartial instant, int fieldIndex, int[] values, int valueToAdd) { + throw unsupported(); + } + + /** + * Delegates to the duration field. + * + * @throws UnsupportedOperationException if the duration is unsupported + */ + public int getDifference(long minuendInstant, long subtrahendInstant) { + return getDurationField().getDifference(minuendInstant, subtrahendInstant); + } + + /** + * Delegates to the duration field. + * + * @throws UnsupportedOperationException if the duration is unsupported + */ + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + return getDurationField().getDifferenceAsLong(minuendInstant, subtrahendInstant); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long set(long instant, int value) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int[] set(ReadablePartial instant, int fieldIndex, int[] values, int newValue) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long set(long instant, String text, Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long set(long instant, String text) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int[] set(ReadablePartial instant, int fieldIndex, int[] values, String text, Locale locale) { + throw unsupported(); + } + + /** + * Even though this DateTimeField is unsupported, the duration field might + * be supported. + * + * @return a possibly supported DurationField + */ + public DurationField getDurationField() { + return iDurationField; + } + + /** + * Always returns null. + * + * @return null always + */ + public DurationField getRangeDurationField() { + return null; + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public boolean isLeap(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getLeapAmount(long instant) { + throw unsupported(); + } + + /** + * Always returns null. + * + * @return null always + */ + public DurationField getLeapDurationField() { + return null; + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMinimumValue() { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMinimumValue(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMinimumValue(ReadablePartial instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMinimumValue(ReadablePartial instant, int[] values) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMaximumValue() { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMaximumValue(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMaximumValue(ReadablePartial instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMaximumValue(ReadablePartial instant, int[] values) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMaximumTextLength(Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getMaximumShortTextLength(Locale locale) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long roundFloor(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long roundCeiling(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long roundHalfFloor(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long roundHalfCeiling(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long roundHalfEven(long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long remainder(long instant) { + throw unsupported(); + } + + //------------------------------------------------------------------------ + /** + * Get a suitable debug string. + * + * @return debug string + */ + public String toString() { + return "UnsupportedDateTimeField"; + } + + /** + * Ensure proper singleton serialization + */ + private Object readResolve() { + return getInstance(iType, iDurationField); + } + + private UnsupportedOperationException unsupported() { + return new UnsupportedOperationException(iType + " field is unsupported"); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/UnsupportedDurationField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/UnsupportedDurationField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/UnsupportedDurationField.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,316 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.field; + +import java.io.Serializable; +import java.util.HashMap; +import org.joda.time.DurationField; +import org.joda.time.DurationFieldType; + +/** + * A placeholder implementation to use when a duration field is not supported. + *

+ * UnsupportedDurationField is thread-safe and immutable. + * + * @author Brian S O'Neill + */ +public final class UnsupportedDurationField extends DurationField implements Serializable { + + /** Serialization lock. */ + private static final long serialVersionUID = -6390301302770925357L; + + /** The cache of unsupported duration field instances */ + private static HashMap cCache; + + /** + * Gets an instance of UnsupportedDurationField for a specific named field. + * Names should be plural, such as 'years' or 'hours'. + * The returned instance is cached. + * + * @param type the type to obtain + * @return the instance + */ + public static synchronized UnsupportedDurationField getInstance(DurationFieldType type) { + UnsupportedDurationField field; + if (cCache == null) { + cCache = new HashMap(7); + field = null; + } else { + field = (UnsupportedDurationField) cCache.get(type); + } + if (field == null) { + field = new UnsupportedDurationField(type); + cCache.put(type, field); + } + return field; + } + + /** The name of the field */ + private final DurationFieldType iType; + + /** + * Constructor. + * + * @param type the type to use + */ + private UnsupportedDurationField(DurationFieldType type) { + iType = type; + } + + //----------------------------------------------------------------------- + // Design note: Simple Accessors return a suitable value, but methods + // intended to perform calculations throw an UnsupportedOperationException. + + public final DurationFieldType getType() { + return iType; + } + + public String getName() { + return iType.getName(); + } + + /** + * This field is not supported. + * + * @return false always + */ + public boolean isSupported() { + return false; + } + + /** + * This field is precise. + * + * @return true always + */ + public boolean isPrecise() { + return true; + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getValue(long duration) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long getValueAsLong(long duration) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getValue(long duration, long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long getValueAsLong(long duration, long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long getMillis(int value) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long getMillis(long value) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long getMillis(int value, long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long getMillis(long value, long instant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long add(long instant, int value) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long add(long instant, long value) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public int getDifference(long minuendInstant, long subtrahendInstant) { + throw unsupported(); + } + + /** + * Always throws UnsupportedOperationException + * + * @throws UnsupportedOperationException + */ + public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { + throw unsupported(); + } + + /** + * Always returns zero. + * + * @return zero always + */ + public long getUnitMillis() { + return 0; + } + + /** + * Always returns zero, indicating that sort order is not relevent. + * + * @return zero always + */ + public int compareTo(Object durationField) { + return 0; + } + + //------------------------------------------------------------------------ + /** + * Compares this duration field to another. + * + * @param obj the object to compare to + * @return true if equal + */ + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj instanceof UnsupportedDurationField) { + UnsupportedDurationField other = (UnsupportedDurationField) obj; + if (other.getName() == null) { + return (getName() == null); + } + return (other.getName().equals(getName())); + } + return false; + } + + /** + * Gets a suitable hashcode. + * + * @return the hashcode + */ + public int hashCode() { + return getName().hashCode(); + } + + /** + * Get a suitable debug string. + * + * @return debug string + */ + public String toString() { + return "UnsupportedDurationField[" + getName() + ']'; + } + + /** + * Ensure proper singleton serialization + */ + private Object readResolve() { + return getInstance(iType); + } + + private UnsupportedOperationException unsupported() { + return new UnsupportedOperationException(iType + " field is unsupported"); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/field/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/field/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/field/package.html 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,71 @@ + + + +org.joda.time.field package + + + +

+Implementation package providing abstract and standard field classes. +

+

+Provides DateTimeField and DurationField implementations and support. +Applications will only use this package directly if they want to write +their own DateTimeField implementation. +

+ + Index: 3rdParty_sources/joda-time/org/joda/time/format/BaseDateTimeFormatter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/Attic/BaseDateTimeFormatter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/BaseDateTimeFormatter.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,648 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; +import java.util.Arrays; +import java.util.Locale; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.MutableDateTime; +import org.joda.time.ReadWritableInstant; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadablePartial; +import org.joda.time.chrono.ISOChronology; + +/** + * Abstract base class for implementing {@link DateTimePrinter}s, + * {@link DateTimeParser}s, and {@link DateTimeFormatter}s. This class + * intentionally does not implement any of those interfaces. You can subclass + * and implement only the interfaces that you need to. + *

+ * The print methods assume that your subclass has implemented DateTimePrinter or + * DateTimeFormatter. If not, a ClassCastException is thrown when calling those + * methods. + *

+ * Likewise, the parse methods assume that your subclass has implemented + * DateTimeParser or DateTimeFormatter. If not, a ClassCastException is thrown + * when calling the parse methods. + *

+ * BaseDateTimeFormatter is thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public abstract class BaseDateTimeFormatter { + + public void printTo(StringBuffer buf, ReadableInstant instant) { + long millis = DateTimeUtils.getInstantMillis(instant); + Chronology chrono = DateTimeUtils.getInstantChronology(instant); + printTo(buf, millis, chrono); + } + + public void printTo(Writer out, ReadableInstant instant) throws IOException { + long millis = DateTimeUtils.getInstantMillis(instant); + Chronology chrono = DateTimeUtils.getInstantChronology(instant); + printTo(out, millis, chrono); + } + + public void printTo(StringBuffer buf, long instant) { + printTo(buf, instant, ISOChronology.getInstance()); + } + + public void printTo(Writer out, long instant) throws IOException { + printTo(out, instant, ISOChronology.getInstance()); + } + + public void printTo(StringBuffer buf, long instant, DateTimeZone zone) { + zone = DateTimeUtils.getZone(zone); + printTo(buf, instant, ISOChronology.getInstance(zone)); + } + + public void printTo(Writer out, long instant, DateTimeZone zone) throws IOException { + zone = DateTimeUtils.getZone(zone); + printTo(out, instant, ISOChronology.getInstance(zone)); + } + + public void printTo(StringBuffer buf, long instant, Chronology chrono) { + chrono = DateTimeUtils.getChronology(chrono); + printTo(buf, + instant + chrono.getZone().getOffset(instant), chrono.withUTC(), + instant, chrono); + } + + public void printTo(Writer out, long instant, Chronology chrono) throws IOException { + chrono = DateTimeUtils.getChronology(chrono); + printTo(out, + instant + chrono.getZone().getOffset(instant), chrono.withUTC(), + instant, chrono); + } + + //----------------------------------------------------------------------- + public String print(ReadableInstant instant) { + long millis = DateTimeUtils.getInstantMillis(instant); + Chronology chrono = DateTimeUtils.getInstantChronology(instant); + return print(millis, chrono); + } + + public String print(long instant) { + return print(instant, ISOChronology.getInstance()); + } + + public String print(long instant, DateTimeZone zone) { + zone = DateTimeUtils.getZone(zone); + return print(instant, ISOChronology.getInstance(zone)); + } + + public String print(long instant, Chronology chrono) { + chrono = DateTimeUtils.getChronology(chrono); + return print(instant + chrono.getZone().getOffset(instant), chrono.withUTC(), + instant, chrono); + } + + public String print(ReadablePartial partial) { + StringBuffer buf = new StringBuffer(estimatePrintedLength()); + printTo(buf, partial); + return buf.toString(); + } + + //----------------------------------------------------------------------- + protected int estimatePrintedLength() { + throw new UnsupportedOperationException("Printing not supported"); + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + throw new UnsupportedOperationException("Printing not supported"); + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + throw new UnsupportedOperationException("Printing not supported"); + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + throw new UnsupportedOperationException("Printing not supported"); + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + throw new UnsupportedOperationException("Printing not supported"); + } + + protected String print(long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + StringBuffer buf = new StringBuffer(estimatePrintedLength()); + printTo(buf, instantLocal, chronoLocal, instant, chrono); + return buf.toString(); + } + + //----------------------------------------------------------------------- + public int parseInto(ReadWritableInstant instant, String text, int position) { + if (instant == null) { + throw new IllegalArgumentException("Instant must not be null"); + } + + long millis = instant.getMillis(); + Chronology chrono = instant.getChronology(); + long instantLocal = millis + chrono.getZone().getOffset(millis); + + ParseBucket bucket = new ParseBucket(instantLocal, chrono); + int resultPos = parseInto(bucket, text, position); + instant.setMillis(bucket.computeMillis()); + return resultPos; + } + + public long parseMillis(String text) { + return parseMillis(text, ISOChronology.getInstance()); + } + + public long parseMillis(String text, Chronology chrono) { + ParseBucket bucket = new ParseBucket(0, chrono); + + int newPos = parseInto(bucket, text, 0); + if (newPos >= 0) { + if (newPos >= text.length()) { + return bucket.computeMillis(true); + } + } else { + newPos = ~newPos; + } + + throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); + } + + public long parseMillis(String text, long instant) { + return parseMillis(text, instant, ISOChronology.getInstance()); + } + + public long parseMillis(String text, long instant, Chronology chrono) { + chrono = DateTimeUtils.getChronology(chrono); + long instantLocal = instant + chrono.getZone().getOffset(instant); + ParseBucket bucket = new ParseBucket(instantLocal, chrono); + + int newPos = parseInto(bucket, text, 0); + if (newPos >= 0) { + if (newPos >= text.length()) { + return bucket.computeMillis(); + } + } else { + newPos = ~newPos; + } + + throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); + } + + public DateTime parseDateTime(String text) { + return parseDateTime(text, ISOChronology.getInstance()); + } + + public DateTime parseDateTime(String text, Chronology chrono) { + return new DateTime(parseMillis(text, chrono), chrono); + } + + public DateTime parseDateTime(String text, ReadableInstant instant) { + Chronology chrono = DateTimeUtils.getInstantChronology(instant); + long millis = DateTimeUtils.getInstantMillis(instant); + return new DateTime(parseMillis(text, millis, chrono), chrono); + } + + public MutableDateTime parseMutableDateTime(String text) { + return parseMutableDateTime(text, ISOChronology.getInstance()); + } + + public MutableDateTime parseMutableDateTime(String text, Chronology chrono) { + return new MutableDateTime(parseMillis(text, chrono), chrono); + } + + public MutableDateTime parseMutableDateTime(String text, ReadableInstant instant) { + Chronology chrono = DateTimeUtils.getInstantChronology(instant); + long millis = DateTimeUtils.getInstantMillis(instant); + return new MutableDateTime(parseMillis(text, millis, chrono), chrono); + } + + //----------------------------------------------------------------------- + protected int estimateParsedLength() { + throw new UnsupportedOperationException("Parsing not supported"); + } + + protected int parseInto(ParseBucket bucket, String text, int position) { + throw new UnsupportedOperationException("Parsing not supported"); + } + + //----------------------------------------------------------------------- + /** + * Internal class used to build the state during parsing. + *

+ * Allows fields to be saved in any order, but be physically set in a + * consistent order. This is useful for parsing against formats that allow + * field values to contradict each other. + *

+ * Field values are applied in an order where the "larger" fields are set + * first, making their value less likely to stick. A field is larger than + * another when it's range duration is longer. If both ranges are the same, + * then the larger field has the longer duration. If it cannot be determined + * which field is larger, then the fields are set in the order they were saved. + *

+ * For example, these fields were saved in this order: dayOfWeek, monthOfYear, + * dayOfMonth, dayOfYear. When computeMillis is called, the fields are set in + * this order: monthOfYear, dayOfYear, dayOfMonth, dayOfWeek. + *

+ * ParseBucket is mutable and not thread-safe. + * + * @author Brian S O'Neill + * @since 1.0 + */ + public static class ParseBucket { + + private final Chronology iChrono; + private final long iMillis; + + // TimeZone to switch to in computeMillis. If null, use offset. + DateTimeZone iZone; + int iOffset; + + SavedField[] iSavedFields = new SavedField[8]; + int iSavedFieldsCount; + boolean iSavedFieldsShared; + + private Object iSavedState; + + /** + * Constucts a bucket. + * + * @param instantLocal the initial millis from 1970-01-01T00:00:00, local time + * @param chrono the chronology to use + */ + public ParseBucket(long instantLocal, Chronology chrono) { + super(); + chrono = DateTimeUtils.getChronology(chrono); + iMillis = instantLocal; + iChrono = chrono.withUTC(); + setZone(chrono.getZone()); + } + + //----------------------------------------------------------------------- + /** + * Gets the chronology of the bucket, which will be a local (UTC) chronology. + */ + public Chronology getChronology() { + return iChrono; + } + + //----------------------------------------------------------------------- + /** + * Returns the time zone used by computeMillis, or null if an offset is + * used instead. + */ + public DateTimeZone getZone() { + return iZone; + } + + /** + * Set a time zone to be used when computeMillis is called, which + * overrides any set time zone offset. + * + * @param zone the date time zone to operate in, or null if UTC + */ + public void setZone(DateTimeZone zone) { + iSavedState = null; + iZone = zone == DateTimeZone.UTC ? null : zone; + iOffset = 0; + } + + //----------------------------------------------------------------------- + /** + * Returns the time zone offset used by computeMillis, unless + * getZone doesn't return null. + */ + public int getOffset() { + return iOffset; + } + + /** + * Set a time zone offset to be used when computeMillis is called, which + * overrides the time zone. + */ + public void setOffset(int offset) { + iSavedState = null; + iOffset = offset; + iZone = null; + } + + //----------------------------------------------------------------------- + /** + * Saves a datetime field value. + * + * @param field the field, whose chronology must match that of this bucket + * @param value the value + */ + public void saveField(DateTimeField field, int value) { + saveField(new SavedField(field, value)); + } + + /** + * Saves a datetime field value. + * + * @param fieldType the field type + * @param value the value + */ + public void saveField(DateTimeFieldType fieldType, int value) { + saveField(new SavedField(fieldType.getField(iChrono), value)); + } + + /** + * Saves a datetime field text value. + * + * @param fieldType the field type + * @param text the text value + * @param locale the locale to use + */ + public void saveField(DateTimeFieldType fieldType, String text, Locale locale) { + saveField(new SavedField(fieldType.getField(iChrono), text, locale)); + } + + private void saveField(SavedField field) { + SavedField[] savedFields = iSavedFields; + int savedFieldsCount = iSavedFieldsCount; + + if (savedFieldsCount == savedFields.length || iSavedFieldsShared) { + // Expand capacity or merely copy if saved fields are shared. + SavedField[] newArray = new SavedField + [savedFieldsCount == savedFields.length ? savedFieldsCount * 2 : savedFields.length]; + System.arraycopy(savedFields, 0, newArray, 0, savedFieldsCount); + iSavedFields = savedFields = newArray; + iSavedFieldsShared = false; + } + + iSavedState = null; + savedFields[savedFieldsCount] = field; + iSavedFieldsCount = savedFieldsCount + 1; + } + + /** + * Saves the state of this bucket, returning it in an opaque object. Call + * restoreState to undo any changes that were made since the state was + * saved. Calls to saveState may be nested. + * + * @return opaque saved state, which may be passed to restoreState + */ + public Object saveState() { + if (iSavedState == null) { + iSavedState = new SavedState(); + } + return iSavedState; + } + + /** + * Restores the state of this bucket from a previously saved state. The + * state object passed into this method is not consumed, and it can be used + * later to restore to that state again. + * + * @param savedState opaque saved state, returned from saveState + * @return true state object is valid and state restored + */ + public boolean restoreState(Object savedState) { + if (savedState instanceof SavedState) { + if (((SavedState) savedState).restoreState(this)) { + iSavedState = savedState; + return true; + } + } + return false; + } + + /** + * Computes the parsed datetime by setting the saved fields. + * This method is idempotent, but it is not thread-safe. + * + * @return milliseconds since 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if any field is out of range + */ + public long computeMillis() { + return computeMillis(false); + } + + /** + * Computes the parsed datetime by setting the saved fields. + * This method is idempotent, but it is not thread-safe. + * + * @param resetFields false by default, but when true, unsaved field values are cleared + * @return milliseconds since 1970-01-01T00:00:00Z + * @throws IllegalArgumentException if any field is out of range + */ + public long computeMillis(boolean resetFields) { + SavedField[] savedFields = iSavedFields; + int count = iSavedFieldsCount; + if (iSavedFieldsShared) { + iSavedFields = savedFields = (SavedField[])iSavedFields.clone(); + iSavedFieldsShared = false; + } + sort(savedFields, count); + + long millis = iMillis; + for (int i=0; i + * This method has a modified version of that insertion sort, except it + * doesn't create an unnecessary array copy. If high is over 10, then + * java.util.Arrays is called, which will perform a merge sort, which is + * faster than insertion sort on large lists. + *

+ * The end result is much greater performace when computeMillis is called. + * Since the amount of saved fields is small, the insertion sort is a + * better choice. Additional performance is gained since there is no extra + * array allocation and copying. Also, the insertion sort here does not + * perform any casting operations. The version in java.util.Arrays performs + * casts within the insertion sort loop. + */ + private static void sort(Comparable[] array, int high) { + if (high > 10) { + Arrays.sort(array, 0, high); + } else { + for (int i=0; i0 && (array[j-1]).compareTo(array[j])>0; j--) { + Comparable t = array[j]; + array[j] = array[j-1]; + array[j-1] = t; + } + } + } + } + + class SavedState { + final DateTimeZone iZone; + final int iOffset; + final SavedField[] iSavedFields; + final int iSavedFieldsCount; + + SavedState() { + this.iZone = ParseBucket.this.iZone; + this.iOffset = ParseBucket.this.iOffset; + this.iSavedFields = ParseBucket.this.iSavedFields; + this.iSavedFieldsCount = ParseBucket.this.iSavedFieldsCount; + } + + boolean restoreState(ParseBucket enclosing) { + if (enclosing != ParseBucket.this) { + return false; + } + enclosing.iZone = this.iZone; + enclosing.iOffset = this.iOffset; + enclosing.iSavedFields = this.iSavedFields; + if (this.iSavedFieldsCount < enclosing.iSavedFieldsCount) { + // Since count is being restored to a lower count, the + // potential exists for new saved fields to destroy data being + // shared by another state. Set this flag such that the array + // of saved fields is cloned prior to modification. + enclosing.iSavedFieldsShared = true; + } + enclosing.iSavedFieldsCount = this.iSavedFieldsCount; + return true; + } + } + + static class SavedField implements Comparable { + final DateTimeField iField; + final int iValue; + final String iText; + final Locale iLocale; + + SavedField(DateTimeField field, int value) { + iField = field; + iValue = value; + iText = null; + iLocale = null; + } + + SavedField(DateTimeField field, String text, Locale locale) { + iField = field; + iValue = 0; + iText = text; + iLocale = locale; + } + + long set(long millis, boolean reset) { + if (iText == null) { + millis = iField.set(millis, iValue); + } else { + millis = iField.set(millis, iText, iLocale); + } + if (reset) { + millis = iField.roundFloor(millis); + } + return millis; + } + + /** + * The field with the longer range duration is ordered first, where + * null is considered infinite. If the ranges match, then the field + * with the longer duration is ordered first. + */ + public int compareTo(Object obj) { + DateTimeField other = ((SavedField)obj).iField; + int result = compareReverse + (iField.getRangeDurationField(), other.getRangeDurationField()); + if (result != 0) { + return result; + } + return compareReverse + (iField.getDurationField(), other.getDurationField()); + } + + private int compareReverse(Comparable a, Comparable b) { + if (a == null) { + if (b == null) { + return 0; + } + return -1; + } + if (b == null) { + return 1; + } + return -a.compareTo(b); + } + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/BasePeriodFormatter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/Attic/BasePeriodFormatter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/BasePeriodFormatter.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,157 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; + +import org.joda.time.MutablePeriod; +import org.joda.time.Period; +import org.joda.time.PeriodType; +import org.joda.time.ReadWritablePeriod; +import org.joda.time.ReadablePeriod; + +/** + * Abstract base class for implementing {@link PeriodPrinter}s, + * {@link PeriodParser}s, and {@link PeriodFormatter}s. This class + * intentionally does not implement any of those interfaces. You can subclass + * and implement only the interfaces that you need to. + *

+ * The print methods assume that your subclass has implemented PeriodPrinter or + * PeriodFormatter. If not, a ClassCastException is thrown when calling those + * methods. + *

+ * Likewise, the parse methods assume that your subclass has implemented + * PeriodParser or PeriodFormatter. If not, a ClassCastException is thrown + * when calling the parse methods. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public abstract class BasePeriodFormatter { + + /** + * Returns the exact number of characters produced for the given period. + * + * @param period the period to use + * @return the estimated length + */ + protected int calculatePrintedLength(ReadablePeriod period) { + throw new UnsupportedOperationException("Printing not supported"); + } + + /** + * Returns the amount of fields from the given period that this printer + * will print. + * + * @param period the period to use + * @return amount of fields printed + */ + protected int countFieldsToPrint(ReadablePeriod period) { + return countFieldsToPrint(period, Integer.MAX_VALUE); + } + + /** + * Returns the amount of fields from the given period that this printer + * will print. + * + * @param period the period to use + * @param stopAt stop counting at this value + * @return amount of fields printed + */ + protected int countFieldsToPrint(ReadablePeriod period, int stopAt) { + throw new UnsupportedOperationException("Printing not supported"); + } + + //----------------------------------------------------------------------- + public void printTo(StringBuffer buf, ReadablePeriod period) { + throw new UnsupportedOperationException("Printing not supported"); + } + + public void printTo(Writer out, ReadablePeriod period) throws IOException { + throw new UnsupportedOperationException("Printing not supported"); + } + + public String print(ReadablePeriod period) { + StringBuffer buf = new StringBuffer(calculatePrintedLength(period)); + printTo(buf, period); + return buf.toString(); + } + + //----------------------------------------------------------------------- + public int parseInto(ReadWritablePeriod period, String periodStr, int position) { + throw new UnsupportedOperationException("Parsing not supported"); + } + + public Period parsePeriod(PeriodType type, String text) { + return parseMutablePeriod(type, text).toPeriod(); + } + + public MutablePeriod parseMutablePeriod(PeriodType type, String text) { + PeriodParser p = (PeriodParser) this; + MutablePeriod period = new MutablePeriod(0, type); + + int newPos = p.parseInto(period, text, 0); + if (newPos >= 0) { + if (newPos >= text.length()) { + return period; + } + } else { + newPos = ~newPos; + } + + throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos)); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormat.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormat.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormat.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,879 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeZone; +import org.joda.time.DurationFieldType; +import org.joda.time.MutableDateTime; +import org.joda.time.ReadWritableInstant; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadablePartial; +import org.joda.time.field.RemainderDateTimeField; + +/** + * DateTimeFormat provides localized printing and parsing capabilities for all + * dates and times. + *

+ * This class provides access to the actual DateTimeFormatter instances in two ways: + *

    + *
  • {@link #forPattern(String) Pattern} provides a DateTimeFormatter based on + * a pattern string that is compatible with the JDK date patterns. + *
  • {@link #forStyle(String) Style} provides a DateTimeFormatter based on a + * two character style, representing short, medium, long and full. + *
+ *

+ * For example, to use a patterm: + *

+ * DateTime dt = new DateTime();
+ * DateTimeFormatter fmt = DateTimeFormat.getInstance().forPattern("MMMM, yyyy");
+ * String str = fmt.print(dt);
+ * 
+ * + * The pattern syntax is compatible with java.text.SimpleDateFormat, but a few + * more symbols are also supported. All ASCII letters are reserved as pattern + * letters, which are defined as the following: + *
+ *
+ * Symbol  Meaning                      Presentation  Examples
+ * ------  -------                      ------------  -------
+ * G       era                          text          AD
+ * C       century of era (>=0)         number        20
+ * Y       year of era (>=0)            year          1996
+ *
+ * x       weekyear                     year          1996
+ * w       week of weekyear             number        27
+ * e       day of week                  number        2
+ * E       day of week                  text          Tuesday; Tue
+ *
+ * y       year                         year          1996
+ * D       day of year                  number        189
+ * M       month of year                month         July; Jul; 07
+ * d       day of month                 number        10
+ *
+ * a       halfday of day               text          PM
+ * K       hour of halfday (0~11)       number        0
+ * h       clockhour of halfday (1~12)  number        12
+ *
+ * H       hour of day (0~23)           number        0
+ * k       clockhour of day (1~24)      number        24
+ * m       minute of hour               number        30
+ * s       second of minute             number        55
+ * S       fraction of second           number        978
+ *
+ * z       time zone                    text          Pacific Standard Time; PST
+ * Z       time zone offset             text          -08:00; -0800
+ *
+ * '       escape for text              delimiter
+ * ''      single quote                 literal       '
+ * 
+ *
+ * The count of pattern letters determine the format. + *

+ * Text: If the number of pattern letters is 4 or more, + * the full form is used; otherwise a short or abbreviated form is used if + * available. + *

+ * Number: The minimum number of digits. Shorter numbers + * are zero-padded to this amount. + *

+ * Year: Numeric presentation for year and weekyear fields + * are handled specially. For example, if the count of 'y' is 2, the year + * will be displayed as the zero-based year of the century, which is two + * digits. + *

+ * Month: 3 or over, use text, otherwise use number. + *

+ * Any characters in the pattern that are not in the ranges of ['a'..'z'] + * and ['A'..'Z'] will be treated as quoted text. For instance, characters + * like ':', '.', ' ', '#' and '@' will appear in the resulting time text + * even they are not embraced within single quotes. + *

+ * DateTimeFormat is thread-safe and immutable, and the formatters it returns + * are as well. + * + * @author Brian S O'Neill + * @since 1.0 + * @see ISODateTimeFormat + * @see DateTimeFormatterBuilder + */ +public class DateTimeFormat { + + /** + * Cache that maps Chronology instances to maps that map + * Locales to DateTimeFormat instances. + */ + private static Map cInstanceCache = new HashMap(7); + + //----------------------------------------------------------------------- + /** + * Gets an instance of the formatter provider that works with the default locale. + * + * @return a format provider + */ + public static DateTimeFormat getInstance() { + return getInstance(Locale.getDefault()); + } + + /** + * Gets an instance of the formatter provider that works with the given locale. + * + * @param locale the Locale to use, null for default locale + * @return a format provider + */ + public synchronized static DateTimeFormat getInstance(Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + DateTimeFormat dtf = (DateTimeFormat) cInstanceCache.get(locale); + if (dtf == null) { + dtf = new DateTimeFormat(locale); + cInstanceCache.put(locale, dtf); + } + return dtf; + } + + //----------------------------------------------------------------------- + /** + * Parses the given pattern and appends the rules to the given + * DateTimeFormatterBuilder. + * + * @param pattern pattern specification + * @throws IllegalArgumentException if the pattern is invalid + * @see #forPattern + */ + public static void appendPatternTo(DateTimeFormatterBuilder builder, String pattern) { + int length = pattern.length(); + int[] indexRef = new int[1]; + + for (int i=0; i= 3) { + if (tokenLen >= 4) { + builder.appendMonthOfYearText(); + } else { + builder.appendMonthOfYearShortText(); + } + } else { + builder.appendMonthOfYear(tokenLen); + } + break; + case 'd': // day of month (number) + builder.appendDayOfMonth(tokenLen); + break; + case 'h': // hour of day (number, 1..12) + builder.appendClockhourOfHalfday(tokenLen); + break; + case 'H': // hour of day (number, 0..23) + builder.appendHourOfDay(tokenLen); + break; + case 'm': // minute of hour (number) + builder.appendMinuteOfHour(tokenLen); + break; + case 's': // second of minute (number) + builder.appendSecondOfMinute(tokenLen); + break; + case 'S': // fraction of second (number) + builder.appendFractionOfSecond(tokenLen, tokenLen); + break; + case 'e': // day of week (number) + builder.appendDayOfWeek(tokenLen); + break; + case 'E': // dayOfWeek (text) + if (tokenLen >= 4) { + builder.appendDayOfWeekText(); + } else { + builder.appendDayOfWeekShortText(); + } + break; + case 'D': // day of year (number) + builder.appendDayOfYear(tokenLen); + break; + case 'w': // week of weekyear (number) + builder.appendWeekOfWeekyear(tokenLen); + break; + case 'a': // am/pm marker (text) + builder.appendHalfdayOfDayText(); + break; + case 'k': // hour of day (1..24) + builder.appendClockhourOfDay(tokenLen); + break; + case 'K': // hour of day (0..11) + builder.appendClockhourOfHalfday(tokenLen); + break; + case 'z': // time zone (text) + if (tokenLen >= 4) { + builder.appendTimeZoneName(); + } else { + builder.appendTimeZoneShortName(); + } + break; + case 'Z': // time zone offset + if (tokenLen >= 4) { + builder.appendTimeZoneOffset(null, true, 2, 2); + } else { + builder.appendTimeZoneOffset(null, false, 2, 2); + } + break; + case '\'': // literal text + String sub = token.substring(1); + if (sub.length() == 1) { + builder.appendLiteral(sub.charAt(0)); + } else { + // Create copy of sub since otherwise the temporary quoted + // string would still be referenced internally. + builder.appendLiteral(new String(sub)); + } + break; + default: + throw new IllegalArgumentException + ("Illegal pattern component: " + token); + } + } + } + + private static String parseToken(final String pattern, final int[] indexRef) { + StringBuffer buf = new StringBuffer(); + + int i = indexRef[0]; + int length = pattern.length(); + + char c = pattern.charAt(i); + if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { + // Scan a run of the same character, which indicates a time + // pattern. + buf.append(c); + + while (i + 1 < length) { + char peek = pattern.charAt(i + 1); + if (peek == c) { + buf.append(c); + i++; + } else { + break; + } + } + } else { + // This will identify token as text. + buf.append('\''); + + boolean inLiteral = false; + + for (; i < length; i++) { + c = pattern.charAt(i); + + if (c == '\'') { + if (i + 1 < length && pattern.charAt(i + 1) == '\'') { + // '' is treated as escaped ' + i++; + buf.append(c); + } else { + inLiteral = !inLiteral; + } + } else if (!inLiteral && + (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { + i--; + break; + } else { + buf.append(c); + } + } + } + + indexRef[0] = i; + return buf.toString(); + } + + // Returns true if token should be parsed as a numeric field. + private static boolean isNumericToken(final String token) { + int tokenLen = token.length(); + if (tokenLen > 0) { + char c = token.charAt(0); + switch (c) { + case 'c': // century (number) + case 'C': // century of era (number) + case 'x': // weekyear (number) + case 'y': // year (number) + case 'Y': // year of era (number) + case 'd': // day of month (number) + case 'h': // hour of day (number, 1..12) + case 'H': // hour of day (number, 0..23) + case 'm': // minute of hour (number) + case 's': // second of minute (number) + case 'S': // fraction of second (number) + case 'e': // day of week (number) + case 'D': // day of year (number) + case 'F': // day of week in month (number) + case 'w': // week of year (number) + case 'W': // week of month (number) + case 'k': // hour of day (1..24) + case 'K': // hour of day (0..11) + return true; + case 'M': // month of year (text and number) + if (tokenLen <= 2) { + return true; + } + } + } + + return false; + } + + //----------------------------------------------------------------------- + /** The locale to use */ + private final Locale iLocale; + + /** Maps patterns to formatters */ + private transient Map iPatternedCache = new HashMap(7); + + /** Maps styles to formatters */ + private transient Map iStyledCache = new HashMap(7); + + /** + * Constructor. + * + * @param locale the locale to use, must not be null + */ + private DateTimeFormat(final Locale locale) { + super(); + iLocale = locale; + } + + //----------------------------------------------------------------------- + /** + * Select a format from a custom pattern. + * + * @param pattern pattern specification + * @throws IllegalArgumentException if the pattern is invalid + * @see #appendPatternTo + */ + public synchronized DateTimeFormatter forPattern(final String pattern) { + DateTimeFormatter formatter = (DateTimeFormatter) iPatternedCache.get(pattern); + if (formatter != null) { + return formatter; + } + + if (pattern == null) { + throw new IllegalArgumentException("Invalid pattern specification"); + } + + DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(iLocale); + appendPatternTo(builder, pattern); + + if (builder.canBuildFormatter()) { + formatter = builder.toFormatter(); + } else if (builder.canBuildPrinter()) { + formatter = new FPrinter(builder.toPrinter()); + } else if (builder.canBuildParser()) { + // I don't expect this case to ever occur. + formatter = new FParser(builder.toParser()); + } else { + throw new UnsupportedOperationException("Pattern unsupported: " + pattern); + } + + iPatternedCache.put(pattern, formatter); + return formatter; + } + + /** + * Select a format from a two character style pattern. The first character + * is the date style, and the second character is the time style. Specify a + * character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' + * for full. A date or time may be ommitted by specifying a style character '-'. + * + * @param style two characters from the set {"S", "M", "L", "F", "-"} + * @throws IllegalArgumentException if the style is invalid + */ + public synchronized DateTimeFormatter forStyle(final String style) { + DateTimeFormatter formatter = (DateTimeFormatter)iStyledCache.get(style); + if (formatter == null) { + formatter = forPattern(getPatternForStyle(style)); + iStyledCache.put(style, formatter); + } + return formatter; + } + + /** + * Returns a pattern specification from a two character style. The first + * character is the date style, and the second character is the time + * style. Specify a character of 'S' for short style, 'M' for medium, 'L' + * for long, and 'F' for full. A date or time may be ommitted by specifying + * a style character '-'. + * + * @param style two characters from the set {"S", "M", "L", "F", "-"} + * @throws IllegalArgumentException if the style is invalid + */ + public String getPatternForStyle(final String style) { + if (style == null || style.length() != 2) { + throw new IllegalArgumentException("Invalid style specification: " + style); + } + + if (style.charAt(1) == '-') { + // date only + return getDatePattern(style.charAt(0)); + } else if (style.charAt(0) == '-') { + // time only + return getTimePattern(style.charAt(1)); + } else { + // datetime + return getDateTimePattern(style.charAt(0), style.charAt(1)); + } + } + + private String getDatePattern(final char style) { + int istyle = selectStyle(style); + try { + return ((SimpleDateFormat)DateFormat.getDateInstance(istyle, iLocale)).toPattern(); + } catch (ClassCastException e) { + throw new IllegalArgumentException("No date pattern for locale: " + iLocale); + } + } + + private String getTimePattern(final char style) { + int istyle = selectStyle(style); + try { + return ((SimpleDateFormat)DateFormat.getTimeInstance(istyle, iLocale)).toPattern(); + } catch (ClassCastException e) { + throw new IllegalArgumentException("No time pattern for locale: " + iLocale); + } + } + + private String getDateTimePattern(final char dateStyle, final char timeStyle) { + int idateStyle = selectStyle(dateStyle); + int itimeStyle = selectStyle(dateStyle); + try { + return ((SimpleDateFormat)DateFormat.getDateTimeInstance + (idateStyle, itimeStyle, iLocale)).toPattern(); + } catch (ClassCastException e) { + throw new IllegalArgumentException("No datetime pattern for locale: " + iLocale); + } + } + + private int selectStyle(final char c) { + switch (c) { + case 'S': + return DateFormat.SHORT; + case 'M': + return DateFormat.MEDIUM; + case 'L': + return DateFormat.LONG; + case 'F': + return DateFormat.FULL; + default: + throw new IllegalArgumentException("Invalid style character: " + c); + } + } + + //----------------------------------------------------------------------- + /** + * Special field type which derives a new field as a remainder. + */ + static class RemainderType extends DateTimeFieldType { + private final DateTimeFieldType iWrappedType; + private final DateTimeFieldType iType; + private final int iDivisor; + + private transient RemainderDateTimeField iRecent; + + RemainderType(DateTimeFieldType wrappedType, DateTimeFieldType type, int divisor) { + super(type.getName()); + iWrappedType = wrappedType; + iType = type; + iDivisor = divisor; + } + + public DurationFieldType getDurationType() { + return iType.getDurationType(); + } + + public DurationFieldType getRangeDurationType() { + return iType.getRangeDurationType(); + } + + public DateTimeField getField(Chronology chrono) { + DateTimeField wrappedField = iWrappedType.getField(chrono); + RemainderDateTimeField field = iRecent; + if (field.getWrappedField() == wrappedField) { + return field; + } + field = new RemainderDateTimeField(wrappedField, iType, iDivisor); + iRecent = field; + return field; + } + } + + /** + * A fake formatter that can only print. + */ + static class FPrinter implements DateTimeFormatter { + private final DateTimePrinter mPrinter; + + FPrinter(DateTimePrinter printer) { + super(); + mPrinter = printer; + } + + public void printTo(StringBuffer buf, ReadableInstant instant) { + mPrinter.printTo(buf, instant); + } + + public void printTo(Writer out, ReadableInstant instant) throws IOException { + mPrinter.printTo(out, instant); + } + + public void printTo(StringBuffer buf, long instant) { + mPrinter.printTo(buf, instant); + } + + public void printTo(Writer out, long instant) throws IOException { + mPrinter.printTo(out, instant); + } + + public void printTo(StringBuffer buf, long instant, DateTimeZone zone) { + mPrinter.printTo(buf, instant, zone); + } + + public void printTo(Writer out, long instant, DateTimeZone zone) + throws IOException { + mPrinter.printTo(out, instant, zone); + } + + public void printTo(StringBuffer buf, long instant, Chronology chrono) { + mPrinter.printTo(buf, instant, chrono); + } + + public void printTo(Writer out, long instant, Chronology chrono) throws IOException { + mPrinter.printTo(out, instant, chrono); + } + + public void printTo(StringBuffer buf, ReadablePartial instant) { + mPrinter.printTo(buf, instant); + } + + public void printTo(Writer out, ReadablePartial instant) throws IOException { + mPrinter.printTo(out, instant); + } + + public String print(ReadableInstant instant) { + return mPrinter.print(instant); + } + + public String print(long instant) { + return mPrinter.print(instant); + } + + public String print(long instant, DateTimeZone zone) { + return mPrinter.print(instant, zone); + } + + public String print(long instant, Chronology chrono) { + return mPrinter.print(instant, chrono); + } + + public String print(ReadablePartial partial) { + return mPrinter.print(partial); + } + + public int estimateParsedLength() { + return 0; + } + + public int parseInto(ReadWritableInstant instant, String text, int position) { + throw unsupported(); + } + + public long parseMillis(String text) { + throw unsupported(); + } + + public long parseMillis(String text, Chronology chrono) { + throw unsupported(); + } + + public long parseMillis(String text, long instantLocal) { + throw unsupported(); + } + + public long parseMillis(String text, long instant, Chronology chrono) { + throw unsupported(); + } + + public DateTime parseDateTime(String text) { + throw unsupported(); + } + + public DateTime parseDateTime(String text, Chronology chrono) { + throw unsupported(); + } + + public DateTime parseDateTime(String text, ReadableInstant instant) { + throw unsupported(); + } + + public MutableDateTime parseMutableDateTime(String text) { + throw unsupported(); + } + + public MutableDateTime parseMutableDateTime(String text, Chronology chrono) { + throw unsupported(); + } + + public MutableDateTime parseMutableDateTime(String text, + ReadableInstant instant) { + throw unsupported(); + } + + private UnsupportedOperationException unsupported() { + return new UnsupportedOperationException("Parsing not supported"); + } + } + + //----------------------------------------------------------------------- + /** + * A fake formatter that can only parse. + */ + static class FParser implements DateTimeFormatter { + private final DateTimeParser mParser; + + FParser(DateTimeParser parser) { + super(); + mParser = parser; + } + + public void printTo(StringBuffer buf, ReadableInstant instant) { + throw unsupported(); + } + + public void printTo(Writer out, ReadableInstant instant) throws IOException { + throw unsupported(); + } + + public void printTo(StringBuffer buf, long instant) { + throw unsupported(); + } + + public void printTo(Writer out, long instant) throws IOException { + throw unsupported(); + } + + public void printTo(StringBuffer buf, long instant, DateTimeZone zone) { + throw unsupported(); + } + + public void printTo(Writer out, long instant, DateTimeZone zone) { + throw unsupported(); + } + + public void printTo(StringBuffer buf, long instant, Chronology chrono) { + throw unsupported(); + } + + public void printTo(Writer out, long instant, Chronology chrono) throws IOException { + throw unsupported(); + } + + public void printTo(StringBuffer buf, ReadablePartial instant) { + throw unsupported(); + } + + public void printTo(Writer out, ReadablePartial instant) throws IOException { + throw unsupported(); + } + + public String print(ReadableInstant instant) { + throw unsupported(); + } + + public String print(long instant) { + throw unsupported(); + } + + public String print(long instant, DateTimeZone zone) { + throw unsupported(); + } + + public String print(long instant, Chronology chrono) { + throw unsupported(); + } + + public String print(ReadablePartial partial) { + throw unsupported(); + } + + public int parseInto(ReadWritableInstant instant, String text, int position) { + return mParser.parseInto(instant, text, position); + } + + public long parseMillis(String text) { + return mParser.parseMillis(text); + } + + public long parseMillis(String text, Chronology chrono) { + return mParser.parseMillis(text, chrono); + } + + public long parseMillis(String text, long instant) { + return mParser.parseMillis(text, instant); + } + + public long parseMillis(String text, long instant, Chronology chrono) { + return mParser.parseMillis(text, instant, chrono); + } + + public DateTime parseDateTime(String text) { + return mParser.parseDateTime(text); + } + + public DateTime parseDateTime(String text, Chronology chrono) { + return mParser.parseDateTime(text, chrono); + } + + public DateTime parseDateTime(String text, ReadableInstant instant) { + return mParser.parseDateTime(text, instant); + } + + public MutableDateTime parseMutableDateTime(String text) { + return mParser.parseMutableDateTime(text); + } + + public MutableDateTime parseMutableDateTime(String text, Chronology chrono) { + return mParser.parseMutableDateTime(text, chrono); + } + + public MutableDateTime parseMutableDateTime(String text, ReadableInstant instant) { + return mParser.parseMutableDateTime(text, instant); + } + + private UnsupportedOperationException unsupported() { + return new UnsupportedOperationException("Printing not supported"); + } + } +} Index: 3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormatter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormatter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormatter.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +/** + * Combined interface for printing and parsing. + *

+ * See each extended interface for details of the methods. + *

+ * Note: This interface represents a view onto {@link BaseDateTimeFormatter}. + * All implementations must extend BaseDateTimeFormatter. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public interface DateTimeFormatter extends DateTimePrinter, DateTimeParser { + + // Methods inherited +} Index: 3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormatterBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormatterBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/DateTimeFormatterBuilder.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,2449 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeConstants; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeFieldType; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadablePartial; +import org.joda.time.field.MillisDurationField; +import org.joda.time.field.PreciseDateTimeField; + +/** + * DateTimeFormatterBuilder is used for constructing {@link DateTimeFormatter}s. + * DateTimeFormatters can be built by appending specific fields or other + * formatters. All formatters must extend {@link BaseDateTimeFormatter}. + * + *

+ * For example, a formatter that prints month and year, like "January 1970", + * can be constructed as follows: + *

+ *

+ * DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
+ *     .appendMonthOfYearText()
+ *     .appendLiteral(' ')
+ *     .appendYear(4, 4)
+ *     .toFormatter();
+ * 
+ *

+ * DateTimeFormatterBuilder itself is mutable and not thread-safe, but the + * formatters that it builds are thread-safe and immutable. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + * @see DateTimeFormat + * @see ISODateTimeFormat + */ +public class DateTimeFormatterBuilder { + + /** The locale the builder uses. */ + private final Locale iLocale; + + // Array contents alternate between printers and parsers. + private ArrayList iElementPairs; + private Object iFormatter; + + //----------------------------------------------------------------------- + /** + * Creates a DateTimeFormatterBuilder for the default locale. + */ + public DateTimeFormatterBuilder() { + this(Locale.getDefault()); + } + + /** + * Creates a DateTimeFormatterBuilder for the specified locale. + * + * @param locale Locale to use, or null for default + */ + public DateTimeFormatterBuilder(Locale locale) { + if (locale == null) { + locale = Locale.getDefault(); + } + iLocale = locale; + iElementPairs = new ArrayList(); + } + + //----------------------------------------------------------------------- + /** + * Returns the locale being used by the formatter builder, never null. + */ + public Locale getLocale() { + return iLocale; + } + + //----------------------------------------------------------------------- + /** + * Converts to a DateTimePrinter that prints using all the appended + * elements. Subsequent changes to this builder do not affect the returned + * printer. + * + * @throws UnsupportedOperationException if any formatter element doesn't support + * printing + */ + public DateTimePrinter toPrinter() throws UnsupportedOperationException { + Object f = getFormatter(); + if (isPrinter(f)) { + return (DateTimePrinter)f; + } + throw new UnsupportedOperationException("Printing not supported"); + } + + /** + * Converts to a DateTimeParser that parses using all the appended + * elements. Subsequent changes to this builder do not affect the returned + * parser. + * + * @throws UnsupportedOperationException if any formatter element doesn't support + * parsing + */ + public DateTimeParser toParser() throws UnsupportedOperationException { + Object f = getFormatter(); + if (isParser(f)) { + return (DateTimeParser)f; + } + throw new UnsupportedOperationException("Parsing not supported"); + } + + /** + * Converts to a DateTimeFormatter that prints and parses using all the + * appended elements. Subsequent changes to this builder do not affect the + * returned formatter. + * + * @throws UnsupportedOperationException if any formatter element doesn't support + * both printing and parsing + */ + public DateTimeFormatter toFormatter() throws UnsupportedOperationException { + Object f = getFormatter(); + if (isFormatter(f)) { + return (DateTimeFormatter)f; + } + throw new UnsupportedOperationException("Both printing and parsing not supported"); + } + + //----------------------------------------------------------------------- + /** + * Returns true if toPrinter can be called without throwing an + * UnsupportedOperationException. + */ + public boolean canBuildPrinter() { + return isPrinter(getFormatter()); + } + + /** + * Returns true if toParser can be called without throwing an + * UnsupportedOperationException. + */ + public boolean canBuildParser() { + return isParser(getFormatter()); + } + + /** + * Returns true if toFormatter can be called without throwing an + * UnsupportedOperationException. + */ + public boolean canBuildFormatter() { + return isFormatter(getFormatter()); + } + + //----------------------------------------------------------------------- + /** + * Clears out all the appended elements, allowing this builder to be + * reused. + */ + public void clear() { + iFormatter = null; + iElementPairs.clear(); + } + + //----------------------------------------------------------------------- + /** + * Appends another formatter. + *

+ * The formatter must extend DateTimeFormatterProvider. + * This is an internal class, which all supplied format classes extend. + * + * @param formatter the formatter to add + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if formatter is null or of an invalid type + */ + public DateTimeFormatterBuilder append(DateTimeFormatter formatter) { + if (formatter == null) { + throw new IllegalArgumentException("No formatter supplied"); + } + if (formatter instanceof BaseDateTimeFormatter == false) { + throw new IllegalArgumentException("Formatter must extend BaseDateTimeFormatter"); + } + return append0(formatter); + } + + /** + * Appends just a printer. With no matching parser, a parser cannot be + * built from this DateTimeFormatterBuilder. + *

+ * The printer added must extend BaseDateTimeFormatter. + * This is an internal class, which all supplied format classes extend. + * + * @param printer the printer to add + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if printer is null or of an invalid type + */ + public DateTimeFormatterBuilder append(DateTimePrinter printer) { + checkPrinter(printer); + return append0(printer, null); + } + + /** + * Appends just a parser. With no matching printer, a printer cannot be + * built from this builder. + *

+ * The parser added must extend BaseDateTimeFormatter. + * This is an internal class, which all supplied format classes extend. + * + * @param parser the parser to add + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if parser is null or of an invalid type + */ + public DateTimeFormatterBuilder append(DateTimeParser parser) { + checkParser(parser); + return append0(null, parser); + } + + /** + * Appends a printer/parser pair. + *

+ * The printer and parser must extend BaseDateTimeFormatter. + * This is an internal class, which all supplied format classes extend. + * + * @param printer the printer to add + * @param parser the parser to add + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if printer or parser is null or of an invalid type + */ + public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser parser) { + checkPrinter(printer); + checkParser(parser); + return append0(printer, parser); + } + + /** + * Appends a printer and a set of matching parsers. When parsing, the first + * parser in the list is selected for parsing. If it fails, the next is + * chosen, and so on. If none of these parsers succeeds, then the failed + * position of the parser that made the greatest progress is returned. + *

+ * Only the printer is optional. In addtion, it is illegal for any but the + * last of the parser array elements to be null. If the last element is + * null, this represents the empty parser. The presence of an empty parser + * indicates that the entire array of parse formats is optional. + *

+ * The printer and parsers must extend BaseDateTimeFormatter. + * This is an internal class, which all supplied format classes extend. + * + * @param printer the printer to add + * @param parsers the parsers to add + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if any printer or parser is of an invalid type + * @throws IllegalArgumentException if any parser element but the last is null + */ + public DateTimeFormatterBuilder append(DateTimePrinter printer, DateTimeParser[] parsers) { + if (printer != null) { + checkPrinter(printer); + } + if (parsers == null) { + throw new IllegalArgumentException("No parsers supplied"); + } + int length = parsers.length; + BaseDateTimeFormatter[] copyOfParsers = new BaseDateTimeFormatter[length]; + for (int i = 0; i < length; i++) { + DateTimeParser parser = parsers[i]; + if (i == length - 1 && parser == null) { + // ok + } else { + if (parser == null) { + throw new IllegalArgumentException("Incomplete parser array"); + } else if (parser instanceof BaseDateTimeFormatter == false) { + throw new IllegalArgumentException("Parser must extend BaseDateTimeFormatter"); + } + copyOfParsers[i] = (BaseDateTimeFormatter) parser; + } + } + + return append0(printer, new MatchingParser(copyOfParsers)); + } + + /** + * Appends just a parser element which is optional. With no matching + * printer, a printer cannot be built from this DateTimeFormatterBuilder. + *

+ * The parser must implement BaseDateTimeFormatter. + * This is an internal interface, which all supplied format classes implement. + * + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if parser is null or of an invalid type + */ + public DateTimeFormatterBuilder appendOptional(DateTimeParser parser) { + checkParser(parser); + BaseDateTimeFormatter[] parsers = new BaseDateTimeFormatter[] { + (BaseDateTimeFormatter) parser, null}; + return append0(null, new MatchingParser(parsers)); + } + + //----------------------------------------------------------------------- + /** + * Checks if the parser is non null and a provider. + * + * @param parser the parser to check + */ + private void checkParser(DateTimeParser parser) { + if (parser == null) { + throw new IllegalArgumentException("No parser supplied"); + } + if (parser instanceof BaseDateTimeFormatter == false) { + throw new IllegalArgumentException("Parser must extend BaseDateTimeFormatter"); + } + } + + /** + * Checks if the printer is non null and a provider. + * + * @param printer the printer to check + */ + private void checkPrinter(DateTimePrinter printer) { + if (printer == null) { + throw new IllegalArgumentException("No printer supplied"); + } + if (printer instanceof BaseDateTimeFormatter == false) { + throw new IllegalArgumentException("Printer must extend BaseDateTimeFormatter"); + } + } + + private DateTimeFormatterBuilder append0(Object element) { + iFormatter = null; + // Add the element as both a printer and parser. + iElementPairs.add(element); + iElementPairs.add(element); + return this; + } + + private DateTimeFormatterBuilder append0( + DateTimePrinter printer, DateTimeParser parser) { + iFormatter = null; + iElementPairs.add(printer); + iElementPairs.add(parser); + return this; + } + + //----------------------------------------------------------------------- + /** + * Instructs the printer to emit a specific character, and the parser to + * expect it. The parser is case-insensitive. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendLiteral(char c) { + return append0(new CharacterLiteral(c)); + } + + /** + * Instructs the printer to emit specific text, and the parser to expect + * it. The parser is case-insensitive. + * + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if text is null + */ + public DateTimeFormatterBuilder appendLiteral(String text) { + if (text == null) { + throw new IllegalArgumentException("Literal must not be null"); + } + switch (text.length()) { + case 0: + return this; + case 1: + return append0(new CharacterLiteral(text.charAt(0))); + default: + return append0(new StringLiteral(text)); + } + } + + /** + * Instructs the printer to emit a field value as a decimal number, and the + * parser to expect an unsigned decimal number. + * + * @param fieldType type of field to append + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to parse, or the estimated + * maximum number of digits to print + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if field type is null + */ + public DateTimeFormatterBuilder appendDecimal( + DateTimeFieldType fieldType, int minDigits, int maxDigits) { + if (fieldType == null) { + throw new IllegalArgumentException("Field type must not be null"); + } + if (maxDigits < minDigits) { + maxDigits = minDigits; + } + if (minDigits < 0 || maxDigits <= 0) { + throw new IllegalArgumentException(); + } + if (minDigits <= 1) { + return append0(new UnpaddedNumber(fieldType, maxDigits, false)); + } else { + return append0(new PaddedNumber(fieldType, maxDigits, false, minDigits)); + } + } + + /** + * Instructs the printer to emit a field value as a decimal number, and the + * parser to expect a signed decimal number. + * + * @param fieldType type of field to append + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to parse, or the estimated + * maximum number of digits to print + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if field type is null + */ + public DateTimeFormatterBuilder appendSignedDecimal( + DateTimeFieldType fieldType, int minDigits, int maxDigits) { + if (fieldType == null) { + throw new IllegalArgumentException("Field type must not be null"); + } + if (maxDigits < minDigits) { + maxDigits = minDigits; + } + if (minDigits < 0 || maxDigits <= 0) { + throw new IllegalArgumentException(); + } + if (minDigits <= 1) { + return append0(new UnpaddedNumber(fieldType, maxDigits, true)); + } else { + return append0(new PaddedNumber(fieldType, maxDigits, true, minDigits)); + } + } + + /** + * Instructs the printer to emit a field value as text, and the + * parser to expect text. + * + * @param fieldType type of field to append + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if field type is null + */ + public DateTimeFormatterBuilder appendText(DateTimeFieldType fieldType) { + if (fieldType == null) { + throw new IllegalArgumentException("Field type must not be null"); + } + return append0(new TextField(fieldType, iLocale, false)); + } + + /** + * Instructs the printer to emit a field value as short text, and the + * parser to expect text. + * + * @param fieldType type of field to append + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if field type is null + */ + public DateTimeFormatterBuilder appendShortText(DateTimeFieldType fieldType) { + if (fieldType == null) { + throw new IllegalArgumentException("Field type must not be null"); + } + return append0(new TextField(fieldType, iLocale, true)); + } + + /** + * Instructs the printer to emit a remainder of time as a decimal fraction, + * sans decimal point. For example, if the field is specified as + * minuteOfHour and the time is 12:30:45, the value printed is 75. A + * decimal point is implied, so the fraction is 0.75, or three-quarters of + * a minute. + * + * @param fieldType type of field to append + * @param minDigits minumum number of digits to print. + * @param maxDigits maximum number of digits to print or parse. + * @return this DateTimeFormatterBuilder + * @throws IllegalArgumentException if field type is null + */ + public DateTimeFormatterBuilder appendFraction( + DateTimeFieldType fieldType, int minDigits, int maxDigits) { + if (fieldType == null) { + throw new IllegalArgumentException("Field type must not be null"); + } + if (maxDigits < minDigits) { + maxDigits = minDigits; + } + if (minDigits < 0 || maxDigits <= 0) { + throw new IllegalArgumentException(); + } + return append0(new Fraction(fieldType, minDigits, maxDigits)); + } + + /** + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to print or parse + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendFractionOfSecond(int minDigits, int maxDigits) { + return appendFraction(DateTimeFieldType.secondOfDay(), minDigits, maxDigits); + } + + /** + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to print or parse + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendFractionOfMinute(int minDigits, int maxDigits) { + return appendFraction(DateTimeFieldType.minuteOfDay(), minDigits, maxDigits); + } + + /** + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to print or parse + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendFractionOfHour(int minDigits, int maxDigits) { + return appendFraction(DateTimeFieldType.hourOfDay(), minDigits, maxDigits); + } + + /** + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to print or parse + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendFractionOfDay(int minDigits, int maxDigits) { + return appendFraction(DateTimeFieldType.dayOfYear(), minDigits, maxDigits); + } + + /** + * Instructs the printer to emit a numeric millisOfSecond field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendMillisOfSecond(int minDigits) { + return appendDecimal(DateTimeFieldType.millisOfSecond(), minDigits, 3); + } + + /** + * Instructs the printer to emit a numeric millisOfDay field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendMillisOfDay(int minDigits) { + return appendDecimal(DateTimeFieldType.millisOfDay(), minDigits, 8); + } + + /** + * Instructs the printer to emit a numeric secondOfMinute field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendSecondOfMinute(int minDigits) { + return appendDecimal(DateTimeFieldType.secondOfMinute(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric secondOfDay field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendSecondOfDay(int minDigits) { + return appendDecimal(DateTimeFieldType.secondOfDay(), minDigits, 5); + } + + /** + * Instructs the printer to emit a numeric minuteOfHour field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendMinuteOfHour(int minDigits) { + return appendDecimal(DateTimeFieldType.minuteOfHour(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric minuteOfDay field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendMinuteOfDay(int minDigits) { + return appendDecimal(DateTimeFieldType.minuteOfDay(), minDigits, 4); + } + + /** + * Instructs the printer to emit a numeric hourOfDay field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendHourOfDay(int minDigits) { + return appendDecimal(DateTimeFieldType.hourOfDay(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric clockhourOfDay field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendClockhourOfDay(int minDigits) { + return appendDecimal(DateTimeFieldType.clockhourOfDay(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric hourOfHalfday field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendHourOfHalfday(int minDigits) { + return appendDecimal(DateTimeFieldType.hourOfHalfday(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric clockhourOfHalfday field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendClockhourOfHalfday(int minDigits) { + return appendDecimal(DateTimeFieldType.clockhourOfHalfday(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric dayOfWeek field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendDayOfWeek(int minDigits) { + return appendDecimal(DateTimeFieldType.dayOfWeek(), minDigits, 1); + } + + /** + * Instructs the printer to emit a numeric dayOfMonth field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendDayOfMonth(int minDigits) { + return appendDecimal(DateTimeFieldType.dayOfMonth(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric dayOfYear field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendDayOfYear(int minDigits) { + return appendDecimal(DateTimeFieldType.dayOfYear(), minDigits, 3); + } + + /** + * Instructs the printer to emit a numeric weekOfWeekyear field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendWeekOfWeekyear(int minDigits) { + return appendDecimal(DateTimeFieldType.weekOfWeekyear(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric weekyear field. + * + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to parse, or the estimated + * maximum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendWeekyear(int minDigits, int maxDigits) { + return appendSignedDecimal(DateTimeFieldType.weekyear(), minDigits, maxDigits); + } + + /** + * Instructs the printer to emit a numeric monthOfYear field. + * + * @param minDigits minumum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendMonthOfYear(int minDigits) { + return appendDecimal(DateTimeFieldType.monthOfYear(), minDigits, 2); + } + + /** + * Instructs the printer to emit a numeric year field. + * + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to parse, or the estimated + * maximum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendYear(int minDigits, int maxDigits) { + return appendSignedDecimal(DateTimeFieldType.year(), minDigits, maxDigits); + } + + /** + * Instructs the printer to emit a numeric year field which always prints + * and parses two digits. A pivot year is used during parsing to determine + * the range of supported years as (pivot - 50) .. (pivot + 49). + * + *

+     * pivot   supported range   00 is   20 is   40 is   60 is   80 is
+     * ---------------------------------------------------------------
+     * 1950      1900..1999      1900    1920    1940    1960    1980
+     * 1975      1925..2024      2000    2020    1940    1960    1980
+     * 2000      1950..2049      2000    2020    2040    1960    1980
+     * 2025      1975..2074      2000    2020    2040    2060    1980
+     * 2050      2000..2099      2000    2020    2040    2060    2080
+     * 
+ * + * @param pivot pivot year to use when parsing + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendTwoDigitYear(int pivot) { + return append0(new TwoDigitYear(pivot)); + } + + /** + * Instructs the printer to emit a numeric yearOfEra field. + * + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to parse, or the estimated + * maximum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendYearOfEra(int minDigits, int maxDigits) { + return appendDecimal(DateTimeFieldType.yearOfEra(), minDigits, maxDigits); + } + + /** + * Instructs the printer to emit a numeric year of century field. + * + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to parse, or the estimated + * maximum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendYearOfCentury(int minDigits, int maxDigits) { + return appendDecimal(DateTimeFieldType.yearOfCentury(), minDigits, maxDigits); + } + + /** + * Instructs the printer to emit a numeric century of era field. + * + * @param minDigits minumum number of digits to print + * @param maxDigits maximum number of digits to parse, or the estimated + * maximum number of digits to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendCenturyOfEra(int minDigits, int maxDigits) { + return appendSignedDecimal(DateTimeFieldType.centuryOfEra(), minDigits, maxDigits); + } + + /** + * Instructs the printer to emit a locale-specific AM/PM text, and the + * parser to expect it. The parser is case-insensitive. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendHalfdayOfDayText() { + return appendText(DateTimeFieldType.halfdayOfDay()); + } + + /** + * Instructs the printer to emit a locale-specific dayOfWeek text. The + * parser will accept a long or short dayOfWeek text, case-insensitive. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendDayOfWeekText() { + return appendText(DateTimeFieldType.dayOfWeek()); + } + + /** + * Instructs the printer to emit a short locale-specific dayOfWeek + * text. The parser will accept a long or short dayOfWeek text, + * case-insensitive. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendDayOfWeekShortText() { + return appendShortText(DateTimeFieldType.dayOfWeek()); + } + + /** + * Instructs the printer to emit a short locale-specific monthOfYear + * text. The parser will accept a long or short monthOfYear text, + * case-insensitive. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendMonthOfYearText() { + return appendText(DateTimeFieldType.monthOfYear()); + } + + /** + * Instructs the printer to emit a locale-specific monthOfYear text. The + * parser will accept a long or short monthOfYear text, case-insensitive. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendMonthOfYearShortText() { + return appendShortText(DateTimeFieldType.monthOfYear()); + } + + /** + * Instructs the printer to emit a locale-specific era text (BC/AD), and + * the parser to expect it. The parser is case-insensitive. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendEraText() { + return appendText(DateTimeFieldType.era()); + } + + /** + * Instructs the printer to emit a locale-specific time zone name. A + * parser cannot be created from this builder if a time zone name is + * appended. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendTimeZoneName() { + return append0(new TimeZonePrinter( iLocale, false), null); + } + + /** + * Instructs the printer to emit a short locale-specific time zone + * name. A parser cannot be created from this builder if time zone + * name is appended. + * + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendTimeZoneShortName() { + return append0(new TimeZonePrinter( iLocale, true), null); + } + + /** + * Instructs the printer to emit text and numbers to display time zone + * offset from UTC. A parser will use the parsed time zone offset to adjust + * the datetime. + * + * @param zeroOffsetText Text to use if time zone offset is zero. If + * null, offset is always shown. + * @param showSeparators If true, prints ':' separator before minute and + * second field and prints '.' separator before fraction field. + * @param minFields minimum number of fields to print, stopping when no + * more precision is required. 1=hours, 2=minutes, 3=seconds, 4=fraction + * @param maxFields maximum number of fields to print + * @return this DateTimeFormatterBuilder + */ + public DateTimeFormatterBuilder appendTimeZoneOffset( + String zeroOffsetText, boolean showSeparators, + int minFields, int maxFields) { + return append0(new TimeZoneOffsetFormatter + (zeroOffsetText, showSeparators, minFields, maxFields)); + } + + /** + * Calls upon {@link DateTimeFormat} to parse the pattern and append the + * results into this builder. + * + * @param pattern pattern specification + * @throws IllegalArgumentException if the pattern is invalid + * @see DateTimeFormat#appendPatternTo(DateTimeFormatterBuilder,String) + */ + public DateTimeFormatterBuilder appendPattern(String pattern) { + DateTimeFormat.appendPatternTo(this, pattern); + return this; + } + + private Object getFormatter() { + Object f = iFormatter; + + if (f == null) { + if (iElementPairs.size() == 2) { + Object printer = iElementPairs.get(0); + Object parser = iElementPairs.get(1); + + if (printer != null) { + if (printer == parser || parser == null) { + f = printer; + } + } else { + f = parser; + } + } + + if (f == null) { + f = new Composite(iElementPairs); + } + + iFormatter = f; + } + + return f; + } + + private boolean isPrinter(Object f) { + if (f instanceof DateTimePrinter) { + if (f instanceof Composite) { + return ((Composite)f).isPrinter(); + } + return true; + } + return false; + } + + private boolean isParser(Object f) { + if (f instanceof DateTimeParser) { + if (f instanceof Composite) { + return ((Composite)f).isParser(); + } + return true; + } + return false; + } + + private boolean isFormatter(Object f) { + if (f instanceof DateTimeFormatter) { + if (f instanceof Composite) { + return ((Composite)f).isPrinter() + && ((Composite)f).isParser(); + } + return true; + } + return false; + } + + static void appendUnknownString(StringBuffer buf, int len) { + for (int i = len; --i >= 0;) { + buf.append('\ufffd'); + } + } + + static void printUnknownString(Writer out, int len) throws IOException { + for (int i = len; --i >= 0;) { + out.write('\ufffd'); + } + } + + //----------------------------------------------------------------------- + static class CharacterLiteral + extends BaseDateTimeFormatter + implements DateTimeFormatter { + + private final char iValue; + + CharacterLiteral(char value) { + super(); + iValue = value; + } + + public int estimatePrintedLength() { + return 1; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + buf.append(iValue); + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + out.write(iValue); + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + buf.append(iValue); + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + out.write(iValue); + } + + protected String print(long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + return String.valueOf(iValue); + } + + public String print(ReadablePartial partial) { + return String.valueOf(iValue); + } + + protected int estimateParsedLength() { + return 1; + } + + protected int parseInto(ParseBucket bucket, String text, int position) { + if (position >= text.length()) { + return ~position; + } + + char a = text.charAt(position); + char b = iValue; + + if (a != b) { + a = Character.toUpperCase(a); + b = Character.toUpperCase(b); + if (a != b) { + a = Character.toLowerCase(a); + b = Character.toLowerCase(b); + if (a != b) { + return ~position; + } + } + } + + return position + 1; + } + } + + //----------------------------------------------------------------------- + static class StringLiteral + extends BaseDateTimeFormatter + implements DateTimeFormatter { + + private final String iValue; + + StringLiteral(String value) { + super(); + iValue = value; + } + + public int estimatePrintedLength() { + return iValue.length(); + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + buf.append(iValue); + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + out.write(iValue); + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + buf.append(iValue); + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + out.write(iValue); + } + + protected String print(long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + return iValue; + } + + public String print(ReadablePartial partial) { + return iValue; + } + + public int estimateParsedLength() { + return iValue.length(); + } + + public int parseInto(ParseBucket bucket, String text, int position) { + if (text.regionMatches(true, position, iValue, 0, iValue.length())) { + return position + iValue.length(); + } + return ~position; + } + } + + //----------------------------------------------------------------------- + static abstract class NumberFormatter + extends BaseDateTimeFormatter + implements DateTimeFormatter { + protected final DateTimeFieldType iFieldType; + protected final int iMaxParsedDigits; + protected final boolean iSigned; + + NumberFormatter(DateTimeFieldType fieldType, + int maxParsedDigits, boolean signed) { + super(); + iFieldType = fieldType; + iMaxParsedDigits = maxParsedDigits; + iSigned = signed; + } + + protected int estimateParsedLength() { + return iMaxParsedDigits; + } + + protected int parseInto(ParseBucket bucket, String text, int position) { + int limit = Math.min(iMaxParsedDigits, text.length() - position); + + boolean negative = false; + int length = 0; + while (length < limit) { + char c = text.charAt(position + length); + if (length == 0 && (c == '-' || c == '+') && iSigned) { + negative = c == '-'; + if (negative) { + length++; + } else { + // Skip the '+' for parseInt to succeed. + position++; + } + // Expand the limit to disregard the sign character. + limit = Math.min(limit + 1, text.length() - position); + continue; + } + if (c < '0' || c > '9') { + break; + } + length++; + } + + if (length == 0) { + return ~position; + } + + int value; + if (length >= 9) { + // Since value may exceed integer limits, use stock parser + // which checks for this. + value = Integer.parseInt + (text.substring(position, position += length)); + } else { + int i = position; + if (negative) { + i++; + } + value = text.charAt(i++) - '0'; + position += length; + while (i < position) { + value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0'; + } + if (negative) { + value = -value; + } + } + + bucket.saveField(iFieldType, value); + return position; + } + } + + //----------------------------------------------------------------------- + static class UnpaddedNumber extends NumberFormatter { + + protected UnpaddedNumber(DateTimeFieldType fieldType, + int maxParsedDigits, boolean signed) + { + super(fieldType, maxParsedDigits, signed); + } + + protected int estimatePrintedLength() { + return iMaxParsedDigits; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + try { + DateTimeField field = iFieldType.getField(chronoLocal); + FormatUtils.appendUnpaddedInteger(buf, field.get(instantLocal)); + } catch (RuntimeException e) { + buf.append('\ufffd'); + } + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + try { + DateTimeField field = iFieldType.getField(chronoLocal); + FormatUtils.writeUnpaddedInteger(out, field.get(instantLocal)); + } catch (RuntimeException e) { + out.write('\ufffd'); + } + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + if (partial.isSupported(iFieldType)) { + try { + FormatUtils.appendUnpaddedInteger(buf, partial.get(iFieldType)); + } catch (RuntimeException e) { + buf.append('\ufffd'); + } + } else { + buf.append('\ufffd'); + } + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + if (partial.isSupported(iFieldType)) { + try { + FormatUtils.writeUnpaddedInteger(out, partial.get(iFieldType)); + } catch (RuntimeException e) { + out.write('\ufffd'); + } + } else { + out.write('\ufffd'); + } + } + } + + //----------------------------------------------------------------------- + static class PaddedNumber extends NumberFormatter { + + protected final int iMinPrintedDigits; + + protected PaddedNumber(DateTimeFieldType fieldType, int maxParsedDigits, + boolean signed, int minPrintedDigits) + { + super(fieldType, maxParsedDigits, signed); + iMinPrintedDigits = minPrintedDigits; + } + + protected int estimatePrintedLength() { + return iMaxParsedDigits; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + try { + DateTimeField field = iFieldType.getField(chronoLocal); + FormatUtils.appendPaddedInteger(buf, field.get(instantLocal), iMinPrintedDigits); + } catch (RuntimeException e) { + appendUnknownString(buf, iMinPrintedDigits); + } + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + try { + DateTimeField field = iFieldType.getField(chronoLocal); + FormatUtils.writePaddedInteger(out, field.get(instantLocal), iMinPrintedDigits); + } catch (RuntimeException e) { + printUnknownString(out, iMinPrintedDigits); + } + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + if (partial.isSupported(iFieldType)) { + try { + FormatUtils.appendPaddedInteger(buf, partial.get(iFieldType), iMinPrintedDigits); + } catch (RuntimeException e) { + appendUnknownString(buf, iMinPrintedDigits); + } + } else { + appendUnknownString(buf, iMinPrintedDigits); + } + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + if (partial.isSupported(iFieldType)) { + try { + FormatUtils.writePaddedInteger(out, partial.get(iFieldType), iMinPrintedDigits); + } catch (RuntimeException e) { + printUnknownString(out, iMinPrintedDigits); + } + } else { + printUnknownString(out, iMinPrintedDigits); + } + } + } + + //----------------------------------------------------------------------- + static class TwoDigitYear + extends BaseDateTimeFormatter + implements DateTimeFormatter { + + private final int iPivot; + + TwoDigitYear(int pivot) { + super(); + iPivot = pivot; + } + + protected int estimateParsedLength() { + return 2; + } + + protected int parseInto(ParseBucket bucket, String text, int position) { + int limit = Math.min(2, text.length() - position); + if (limit < 2) { + return ~position; + } + + int year; + char c = text.charAt(position); + if (c < '0' || c > '9') { + return ~position; + } + year = c - '0'; + c = text.charAt(position + 1); + if (c < '0' || c > '9') { + return ~position; + } + year = ((year << 3) + (year << 1)) + c - '0'; + + int low = iPivot - 50; + + int t; + if (low >= 0) { + t = low % 100; + } else { + t = 99 + ((low + 1) % 100); + } + + year += low + ((year < t) ? 100 : 0) - t; + + bucket.saveField(DateTimeFieldType.year(), year); + return position + 2; + } + + protected int estimatePrintedLength() { + return 2; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + int year = getTwoDigitYear(instantLocal, chronoLocal); + if (year < 0) { + buf.append('\ufffd'); + buf.append('\ufffd'); + } else { + FormatUtils.appendPaddedInteger(buf, year, 2); + } + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + int year = getTwoDigitYear(instantLocal, chronoLocal); + if (year < 0) { + out.write('\ufffd'); + out.write('\ufffd'); + } else { + FormatUtils.writePaddedInteger(out, year, 2); + } + } + + private int getTwoDigitYear(long instantLocal, Chronology chronoLocal) { + try { + int year = chronoLocal.year().get(instantLocal); + if (year < 0) { + year = -year; + } + return year % 100; + } catch (RuntimeException e) { + return -1; + } + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + int year = getTwoDigitYear(partial); + if (year < 0) { + buf.append('\ufffd'); + buf.append('\ufffd'); + } else { + FormatUtils.appendPaddedInteger(buf, year, 2); + } + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + int year = getTwoDigitYear(partial); + if (year < 0) { + out.write('\ufffd'); + out.write('\ufffd'); + } else { + FormatUtils.writePaddedInteger(out, year, 2); + } + } + + private int getTwoDigitYear(ReadablePartial partial) { + if (partial.isSupported(DateTimeFieldType.year())) { + try { + int year = partial.get(DateTimeFieldType.year()); + if (year < 0) { + year = -year; + } + return year % 100; + } catch (RuntimeException e) {} + } + return -1; + } + } + + //----------------------------------------------------------------------- + static class TextField + extends BaseDateTimeFormatter + implements DateTimeFormatter { + + private final DateTimeFieldType iFieldType; + private final Locale iLocale; + private final boolean iShort; + + TextField(DateTimeFieldType fieldType, Locale locale, boolean isShort) { + super(); + iFieldType = fieldType; + iLocale = locale; + iShort = isShort; + } + + protected int estimatePrintedLength() { + return iShort ? 6 : 20; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + try { + buf.append(print(instantLocal, chronoLocal, instant, chrono)); + } catch (RuntimeException e) { + buf.append('\ufffd'); + } + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + try { + out.write(print(instantLocal, chronoLocal, instant, chrono)); + } catch (RuntimeException e) { + out.write('\ufffd'); + } + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + try { + buf.append(print(partial)); + } catch (RuntimeException e) { + buf.append('\ufffd'); + } + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + try { + out.write(print(partial)); + } catch (RuntimeException e) { + out.write('\ufffd'); + } + } + + protected String print(long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + DateTimeField field = iFieldType.getField(chrono); + if (iShort) { + return field.getAsShortText(instantLocal, iLocale); + } else { + return field.getAsText(instantLocal, iLocale); + } + } + + public String print(ReadablePartial partial) { + if (partial.isSupported(iFieldType)) { + DateTimeField field = iFieldType.getField(partial.getChronology()); + if (iShort) { + return field.getAsShortText(partial, iLocale); + } else { + return field.getAsText(partial, iLocale); + } + } else { + return "\ufffd"; + } + } + + protected int estimateParsedLength() { + return estimatePrintedLength(); + } + + protected int parseInto(ParseBucket bucket, String text, int position) { + int limit = text.length(); + int i = position; + for (; i= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || Character.isLetter(c)) { + continue; + } + break; + } + + if (i == position) { + return ~position; + } + + bucket.saveField(iFieldType, text.substring(position, i), iLocale); + + return i; + } + } + + //----------------------------------------------------------------------- + static class Fraction + extends BaseDateTimeFormatter + implements DateTimeFormatter { + + private final DateTimeFieldType iFieldType; + protected int iMinDigits; + protected int iMaxDigits; + + protected Fraction(DateTimeFieldType fieldType, int minDigits, int maxDigits) { + super(); + iFieldType = fieldType; + // Limit the precision requirements. + if (maxDigits > 18) { + maxDigits = 18; + } + iMinDigits = minDigits; + iMaxDigits = maxDigits; + } + + protected int estimatePrintedLength() { + return iMaxDigits; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + try { + printTo(buf, null, instantLocal, chronoLocal); + } catch (IOException e) { + // Not gonna happen. + } + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + printTo(null, out, instantLocal, chronoLocal); + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + if (partial.isSupported(iFieldType)) { + long millis = partial.getChronology().set(partial, 0L); + try { + printTo(buf, null, millis, partial.getChronology()); + } catch (IOException e) { + // Not gonna happen. + } + } else { + buf.append('\ufffd'); + } + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + if (partial.isSupported(iFieldType)) { + long millis = partial.getChronology().set(partial, 0L); + printTo(null, out, millis, partial.getChronology()); + } else { + out.write('\ufffd'); + } + } + + protected void printTo(StringBuffer buf, Writer out, long instantLocal, Chronology chronoLocal) + throws IOException + { + DateTimeField field = iFieldType.getField(chronoLocal); + int minDigits = iMinDigits; + + long fraction; + try { + fraction = field.remainder(instantLocal); + } catch (RuntimeException e) { + if (buf != null) { + appendUnknownString(buf, minDigits); + } else { + printUnknownString(out, minDigits); + } + return; + } + + if (fraction == 0) { + if (buf != null) { + while (--minDigits >= 0) { + buf.append('0'); + } + } else { + while (--minDigits >= 0) { + out.write('0'); + } + } + return; + } + + String str; + long[] fractionData = getFractionData(fraction, field); + long scaled = fractionData[0]; + int maxDigits = (int) fractionData[1]; + + if ((scaled & 0x7fffffff) == scaled) { + str = Integer.toString((int) scaled); + } else { + str = Long.toString(scaled); + } + + int length = str.length(); + int digits = maxDigits; + while (length < digits) { + if (buf != null) { + buf.append('0'); + } else { + out.write('0'); + } + minDigits--; + digits--; + } + + if (minDigits < digits) { + // Chop off as many trailing zero digits as necessary. + while (minDigits < digits) { + if (length <= 1 || str.charAt(length - 1) != '0') { + break; + } + digits--; + length--; + } + if (length < str.length()) { + if (buf != null) { + for (int i=0; i '9') { + break; + } + length++; + long nn = n / 10; + value += (c - '0') * nn; + n = nn; + } + + value /= 10; + + if (length == 0) { + return ~position; + } + + if (value > Integer.MAX_VALUE) { + return ~position; + } + + DateTimeField parseField = new PreciseDateTimeField( + DateTimeFieldType.millisOfSecond(), + MillisDurationField.INSTANCE, + field.getDurationField()); + + bucket.saveField(parseField, (int) value); + + return position + length; + } + } + + //----------------------------------------------------------------------- + static class TimeZoneOffsetFormatter + extends BaseDateTimeFormatter + implements DateTimeFormatter { + + private final String iZeroOffsetText; + private final boolean iShowSeparators; + private final int iMinFields; + private final int iMaxFields; + + TimeZoneOffsetFormatter(String zeroOffsetText, + boolean showSeparators, + int minFields, int maxFields) + { + super(); + iZeroOffsetText = zeroOffsetText; + iShowSeparators = showSeparators; + if (minFields <= 0 || maxFields < minFields) { + throw new IllegalArgumentException(); + } + if (minFields > 4) { + minFields = 4; + maxFields = 4; + } + iMinFields = minFields; + iMaxFields = maxFields; + } + + protected int estimatePrintedLength() { + int est = 1 + iMinFields << 1; + if (iShowSeparators) { + est += iMinFields - 1; + } + if (iZeroOffsetText != null && iZeroOffsetText.length() > est) { + est = iZeroOffsetText.length(); + } + return est; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + int offset = (int)(instantLocal - instant); + + if (offset == 0 && iZeroOffsetText != null) { + buf.append(iZeroOffsetText); + return; + } + if (offset >= 0) { + buf.append('+'); + } else { + buf.append('-'); + offset = -offset; + } + + int hours = offset / DateTimeConstants.MILLIS_PER_HOUR; + FormatUtils.appendPaddedInteger(buf, hours, 2); + if (iMaxFields == 1) { + return; + } + offset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR; + if (offset == 0 && iMinFields <= 1) { + return; + } + + int minutes = offset / DateTimeConstants.MILLIS_PER_MINUTE; + if (iShowSeparators) { + buf.append(':'); + } + FormatUtils.appendPaddedInteger(buf, minutes, 2); + if (iMaxFields == 2) { + return; + } + offset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; + if (offset == 0 && iMinFields <= 2) { + return; + } + + int seconds = offset / DateTimeConstants.MILLIS_PER_SECOND; + if (iShowSeparators) { + buf.append(':'); + } + FormatUtils.appendPaddedInteger(buf, seconds, 2); + if (iMaxFields == 3) { + return; + } + offset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; + if (offset == 0 && iMinFields <= 3) { + return; + } + + if (iShowSeparators) { + buf.append('.'); + } + FormatUtils.appendPaddedInteger(buf, offset, 3); + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + int offset = (int)(instantLocal - instant); + + if (offset == 0 && iZeroOffsetText != null) { + out.write(iZeroOffsetText); + return; + } + if (offset >= 0) { + out.write('+'); + } else { + out.write('-'); + offset = -offset; + } + + int hours = offset / DateTimeConstants.MILLIS_PER_HOUR; + FormatUtils.writePaddedInteger(out, hours, 2); + if (iMaxFields == 1) { + return; + } + offset -= hours * (int)DateTimeConstants.MILLIS_PER_HOUR; + if (offset == 0 && iMinFields == 1) { + return; + } + + int minutes = offset / DateTimeConstants.MILLIS_PER_MINUTE; + if (iShowSeparators) { + out.write(':'); + } + FormatUtils.writePaddedInteger(out, minutes, 2); + if (iMaxFields == 2) { + return; + } + offset -= minutes * DateTimeConstants.MILLIS_PER_MINUTE; + if (offset == 0 && iMinFields == 2) { + return; + } + + int seconds = offset / DateTimeConstants.MILLIS_PER_SECOND; + if (iShowSeparators) { + out.write(':'); + } + FormatUtils.writePaddedInteger(out, seconds, 2); + if (iMaxFields == 3) { + return; + } + offset -= seconds * DateTimeConstants.MILLIS_PER_SECOND; + if (offset == 0 && iMinFields == 3) { + return; + } + + if (iShowSeparators) { + out.write('.'); + } + FormatUtils.writePaddedInteger(out, offset, 3); + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + // no zone info + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + // no zone info + } + + protected int estimateParsedLength() { + return estimatePrintedLength(); + } + + protected int parseInto(ParseBucket bucket, String text, int position) { + int limit = text.length() - position; + + zeroOffset: + if (iZeroOffsetText != null) { + if (iZeroOffsetText.length() == 0) { + // Peek ahead, looking for sign character. + if (limit > 0) { + char c = text.charAt(position); + if (c == '-' || c == '+') { + break zeroOffset; + } + } + bucket.setOffset(0); + return position; + } + if (text.regionMatches(true, position, iZeroOffsetText, 0, + iZeroOffsetText.length())) { + bucket.setOffset(0); + return position + iZeroOffsetText.length(); + } + } + + // Format to expect is sign character followed by at least one digit. + + if (limit <= 1) { + return ~position; + } + + boolean negative; + char c = text.charAt(position); + if (c == '-') { + negative = true; + } else if (c == '+') { + negative = false; + } else { + return ~position; + } + + limit--; + position++; + + // Format following sign is one of: + // + // hh + // hhmm + // hhmmss + // hhmmssSSS + // hh:mm + // hh:mm:ss + // hh:mm:ss.SSS + + // First parse hours. + + if (digitCount(text, position, 2) < 2) { + // Need two digits for hour. + return ~position; + } + + int offset; + + int hours = FormatUtils.parseTwoDigits(text, position); + if (hours > 23) { + return ~position; + } + offset = hours * DateTimeConstants.MILLIS_PER_HOUR; + limit -= 2; + position += 2; + + parse: { + // Need to decide now if separators are expected or parsing + // stops at hour field. + + if (limit <= 0) { + break parse; + } + + boolean expectSeparators; + c = text.charAt(position); + if (c == ':') { + expectSeparators = true; + limit--; + position++; + } else if (c >= '0' && c <= '9') { + expectSeparators = false; + } else { + break parse; + } + + // Proceed to parse minutes. + + int count = digitCount(text, position, 2); + if (count == 0 && !expectSeparators) { + break parse; + } else if (count < 2) { + // Need two digits for minute. + return ~position; + } + + int minutes = FormatUtils.parseTwoDigits(text, position); + if (minutes > 59) { + return ~position; + } + offset += minutes * DateTimeConstants.MILLIS_PER_MINUTE; + limit -= 2; + position += 2; + + // Proceed to parse seconds. + + if (limit <= 0) { + break parse; + } + + if (expectSeparators) { + if (text.charAt(position) != ':') { + break parse; + } + limit--; + position++; + } + + count = digitCount(text, position, 2); + if (count == 0 && !expectSeparators) { + break parse; + } else if (count < 2) { + // Need two digits for second. + return ~position; + } + + int seconds = FormatUtils.parseTwoDigits(text, position); + if (seconds > 59) { + return ~position; + } + offset += seconds * DateTimeConstants.MILLIS_PER_SECOND; + limit -= 2; + position += 2; + + // Proceed to parse fraction of second. + + if (limit <= 0) { + break parse; + } + + if (expectSeparators) { + if (text.charAt(position) != '.' && text.charAt(position) != ',') { + break parse; + } + limit--; + position++; + } + + count = digitCount(text, position, 3); + if (count == 0 && !expectSeparators) { + break parse; + } else if (count < 1) { + // Need at least one digit for fraction of second. + return ~position; + } + + offset += (text.charAt(position++) - '0') * 100; + if (count > 1) { + offset += (text.charAt(position++) - '0') * 10; + if (count > 2) { + offset += text.charAt(position++) - '0'; + } + } + } + + bucket.setOffset(negative ? -offset : offset); + return position; + } + + /** + * Returns actual amount of digits to parse, but no more than original + * 'amount' parameter. + */ + private int digitCount(String text, int position, int amount) { + int limit = Math.min(text.length() - position, amount); + amount = 0; + for (; limit > 0; limit--) { + char c = text.charAt(position + amount); + if (c < '0' || c > '9') { + break; + } + amount++; + } + return amount; + } + } + + //----------------------------------------------------------------------- + static class TimeZonePrinter + extends BaseDateTimeFormatter + implements DateTimePrinter { + + private final Locale iLocale; + private final boolean iShortFormat; + + TimeZonePrinter(Locale locale, boolean shortFormat) { + super(); + iLocale = locale; + iShortFormat = shortFormat; + } + + protected int estimatePrintedLength() { + return iShortFormat ? 4 : 20; + } + + protected void printTo(StringBuffer buf, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + buf.append(print(instantLocal, chronoLocal, instant, chrono)); + } + + protected void printTo(Writer out, + long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) throws IOException { + out.write(print(instantLocal, chronoLocal, instant, chrono)); + } + + protected String print(long instantLocal, Chronology chronoLocal, + long instant, Chronology chrono) { + DateTimeZone zone = chrono.getZone(); + if (iShortFormat) { + return zone.getShortName(instant, this.iLocale); + } else { + return zone.getName(instant, this.iLocale); + } + } + + public void printTo(StringBuffer buf, ReadablePartial partial) { + // no zone info + } + + public void printTo(Writer out, ReadablePartial partial) throws IOException { + // no zone info + } + } + + //----------------------------------------------------------------------- + static class Composite + extends BaseDateTimeFormatter + implements DateTimeFormatter { + + private final BaseDateTimeFormatter[] iPrinters; + private final BaseDateTimeFormatter[] iParsers; + + private final int iPrintedLengthEstimate; + private final int iParsedLengthEstimate; + + Composite(List elementPairs) { + super(); + + List printerList = new ArrayList(); + List parserList = new ArrayList(); + + decompose(elementPairs, printerList, parserList); + + if (printerList.size() <= 0) { + iPrinters = null; + iPrintedLengthEstimate = 0; + } else { + int size = printerList.size(); + iPrinters = new BaseDateTimeFormatter[size]; + int printEst = 0; + for (int i=0; i= 0; i++) { + position = elements[i].parseInto(bucket, text, position); + } + return position; + } + + boolean isPrinter() { + return iPrinters != null; + } + + boolean isParser() { + return iParsers != null; + } + + /** + * Processes the element pairs, putting results into the given printer + * and parser lists. + */ + private void decompose(List elementPairs, List printerList, List parserList) { + int size = elementPairs.size(); + for (int i=0; i=0 ;) { + BaseDateTimeFormatter parser = parsers[i]; + if (parser != null) { + int len = parser.estimateParsedLength(); + if (len > est) { + len = est; + } + } + } + iParsedLengthEstimate = est; + } + + protected int estimateParsedLength() { + return iParsedLengthEstimate; + } + + protected int parseInto(ParseBucket bucket, String text, int position) { + BaseDateTimeFormatter[] parsers = iParsers; + int length = parsers.length; + + final Object originalState = bucket.saveState(); + boolean isOptional = false; + + int bestValidPos = position; + Object bestValidState = null; + + int bestInvalidPos = position; + + for (int i=0; i= position) { + if (parsePos > bestValidPos) { + if (parsePos >= text.length() || + (i + 1) >= length || parsers[i + 1] == null) { + + // Completely parsed text or no more parsers to + // check. Skip the rest. + return parsePos; + } + bestValidPos = parsePos; + bestValidState = bucket.saveState(); + } + } else { + if (parsePos < 0) { + parsePos = ~parsePos; + if (parsePos > bestInvalidPos) { + bestInvalidPos = parsePos; + } + } + } + bucket.restoreState(originalState); + } + + if (bestValidPos > position || (bestValidPos == position && isOptional)) { + // Restore the state to the best valid parse. + if (bestValidState != null) { + bucket.restoreState(bestValidState); + } + return bestValidPos; + } + + return ~bestInvalidPos; + } + } +} Index: 3rdParty_sources/joda-time/org/joda/time/format/DateTimeParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/DateTimeParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/DateTimeParser.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,240 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.MutableDateTime; +import org.joda.time.ReadWritableInstant; +import org.joda.time.ReadableInstant; + +/** + * Defines an interface for parsing textual representations of datetimes. + *

+ * Note: This interface represents a view onto {@link BaseDateTimeFormatter}. + * All implementations must extend BaseDateTimeFormatter. + * + * @author Brian S O'Neill + * @see DateTimeFormatter + * @see DateTimeFormatterBuilder + * @see DateTimeFormat + * @since 1.0 + */ +public interface DateTimeParser { + + /** + * Parses a datetime from the given text, at the given position, saving the + * result into the fields of the given ReadWritableInstant. If the parse + * succeeds, the return value is the new text position. Note that the parse + * may succeed without fully reading the text. + *

+ * If it fails, the return value is negative, but the instant may still be + * modified. To determine the position where the parse failed, apply the + * one's complement operator (~) on the return value. + *

+ * The parse will use the chronology of the instant. + * + * @param instant an instant that will be modified + * @param text the text to parse + * @param position position to start parsing from + * @return new position, negative value means parse failed - + * apply complement operator (~) to get position of failure + * @throws IllegalArgumentException if the instant is null + * @throws IllegalArgumentException if any field is out of range + */ + int parseInto(ReadWritableInstant instant, String text, int position); + + //----------------------------------------------------------------------- + /** + * Parses a datetime from the given text, returning the number of + * milliseconds since the epoch, 1970-01-01T00:00:00Z. + *

+ * The parse will use the ISO chronology, and the default time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text text to parse + * @return parsed value expressed in milliseconds since the epoch + * @throws IllegalArgumentException if the text to parse is invalid + */ + long parseMillis(String text); + + /** + * Parses a datetime from the given text, returning the number of + * milliseconds since the epoch, 1970-01-01T00:00:00Z. + *

+ * The parse will use the given chronology and time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @param chrono the chronology to use, null means ISO default + * @return parsed value expressed in milliseconds since the epoch + * @throws IllegalArgumentException if the text to parse is invalid + */ + long parseMillis(String text, Chronology chrono); + + //----------------------------------------------------------------------- + /** + * Parses a datetime from the given text, at the given position, returning + * the number of milliseconds since the epoch, 1970-01-01T00:00:00Z. + * An initial millisecond value is passed in, which is relative to the epoch, + * local time, and which can default field values. + *

+ * The parse will use the ISO chronology and default time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @param instant initial value of instant, relative to the epoch, local time + * @return parsed value expressed in milliseconds since the epoch, UTC + * @throws IllegalArgumentException if the text to parse is invalid + */ + long parseMillis(String text, long instant); + + /** + * Parses a datetime from the given text, at the given position, returning + * the number of milliseconds since the epoch, 1970-01-01T00:00:00Z. + * An initial millisecond value is passed in, which is relative to the epoch, + * which can default field values. + *

+ * The parse will use the given chronology and time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @param instant initial value of instant, relative to the epoch + * @param chrono the chronology to use, null means ISO default + * @return parsed value expressed in milliseconds since the epoch, UTC + * @throws IllegalArgumentException if the text to parse is invalid + */ + long parseMillis(String text, long instant, Chronology chrono); + + //----------------------------------------------------------------------- + /** + * Parses a datetime from the given text, returning a new DateTime. + *

+ * The parse will use the ISO chronology and default time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @return parsed value in a DateTime object + * @throws IllegalArgumentException if the text to parse is invalid + */ + DateTime parseDateTime(String text); + + /** + * Parses a datetime from the given text, returning a new DateTime. + *

+ * The parse will use the given chronology and time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @param chrono the chronology to use, null means ISO default + * @return parsed value in a DateTime object + * @throws IllegalArgumentException if the text to parse is invalid + */ + DateTime parseDateTime(String text, Chronology chrono); + + /** + * Parses a datetime from the given text, returning a new DateTime, using + * the given instant to supply field values that were not parsed. + *

+ * The parse will use the instant's chronology and time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @param instant initial value of DateTime + * @return parsed value in a DateTime object + * @throws IllegalArgumentException if the text to parse is invalid + */ + DateTime parseDateTime(String text, ReadableInstant instant); + + //----------------------------------------------------------------------- + /** + * Parses a datetime from the given text, returning a new MutableDateTime. + *

+ * The parse will use the ISO chronology and default time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @return parsed value in a MutableDateTime object + * @throws IllegalArgumentException if the text to parse is invalid + */ + MutableDateTime parseMutableDateTime(String text); + + /** + * Parses a datetime from the given text, returning a new MutableDateTime. + *

+ * The parse will use the given chronology and time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @param chrono the chronology to use, null means ISO default + * @return parsed value in a MutableDateTime object + * @throws IllegalArgumentException if the text to parse is invalid + */ + MutableDateTime parseMutableDateTime(String text, Chronology chrono); + + /** + * Parses a datetime from the given text, returning a new MutableDateTime, + * using the given instant to supply field values that were not parsed. + *

+ * The parse will use the instant's chronology and time zone. + * If the text contains a time zone string then that will be taken into account. + * + * @param text the text to parse + * @param instant initial value of DateTime + * @return parsed value in a MutableDateTime object + * @throws IllegalArgumentException if the text to parse is invalid + */ + MutableDateTime parseMutableDateTime(String text, ReadableInstant instant); + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/DateTimePrinter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/DateTimePrinter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/DateTimePrinter.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,221 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeZone; +import org.joda.time.ReadableInstant; +import org.joda.time.ReadablePartial; + +/** + * Defines an interface for creating textual representations of datetimes. + *

+ * Instances of this interface are provided by the various builder classes. + *

+ * Note: This interface represents a view onto {@link BaseDateTimeFormatter}. + * All implementations must extend BaseDateTimeFormatter. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @see DateTimeFormatterBuilder + * @see DateTimeFormat + * @see ISODateTimeFormat + * @since 1.0 + */ +public interface DateTimePrinter { + + /** + * Prints a ReadableInstant, using the chronology supplied by the instant. + * + * @param buf formatted instant is appended to this buffer + * @param instant instant to format, null means now + */ + void printTo(StringBuffer buf, ReadableInstant instant); + + /** + * Prints a ReadableInstant, using the chronology supplied by the instant. + * + * @param out formatted instant is written out + * @param instant instant to format, null means now + */ + void printTo(Writer out, ReadableInstant instant) throws IOException; + + //----------------------------------------------------------------------- + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using ISO chronology in the default DateTimeZone. + * + * @param buf formatted instant is appended to this buffer + * @param instant millis since 1970-01-01T00:00:00Z + */ + void printTo(StringBuffer buf, long instant); + + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using ISO chronology in the default DateTimeZone. + * + * @param out formatted instant is written out + * @param instant millis since 1970-01-01T00:00:00Z + */ + void printTo(Writer out, long instant) throws IOException; + + //----------------------------------------------------------------------- + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using ISO chronology in the given DateTimeZone. + * + * @param buf formatted instant is appended to this buffer + * @param instant millis since 1970-01-01T00:00:00Z + * @param zone the zone to use, null means default + */ + void printTo(StringBuffer buf, long instant, DateTimeZone zone); + + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using ISO chronology in the given DateTimeZone. + * + * @param out formatted instant is written out + * @param instant millis since 1970-01-01T00:00:00Z + * @param zone the zone to use, null means default + */ + void printTo(Writer out, long instant, DateTimeZone zone) throws IOException; + + //----------------------------------------------------------------------- + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using the given Chronology. + * + * @param buf formatted instant is appended to this buffer + * @param instant millis since 1970-01-01T00:00:00Z + * @param chrono the chronology to use, null means ISO default + */ + void printTo(StringBuffer buf, long instant, Chronology chrono); + + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using the given Chronology. + * + * @param out formatted instant is written out + * @param instant millis since 1970-01-01T00:00:00Z + * @param chrono the chronology to use, null means ISO default + */ + void printTo(Writer out, long instant, Chronology chrono) throws IOException; + + //----------------------------------------------------------------------- + /** + * Prints a ReadablePartial. + * + * @param buf formatted partial is appended to this buffer + * @param partial partial to format + */ + void printTo(StringBuffer buf, ReadablePartial partial); + + /** + * Prints a ReadablePartial. + * + * @param out formatted partial is written out + * @param partial partial to format + */ + void printTo(Writer out, ReadablePartial partial) throws IOException; + + //----------------------------------------------------------------------- + /** + * Prints a ReadableInstant to a new String, using the chronology of the instant. + * + * @param instant instant to format, null means now + * @return the printed result + */ + String print(ReadableInstant instant); + + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using ISO chronology in the default zone. + * + * @param instant millis since 1970-01-01T00:00:00Z + * @return the printed result + */ + String print(long instant); + + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using ISO chronology in the given zone. + * + * @param instant millis since 1970-01-01T00:00:00Z + * @param zone the zone to use, null means default + * @return the printed result + */ + String print(long instant, DateTimeZone zone); + + /** + * Prints an instant from milliseconds since 1970-01-01T00:00:00Z, + * using the given chronology. + * + * @param instant millis since 1970-01-01T00:00:00Z + * @param chrono the chronoogy to use + * @return the printed result + */ + String print(long instant, Chronology chrono); + + /** + * Prints a ReadablePartial to a new String. + * + * @param partial partial to format + * @return the printed result + */ + String print(ReadablePartial partial); + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/FormatUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/FormatUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/FormatUtils.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,395 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; + +/** + * Utility methods used by formatters. + *

+ * FormatUtils is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public class FormatUtils { + + private static final double LOG_10 = Math.log(10); + + /** + * Restricted constructor. + */ + private FormatUtils() { + } + + /** + * Converts an integer to a string, prepended with a variable amount of '0' + * pad characters, and appends it to the given buffer. + * + *

This method is optimized for converting small values to strings. + * + * @param buf receives integer converted to a string + * @param value value to convert to a string + * @param size minumum amount of digits to append + */ + public static void appendPaddedInteger(StringBuffer buf, int value, int size) { + if (value < 0) { + buf.append('-'); + if (value != Integer.MIN_VALUE) { + value = -value; + } else { + for (; size > 10; size--) { + buf.append('0'); + } + buf.append("" + -(long)Integer.MIN_VALUE); + return; + } + } + if (value < 10) { + for (; size > 1; size--) { + buf.append('0'); + } + buf.append((char)(value + '0')); + } else if (value < 100) { + for (; size > 2; size--) { + buf.append('0'); + } + buf.append((char)(value / 10 + '0')); + buf.append((char)(value % 10 + '0')); + } else { + int digits; + if (value < 1000) { + digits = 3; + } else if (value < 10000) { + digits = 4; + } else { + digits = (int)(Math.log(value) / LOG_10) + 1; + } + for (; size > digits; size--) { + buf.append('0'); + } + buf.append(Integer.toString(value)); + } + } + + /** + * Converts an integer to a string, prepended with a variable amount of '0' + * pad characters, and appends it to the given buffer. + * + *

This method is optimized for converting small values to strings. + * + * @param buf receives integer converted to a string + * @param value value to convert to a string + * @param size minumum amount of digits to append + */ + public static void appendPaddedInteger(StringBuffer buf, long value, int size) { + int intValue = (int)value; + if (intValue == value) { + appendPaddedInteger(buf, intValue, size); + } else if (size <= 19) { + buf.append(Long.toString(value)); + } else { + if (value < 0) { + buf.append('-'); + if (value != Long.MIN_VALUE) { + value = -value; + } else { + for (; size > 19; size--) { + buf.append('0'); + } + buf.append("9223372036854775808"); + return; + } + } + int digits = (int)(Math.log(value) / LOG_10) + 1; + for (; size > digits; size--) { + buf.append('0'); + } + buf.append(Long.toString(value)); + } + } + + /** + * Converts an integer to a string, prepended with a variable amount of '0' + * pad characters, and writes it to the given writer. + * + *

This method is optimized for converting small values to strings. + * + * @param out receives integer converted to a string + * @param value value to convert to a string + * @param size minumum amount of digits to append + */ + public static void writePaddedInteger(Writer out, int value, int size) + throws IOException + { + if (value < 0) { + out.write('-'); + if (value != Integer.MIN_VALUE) { + value = -value; + } else { + for (; size > 10; size--) { + out.write('0'); + } + out.write("" + -(long)Integer.MIN_VALUE); + return; + } + } + if (value < 10) { + for (; size > 1; size--) { + out.write('0'); + } + out.write(value + '0'); + } else if (value < 100) { + for (; size > 2; size--) { + out.write('0'); + } + out.write(value / 10 + '0'); + out.write(value % 10 + '0'); + } else { + int digits; + if (value < 1000) { + digits = 3; + } else if (value < 10000) { + digits = 4; + } else { + digits = (int)(Math.log(value) / LOG_10) + 1; + } + for (; size > digits; size--) { + out.write('0'); + } + out.write(Integer.toString(value)); + } + } + + /** + * Converts an integer to a string, prepended with a variable amount of '0' + * pad characters, and writes it to the given writer. + * + *

This method is optimized for converting small values to strings. + * + * @param out receives integer converted to a string + * @param value value to convert to a string + * @param size minumum amount of digits to append + */ + public static void writePaddedInteger(Writer out, long value, int size) + throws IOException + { + int intValue = (int)value; + if (intValue == value) { + writePaddedInteger(out, intValue, size); + } else if (size <= 19) { + out.write(Long.toString(value)); + } else { + if (value < 0) { + out.write('-'); + if (value != Long.MIN_VALUE) { + value = -value; + } else { + for (; size > 19; size--) { + out.write('0'); + } + out.write("9223372036854775808"); + return; + } + } + int digits = (int)(Math.log(value) / LOG_10) + 1; + for (; size > digits; size--) { + out.write('0'); + } + out.write(Long.toString(value)); + } + } + + /** + * Converts an integer to a string, and appends it to the given buffer. + * + *

This method is optimized for converting small values to strings. + * + * @param buf receives integer converted to a string + * @param value value to convert to a string + */ + public static void appendUnpaddedInteger(StringBuffer buf, int value) { + if (value < 0) { + buf.append('-'); + if (value != Integer.MIN_VALUE) { + value = -value; + } else { + buf.append("" + -(long)Integer.MIN_VALUE); + return; + } + } + if (value < 10) { + buf.append((char)(value + '0')); + } else if (value < 100) { + buf.append((char)(value / 10 + '0')); + buf.append((char)(value % 10 + '0')); + } else { + buf.append(Integer.toString(value)); + } + } + + /** + * Converts an integer to a string, and appends it to the given buffer. + * + *

This method is optimized for converting small values to strings. + * + * @param buf receives integer converted to a string + * @param value value to convert to a string + */ + public static void appendUnpaddedInteger(StringBuffer buf, long value) { + int intValue = (int)value; + if (intValue == value) { + appendUnpaddedInteger(buf, intValue); + } else { + buf.append(Long.toString(value)); + } + } + + /** + * Converts an integer to a string, and writes it to the given writer. + * + *

This method is optimized for converting small values to strings. + * + * @param out receives integer converted to a string + * @param value value to convert to a string + */ + public static void writeUnpaddedInteger(Writer out, int value) + throws IOException + { + if (value < 0) { + out.write('-'); + if (value != Integer.MIN_VALUE) { + value = -value; + } else { + out.write("" + -(long)Integer.MIN_VALUE); + return; + } + } + if (value < 10) { + out.write(value + '0'); + } else if (value < 100) { + out.write(value / 10 + '0'); + out.write(value % 10 + '0'); + } else { + out.write(Integer.toString(value)); + } + } + + /** + * Converts an integer to a string, and writes it to the given writer. + * + *

This method is optimized for converting small values to strings. + * + * @param out receives integer converted to a string + * @param value value to convert to a string + */ + public static void writeUnpaddedInteger(Writer out, long value) + throws IOException + { + int intValue = (int)value; + if (intValue == value) { + writeUnpaddedInteger(out, intValue); + } else { + out.write(Long.toString(value)); + } + } + + /** + * Calculates the number of decimal digits for the given value, + * including the sign. + */ + public static int calculateDigitCount(long value) { + if (value < 0) { + if (value != Long.MIN_VALUE) { + return calculateDigitCount(-value) + 1; + } else { + return 20; + } + } + return + (value < 10 ? 1 : + (value < 100 ? 2 : + (value < 1000 ? 3 : + (value < 10000 ? 4 : + ((int)(Math.log(value) / LOG_10) + 1))))); + } + + static int parseTwoDigits(String text, int position) { + int value = text.charAt(position) - '0'; + return ((value << 3) + (value << 1)) + text.charAt(position + 1) - '0'; + } + + static String createErrorMessage(final String text, final int errorPos) { + int sampleLen = errorPos + 20; + String sampleText; + if (text.length() <= sampleLen + 3) { + sampleText = text; + } else { + sampleText = text.substring(0, sampleLen).concat("..."); + } + + if (errorPos <= 0) { + return "Invalid format: \"" + sampleText + '"'; + } + + if (errorPos >= text.length()) { + return "Invalid format: \"" + sampleText + "\" is too short"; + } + + return "Invalid format: \"" + sampleText + "\" is malformed at \"" + + sampleText.substring(errorPos) + '"'; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/ISODateTimeFormat.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/ISODateTimeFormat.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/ISODateTimeFormat.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,1102 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + + +/** + * ISODateTimeFormat provides factory methods for the ISO8601 standard. + *

+ * ISO8601 is the international standard for data interchange. It defines a + * framework, rather than an absolute standard. As a result this provider has a + * number of methods that represent common uses of the framework. The most common + * formats are {@link #date() date}, {@link #time() time}, and {@link #dateTime() dateTime}. + *

+ * For example, to format a date time in ISO format: + *

+ * DateTime dt = new DateTime();
+ * DateTimeFormatter fmt = DateTimeFormat.getInstance().dateTime();
+ * String str = fmt.print(dt);
+ * 
+ *

+ * ISODateTimeFormat is thread-safe and immutable, and the formatters it + * returns are as well. + * + * @author Brian S O'Neill + * @since 1.0 + * @see DateTimeFormat + * @see DateTimeFormatterBuilder + */ +public class ISODateTimeFormat { + + /** The singleton instance. */ + private static final ISODateTimeFormat INSTANCE = new ISODateTimeFormat(); + + /** + * Gets an instance of a the format provider. + * + * @return a format provider + */ + public static ISODateTimeFormat getInstance() { + return INSTANCE; + } + + //----------------------------------------------------------------------- + private transient DateTimeFormatter + ye, // year element (yyyy) + mye, // monthOfYear element (-MM) + dme, // dayOfMonth element (-dd) + we, // weekyear element (xxxx) + wwe, // weekOfWeekyear element (-ww) + dwe, // dayOfWeek element (-ee) + dye, // dayOfYear element (-DDD) + hde, // hourOfDay element (HH) + mhe, // minuteOfHour element (:mm) + sme, // secondOfMinute element (:ss) + lse, // millisOfSecond element (.SSS) + fse, // fractionOfSecond element (.SSSSSSSSS) + ze, // zone offset element + lte, // literal 'T' element + + //y, // year (same as year element) + ym, // year month + ymd, // year month day + + //w, // weekyear (same as weekyear element) + ww, // weekyear week + wwd, // weekyear week day + + //h, // hour (same as hour element) + hm, // hour minute + hms, // hour minute second + hmsl, // hour minute second millis + hmsf, // hour minute second fraction + + dh, // date hour + dhm, // date hour minute + dhms, // date hour minute second + dhmsl, // date hour minute second millis + dhmsf, // date hour minute second fraction + + //d, // date (same as ymd) + t, // time + tx, // time no millis + tt, // Ttime + ttx, // Ttime no millis + dt, // date time + dtx, // date time no millis + + //wd, // week date (same as wwd) + wdt, // week date time + wdtx, // week date time no millis + + bd, // basic date + bt, // basic time + btx, // basic time no millis + btt, // basic Ttime + bttx, // basic Ttime no millis + bdt, // basic date time + bdtx, // basic date time no millis + + bwd, // basic week date + bwdt, // basic week date time + bwdtx; // basic week date time no millis + + private transient DateTimeParser + dpe, // date parser element + tpe, // time parser element + dp, // date parser + tp, // time parser + dtp; // date time parser + + /** + * Restricted constructor. + * + * @param chrono the chronology to use, must not be null + */ + private ISODateTimeFormat() { + } + + //----------------------------------------------------------------------- + /** + * Returns a generic ISO date parser. It accepts formats described by + * the following syntax: + *

+     * date              = date-element ['T' offset]
+     * date-element      = std-date-element | ord-date-element | week-date-element
+     * std-date-element  = yyyy ['-' MM ['-' dd]]
+     * ord-date-element  = yyyy ['-' DDD]
+     * week-date-element = xxxx '-W' ww ['-' e]
+     * offset            = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
+     * 
+ */ + public DateTimeParser dateParser() { + if (dp == null) { + dp = new DateTimeFormatterBuilder() + .append(dateElementParser()) + .appendOptional + (new DateTimeFormatterBuilder() + .appendLiteral('T') + .append(offsetElement()) + .toParser()) + .toParser(); + } + return dp; + } + + /** + * Returns a generic ISO date parser. It accepts formats described by + * the following syntax: + *
+     * date-element      = std-date-element | ord-date-element | week-date-element
+     * std-date-element  = yyyy ['-' MM ['-' dd]]
+     * ord-date-element  = yyyy ['-' DDD]
+     * week-date-element = xxxx '-W' ww ['-' e]
+     * 
+ */ + public DateTimeParser dateElementParser() { + if (dpe == null) { + dpe = new DateTimeFormatterBuilder() + .append(null, new DateTimeParser[] { + new DateTimeFormatterBuilder() + .append(yearElement()) + .appendOptional + (new DateTimeFormatterBuilder() + .append(monthElement()) + .appendOptional(dayOfMonthElement()) + .toParser()) + .toParser(), + new DateTimeFormatterBuilder() + .append(weekyearElement()) + .append(weekElement()) + .appendOptional(dayOfWeekElement()) + .toParser(), + new DateTimeFormatterBuilder() + .append(yearElement()) + .append(dayOfYearElement()) + .toParser() + }) + .toParser(); + } + return dpe; + } + + /** + * Returns a generic ISO time parser. It accepts formats described by + * the following syntax: + *
+     * time           = ['T'] time-element [offset]
+     * time-element   = HH [minute-element] | [fraction]
+     * minute-element = ':' mm [second-element] | [fraction]
+     * second-element = ':' ss [fraction]
+     * fraction       = ('.' | ',') digit+
+     * offset         = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
+     * 
+ */ + public DateTimeParser timeParser() { + if (tp == null) { + tp = new DateTimeFormatterBuilder() + .appendOptional + (new DateTimeFormatterBuilder() + .appendLiteral('T') + .toParser()) + .append(timeElementParser()) + .appendOptional(offsetElement()) + .toParser(); + } + return tp; + } + + /** + * Returns a generic ISO time parser. It accepts formats described by + * the following syntax: + *
+     * time-element   = HH [minute-element] | [fraction]
+     * minute-element = ':' mm [second-element] | [fraction]
+     * second-element = ':' ss [fraction]
+     * fraction       = ('.' | ',') digit+
+     * 
+ */ + public DateTimeParser timeElementParser() { + if (tpe == null) { + // Decimal point can be either '.' or ',' + DateTimeParser decimalPoint = new DateTimeFormatterBuilder() + .append(null, new DateTimeParser[] { + new DateTimeFormatterBuilder() + .appendLiteral('.') + .toParser(), + new DateTimeFormatterBuilder() + .appendLiteral(',') + .toParser() + }) + .toParser(); + + tpe = new DateTimeFormatterBuilder() + // time-element + .append(hourElement()) + .append + (null, new DateTimeParser[] { + new DateTimeFormatterBuilder() + // minute-element + .append(minuteElement()) + .append + (null, new DateTimeParser[] { + new DateTimeFormatterBuilder() + // second-element + .append(secondElement()) + // second fraction + .appendOptional(new DateTimeFormatterBuilder() + .append(decimalPoint) + .appendFractionOfSecond(1, 9) + .toParser()) + .toParser(), + // minute fraction + new DateTimeFormatterBuilder() + .append(decimalPoint) + .appendFractionOfMinute(1, 9) + .toParser(), + null + }) + .toParser(), + // hour fraction + new DateTimeFormatterBuilder() + .append(decimalPoint) + .appendFractionOfHour(1, 9) + .toParser(), + null + }) + .toParser(); + } + return tpe; + } + + /** + * Returns a generic ISO datetime parser. It accepts formats described by + * the following syntax: + *
+     * datetime          = time | (date-element [time | ('T' offset)])
+     * time              = 'T' time-element [offset]
+     * date-element      = std-date-element | ord-date-element | week-date-element
+     * std-date-element  = yyyy ['-' MM ['-' dd]]
+     * ord-date-element  = yyyy ['-' DDD]
+     * week-date-element = xxxx '-W' ww ['-' e]
+     * time-element      = HH [minute-element] | [fraction]
+     * minute-element    = ':' mm [second-element] | [fraction]
+     * second-element    = ':' ss [fraction]
+     * fraction          = ('.' | ',') digit+
+     * offset            = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
+     * 
+ */ + public DateTimeParser dateTimeParser() { + if (dtp == null) { + // This is different from the general time parser in that the 'T' + // is required. + DateTimeParser time = new DateTimeFormatterBuilder() + .appendLiteral('T') + .append(timeElementParser()) + .appendOptional(offsetElement()) + .toParser(); + + dtp = new DateTimeFormatterBuilder() + .append(null, new DateTimeParser[] { + time, + new DateTimeFormatterBuilder() + .append(dateElementParser()) + .append(null, new DateTimeParser[] { + time, + new DateTimeFormatterBuilder() + .appendLiteral('T') + .append(offsetElement()) + .toParser(), + null + }) + .toParser() + }) + .toParser(); + } + return dtp; + } + + //----------------------------------------------------------------------- + /** + * Returns a formatter for a full date as four digit year, two digit month + * of year, and two digit day of month (yyyy-MM-dd). + * + * @return a formatter for yyyy-MM-dd + */ + public DateTimeFormatter date() { + return yearMonthDay(); + } + + /** + * Returns a formatter for a two digit hour of day, two digit minute of + * hour, two digit second of minute, three digit fraction of second, and + * time zone offset (HH:mm:ss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for HH:mm:ss.SSSZ + */ + public DateTimeFormatter time() { + if (t == null) { + t = new DateTimeFormatterBuilder() + .append(hourMinuteSecondMillis()) + .append(offsetElement()) + .toFormatter(); + } + return t; + } + + /** + * Returns a formatter for a two digit hour of day, two digit minute of + * hour, two digit second of minute, and time zone offset (HH:mm:ssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for HH:mm:ssZ + */ + public DateTimeFormatter timeNoMillis() { + if (tx == null) { + tx = new DateTimeFormatterBuilder() + .append(hourMinuteSecond()) + .append(offsetElement()) + .toFormatter(); + } + return tx; + } + + /** + * Returns a formatter for a two digit hour of day, two digit minute of + * hour, two digit second of minute, three digit fraction of second, and + * time zone offset prefixed by 'T' ('T'HH:mm:ss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for 'T'HH:mm:ss.SSSZ + */ + public DateTimeFormatter tTime() { + if (tt == null) { + tt = new DateTimeFormatterBuilder() + .append(literalTElement()) + .append(time()) + .toFormatter(); + } + return tt; + } + + /** + * Returns a formatter for a two digit hour of day, two digit minute of + * hour, two digit second of minute, and time zone offset prefixed + * by 'T' ('T'HH:mm:ssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for 'T'HH:mm:ssZ + */ + public DateTimeFormatter tTimeNoMillis() { + if (ttx == null) { + ttx = new DateTimeFormatterBuilder() + .append(literalTElement()) + .append(timeNoMillis()) + .toFormatter(); + } + return ttx; + } + + /** + * Returns a formatter that combines a full date and time, separated by a 'T' + * (yyyy-MM-dd'T'HH:mm:ss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSSZ + */ + public DateTimeFormatter dateTime() { + if (dt == null) { + dt = new DateTimeFormatterBuilder() + .append(date()) + .append(tTime()) + .toFormatter(); + } + return dt; + } + + /** + * Returns a formatter that combines a full date and time without millis, + * separated by a 'T' (yyyy-MM-dd'T'HH:mm:ssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for yyyy-MM-dd'T'HH:mm:ssZ + */ + public DateTimeFormatter dateTimeNoMillis() { + if (dtx == null) { + dtx = new DateTimeFormatterBuilder() + .append(date()) + .append(tTimeNoMillis()) + .toFormatter(); + } + return dtx; + } + + /** + * Returns a formatter for a full date as four digit weekyear, two digit + * week of weekyear, and one digit day of week (xxxx-'W'ww-e). + * + * @return a formatter for xxxx-'W'ww-e + */ + public DateTimeFormatter weekDate() { + return weekyearWeekDay(); + } + + /** + * Returns a formatter that combines a full weekyear date and time, + * separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for xxxx-'W'ww-e'T'HH:mm:ss.SSSZ + */ + public DateTimeFormatter weekDateTime() { + if (wdt == null) { + wdt = new DateTimeFormatterBuilder() + .append(weekDate()) + .append(tTime()) + .toFormatter(); + } + return wdt; + } + + /** + * Returns a formatter that combines a full weekyear date and time without millis, + * separated by a 'T' (xxxx-'W'ww-e'T'HH:mm:ssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for xxxx-'W'ww-e'T'HH:mm:ssZ + */ + public DateTimeFormatter weekDateTimeNoMillis() { + if (wdtx == null) { + wdtx = new DateTimeFormatterBuilder() + .append(weekDate()) + .append(tTimeNoMillis()) + .toFormatter(); + } + return wdtx; + } + + //----------------------------------------------------------------------- + /** + * Returns a basic formatter for a full date as four digit year, two digit + * month of year, and two digit day of month (yyyyMMdd). + * + * @return a formatter for yyyyMMdd + */ + public DateTimeFormatter basicDate() { + if (bd == null) { + bd = new DateTimeFormatterBuilder() + .appendYear(4, 4) + .appendMonthOfYear(2) + .appendDayOfMonth(2) + .toFormatter(); + } + return bd; + } + + /** + * Returns a basic formatter for a two digit hour of day, two digit minute + * of hour, two digit second of minute, three digit millis, and time zone + * offset (HHmmss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for HHmmss.SSSZ + */ + public DateTimeFormatter basicTime() { + if (bt == null) { + bt = new DateTimeFormatterBuilder() + .appendHourOfDay(2) + .appendMinuteOfHour(2) + .appendSecondOfMinute(2) + .appendLiteral('.') + .appendMillisOfSecond(3) + .appendTimeZoneOffset("Z", false, 2, 2) + .toFormatter(); + } + return bt; + } + + /** + * Returns a basic formatter for a two digit hour of day, two digit minute + * of hour, two digit second of minute, and time zone offset (HHmmssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for HHmmssZ + */ + public DateTimeFormatter basicTimeNoMillis() { + if (btx == null) { + btx = new DateTimeFormatterBuilder() + .appendHourOfDay(2) + .appendMinuteOfHour(2) + .appendSecondOfMinute(2) + .appendTimeZoneOffset("Z", false, 2, 2) + .toFormatter(); + } + return btx; + } + + /** + * Returns a basic formatter for a two digit hour of day, two digit minute + * of hour, two digit second of minute, three digit millis, and time zone + * offset prefixed by 'T' ('T'HHmmss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for 'T'HHmmss.SSSZ + */ + public DateTimeFormatter basicTTime() { + if (btt == null) { + btt = new DateTimeFormatterBuilder() + .append(literalTElement()) + .append(basicTime()) + .toFormatter(); + } + return btt; + } + + /** + * Returns a basic formatter for a two digit hour of day, two digit minute + * of hour, two digit second of minute, and time zone offset prefixed by 'T' + * ('T'HHmmssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for 'T'HHmmssZ + */ + public DateTimeFormatter basicTTimeNoMillis() { + if (bttx == null) { + bttx = new DateTimeFormatterBuilder() + .append(literalTElement()) + .append(basicTimeNoMillis()) + .toFormatter(); + } + return bttx; + } + + /** + * Returns a basic formatter that combines a basic date and time, separated + * by a 'T' (yyyyMMdd'T'HHmmss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for yyyyMMdd'T'HHmmss.SSSZ + */ + public DateTimeFormatter basicDateTime() { + if (bdt == null) { + bdt = new DateTimeFormatterBuilder() + .append(basicDate()) + .append(basicTTime()) + .toFormatter(); + } + return bdt; + } + + /** + * Returns a basic formatter that combines a basic date and time without millis, + * separated by a 'T' (yyyyMMdd'T'HHmmssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for yyyyMMdd'T'HHmmssZ + */ + public DateTimeFormatter basicDateTimeNoMillis() { + if (bdtx == null) { + bdtx = new DateTimeFormatterBuilder() + .append(basicDate()) + .append(basicTTimeNoMillis()) + .toFormatter(); + } + return bdtx; + } + + /** + * Returns a basic formatter for a full date as four digit weekyear, two + * digit week of weekyear, and one digit day of week (xxxx'W'wwe). + * + * @return a formatter for xxxx'W'wwe + */ + public DateTimeFormatter basicWeekDate() { + if (bwd == null) { + bwd = new DateTimeFormatterBuilder() + .appendWeekyear(4, 4) + .appendLiteral('W') + .appendWeekOfWeekyear(2) + .appendDayOfWeek(1) + .toFormatter(); + } + return bwd; + } + + /** + * Returns a basic formatter that combines a basic weekyear date and time, + * separated by a 'T' (xxxx'W'wwe'T'HHmmss.SSSZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for xxxx'W'wwe'T'HHmmss.SSSZ + */ + public DateTimeFormatter basicWeekDateTime() { + if (bwdt == null) { + bwdt = new DateTimeFormatterBuilder() + .append(basicWeekDate()) + .append(basicTTime()) + .toFormatter(); + } + return bwdt; + } + + /** + * Returns a basic formatter that combines a basic weekyear date and time + * without millis, separated by a 'T' (xxxx'W'wwe'T'HHmmssZ). + * The time zone offset is 'Z' for zero, and of the form '\u00b1HH:mm' for non-zero. + * + * @return a formatter for xxxx'W'wwe'T'HHmmssZ + */ + public DateTimeFormatter basicWeekDateTimeNoMillis() { + if (bwdtx == null) { + bwdtx = new DateTimeFormatterBuilder() + .append(basicWeekDate()) + .append(basicTTimeNoMillis()) + .toFormatter(); + } + return bwdtx; + } + + //----------------------------------------------------------------------- + /** + * Returns a formatter for a four digit year. (yyyy) + * + * @return a formatter for yyyy + */ + public DateTimeFormatter year() { + return yearElement(); + } + + /** + * Returns a formatter for a four digit year and two digit month of + * year. (yyyy-MM) + * + * @return a formatter for yyyy-MM + */ + public DateTimeFormatter yearMonth() { + if (ym == null) { + ym = new DateTimeFormatterBuilder() + .append(yearElement()) + .append(monthElement()) + .toFormatter(); + } + return ym; + } + + /** + * Returns a formatter for a four digit year, two digit month of year, and + * two digit day of month. (yyyy-MM-dd) + * + * @return a formatter for yyyy-MM-dd + */ + public DateTimeFormatter yearMonthDay() { + if (ymd == null) { + ymd = new DateTimeFormatterBuilder() + .append(yearElement()) + .append(monthElement()) + .append(dayOfMonthElement()) + .toFormatter(); + } + return ymd; + } + + /** + * Returns a formatter for a four digit weekyear. (xxxx) + * + * @return a formatter for xxxx + */ + public DateTimeFormatter weekyear() { + return weekyearElement(); + } + + /** + * Returns a formatter for a four digit weekyear and two digit week of + * weekyear. (xxxx-'W'ww) + * + * @return a formatter for xxxx-'W'ww + */ + public DateTimeFormatter weekyearWeek() { + if (ww == null) { + ww = new DateTimeFormatterBuilder() + .append(weekyearElement()) + .append(weekElement()) + .toFormatter(); + } + return ww; + } + + /** + * Returns a formatter for a four digit weekyear, two digit week of + * weekyear, and one digit day of week. (xxxx-'W'ww-e) + * + * @return a formatter for xxxx-'W'ww-e + */ + public DateTimeFormatter weekyearWeekDay() { + if (wwd == null) { + wwd = new DateTimeFormatterBuilder() + .append(weekyearElement()) + .append(weekElement()) + .append(dayOfWeekElement()) + .toFormatter(); + } + return wwd; + } + + /** + * Returns a formatter for a two digit hour of day. (HH) + * + * @return a formatter for HH + */ + public DateTimeFormatter hour() { + return hourElement(); + } + + /** + * Returns a formatter for a two digit hour of day and two digit minute of + * hour. (HH:mm) + * + * @return a formatter for HH:mm + */ + public DateTimeFormatter hourMinute() { + if (hm == null) { + hm = new DateTimeFormatterBuilder() + .append(hourElement()) + .append(minuteElement()) + .toFormatter(); + } + return hm; + } + + /** + * Returns a formatter for a two digit hour of day, two digit minute of + * hour, and two digit second of minute. (HH:mm:ss) + * + * @return a formatter for HH:mm:ss + */ + public DateTimeFormatter hourMinuteSecond() { + if (hms == null) { + hms = new DateTimeFormatterBuilder() + .append(hourElement()) + .append(minuteElement()) + .append(secondElement()) + .toFormatter(); + } + return hms; + } + + /** + * Returns a formatter for a two digit hour of day, two digit minute of + * hour, two digit second of minute, and three digit fraction of + * second. (HH:mm:ss.SSS) + * + * @return a formatter for HH:mm:ss.SSS + */ + public DateTimeFormatter hourMinuteSecondMillis() { + if (hmsl == null) { + hmsl = new DateTimeFormatterBuilder() + .append(hourElement()) + .append(minuteElement()) + .append(secondElement()) + .append(millisElement()) + .toFormatter(); + } + return hmsl; + } + + /** + * Returns a formatter for a two digit hour of day, two digit minute of + * hour, two digit second of minute, and three digit fraction of + * second. (HH:mm:ss.SSS) + * + * @return a formatter for HH:mm:ss.SSS + */ + public DateTimeFormatter hourMinuteSecondFraction() { + if (hmsf == null) { + hmsf = new DateTimeFormatterBuilder() + .append(hourElement()) + .append(minuteElement()) + .append(secondElement()) + .append(fractionElement()) + .toFormatter(); + } + return hmsf; + } + + /** + * Returns a formatter that combines a full date and two digit hour of + * day. (yyyy-MM-dd'T'HH) + * + * @return a formatter for yyyy-MM-dd'T'HH + */ + public DateTimeFormatter dateHour() { + if (dh == null) { + dh = new DateTimeFormatterBuilder() + .append(date()) + .append(literalTElement()) + .append(hour()) + .toFormatter(); + } + return dh; + } + + /** + * Returns a formatter that combines a full date, two digit hour of day, + * and two digit minute of hour. (yyyy-MM-dd'T'HH:mm) + * + * @return a formatter for yyyy-MM-dd'T'HH:mm + */ + public DateTimeFormatter dateHourMinute() { + if (dhm == null) { + dhm = new DateTimeFormatterBuilder() + .append(date()) + .append(literalTElement()) + .append(hourMinute()) + .toFormatter(); + } + return dhm; + } + + /** + * Returns a formatter that combines a full date, two digit hour of day, + * two digit minute of hour, and two digit second of + * minute. (yyyy-MM-dd'T'HH:mm:ss) + * + * @return a formatter for yyyy-MM-dd'T'HH:mm:ss + */ + public DateTimeFormatter dateHourMinuteSecond() { + if (dhms == null) { + dhms = new DateTimeFormatterBuilder() + .append(date()) + .append(literalTElement()) + .append(hourMinuteSecond()) + .toFormatter(); + } + return dhms; + } + + /** + * Returns a formatter that combines a full date, two digit hour of day, + * two digit minute of hour, two digit second of minute, and three digit + * fraction of second. (yyyy-MM-dd'T'HH:mm:ss.SSS) + * + * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS + */ + public DateTimeFormatter dateHourMinuteSecondMillis() { + if (dhmsl == null) { + dhmsl = new DateTimeFormatterBuilder() + .append(date()) + .append(literalTElement()) + .append(hourMinuteSecondMillis()) + .toFormatter(); + } + return dhmsl; + } + + /** + * Returns a formatter that combines a full date, two digit hour of day, + * two digit minute of hour, two digit second of minute, and three digit + * fraction of second. (yyyy-MM-dd'T'HH:mm:ss.SSS) + * + * @return a formatter for yyyy-MM-dd'T'HH:mm:ss.SSS + */ + public DateTimeFormatter dateHourMinuteSecondFraction() { + if (dhmsf == null) { + dhmsf = new DateTimeFormatterBuilder() + .append(date()) + .append(literalTElement()) + .append(hourMinuteSecondFraction()) + .toFormatter(); + } + return dhmsf; + } + + //----------------------------------------------------------------------- + private DateTimeFormatter yearElement() { + if (ye == null) { + ye = new DateTimeFormatterBuilder() + .appendYear(4, 9) + .toFormatter(); + } + return ye; + } + + private DateTimeFormatter monthElement() { + if (mye == null) { + mye = new DateTimeFormatterBuilder() + .appendLiteral('-') + .appendMonthOfYear(2) + .toFormatter(); + } + return mye; + } + + private DateTimeFormatter dayOfMonthElement() { + if (dme == null) { + dme = new DateTimeFormatterBuilder() + .appendLiteral('-') + .appendDayOfMonth(2) + .toFormatter(); + } + return dme; + } + + private DateTimeFormatter weekyearElement() { + if (we == null) { + we = new DateTimeFormatterBuilder() + .appendWeekyear(4, 9) + .toFormatter(); + } + return we; + } + + private DateTimeFormatter weekElement() { + if (wwe == null) { + wwe = new DateTimeFormatterBuilder() + .appendLiteral("-W") + .appendWeekOfWeekyear(2) + .toFormatter(); + } + return wwe; + } + + private DateTimeFormatter dayOfWeekElement() { + if (dwe == null) { + dwe = new DateTimeFormatterBuilder() + .appendLiteral('-') + .appendDayOfWeek(1) + .toFormatter(); + } + return dwe; + } + + private DateTimeFormatter dayOfYearElement() { + if (dye == null) { + dye = new DateTimeFormatterBuilder() + .appendLiteral('-') + .appendDayOfYear(3) + .toFormatter(); + } + return dye; + } + + private DateTimeFormatter literalTElement() { + if (lte == null) { + lte = new DateTimeFormatterBuilder() + .appendLiteral('T') + .toFormatter(); + } + return lte; + } + + private DateTimeFormatter hourElement() { + if (hde == null) { + hde = new DateTimeFormatterBuilder() + .appendHourOfDay(2) + .toFormatter(); + } + return hde; + } + + private DateTimeFormatter minuteElement() { + if (mhe == null) { + mhe = new DateTimeFormatterBuilder() + .appendLiteral(':') + .appendMinuteOfHour(2) + .toFormatter(); + } + return mhe; + } + + private DateTimeFormatter secondElement() { + if (sme == null) { + sme = new DateTimeFormatterBuilder() + .appendLiteral(':') + .appendSecondOfMinute(2) + .toFormatter(); + } + return sme; + } + + private DateTimeFormatter millisElement() { + if (lse == null) { + lse = new DateTimeFormatterBuilder() + .appendLiteral('.') + .appendMillisOfSecond(3) + .toFormatter(); + } + return lse; + } + + private DateTimeFormatter fractionElement() { + if (fse == null) { + fse = new DateTimeFormatterBuilder() + .appendLiteral('.') + // Support parsing up to nanosecond precision even though + // those extra digits will be dropped. + .appendFractionOfSecond(3, 9) + .toFormatter(); + } + return fse; + } + + private DateTimeFormatter offsetElement() { + if (ze == null) { + ze = new DateTimeFormatterBuilder() + .appendTimeZoneOffset("Z", true, 2, 4) + .toFormatter(); + } + return ze; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/ISOPeriodFormat.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/ISOPeriodFormat.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/ISOPeriodFormat.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,238 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +/** + * ISOPeriodFormat provides factory methods for the ISO8601 standard. + *

+ * ISOPeriodFormat is thread-safe and immutable, and the formatters it + * returns are as well. + * + * @author Brian S O'Neill + * @since 1.0 + * @see PeriodFormat + * @see PeriodFormatterBuilder + */ +public class ISOPeriodFormat { + + private static final ISOPeriodFormat INSTANCE = new ISOPeriodFormat(); + + /** + * Returns a singleton instance of ISOPeriodFormat. + */ + public static ISOPeriodFormat getInstance() { + return INSTANCE; + } + + private transient PeriodFormatter + iStandard, + iAlternate, + iAlternateExtended, + iAlternateWithWeeks, + iAlternateExtendedWihWeeks; + + private ISOPeriodFormat() { + } + + /** + * The standard ISO format - PyYmMwWdDThHmMsS. + * Milliseconds are not output. + * Note that the ISO8601 standard actually indicates weeks should not + * be shown if any other field is present and vice versa. + * + * @return the formatter + */ + public PeriodFormatter standard() { + if (iStandard == null) { + iStandard = new PeriodFormatterBuilder() + .appendLiteral("P") + .appendYears() + .appendSuffix("Y") + .appendMonths() + .appendSuffix("M") + .appendWeeks() + .appendSuffix("W") + .appendDays() + .appendSuffix("D") + .appendSeparatorIfFieldsAfter("T") + .appendHours() + .appendSuffix("H") + .appendMinutes() + .appendSuffix("M") + .appendSecondsWithOptionalMillis() + .appendSuffix("S") + .toFormatter(); + } + return iStandard; + } + + /** + * The alternate ISO format, PyyyymmddThhmmss, which excludes weeks. + *

+ * Even if weeks are present in the period, they are not output. + * Fractional seconds (milliseconds) will appear if required. + * + * @return the formatter + */ + public PeriodFormatter alternate() { + if (iAlternate == null) { + iAlternate = new PeriodFormatterBuilder() + .appendLiteral("P") + .printZeroAlways() + .minimumPrintedDigits(4) + .appendYears() + .minimumPrintedDigits(2) + .appendMonths() + .appendDays() + .appendSeparatorIfFieldsAfter("T") + .appendHours() + .appendMinutes() + .appendSecondsWithOptionalMillis() + .toFormatter(); + } + return iAlternate; + } + + /** + * The alternate ISO format, Pyyyy-mm-ddThh:mm:ss, which excludes weeks. + *

+ * Even if weeks are present in the period, they are not output. + * Fractional seconds (milliseconds) will appear if required. + * + * @return the formatter + */ + public PeriodFormatter alternateExtended() { + if (iAlternateExtended == null) { + iAlternateExtended = new PeriodFormatterBuilder() + .appendLiteral("P") + .printZeroAlways() + .minimumPrintedDigits(4) + .appendYears() + .appendSeparator("-") + .minimumPrintedDigits(2) + .appendMonths() + .appendSeparator("-") + .appendDays() + .appendSeparatorIfFieldsAfter("T") + .appendHours() + .appendSeparator(":") + .appendMinutes() + .appendSeparator(":") + .appendSecondsWithOptionalMillis() + .toFormatter(); + } + return iAlternateExtended; + } + + /** + * The alternate ISO format, PyyyyWwwddThhmmss, which excludes months. + *

+ * Even if months are present in the period, they are not output. + * Fractional seconds (milliseconds) will appear if required. + * + * @return the formatter + */ + public PeriodFormatter alternateWithWeeks() { + if (iAlternateWithWeeks == null) { + iAlternateWithWeeks = new PeriodFormatterBuilder() + .appendLiteral("P") + .printZeroAlways() + .minimumPrintedDigits(4) + .appendYears() + .minimumPrintedDigits(2) + .appendPrefix("W") + .appendWeeks() + .appendDays() + .appendSeparatorIfFieldsAfter("T") + .appendHours() + .appendMinutes() + .appendSecondsWithOptionalMillis() + .toFormatter(); + } + return iAlternateWithWeeks; + } + + /** + * The alternate ISO format, Pyyyy-Www-ddThh:mm:ss, which excludes months. + *

+ * Even if months are present in the period, they are not output. + * Fractional seconds (milliseconds) will appear if required. + * + * @return the formatter + */ + public PeriodFormatter alternateExtendedWithWeeks() { + if (iAlternateExtendedWihWeeks == null) { + iAlternateExtendedWihWeeks = new PeriodFormatterBuilder() + .appendLiteral("P") + .printZeroAlways() + .minimumPrintedDigits(4) + .appendYears() + .appendSeparator("-") + .minimumPrintedDigits(2) + .appendPrefix("W") + .appendWeeks() + .appendSeparator("-") + .appendDays() + .appendSeparatorIfFieldsAfter("T") + .appendHours() + .appendSeparator(":") + .appendMinutes() + .appendSeparator(":") + .appendSecondsWithOptionalMillis() + .toFormatter(); + } + return iAlternateExtendedWihWeeks; + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/PeriodFormat.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/PeriodFormat.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/PeriodFormat.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.util.Locale; + +/** + * PeriodFormat provides basic printing and parsing capabilities for + * periods. Eventually, this class will also support localization. + *

+ * PeriodFormat is thread-safe and immutable, and the formatters it returns + * are as well. + * + * @author Brian S O'Neill + * @since 1.0 + * @see ISOPeriodFormat + * @see PeriodFormatterBuilder + */ +public class PeriodFormat { + + private static final PeriodFormat INSTANCE = new PeriodFormat(); + + /** + * Gets a formatter provider that works using the default locale. + * + * @return a format provider + */ + public static PeriodFormat getInstance() { + return INSTANCE; + } + + /** + * Gets a formatter provider that works using the given locale. + * + * @param locale the Locale to use, null for default locale + * @return a format provider + */ + public static PeriodFormat getInstance(Locale locale) { + return INSTANCE; + } + + private final PeriodFormatter iDefault; + + private PeriodFormat() { + iDefault = new PeriodFormatterBuilder() + .appendYears() + .appendSuffix(" year", " years") + .appendSeparator(", ", " and ") + .appendMonths() + .appendSuffix(" month", " months") + .appendSeparator(", ", " and ") + .appendWeeks() + .appendSuffix(" week", " weeks") + .appendSeparator(", ", " and ") + .appendDays() + .appendSuffix(" day", " days") + .appendSeparator(", ", " and ") + .appendHours() + .appendSuffix(" hour", " hours") + .appendSeparator(", ", " and ") + .appendMinutes() + .appendSuffix(" minute", " minutes") + .appendSeparator(", ", " and ") + .appendSeconds() + .appendSuffix(" second", " seconds") + .appendSeparator(", ", " and ") + .appendMillis() + .appendSuffix(" millisecond", " milliseconds") + .toFormatter(); + } + + /** + * Returns the default PeriodFormatter. + */ + public PeriodFormatter getDefault() { + return iDefault; + } +} Index: 3rdParty_sources/joda-time/org/joda/time/format/PeriodFormatter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/PeriodFormatter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/PeriodFormatter.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +/** + * Combined interface for printing and parsing. + *

+ * See each extended interface for details of the methods. + *

+ * Note: This interface represents a view onto {@link BasePeriodFormatter}. + * All implementations must extend BasePeriodFormatter. + * + * @author Brian S O'Neill + * @author Stephen Colebourne + * @since 1.0 + */ +public interface PeriodFormatter extends PeriodPrinter, PeriodParser { + + // Methods inherited +} Index: 3rdParty_sources/joda-time/org/joda/time/format/PeriodFormatterBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/PeriodFormatterBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/PeriodFormatterBuilder.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,1599 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; + +import org.joda.time.DateTimeConstants; +import org.joda.time.DurationFieldType; +import org.joda.time.PeriodType; +import org.joda.time.ReadWritablePeriod; +import org.joda.time.ReadablePeriod; + +/** + * PeriodFormatterBuilder is used for constructing {@link PeriodFormatter}s. + * PeriodFormatters are built by appending specific fields and separators. + * + *

+ * For example, a formatter that prints years and months, like "15 years and 8 months", + * can be constructed as follows: + *

+ *

+ * PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder()
+ *     .printZeroAlways()
+ *     .appendYears()
+ *     .appendSuffix(" year", " years")
+ *     .appendSeparator(" and ")
+ *     .printZeroRarely()
+ *     .appendMonths()
+ *     .appendSuffix(" month", " months")
+ *     .toFormatter();
+ * 
+ *

+ * PeriodFormatterBuilder itself is mutable and not thread-safe, but the + * formatters that it builds are thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + * @see PeriodFormat + */ +public class PeriodFormatterBuilder { + private static final int PRINT_ZERO_RARELY_FIRST = 1; + private static final int PRINT_ZERO_RARELY_LAST = 2; + private static final int PRINT_ZERO_IF_SUPPORTED = 3; + private static final int PRINT_ZERO_ALWAYS = 4; + private static final int PRINT_ZERO_NEVER = 5; + + private static final int YEARS = 0; + private static final int MONTHS = 1; + private static final int WEEKS = 2; + private static final int DAYS = 3; + private static final int HOURS = 4; + private static final int MINUTES = 5; + private static final int SECONDS = 6; + private static final int MILLIS = 7; + private static final int SECONDS_MILLIS = 8; + private static final int SECONDS_OPTIONAL_MILLIS = 9; + + private int iMinPrintedDigits; + private int iPrintZeroSetting; + private int iMaxParsedDigits; + private boolean iRejectSignedValues; + + private PeriodFieldAffix iPrefix; + + // List of PeriodFormatters used to build a final formatter. + private List iFormatters; + + // Last PeriodFormatter appended of each field type. + private FieldFormatter[] iFieldFormatters; + + public PeriodFormatterBuilder() { + clear(); + } + + /** + * Converts to a PeriodPrinter that prints using all the appended elements. + * Subsequent changes to this builder do not affect the returned printer. + * + * @return the newly created printer + */ + public PeriodPrinter toPrinter() { + return toFormatter(); + } + + /** + * Converts to a PeriodParser that parses using all the appended elements. + * Subsequent changes to this builder do not affect the returned parser. + * + * @return the newly created parser + */ + public PeriodParser toParser() { + return toFormatter(); + } + + /** + * Converts to a PeriodFormatter that formats using all the appended elements. + * Subsequent changes to this builder do not affect the returned formatter. + * + * @return the newly created formatter + */ + public PeriodFormatter toFormatter() { + PeriodFormatter formatter = toFormatter(iFormatters); + iFieldFormatters = (FieldFormatter[]) iFieldFormatters.clone(); + return formatter; + } + + private static PeriodFormatter toFormatter(List formatters) { + int size = formatters.size(); + if (size >= 1 && formatters.get(0) instanceof Separator) { + Separator sep = (Separator) formatters.get(0); + return sep.finish((BasePeriodFormatter) toFormatter(formatters.subList(1, size))); + } + return (PeriodFormatter) createComposite(formatters); + } + + /** + * Clears out all the appended elements, allowing this builder to be reused. + */ + public void clear() { + iMinPrintedDigits = 1; + iPrintZeroSetting = PRINT_ZERO_RARELY_LAST; + iMaxParsedDigits = 10; + iRejectSignedValues = false; + iPrefix = null; + if (iFormatters == null) { + iFormatters = new ArrayList(); + } else { + iFormatters.clear(); + } + iFieldFormatters = new FieldFormatter[10]; + } + + /** + * Appends another formatter. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder append(PeriodFormatter formatter) { + if (formatter == null) { + throw new IllegalArgumentException("No formatter supplied"); + } + if (formatter instanceof BasePeriodFormatter == false) { + throw new IllegalArgumentException("Formatter must extend BasePeriodFormatter"); + } + clearPrefix(); + iFormatters.add(formatter); + return this; + } + + /** + * Instructs the printer to emit specific text, and the parser to expect it. + * The parser is case-insensitive. + * + * @return this PeriodFormatterBuilder + * @throws IllegalArgumentException if text is null + */ + public PeriodFormatterBuilder appendLiteral(String text) { + if (text == null) { + throw new IllegalArgumentException("Literal must not be null"); + } + clearPrefix(); + Literal literal = new Literal(text); + iFormatters.add(literal); + return this; + } + + /** + * Set the minimum digits printed for the next and following appended + * fields. By default, the minimum digits printed is one. If the field value + * is zero, it is not printed unless a printZero rule is applied. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder minimumPrintedDigits(int minDigits) { + iMinPrintedDigits = minDigits; + return this; + } + + /** + * Set the maximum digits parsed for the next and following appended + * fields. By default, the maximum digits parsed is ten. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder maximumParsedDigits(int maxDigits) { + iMaxParsedDigits = maxDigits; + return this; + } + + /** + * Reject signed values when parsing the next and following appended fields. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder rejectSignedValues(boolean v) { + iRejectSignedValues = v; + return this; + } + + /** + * Never print zero values for the next and following appended fields, + * unless no fields would be printed. If no fields are printed, the printer + * forces the last "printZeroRarely" field to print a zero. + *

+ * This field setting is the default. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder printZeroRarelyLast() { + iPrintZeroSetting = PRINT_ZERO_RARELY_LAST; + return this; + } + + /** + * Never print zero values for the next and following appended fields, + * unless no fields would be printed. If no fields are printed, the printer + * forces the first "printZeroRarely" field to print a zero. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder printZeroRarelyFirst() { + iPrintZeroSetting = PRINT_ZERO_RARELY_FIRST; + return this; + } + + /** + * Print zero values for the next and following appened fields only if the + * period supports it. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder printZeroIfSupported() { + iPrintZeroSetting = PRINT_ZERO_IF_SUPPORTED; + return this; + } + + /** + * Always print zero values for the next and following appended fields, + * even if the period doesn't support it. The parser requires values for + * fields that always print zero. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder printZeroAlways() { + iPrintZeroSetting = PRINT_ZERO_ALWAYS; + return this; + } + + /** + * Never print zero values for the next and following appended fields, + * unless no fields would be printed. If no fields are printed, the printer + * forces the last "printZeroRarely" field to print a zero. + *

+ * This field setting is the default. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder printZeroNever() { + iPrintZeroSetting = PRINT_ZERO_NEVER; + return this; + } + + /** + * Append a field prefix which applies only to the next appended field. If + * the field is not printed, neither is the prefix. + * + * @param text text to print before field only if field is printed + * @return this PeriodFormatterBuilder + * @see #appendSuffix + */ + public PeriodFormatterBuilder appendPrefix(String text) { + if (text == null) { + throw new IllegalArgumentException(); + } + return appendPrefix(new SimpleAffix(text)); + } + + /** + * Append a field prefix which applies only to the next appended field. If + * the field is not printed, neither is the prefix. + *

+ * During parsing, the singular and plural versions are accepted whether + * or not the actual value matches plurality. + * + * @param singularText text to print if field value is one + * @param pluralText text to print if field value is not one + * @return this PeriodFormatterBuilder + * @see #appendSuffix + */ + public PeriodFormatterBuilder appendPrefix(String singularText, + String pluralText) { + if (singularText == null || pluralText == null) { + throw new IllegalArgumentException(); + } + return appendPrefix(new PluralAffix(singularText, pluralText)); + } + + /** + * Append a field prefix which applies only to the next appended field. If + * the field is not printed, neither is the prefix. + * + * @param prefix custom prefix + * @return this PeriodFormatterBuilder + * @see #appendSuffix + */ + private PeriodFormatterBuilder appendPrefix(PeriodFieldAffix prefix) { + if (prefix == null) { + throw new IllegalArgumentException(); + } + if (iPrefix != null) { + prefix = new CompositeAffix(iPrefix, prefix); + } + iPrefix = prefix; + return this; + } + + /** + * Instruct the printer to emit an integer years field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendYears() { + appendField(YEARS); + return this; + } + + /** + * Instruct the printer to emit an integer years field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendMonths() { + appendField(MONTHS); + return this; + } + + /** + * Instruct the printer to emit an integer weeks field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendWeeks() { + appendField(WEEKS); + return this; + } + + /** + * Instruct the printer to emit an integer days field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendDays() { + appendField(DAYS); + return this; + } + + /** + * Instruct the printer to emit an integer hours field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendHours() { + appendField(HOURS); + return this; + } + + /** + * Instruct the printer to emit an integer minutes field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendMinutes() { + appendField(MINUTES); + return this; + } + + /** + * Instruct the printer to emit an integer seconds field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendSeconds() { + appendField(SECONDS); + return this; + } + + /** + * Instruct the printer to emit a combined seconds and millis field, if supported. + * The millis will overflow into the seconds if necessary. + * The millis are always output. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendSecondsWithMillis() { + appendField(SECONDS_MILLIS); + return this; + } + + /** + * Instruct the printer to emit a combined seconds and millis field, if supported. + * The millis will overflow into the seconds if necessary. + * The millis are only output if non-zero. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendSecondsWithOptionalMillis() { + appendField(SECONDS_OPTIONAL_MILLIS); + return this; + } + + /** + * Instruct the printer to emit an integer millis field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendMillis() { + appendField(MILLIS); + return this; + } + + /** + * Instruct the printer to emit an integer millis field, if supported. + * + * @return this PeriodFormatterBuilder + */ + public PeriodFormatterBuilder appendMillis3Digit() { + appendField(7, 3); + return this; + } + + private void appendField(int type) { + appendField(type, iMinPrintedDigits); + } + + private void appendField(int type, int minPrinted) { + FieldFormatter field = new FieldFormatter(minPrinted, iPrintZeroSetting, + iMaxParsedDigits, iRejectSignedValues, type, iFieldFormatters, iPrefix, null); + iFormatters.add(field); + iFieldFormatters[type] = field; + iPrefix = null; + } + + /** + * Append a field suffix which applies only to the last appended field. If + * the field is not printed, neither is the suffix. + * + * @param text text to print after field only if field is printed + * @return this PeriodFormatterBuilder + * @throws IllegalStateException if no field exists to append to + * @see #appendPrefix + */ + public PeriodFormatterBuilder appendSuffix(String text) { + if (text == null) { + throw new IllegalArgumentException(); + } + return appendSuffix(new SimpleAffix(text)); + } + + /** + * Append a field suffix which applies only to the last appended field. If + * the field is not printed, neither is the suffix. + *

+ * During parsing, the singular and plural versions are accepted whether or + * not the actual value matches plurality. + * + * @param singularText text to print if field value is one + * @param pluralText text to print if field value is not one + * @return this PeriodFormatterBuilder + * @throws IllegalStateException if no field exists to append to + * @see #appendPrefix + */ + public PeriodFormatterBuilder appendSuffix(String singularText, + String pluralText) { + if (singularText == null || pluralText == null) { + throw new IllegalArgumentException(); + } + return appendSuffix(new PluralAffix(singularText, pluralText)); + } + + /** + * Append a field suffix which applies only to the last appended field. If + * the field is not printed, neither is the suffix. + * + * @param suffix custom suffix + * @return this PeriodFormatterBuilder + * @throws IllegalStateException if no field exists to append to + * @see #appendPrefix + */ + private PeriodFormatterBuilder appendSuffix(PeriodFieldAffix suffix) { + final Object originalField; + if (iFormatters.size() > 0) { + originalField = iFormatters.get(iFormatters.size() - 1); + } else { + originalField = null; + } + + if (originalField == null || !(originalField instanceof FieldFormatter)) { + throw new IllegalStateException("No field to apply suffix to"); + } + + clearPrefix(); + FieldFormatter newField = new FieldFormatter((FieldFormatter) originalField, suffix); + iFormatters.set(iFormatters.size() - 1, newField); + iFieldFormatters[newField.getFieldType()] = newField; + + return this; + } + + /** + * Append a separator, which is output if fields are printed both before + * and after the separator. + *

+ * For example, builder.appendDays().appendSeparator(",").appendHours() + * will only output the comma if both the days and hours fields are output. + *

+ * The text will be parsed case-insensitively. + *

+ * Note: appending a separator discontinues any further work on the latest + * appended field. + * + * @param text the text to use as a separator + * @return this PeriodFormatterBuilder + * @throws IllegalStateException if this separator follows a previous one + */ + public PeriodFormatterBuilder appendSeparator(String text) { + return appendSeparator(text, text, true, true); + } + + /** + * Append a separator, which is output only if fields are printed after the separator. + *

+ * For example, builder.appendDays().appendSeparator(",").appendHours() + * will only output the comma if the hours fields is output. + *

+ * The text will be parsed case-insensitively. + *

+ * Note: appending a separator discontinues any further work on the latest + * appended field. + * + * @param text the text to use as a separator + * @return this PeriodFormatterBuilder + * @throws IllegalStateException if this separator follows a previous one + */ + public PeriodFormatterBuilder appendSeparatorIfFieldsAfter(String text) { + return appendSeparator(text, text, false, true); + } + + /** + * Append a separator, which is output only if fields are printed after the separator. + *

+ * For example, builder.appendDays().appendSeparator(",").appendHours() + * will only output the comma if the days fields is output. + *

+ * The text will be parsed case-insensitively. + *

+ * Note: appending a separator discontinues any further work on the latest + * appended field. + * + * @param text the text to use as a separator + * @return this PeriodFormatterBuilder + * @throws IllegalStateException if this separator follows a previous one + */ + public PeriodFormatterBuilder appendSeparatorIfFieldsBefore(String text) { + return appendSeparator(text, text, true, false); + } + + /** + * Append a separator, which is output if fields are printed both before + * and after the separator. + *

+ * This method changes the separator depending on whether it is the last separator + * to be output. + *

+ * For example, builder.appendDays().appendSeparator(",", "&").appendHours().appendSeparator(",", "&").appendMinutes() + * will output '1,2&3' if all three fields are output, '1&2' if two fields are output + * and '1' if just one field is output. + *

+ * The text will be parsed case-insensitively. + *

+ * Note: appending a separator discontinues any further work on the latest + * appended field. + * + * @param text the text to use as a separator + * @param finalText the text used used if this is the final separator to be printed + * @return this PeriodFormatterBuilder + * @throws IllegalStateException if this separator follows a previous one + */ + public PeriodFormatterBuilder appendSeparator(String text, String finalText) { + return appendSeparator(text, finalText, true, true); + } + + private PeriodFormatterBuilder appendSeparator(String text, String finalText, boolean useBefore, boolean useAfter) { + if (text == null || finalText == null) { + throw new IllegalArgumentException(); + } + + clearPrefix(); + + // optimise zero formatter case + List formatters = iFormatters; + if (formatters.size() == 0) { + if (useAfter && useBefore == false) { + formatters.add(new Separator(text, finalText, Literal.EMPTY, useBefore, useAfter)); + } + return this; + } + + // find the last separator added + int i; + Separator lastSeparator = null; + for (i=formatters.size(); --i>=0; ) { + if (formatters.get(i) instanceof Separator) { + lastSeparator = (Separator) formatters.get(i); + formatters = formatters.subList(i + 1, formatters.size()); + break; + } + } + + // merge formatters + if (lastSeparator != null && formatters.size() == 0) { + throw new IllegalStateException("Cannot have two adjacent separators"); + } else { + BasePeriodFormatter composite = createComposite(formatters); + formatters.clear(); + formatters.add(new Separator(text, finalText, composite, useBefore, useAfter)); + } + + return this; + } + + private void clearPrefix() throws IllegalStateException { + if (iPrefix != null) { + throw new IllegalStateException("Prefix not followed by field"); + } + iPrefix = null; + } + + private static BasePeriodFormatter createComposite(List formatters) { + switch (formatters.size()) { + case 0: + return Literal.EMPTY; + case 1: + return (BasePeriodFormatter) formatters.get(0); + default: + return new Composite(formatters); + } + } + + //----------------------------------------------------------------------- + /** + * Defines a formatted field's prefix or suffix text. + * This can be used for fields such as 'n hours' or 'nH' or 'Hour:n'. + */ + static interface PeriodFieldAffix { + int calculatePrintedLength(int value); + + void printTo(StringBuffer buf, int value); + + void printTo(Writer out, int value) throws IOException; + + /** + * @return new position after parsing affix, or ~position of failure + */ + int parse(String periodStr, int position); + + /** + * @return position where affix starts, or original ~position if not found + */ + int scan(String periodStr, int position); + } + + //----------------------------------------------------------------------- + /** + * Implements an affix where the text does not vary by the amount. + */ + static class SimpleAffix implements PeriodFieldAffix { + private final String iText; + + SimpleAffix(String text) { + iText = text; + } + + public int calculatePrintedLength(int value) { + return iText.length(); + } + + public void printTo(StringBuffer buf, int value) { + buf.append(iText); + } + + public void printTo(Writer out, int value) throws IOException { + out.write(iText); + } + + public int parse(String periodStr, int position) { + String text = iText; + int textLength = text.length(); + if (periodStr.regionMatches(true, position, text, 0, textLength)) { + return position + textLength; + } + return ~position; + } + + public int scan(String periodStr, final int position) { + String text = iText; + int textLength = text.length(); + int sourceLength = periodStr.length(); + for (int pos = position; pos < sourceLength; pos++) { + if (periodStr.regionMatches(true, pos, text, 0, textLength)) { + return pos; + } + } + return ~position; + } + } + + //----------------------------------------------------------------------- + /** + * Implements an affix where the text varies by the amount of the field. + * Only singular (1) and plural (not 1) are supported. + */ + static class PluralAffix implements PeriodFieldAffix { + private final String iSingularText; + private final String iPluralText; + + PluralAffix(String singularText, String pluralText) { + iSingularText = singularText; + iPluralText = pluralText; + } + + public int calculatePrintedLength(int value) { + return (value == 1 ? iSingularText : iPluralText).length(); + } + + public void printTo(StringBuffer buf, int value) { + buf.append(value == 1 ? iSingularText : iPluralText); + } + + public void printTo(Writer out, int value) throws IOException { + out.write(value == 1 ? iSingularText : iPluralText); + } + + public int parse(String periodStr, int position) { + String text1 = iPluralText; + String text2 = iSingularText; + + if (text1.length() < text2.length()) { + // Swap in order to match longer one first. + String temp = text1; + text1 = text2; + text2 = temp; + } + + if (periodStr.regionMatches + (true, position, text1, 0, text1.length())) { + return position + text1.length(); + } + if (periodStr.regionMatches + (true, position, text2, 0, text2.length())) { + return position + text2.length(); + } + + return ~position; + } + + public int scan(String periodStr, final int position) { + String text1 = iPluralText; + String text2 = iSingularText; + + if (text1.length() < text2.length()) { + // Swap in order to match longer one first. + String temp = text1; + text1 = text2; + text2 = temp; + } + + int textLength1 = text1.length(); + int textLength2 = text2.length(); + + int sourceLength = periodStr.length(); + for (int pos = position; pos < sourceLength; pos++) { + if (periodStr.regionMatches(true, pos, text1, 0, textLength1)) { + return pos; + } + if (periodStr.regionMatches(true, pos, text2, 0, textLength2)) { + return pos; + } + } + return ~position; + } + } + + //----------------------------------------------------------------------- + /** + * Builds a composite affix by merging two other affix implementations. + */ + static class CompositeAffix implements PeriodFieldAffix { + private final PeriodFieldAffix iLeft; + private final PeriodFieldAffix iRight; + + CompositeAffix(PeriodFieldAffix left, PeriodFieldAffix right) { + iLeft = left; + iRight = right; + } + + public int calculatePrintedLength(int value) { + return iLeft.calculatePrintedLength(value) + + iRight.calculatePrintedLength(value); + } + + public void printTo(StringBuffer buf, int value) { + iLeft.printTo(buf, value); + iRight.printTo(buf, value); + } + + public void printTo(Writer out, int value) throws IOException { + iLeft.printTo(out, value); + iRight.printTo(out, value); + } + + public int parse(String periodStr, int position) { + position = iLeft.parse(periodStr, position); + if (position >= 0) { + position = iRight.parse(periodStr, position); + } + return position; + } + + public int scan(String periodStr, final int position) { + int pos = iLeft.scan(periodStr, position); + if (pos >= 0) { + return iRight.scan(periodStr, pos); + } + return ~position; + } + } + + //----------------------------------------------------------------------- + /** + * Formats the numeric value of a field, potentially with prefix/suffix. + */ + static class FieldFormatter + extends BasePeriodFormatter + implements PeriodFormatter { + private final int iMinPrintedDigits; + private final int iPrintZeroSetting; + private final int iMaxParsedDigits; + private final boolean iRejectSignedValues; + + /** The index of the field type, 0=year, etc. */ + private final int iFieldType; + /** + * The array of the latest formatter added for each type. + * This is shared between all the field formatters in a formatter. + */ + private final FieldFormatter[] iFieldFormatters; + + private final PeriodFieldAffix iPrefix; + private final PeriodFieldAffix iSuffix; + + + FieldFormatter(int minPrintedDigits, int printZeroSetting, + int maxParsedDigits, boolean rejectSignedValues, + int fieldType, FieldFormatter[] fieldFormatters, + PeriodFieldAffix prefix, PeriodFieldAffix suffix) { + iMinPrintedDigits = minPrintedDigits; + iPrintZeroSetting = printZeroSetting; + iMaxParsedDigits = maxParsedDigits; + iRejectSignedValues = rejectSignedValues; + iFieldType = fieldType; + iFieldFormatters = fieldFormatters; + iPrefix = prefix; + iSuffix = suffix; + } + + FieldFormatter(FieldFormatter field, PeriodFieldAffix suffix) { + iMinPrintedDigits = field.iMinPrintedDigits; + iPrintZeroSetting = field.iPrintZeroSetting; + iMaxParsedDigits = field.iMaxParsedDigits; + iRejectSignedValues = field.iRejectSignedValues; + iFieldType = field.iFieldType; + iFieldFormatters = field.iFieldFormatters; + iPrefix = field.iPrefix; + if (field.iSuffix != null) { + suffix = new CompositeAffix(field.iSuffix, suffix); + } + iSuffix = suffix; + } + + public int countFieldsToPrint(ReadablePeriod period) { + if (iPrintZeroSetting == PRINT_ZERO_ALWAYS || getFieldValue(period) != Long.MAX_VALUE) { + return 1; + } + return 0; + } + + public int countFieldsToPrint(ReadablePeriod period, int stopAt) { + return stopAt <= 0 ? 0 : countFieldsToPrint(period); + } + + public int calculatePrintedLength(ReadablePeriod period) { + long valueLong = getFieldValue(period); + if (valueLong == Long.MAX_VALUE) { + return 0; + } + + int sum = Math.max(FormatUtils.calculateDigitCount(valueLong), iMinPrintedDigits); + if (iFieldType >= 8) { + sum++; // decimal point + if (iFieldType == SECONDS_OPTIONAL_MILLIS && + (Math.abs(valueLong) % DateTimeConstants.MILLIS_PER_SECOND) == 0) { + sum -= 4; // remove three digits and decimal point + } + valueLong = valueLong / DateTimeConstants.MILLIS_PER_SECOND; + } + int value = (int) valueLong; + + if (iPrefix != null) { + sum += iPrefix.calculatePrintedLength(value); + } + if (iSuffix != null) { + sum += iSuffix.calculatePrintedLength(value); + } + + return sum; + } + + public void printTo(StringBuffer buf, ReadablePeriod period) { + long valueLong = getFieldValue(period); + if (valueLong == Long.MAX_VALUE) { + return; + } + int value = (int) valueLong; + if (iFieldType >= 8) { + value = (int) (valueLong / DateTimeConstants.MILLIS_PER_SECOND); + } + + if (iPrefix != null) { + iPrefix.printTo(buf, value); + } + int minDigits = iMinPrintedDigits; + if (minDigits <= 1) { + FormatUtils.appendUnpaddedInteger(buf, value); + } else { + FormatUtils.appendPaddedInteger(buf, value, minDigits); + } + if (iFieldType >= 8) { + int dp = (int) (Math.abs(valueLong) % DateTimeConstants.MILLIS_PER_SECOND); + if (iFieldType == SECONDS_MILLIS || dp > 0) { + buf.append('.'); + FormatUtils.appendPaddedInteger(buf, dp, 3); + } + } + if (iSuffix != null) { + iSuffix.printTo(buf, value); + } + } + + public void printTo(Writer out, ReadablePeriod period) throws IOException { + long valueLong = getFieldValue(period); + if (valueLong == Long.MAX_VALUE) { + return; + } + int value = (int) valueLong; + if (iFieldType >= 8) { + value = (int) (valueLong / DateTimeConstants.MILLIS_PER_SECOND); + } + + if (iPrefix != null) { + iPrefix.printTo(out, value); + } + int minDigits = iMinPrintedDigits; + if (minDigits <= 1) { + FormatUtils.writeUnpaddedInteger(out, value); + } else { + FormatUtils.writePaddedInteger(out, value, minDigits); + } + if (iFieldType >= 8) { + int dp = (int) (Math.abs(valueLong) % DateTimeConstants.MILLIS_PER_SECOND); + if (iFieldType == SECONDS_MILLIS || dp > 0) { + out.write('.'); + FormatUtils.writePaddedInteger(out, dp, 3); + } + } + if (iSuffix != null) { + iSuffix.printTo(out, value); + } + } + + public int parseInto(ReadWritablePeriod period, + String text, int position) { + + boolean mustParse = (iPrintZeroSetting == PRINT_ZERO_ALWAYS); + + // Shortcut test. + if (position >= text.length()) { + return mustParse ? ~position : position; + } + + if (iPrefix != null) { + position = iPrefix.parse(text, position); + if (position >= 0) { + // If prefix is found, then the parse must finish. + mustParse = true; + } else { + // Prefix not found, so bail. + if (!mustParse) { + // It's okay because parsing of this field is not + // required. Don't return an error. Fields down the + // chain can continue on, trying to parse. + return ~position; + } + return position; + } + } + + int suffixPos = -1; + if (iSuffix != null && !mustParse) { + // Pre-scan the suffix, to help determine if this field must be + // parsed. + suffixPos = iSuffix.scan(text, position); + if (suffixPos >= 0) { + // If suffix is found, then parse must finish. + mustParse = true; + } else { + // Suffix not found, so bail. + if (!mustParse) { + // It's okay because parsing of this field is not + // required. Don't return an error. Fields down the + // chain can continue on, trying to parse. + return ~suffixPos; + } + return suffixPos; + } + } + + if (!mustParse && !isSupported(period.getPeriodType(), iFieldType)) { + // If parsing is not required and the field is not supported, + // exit gracefully so that another parser can continue on. + return position; + } + + int limit; + if (suffixPos > 0) { + limit = Math.min(iMaxParsedDigits, suffixPos - position); + } else { + limit = Math.min(iMaxParsedDigits, text.length() - position); + } + + // validate input number + boolean negative = false; + int length = 0; + int dp = -1; + while (length < limit) { + char c = text.charAt(position + length); + // leading sign + if (length == 0 && (c == '-' || c == '+') && !iRejectSignedValues) { + negative = (c == '-'); + if (negative) { + length++; + } else { + // Skip the '+' for parseInt to succeed. + position++; + } + // Expand the limit to disregard the sign character. + limit = Math.min(limit + 1, text.length() - position); + continue; + } + // main number + if (c < '0' || c > '9') { + if (c == '.' && (iFieldType == SECONDS_MILLIS || iFieldType == SECONDS_OPTIONAL_MILLIS)) { + if (dp >= 0) { + // can't have two decimals + return position + length; + } + dp = length; + } else { + break; + } + } + length++; + } + if (length == 0 || (length == 1 && dp == 0) || (dp == -1 && iFieldType == SECONDS_MILLIS)) { + return ~position; + } + + if (position + length != suffixPos) { + // If there are additional non-digit characters before the + // suffix is reached, then assume that the suffix found belongs + // to a field not yet reached. Return original position so that + // another parser can continue on. + return position; + } + + if (iFieldType == SECONDS_MILLIS || iFieldType == SECONDS_OPTIONAL_MILLIS) { + if (dp == -1) { + position = parseField(period, text, position, negative, length, SECONDS); + setFieldValue(period, MILLIS, 0); + } else { + if (dp > 0) { + position = parseField(period, text, position, negative, dp, SECONDS); + } else { + setFieldValue(period, SECONDS, 0); + } + position++; // skip dp + int millisLength = length - 1 - dp; + if (millisLength > 3) { + position = parseField(period, text, position, false, 3, MILLIS); + position += (millisLength - 3); + } else if (millisLength == 0) { + setFieldValue(period, MILLIS, 0); + } else { + position = parseField(period, text, position, false, millisLength, MILLIS); + } + } + } else { + position = parseField(period, text, position, negative, length, iFieldType); + } + + if (position >= 0 && iSuffix != null) { + position = iSuffix.parse(text, position); + } + + return position; + } + + private int parseField( + ReadWritablePeriod period, String text, int position, + boolean negative, int length, int type) { + + int value; + if (length >= 9) { + // Since value may exceed max, use stock parser which checks + // for this. + value = Integer.parseInt + (text.substring(position, position += length)); + } else { + int i = position; + if (negative) { + i++; + } + value = text.charAt(i++) - '0'; + position += length; + while (i < position) { + value = ((value << 3) + (value << 1)) + text.charAt(i++) - '0'; + } + if (negative) { + value = -value; + } + } + + setFieldValue(period, type, value); + return position; + } + + /** + * @return Long.MAX_VALUE if nothing to print, otherwise value + */ + long getFieldValue(ReadablePeriod period) { + PeriodType type; + if (iPrintZeroSetting == PRINT_ZERO_ALWAYS) { + type = null; // Don't need to check if supported. + } else { + type = period.getPeriodType(); + } + if (type != null && isSupported(type, iFieldType) == false) { + return Long.MAX_VALUE; + } + + int value; + + switch (iFieldType) { + default: + return Long.MAX_VALUE; + case YEARS: + value = period.get(DurationFieldType.years()); + break; + case MONTHS: + value = period.get(DurationFieldType.months()); + break; + case WEEKS: + value = period.get(DurationFieldType.weeks()); + break; + case DAYS: + value = period.get(DurationFieldType.days()); + break; + case HOURS: + value = period.get(DurationFieldType.hours()); + break; + case MINUTES: + value = period.get(DurationFieldType.minutes()); + break; + case SECONDS: + value = period.get(DurationFieldType.seconds()); + break; + case MILLIS: + value = period.get(DurationFieldType.millis()); + break; + case SECONDS_MILLIS: // drop through + case SECONDS_OPTIONAL_MILLIS: + int seconds = period.get(DurationFieldType.seconds()); + int millis = period.get(DurationFieldType.millis()); + value = seconds * DateTimeConstants.MILLIS_PER_SECOND + millis; + break; + } + + // determine if period is zero and this is the last field + if (value == 0) { + switch (iPrintZeroSetting) { + case PRINT_ZERO_NEVER: + return Long.MAX_VALUE; + case PRINT_ZERO_RARELY_LAST: + if (isZero(period) && iFieldFormatters[iFieldType] == this) { + for (int i = iFieldType + 1; i < 10; i++) { + if (isSupported(type, i) && iFieldFormatters[i] != null) { + return Long.MAX_VALUE; + } + } + } else { + return Long.MAX_VALUE; + } + break; + case PRINT_ZERO_RARELY_FIRST: + if (isZero(period) && iFieldFormatters[iFieldType] == this) { + for (int i = Math.min(iFieldType, 8) - 1; i >= 0; i++) { + if (isSupported(type, i) && iFieldFormatters[i] != null) { + return Long.MAX_VALUE; + } + } + } else { + return Long.MAX_VALUE; + } + break; + } + } + + return value; + } + + boolean isZero(ReadablePeriod period) { + for (int i = 0, isize = period.size(); i < isize; i++) { + if (period.getValue(i) != 0) { + return false; + } + } + return true; + } + + boolean isSupported(PeriodType type, int field) { + switch (field) { + default: + return false; + case YEARS: + return type.isSupported(DurationFieldType.years()); + case MONTHS: + return type.isSupported(DurationFieldType.months()); + case WEEKS: + return type.isSupported(DurationFieldType.weeks()); + case DAYS: + return type.isSupported(DurationFieldType.days()); + case HOURS: + return type.isSupported(DurationFieldType.hours()); + case MINUTES: + return type.isSupported(DurationFieldType.minutes()); + case SECONDS: + return type.isSupported(DurationFieldType.seconds()); + case MILLIS: + return type.isSupported(DurationFieldType.millis()); + case SECONDS_MILLIS: // drop through + case SECONDS_OPTIONAL_MILLIS: + return type.isSupported(DurationFieldType.seconds()) || + type.isSupported(DurationFieldType.millis()); + } + } + + void setFieldValue(ReadWritablePeriod period, int field, int value) { + switch (field) { + default: + break; + case YEARS: + period.setYears(value); + break; + case MONTHS: + period.setMonths(value); + break; + case WEEKS: + period.setWeeks(value); + break; + case DAYS: + period.setDays(value); + break; + case HOURS: + period.setHours(value); + break; + case MINUTES: + period.setMinutes(value); + break; + case SECONDS: + period.setSeconds(value); + break; + case MILLIS: + period.setMillis(value); + break; + } + } + + int getFieldType() { + return iFieldType; + } + } + + //----------------------------------------------------------------------- + /** + * Handles a simple literal piece of text. + */ + static class Literal + extends BasePeriodFormatter + implements PeriodFormatter { + static final Literal EMPTY = new Literal(""); + private final String iText; + + Literal(String text) { + iText = text; + } + + public int countFieldsToPrint(ReadablePeriod period, int stopAt) { + return 0; + } + + public int calculatePrintedLength(ReadablePeriod period) { + return iText.length(); + } + + public void printTo(StringBuffer buf, ReadablePeriod period) { + buf.append(iText); + } + + public void printTo(Writer out, ReadablePeriod period) throws IOException { + out.write(iText); + } + + public int parseInto(ReadWritablePeriod period, + String periodStr, int position) { + if (periodStr.regionMatches(true, position, iText, 0, iText.length())) { + return position + iText.length(); + } + return ~position; + } + } + + //----------------------------------------------------------------------- + /** + * Handles a separator, that splits the fields into multiple parts. + * For example, the 'T' in the ISO8601 standard. + */ + static class Separator + extends BasePeriodFormatter + implements PeriodFormatter { + private final String iText; + private final String iFinalText; + + private final boolean iUseBefore; + private final boolean iUseAfter; + + private BasePeriodFormatter iBefore; + private BasePeriodFormatter iAfter; + + Separator(String text, String finalText, BasePeriodFormatter before, boolean useBefore, boolean useAfter) { + iText = text; + iFinalText = finalText; + iBefore = before; + iUseBefore = useBefore; + iUseAfter = useAfter; + } + + public int countFieldsToPrint(ReadablePeriod period, int stopAt) { + int sum = iBefore.countFieldsToPrint(period, stopAt); + if (sum < stopAt) { + sum += iAfter.countFieldsToPrint(period, stopAt); + } + return sum; + } + + public int calculatePrintedLength(ReadablePeriod period) { + BasePeriodFormatter before = iBefore; + BasePeriodFormatter after = iAfter; + + int sum = before.calculatePrintedLength(period) + + after.calculatePrintedLength(period); + + if (iUseBefore) { + if (before.countFieldsToPrint(period, 1) > 0) { + if (iUseAfter) { + int afterCount = after.countFieldsToPrint(period, 2); + if (afterCount > 0) { + sum += (afterCount > 1 ? iText : iFinalText).length(); + } + } else { + sum += iText.length(); + } + } + } else if (iUseAfter && after.countFieldsToPrint(period, 1) > 0) { + sum += iText.length(); + } + + return sum; + } + + public void printTo(StringBuffer buf, ReadablePeriod period) { + BasePeriodFormatter before = iBefore; + BasePeriodFormatter after = iAfter; + + before.printTo(buf, period); + if (iUseBefore) { + if (before.countFieldsToPrint(period, 1) > 0) { + if (iUseAfter) { + int afterCount = after.countFieldsToPrint(period, 2); + if (afterCount > 0) { + buf.append(afterCount > 1 ? iText : iFinalText); + } + } else { + buf.append(iText); + } + } + } else if (iUseAfter && after.countFieldsToPrint(period, 1) > 0) { + buf.append(iText); + } + after.printTo(buf, period); + } + + public void printTo(Writer out, ReadablePeriod period) throws IOException { + BasePeriodFormatter before = iBefore; + BasePeriodFormatter after = iAfter; + + before.printTo(out, period); + if (iUseBefore) { + if (before.countFieldsToPrint(period, 1) > 0) { + if (iUseAfter) { + int afterCount = after.countFieldsToPrint(period, 2); + if (afterCount > 0) { + out.write(afterCount > 1 ? iText : iFinalText); + } + } else { + out.write(iText); + } + } + } else if (iUseAfter && after.countFieldsToPrint(period, 1) > 0) { + out.write(iText); + } + after.printTo(out, period); + } + + public int parseInto(ReadWritablePeriod period, + String periodStr, int position) { + final int oldPos = position; + + position = iBefore.parseInto(period, periodStr, position); + if (position < 0) { + return position; + } + if (position > oldPos) { + // Since position advanced, this separator is + // allowed. Optionally parse it. + if (periodStr.regionMatches(true, position, iText, 0, iText.length())) { + position += iText.length(); + } else if (iText != iFinalText && periodStr.regionMatches + (true, position, iFinalText, 0, iFinalText.length())) { + position += iFinalText.length(); + } + } + position = iAfter.parseInto(period, periodStr, position); + return position; + } + + Separator finish(BasePeriodFormatter after) { + iAfter = after; + return this; + } + } + + //----------------------------------------------------------------------- + /** + * Composite implementation that merges other fields to create a full pattern. + */ + static class Composite + extends BasePeriodFormatter + implements PeriodFormatter { + + private final BasePeriodFormatter[] iFormatters; + + Composite(List formatters) { + iFormatters = (BasePeriodFormatter[]) formatters.toArray( + new BasePeriodFormatter[formatters.size()]); + } + + public int countFieldsToPrint(ReadablePeriod period, int stopAt) { + int sum = 0; + BasePeriodFormatter[] printers = iFormatters; + for (int i=printers.length; sum < stopAt && --i>=0; ) { + sum += printers[i].countFieldsToPrint(period); + } + return sum; + } + + public int calculatePrintedLength(ReadablePeriod period) { + int sum = 0; + BasePeriodFormatter[] printers = iFormatters; + for (int i=printers.length; --i>=0; ) { + sum += printers[i].calculatePrintedLength(period); + } + return sum; + } + + public void printTo(StringBuffer buf, ReadablePeriod period) { + BasePeriodFormatter[] printers = iFormatters; + int len = printers.length; + for (int i=0; i= 0; i++) { + position = parsers[i].parseInto(period, periodStr, position); + } + return position; + } + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/PeriodParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/PeriodParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/PeriodParser.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import org.joda.time.Period; +import org.joda.time.PeriodType; +import org.joda.time.MutablePeriod; +import org.joda.time.ReadWritablePeriod; + +/** + * Defines an interface for parsing textual representations of time periods. + *

+ * Note: This interface represents a view onto {@link BasePeriodFormatter}. + * All implementations must extend BasePeriodFormatter. + * + * @author Brian S O'Neill + * @since 1.0 + * @see PeriodFormatter + * @see PeriodFormatterBuilder + * @see PeriodFormat + */ +public interface PeriodParser { + + /** + * Parses a period from the given text, at the given position, saving the + * result into the fields of the given ReadWritablePeriod. If the parse + * succeeds, the return value is the new text position. Note that the parse + * may succeed without fully reading the text. + *

+ * If it fails, the return value is negative, but the period may still be + * modified. To determine the position where the parse failed, apply the + * one's complement operator (~) on the return value. + * + * @param period a period that will be modified + * @param periodStr text to parse + * @param position position to start parsing from + * @return new position, if negative, parse failed. Apply complement + * operator (~) to get position of failure + * @throws IllegalArgumentException if any field is out of range + */ + int parseInto(ReadWritablePeriod period, String periodStr, int position); + + /** + * Parses a period from the given text, returning a new Period. + * + * @param type defines which fields may be parsed + * @param periodStr text to parse + * @return parsed value in a Period object + * @throws IllegalArgumentException if any field is out of range + */ + Period parsePeriod(PeriodType type, String periodStr); + + /** + * Parses a period from the given text, returning a new MutablePeriod. + * + * @param type defines which fields may be parsed + * @param periodStr text to parse + * @return parsed value in a MutablePeriod object + * @throws IllegalArgumentException if any field is out of range + */ + MutablePeriod parseMutablePeriod(PeriodType type, String periodStr); + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/PeriodPrinter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/PeriodPrinter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/PeriodPrinter.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.format; + +import java.io.IOException; +import java.io.Writer; + +import org.joda.time.ReadablePeriod; + +/** + * Defines an interface for creating textual representations of time periods. + *

+ * Note: This interface represents a view onto {@link BasePeriodFormatter}. + * All implementations must extend BasePeriodFormatter. + * + * @author Brian S O'Neill + * @since 1.0 + * @see PeriodFormatter + * @see PeriodFormatterBuilder + * @see PeriodFormat + */ +public interface PeriodPrinter { + + /** + * Prints a ReadablePeriod to a StringBuffer. + * + * @param buf the formatted period is appended to this buffer + * @param period the period to format + */ + void printTo(StringBuffer buf, ReadablePeriod period); + + /** + * Prints a ReadablePeriod to a Writer. + * + * @param out the formatted period is written out + * @param period the period to format + */ + void printTo(Writer out, ReadablePeriod period) throws IOException; + + /** + * Prints a ReadablePeriod to a new String. + * + * @param period the period to format + * @return the printed result + */ + String print(ReadablePeriod period); + +} Index: 3rdParty_sources/joda-time/org/joda/time/format/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/format/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/format/package.html 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,79 @@ + + + +org.joda.time.format package + + + +

+Provides printing and parsing support for instants and durations. This package +contains simple and advanced classes for formatting. +

+

+Formatters are defined by interfaces, and instances are obtained from factory classes. +Most datetime formatters can be obtained from +DateTimeFormat and ISODateTimeFormat. +More advanced formatters can be built by using DateTimeFormatterBuilder. +

+

+Similarly there are also classes for parsing and printing periods. +Most period formatters can be obtained from the factory classes +PeriodFormat and ISOPeriodFormat. +More advanced formatters can be built by using PeriodFormatterBuilder. +

+ + Index: 3rdParty_sources/joda-time/org/joda/time/tz/CachedDateTimeZone.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/CachedDateTimeZone.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/CachedDateTimeZone.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,260 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import org.joda.time.DateTimeZone; + +/** + * Improves the performance of requesting time zone offsets and name keys by + * caching the results. Time zones that have simple rules or are fixed should + * not be cached, as it is unlikely to improve performance. + *

+ * CachedDateTimeZone is thread-safe and immutable. + * + * @author Brian S O'Neill + */ +public class CachedDateTimeZone extends DateTimeZone { + + private static final long serialVersionUID = 5472298452022250685L; + + private static final int cInfoCacheMask; + + static { + Integer i; + try { + i = Integer.getInteger("org.joda.time.tz.CachedDateTimeZone.size"); + } catch (SecurityException e) { + i = null; + } + + int cacheSize; + if (i == null) { + // With a cache size of 512, dates that lie within any 69.7 year + // period have no cache collisions. + cacheSize = 512; // (1 << 9) + } else { + cacheSize = i.intValue(); + // Ensure cache size is even power of 2. + cacheSize--; + int shift = 0; + while (cacheSize > 0) { + shift++; + cacheSize >>= 1; + } + cacheSize = 1 << shift; + } + + cInfoCacheMask = cacheSize - 1; + } + + /** + * Returns a new CachedDateTimeZone unless given zone is already cached. + */ + public static CachedDateTimeZone forZone(DateTimeZone zone) { + if (zone instanceof CachedDateTimeZone) { + return (CachedDateTimeZone)zone; + } + return new CachedDateTimeZone(zone); + } + + /* + * Caching is performed by breaking timeline down into periods of 2^32 + * milliseconds, or about 49.7 days. A year has about 7.3 periods, usually + * with only 2 time zone offset periods. Most of the 49.7 day periods will + * have no transition, about one quarter have one transition, and very rare + * cases have multiple transitions. + */ + + private final DateTimeZone iZone; + + private transient Info[] iInfoCache; + + private CachedDateTimeZone(DateTimeZone zone) { + super(zone.getID()); + iZone = zone; + iInfoCache = new Info[cInfoCacheMask + 1]; + } + + private void readObject(java.io.ObjectInputStream in) + throws java.io.IOException, ClassNotFoundException + { + in.defaultReadObject(); + iInfoCache = new Info[cInfoCacheMask + 1]; + } + + /** + * Returns the DateTimeZone being wrapped. + */ + public DateTimeZone getUncachedZone() { + return iZone; + } + + public String getNameKey(long instant) { + return getInfo(instant).getNameKey(instant); + } + + public int getOffset(long instant) { + return getInfo(instant).getOffset(instant); + } + + public int getStandardOffset(long instant) { + return getInfo(instant).getStandardOffset(instant); + } + + public boolean isFixed() { + return iZone.isFixed(); + } + + public long nextTransition(long instant) { + return iZone.nextTransition(instant); + } + + public long previousTransition(long instant) { + return iZone.previousTransition(instant); + } + + public int hashCode() { + return iZone.hashCode(); + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof CachedDateTimeZone) { + return iZone.equals(((CachedDateTimeZone)obj).iZone); + } + return false; + } + + // Although accessed by multiple threads, this method doesn't need to be + // synchronized. + + private Info getInfo(long millis) { + int period = (int)(millis >> 32); + Info[] cache = iInfoCache; + int index = period & cInfoCacheMask; + Info info = cache[index]; + if (info == null || (int)((info.iPeriodStart >> 32)) != period) { + info = createInfo(millis); + cache[index] = info; + } + return info; + } + + private Info createInfo(long millis) { + long periodStart = millis & (0xffffffffL << 32); + Info info = new Info(iZone, periodStart); + + long end = periodStart | 0xffffffffL; + Info chain = info; + while (true) { + long next = iZone.nextTransition(periodStart); + if (next == periodStart || next > end) { + break; + } + periodStart = next; + chain = (chain.iNextInfo = new Info(iZone, periodStart)); + } + + return info; + } + + private final static class Info { + // For first Info in chain, iPeriodStart's lower 32 bits are clear. + public final long iPeriodStart; + public final DateTimeZone iZoneRef; + + Info iNextInfo; + + private String iNameKey; + private int iOffset = Integer.MIN_VALUE; + private int iStandardOffset = Integer.MIN_VALUE; + + Info(DateTimeZone zone, long periodStart) { + iPeriodStart = periodStart; + iZoneRef = zone; + } + + public String getNameKey(long millis) { + if (iNextInfo == null || millis < iNextInfo.iPeriodStart) { + if (iNameKey == null) { + iNameKey = iZoneRef.getNameKey(iPeriodStart); + } + return iNameKey; + } + return iNextInfo.getNameKey(millis); + } + + public int getOffset(long millis) { + if (iNextInfo == null || millis < iNextInfo.iPeriodStart) { + if (iOffset == Integer.MIN_VALUE) { + iOffset = iZoneRef.getOffset(iPeriodStart); + } + return iOffset; + } + return iNextInfo.getOffset(millis); + } + + public int getStandardOffset(long millis) { + if (iNextInfo == null || millis < iNextInfo.iPeriodStart) { + if (iStandardOffset == Integer.MIN_VALUE) { + iStandardOffset = iZoneRef.getStandardOffset(iPeriodStart); + } + return iStandardOffset; + } + return iNextInfo.getStandardOffset(millis); + } + } +} Index: 3rdParty_sources/joda-time/org/joda/time/tz/DateTimeZoneBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/DateTimeZoneBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/DateTimeZoneBuilder.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,1629 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeUtils; +import org.joda.time.DateTimeZone; +import org.joda.time.chrono.ISOChronology; + +/** + * DateTimeZoneBuilder allows complex DateTimeZones to be constructed. Since + * creating a new DateTimeZone this way is a relatively expensive operation, + * built zones can be written to a file. Reading back the encoded data is a + * quick operation. + *

+ * DateTimeZoneBuilder itself is mutable and not thread-safe, but the + * DateTimeZone objects that it builds are thread-safe and immutable. + * + * @author Brian S O'Neill + * @see ZoneInfoCompiler + * @see ZoneInfoProvider + */ +public class DateTimeZoneBuilder { + /** + * Decodes a built DateTimeZone from the given stream, as encoded by + * writeTo. + * + * @param in input stream to read encoded DateTimeZone from. + * @param id time zone id to assign + */ + public static DateTimeZone readFrom(InputStream in, String id) throws IOException { + if (in instanceof DataInput) { + return readFrom((DataInput)in, id); + } else { + return readFrom((DataInput)new DataInputStream(in), id); + } + } + + /** + * Decodes a built DateTimeZone from the given stream, as encoded by + * writeTo. + * + * @param in input stream to read encoded DateTimeZone from. + * @param id time zone id to assign + */ + public static DateTimeZone readFrom(DataInput in, String id) throws IOException { + switch (in.readUnsignedByte()) { + case 'F': + DateTimeZone fixed = new FixedDateTimeZone + (id, in.readUTF(), (int)readMillis(in), (int)readMillis(in)); + if (fixed.equals(DateTimeZone.UTC)) { + fixed = DateTimeZone.UTC; + } + return fixed; + case 'C': + return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id)); + case 'P': + return PrecalculatedZone.readFrom(in, id); + default: + throw new IOException("Invalid encoding"); + } + } + + /** + * Millisecond encoding formats: + * + * upper two bits units field length approximate range + * --------------------------------------------------------------- + * 00 30 minutes 1 byte +/- 16 hours + * 01 minutes 4 bytes +/- 1020 years + * 10 seconds 5 bytes +/- 4355 years + * 11 millis 9 bytes +/- 292,000,000 years + * + * Remaining bits in field form signed offset from 1970-01-01T00:00:00Z. + */ + static void writeMillis(DataOutput out, long millis) throws IOException { + if (millis % (30 * 60000L) == 0) { + // Try to write in 30 minute units. + long units = millis / (30 * 60000L); + if (((units << (64 - 6)) >> (64 - 6)) == units) { + // Form 00 (6 bits effective precision) + out.writeByte((int)(units & 0x3f)); + return; + } + } + + if (millis % 60000L == 0) { + // Try to write minutes. + long minutes = millis / 60000L; + if (((minutes << (64 - 30)) >> (64 - 30)) == minutes) { + // Form 01 (30 bits effective precision) + out.writeInt(0x40000000 | (int)(minutes & 0x3fffffff)); + return; + } + } + + if (millis % 1000L == 0) { + // Try to write seconds. + long seconds = millis / 1000L; + if (((seconds << (64 - 38)) >> (64 - 38)) == seconds) { + // Form 10 (38 bits effective precision) + out.writeByte(0x80 | (int)((seconds >> 32) & 0x3f)); + out.writeInt((int)(seconds & 0xffffffff)); + return; + } + } + + // Write milliseconds either because the additional precision is + // required or the minutes didn't fit in the field. + + // Form 11 (64 bits effective precision, but write as if 70 bits) + out.writeByte(millis < 0 ? 0xff : 0xc0); + out.writeLong(millis); + } + + /** + * Reads encoding generated by writeMillis. + */ + static long readMillis(DataInput in) throws IOException { + int v = in.readUnsignedByte(); + switch (v >> 6) { + case 0: default: + // Form 00 (6 bits effective precision) + v = (v << (32 - 6)) >> (32 - 6); + return v * (30 * 60000L); + + case 1: + // Form 01 (30 bits effective precision) + v = (v << (32 - 6)) >> (32 - 30); + v |= (in.readUnsignedByte()) << 16; + v |= (in.readUnsignedByte()) << 8; + v |= (in.readUnsignedByte()); + return v * 60000L; + + case 2: + // Form 10 (38 bits effective precision) + long w = (((long)v) << (64 - 6)) >> (64 - 38); + w |= (in.readUnsignedByte()) << 24; + w |= (in.readUnsignedByte()) << 16; + w |= (in.readUnsignedByte()) << 8; + w |= (in.readUnsignedByte()); + return w * 1000L; + + case 3: + // Form 11 (64 bits effective precision) + return in.readLong(); + } + } + + private static DateTimeZone buildFixedZone(String id, String nameKey, + int wallOffset, int standardOffset) { + if ("UTC".equals(id) && id.equals(nameKey) && + wallOffset == 0 && standardOffset == 0) { + return DateTimeZone.UTC; + } + return new FixedDateTimeZone(id, nameKey, wallOffset, standardOffset); + } + + // List of RuleSets. + private final ArrayList iRuleSets; + + public DateTimeZoneBuilder() { + iRuleSets = new ArrayList(10); + } + + /** + * Adds a cutover for added rules. The standard offset at the cutover + * defaults to 0. Call setStandardOffset afterwards to change it. + * + * @param year year of cutover + * @param mode 'u' - cutover is measured against UTC, 'w' - against wall + * offset, 's' - against standard offset. + * @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth). + * For example, if -1, set to last day of month + * @param dayOfWeek if 0, ignore + * @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to + * dayOfWeek when true, retreat when false. + * @param millisOfDay additional precision for specifying time of day of + * cutover + */ + public DateTimeZoneBuilder addCutover(int year, + char mode, + int monthOfYear, + int dayOfMonth, + int dayOfWeek, + boolean advanceDayOfWeek, + int millisOfDay) + { + OfYear ofYear = new OfYear + (mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay); + if (iRuleSets.size() > 0) { + RuleSet lastRuleSet = (RuleSet)iRuleSets.get(iRuleSets.size() - 1); + lastRuleSet.setUpperLimit(year, ofYear); + } + iRuleSets.add(new RuleSet()); + return this; + } + + /** + * Sets the standard offset to use for newly added rules until the next + * cutover is added. + */ + public DateTimeZoneBuilder setStandardOffset(int standardOffset) { + getLastRuleSet().setStandardOffset(standardOffset); + return this; + } + + /** + * Set a fixed savings rule at the cutover. + */ + public DateTimeZoneBuilder setFixedSavings(String nameKey, int saveMillis) { + getLastRuleSet().setFixedSavings(nameKey, saveMillis); + return this; + } + + /** + * Add a recurring daylight saving time rule. + * + * @param nameKey name key of new rule + * @param saveMillis milliseconds to add to standard offset + * @param fromYear First year that rule is in effect. MIN_VALUE indicates + * beginning of time. + * @param toYear Last year (inclusive) that rule is in effect. MAX_VALUE + * indicates end of time. + * @param mode 'u' - transitions are calculated against UTC, 'w' - + * transitions are calculated against wall offset, 's' - transitions are + * calculated against standard offset. + * @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth). + * For example, if -1, set to last day of month + * @param dayOfWeek if 0, ignore + * @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to + * dayOfWeek when true, retreat when false. + * @param millisOfDay additional precision for specifying time of day of + * transitions + */ + public DateTimeZoneBuilder addRecurringSavings(String nameKey, int saveMillis, + int fromYear, int toYear, + char mode, + int monthOfYear, + int dayOfMonth, + int dayOfWeek, + boolean advanceDayOfWeek, + int millisOfDay) + { + if (fromYear <= toYear) { + OfYear ofYear = new OfYear + (mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay); + Recurrence recurrence = new Recurrence(ofYear, nameKey, saveMillis); + Rule rule = new Rule(recurrence, fromYear, toYear); + getLastRuleSet().addRule(rule); + } + return this; + } + + private RuleSet getLastRuleSet() { + if (iRuleSets.size() == 0) { + addCutover(Integer.MIN_VALUE, 'w', 1, 1, 0, false, 0); + } + return (RuleSet)iRuleSets.get(iRuleSets.size() - 1); + } + + /** + * Processes all the rules and builds a DateTimeZone. + * + * @param id time zone id to assign + */ + public DateTimeZone toDateTimeZone(String id) { + if (id == null) { + throw new IllegalArgumentException(); + } + + // Discover where all the transitions occur and store the results in + // these lists. + ArrayList transitions = new ArrayList(); + + // Tail zone picks up remaining transitions in the form of an endless + // DST cycle. + DSTZone tailZone = null; + + long millis = Long.MIN_VALUE; + int saveMillis = 0; + + int ruleSetCount = iRuleSets.size(); + for (int i=0; i= 2) { + offsetForLast = ((Transition)transitions.get(size - 2)).getWallOffset(); + } + int offsetForNew = last.getWallOffset(); + + long lastLocal = last.getMillis() + offsetForLast; + long newLocal = tr.getMillis() + offsetForNew; + + if (newLocal != lastLocal) { + transitions.add(tr); + return true; + } + + transitions.remove(size - 1); + return addTransition(transitions, tr); + } + + /** + * Encodes a built DateTimeZone to the given stream. Call readFrom to + * decode the data into a DateTimeZone object. + * + * @param out output stream to receive encoded DateTimeZone. + */ + public void writeTo(OutputStream out) throws IOException { + if (out instanceof DataOutput) { + writeTo((DataOutput)out); + } else { + writeTo((DataOutput)new DataOutputStream(out)); + } + } + + /** + * Encodes a built DateTimeZone to the given stream. Call readFrom to + * decode the data into a DateTimeZone object. + * + * @param out output stream to receive encoded DateTimeZone. + */ + public void writeTo(DataOutput out) throws IOException { + // The zone id is not written out, so the empty string is okay. + DateTimeZone zone = toDateTimeZone(""); + + if (zone instanceof FixedDateTimeZone) { + out.writeByte('F'); // 'F' for fixed + out.writeUTF(zone.getNameKey(0)); + writeMillis(out, zone.getOffset(0)); + writeMillis(out, zone.getStandardOffset(0)); + } else { + if (zone instanceof CachedDateTimeZone) { + out.writeByte('C'); // 'C' for cached, precalculated + zone = ((CachedDateTimeZone)zone).getUncachedZone(); + } else { + out.writeByte('P'); // 'P' for precalculated, uncached + } + ((PrecalculatedZone)zone).writeTo(out); + } + } + + /** + * Supports setting fields of year and moving between transitions. + */ + private static final class OfYear { + static OfYear readFrom(DataInput in) throws IOException { + return new OfYear((char)in.readUnsignedByte(), + (int)in.readUnsignedByte(), + (int)in.readByte(), + (int)in.readUnsignedByte(), + in.readBoolean(), + (int)readMillis(in)); + } + + // Is 'u', 'w', or 's'. + final char iMode; + + final int iMonthOfYear; + final int iDayOfMonth; + final int iDayOfWeek; + final boolean iAdvance; + final int iMillisOfDay; + + OfYear(char mode, + int monthOfYear, + int dayOfMonth, + int dayOfWeek, boolean advanceDayOfWeek, + int millisOfDay) + { + if (mode != 'u' && mode != 'w' && mode != 's') { + throw new IllegalArgumentException("Unknown mode: " + mode); + } + + iMode = mode; + iMonthOfYear = monthOfYear; + iDayOfMonth = dayOfMonth; + iDayOfWeek = dayOfWeek; + iAdvance = advanceDayOfWeek; + iMillisOfDay = millisOfDay; + } + + /** + * @param standardOffset standard offset just before instant + */ + public long setInstant(int year, int standardOffset, int saveMillis) { + int offset; + if (iMode == 'w') { + offset = standardOffset + saveMillis; + } else if (iMode == 's') { + offset = standardOffset; + } else { + offset = 0; + } + + Chronology chrono = ISOChronology.getInstanceUTC(); + long millis = chrono.year().set(0, year); + millis = chrono.monthOfYear().set(millis, iMonthOfYear); + millis = chrono.millisOfDay().set(millis, iMillisOfDay); + millis = setDayOfMonth(chrono, millis); + + if (iDayOfWeek != 0) { + millis = setDayOfWeek(chrono, millis); + } + + // Convert from local time to UTC. + return millis - offset; + } + + /** + * @param standardOffset standard offset just before next recurrence + */ + public long next(long instant, int standardOffset, int saveMillis) { + int offset; + if (iMode == 'w') { + offset = standardOffset + saveMillis; + } else if (iMode == 's') { + offset = standardOffset; + } else { + offset = 0; + } + + // Convert from UTC to local time. + instant += offset; + + Chronology chrono = ISOChronology.getInstanceUTC(); + long next = chrono.monthOfYear().set(instant, iMonthOfYear); + // Be lenient with millisOfDay. + next = chrono.millisOfDay().set(next, 0); + next = chrono.millisOfDay().add(next, iMillisOfDay); + next = setDayOfMonthNext(chrono, next); + + if (iDayOfWeek == 0) { + if (next <= instant) { + next = chrono.year().add(next, 1); + next = setDayOfMonthNext(chrono, next); + } + } else { + next = setDayOfWeek(chrono, next); + if (next <= instant) { + next = chrono.year().add(next, 1); + next = chrono.monthOfYear().set(next, iMonthOfYear); + next = setDayOfMonthNext(chrono, next); + next = setDayOfWeek(chrono, next); + } + } + + // Convert from local time to UTC. + return next - offset; + } + + /** + * @param standardOffset standard offset just before previous recurrence + */ + public long previous(long instant, int standardOffset, int saveMillis) { + int offset; + if (iMode == 'w') { + offset = standardOffset + saveMillis; + } else if (iMode == 's') { + offset = standardOffset; + } else { + offset = 0; + } + + // Convert from UTC to local time. + instant += offset; + + Chronology chrono = ISOChronology.getInstanceUTC(); + long prev = chrono.monthOfYear().set(instant, iMonthOfYear); + // Be lenient with millisOfDay. + prev = chrono.millisOfDay().set(prev, 0); + prev = chrono.millisOfDay().add(prev, iMillisOfDay); + prev = setDayOfMonthPrevious(chrono, prev); + + if (iDayOfWeek == 0) { + if (prev >= instant) { + prev = chrono.year().add(prev, -1); + prev = setDayOfMonthPrevious(chrono, prev); + } + } else { + prev = setDayOfWeek(chrono, prev); + if (prev >= instant) { + prev = chrono.year().add(prev, -1); + prev = chrono.monthOfYear().set(prev, iMonthOfYear); + prev = setDayOfMonthPrevious(chrono, prev); + prev = setDayOfWeek(chrono, prev); + } + } + + // Convert from local time to UTC. + return prev - offset; + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof OfYear) { + OfYear other = (OfYear)obj; + return + iMode == other.iMode && + iMonthOfYear == other.iMonthOfYear && + iDayOfMonth == other.iDayOfMonth && + iDayOfWeek == other.iDayOfWeek && + iAdvance == other.iAdvance && + iMillisOfDay == other.iMillisOfDay; + } + return false; + } + + /* + public String toString() { + return + "[OfYear]\n" + + "Mode: " + iMode + '\n' + + "MonthOfYear: " + iMonthOfYear + '\n' + + "DayOfMonth: " + iDayOfMonth + '\n' + + "DayOfWeek: " + iDayOfWeek + '\n' + + "AdvanceDayOfWeek: " + iAdvance + '\n' + + "MillisOfDay: " + iMillisOfDay + '\n'; + } + */ + + public void writeTo(DataOutput out) throws IOException { + out.writeByte(iMode); + out.writeByte(iMonthOfYear); + out.writeByte(iDayOfMonth); + out.writeByte(iDayOfWeek); + out.writeBoolean(iAdvance); + writeMillis(out, iMillisOfDay); + } + + /** + * If month-day is 02-29 and year isn't leap, advances to next leap year. + */ + private long setDayOfMonthNext(Chronology chrono, long next) { + try { + next = setDayOfMonth(chrono, next); + } catch (IllegalArgumentException e) { + if (iMonthOfYear == 2 && iDayOfMonth == 29) { + while (chrono.year().isLeap(next) == false) { + next = chrono.year().add(next, 1); + } + next = setDayOfMonth(chrono, next); + } else { + throw e; + } + } + return next; + } + + /** + * If month-day is 02-29 and year isn't leap, retreats to previous leap year. + */ + private long setDayOfMonthPrevious(Chronology chrono, long prev) { + try { + prev = setDayOfMonth(chrono, prev); + } catch (IllegalArgumentException e) { + if (iMonthOfYear == 2 && iDayOfMonth == 29) { + while (chrono.year().isLeap(prev) == false) { + prev = chrono.year().add(prev, -1); + } + prev = setDayOfMonth(chrono, prev); + } else { + throw e; + } + } + return prev; + } + + private long setDayOfMonth(Chronology chrono, long instant) { + if (iDayOfMonth >= 0) { + instant = chrono.dayOfMonth().set(instant, iDayOfMonth); + } else { + instant = chrono.dayOfMonth().set(instant, 1); + instant = chrono.monthOfYear().add(instant, 1); + instant = chrono.dayOfMonth().add(instant, iDayOfMonth); + } + return instant; + } + + private long setDayOfWeek(Chronology chrono, long instant) { + int dayOfWeek = chrono.dayOfWeek().get(instant); + int daysToAdd = iDayOfWeek - dayOfWeek; + if (daysToAdd != 0) { + if (iAdvance) { + if (daysToAdd < 0) { + daysToAdd += 7; + } + } else { + if (daysToAdd > 0) { + daysToAdd -= 7; + } + } + instant = chrono.dayOfWeek().add(instant, daysToAdd); + } + return instant; + } + } + + /** + * Extends OfYear with a nameKey and savings. + */ + private static final class Recurrence { + static Recurrence readFrom(DataInput in) throws IOException { + return new Recurrence(OfYear.readFrom(in), in.readUTF(), (int)readMillis(in)); + } + + final OfYear iOfYear; + final String iNameKey; + final int iSaveMillis; + + Recurrence(OfYear ofYear, String nameKey, int saveMillis) { + iOfYear = ofYear; + iNameKey = nameKey; + iSaveMillis = saveMillis; + } + + public OfYear getOfYear() { + return iOfYear; + } + + /** + * @param standardOffset standard offset just before next recurrence + */ + public long next(long instant, int standardOffset, int saveMillis) { + return iOfYear.next(instant, standardOffset, saveMillis); + } + + /** + * @param standardOffset standard offset just before previous recurrence + */ + public long previous(long instant, int standardOffset, int saveMillis) { + return iOfYear.previous(instant, standardOffset, saveMillis); + } + + public String getNameKey() { + return iNameKey; + } + + public int getSaveMillis() { + return iSaveMillis; + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof Recurrence) { + Recurrence other = (Recurrence)obj; + return + iSaveMillis == other.iSaveMillis && + iNameKey.equals(other.iNameKey) && + iOfYear.equals(other.iOfYear); + } + return false; + } + + public void writeTo(DataOutput out) throws IOException { + iOfYear.writeTo(out); + out.writeUTF(iNameKey); + writeMillis(out, iSaveMillis); + } + } + + /** + * Extends Recurrence with inclusive year limits. + */ + private static final class Rule { + final Recurrence iRecurrence; + final int iFromYear; // inclusive + final int iToYear; // inclusive + + Rule(Recurrence recurrence, int fromYear, int toYear) { + iRecurrence = recurrence; + iFromYear = fromYear; + iToYear = toYear; + } + + public int getFromYear() { + return iFromYear; + } + + public int getToYear() { + return iToYear; + } + + public OfYear getOfYear() { + return iRecurrence.getOfYear(); + } + + public String getNameKey() { + return iRecurrence.getNameKey(); + } + + public int getSaveMillis() { + return iRecurrence.getSaveMillis(); + } + + public long next(final long instant, int standardOffset, int saveMillis) { + Chronology chrono = ISOChronology.getInstanceUTC(); + + final int wallOffset = standardOffset + saveMillis; + long testInstant = instant; + + int year; + if (instant == Long.MIN_VALUE) { + year = Integer.MIN_VALUE; + } else { + year = chrono.year().get(instant + wallOffset); + } + + if (year < iFromYear) { + // First advance instant to start of from year. + testInstant = chrono.year().set(0, iFromYear) - wallOffset; + // Back off one millisecond to account for next recurrence + // being exactly at the beginning of the year. + testInstant -= 1; + } + + long next = iRecurrence.next(testInstant, standardOffset, saveMillis); + + if (next > instant) { + year = chrono.year().get(next + wallOffset); + if (year > iToYear) { + // Out of range, return original value. + next = instant; + } + } + + return next; + } + } + + private static final class Transition { + private final long iMillis; + private final String iNameKey; + private final int iWallOffset; + private final int iStandardOffset; + + Transition(long millis, Transition tr) { + iMillis = millis; + iNameKey = tr.iNameKey; + iWallOffset = tr.iWallOffset; + iStandardOffset = tr.iStandardOffset; + } + + Transition(long millis, Rule rule, int standardOffset) { + iMillis = millis; + iNameKey = rule.getNameKey(); + iWallOffset = standardOffset + rule.getSaveMillis(); + iStandardOffset = standardOffset; + } + + Transition(long millis, String nameKey, + int wallOffset, int standardOffset) { + iMillis = millis; + iNameKey = nameKey; + iWallOffset = wallOffset; + iStandardOffset = standardOffset; + } + + public long getMillis() { + return iMillis; + } + + public String getNameKey() { + return iNameKey; + } + + public int getWallOffset() { + return iWallOffset; + } + + public int getStandardOffset() { + return iStandardOffset; + } + + public int getSaveMillis() { + return iWallOffset - iStandardOffset; + } + + /** + * There must be a change in the millis, wall offsets or name keys. + */ + public boolean isTransitionFrom(Transition other) { + if (other == null) { + return true; + } + return iMillis > other.iMillis && + (iWallOffset != other.iWallOffset || + //iStandardOffset != other.iStandardOffset || + !(iNameKey.equals(other.iNameKey))); + } + } + + private static final class RuleSet { + private static final int YEAR_LIMIT; + + static { + // Don't pre-calculate more than 100 years into the future. Almost + // all zones will stop pre-calculating far sooner anyhow. Either a + // simple DST cycle is detected or the last rule is a fixed + // offset. If a zone has a fixed offset set more than 100 years + // into the future, then it won't be observed. + long now = DateTimeUtils.currentTimeMillis(); + YEAR_LIMIT = ISOChronology.getInstanceUTC().year().get(now) + 100; + } + + private int iStandardOffset; + private ArrayList iRules; + + // Optional. + private String iInitialNameKey; + private int iInitialSaveMillis; + + // Upper limit is exclusive. + private int iUpperYear; + private OfYear iUpperOfYear; + + RuleSet() { + iRules = new ArrayList(10); + iUpperYear = Integer.MAX_VALUE; + } + + /** + * Copy constructor. + */ + RuleSet(RuleSet rs) { + iStandardOffset = rs.iStandardOffset; + iRules = new ArrayList(rs.iRules); + iInitialNameKey = rs.iInitialNameKey; + iInitialSaveMillis = rs.iInitialSaveMillis; + iUpperYear = rs.iUpperYear; + iUpperOfYear = rs.iUpperOfYear; + } + + public int getStandardOffset() { + return iStandardOffset; + } + + public void setStandardOffset(int standardOffset) { + iStandardOffset = standardOffset; + } + + public void setFixedSavings(String nameKey, int saveMillis) { + iInitialNameKey = nameKey; + iInitialSaveMillis = saveMillis; + } + + public void addRule(Rule rule) { + if (!iRules.contains(rule)) { + iRules.add(rule); + } + } + + public void setUpperLimit(int year, OfYear ofYear) { + iUpperYear = year; + iUpperOfYear = ofYear; + } + + /** + * Returns a transition at firstMillis with the first name key and + * offsets for this rule set. This method may return null. + * + * @param firstMillis millis of first transition + */ + public Transition firstTransition(final long firstMillis) { + if (iInitialNameKey != null) { + // Initial zone info explicitly set, so don't search the rules. + return new Transition(firstMillis, iInitialNameKey, + iStandardOffset + iInitialSaveMillis, iStandardOffset); + } + + // Make a copy before we destroy the rules. + ArrayList copy = new ArrayList(iRules); + + // Iterate through all the transitions until firstMillis is + // reached. Use the name key and savings for whatever rule reaches + // the limit. + + long millis = Long.MIN_VALUE; + int saveMillis = 0; + Transition first = null; + + Transition next; + while ((next = nextTransition(millis, saveMillis)) != null) { + millis = next.getMillis(); + + if (millis == firstMillis) { + first = new Transition(firstMillis, next); + break; + } + + if (millis > firstMillis) { + if (first == null) { + // Find first rule without savings. This way a more + // accurate nameKey is found even though no rule + // extends to the RuleSet's lower limit. + Iterator it = copy.iterator(); + while (it.hasNext()) { + Rule rule = (Rule)it.next(); + if (rule.getSaveMillis() == 0) { + first = new Transition(firstMillis, rule, iStandardOffset); + break; + } + } + } + if (first == null) { + // Found no rule without savings. Create a transition + // with no savings anyhow, and use the best available + // name key. + first = new Transition(firstMillis, next.getNameKey(), + iStandardOffset, iStandardOffset); + } + break; + } + + // Set first to the best transition found so far, but next + // iteration may find something closer to lower limit. + first = new Transition(firstMillis, next); + + saveMillis = next.getSaveMillis(); + } + + iRules = copy; + return first; + } + + /** + * Returns null if RuleSet is exhausted or upper limit reached. Calling + * this method will throw away rules as they each become + * exhausted. Copy the RuleSet before using it to compute transitions. + * + * Returned transition may be a duplicate from previous + * transition. Caller must call isTransitionFrom to filter out + * duplicates. + * + * @param saveMillis savings before next transition + */ + public Transition nextTransition(final long instant, final int saveMillis) { + Chronology chrono = ISOChronology.getInstanceUTC(); + + // Find next matching rule. + Rule nextRule = null; + long nextMillis = Long.MAX_VALUE; + + Iterator it = iRules.iterator(); + while (it.hasNext()) { + Rule rule = (Rule)it.next(); + long next = rule.next(instant, iStandardOffset, saveMillis); + if (next <= instant) { + it.remove(); + continue; + } + // Even if next is same as previous next, choose the rule + // in order for more recently added rules to override. + if (next <= nextMillis) { + // Found a better match. + nextRule = rule; + nextMillis = next; + } + } + + if (nextRule == null) { + return null; + } + + // Stop precalculating if year reaches some arbitrary limit. + if (chrono.year().get(nextMillis) >= YEAR_LIMIT) { + return null; + } + + // Check if upper limit reached or passed. + if (iUpperYear < Integer.MAX_VALUE) { + long upperMillis = + iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis); + if (nextMillis >= upperMillis) { + // At or after upper limit. + return null; + } + } + + return new Transition(nextMillis, nextRule, iStandardOffset); + } + + /** + * @param saveMillis savings before upper limit + */ + public long getUpperLimit(int saveMillis) { + if (iUpperYear == Integer.MAX_VALUE) { + return Long.MAX_VALUE; + } + return iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis); + } + + /** + * Returns null if none can be built. + */ + public DSTZone buildTailZone(String id) { + if (iRules.size() == 2) { + Rule startRule = (Rule)iRules.get(0); + Rule endRule = (Rule)iRules.get(1); + if (startRule.getToYear() == Integer.MAX_VALUE && + endRule.getToYear() == Integer.MAX_VALUE) { + + // With exactly two infinitely recurring rules left, a + // simple DSTZone can be formed. + + // The order of rules can come in any order, and it doesn't + // really matter which rule was chosen the 'start' and + // which is chosen the 'end'. DSTZone works properly either + // way. + return new DSTZone(id, iStandardOffset, + startRule.iRecurrence, endRule.iRecurrence); + } + } + return null; + } + } + + private static final class DSTZone extends DateTimeZone { + private static final long serialVersionUID = 6941492635554961361L; + + static DSTZone readFrom(DataInput in, String id) throws IOException { + return new DSTZone(id, (int)readMillis(in), + Recurrence.readFrom(in), Recurrence.readFrom(in)); + } + + private final int iStandardOffset; + private final Recurrence iStartRecurrence; + private final Recurrence iEndRecurrence; + + DSTZone(String id, int standardOffset, + Recurrence startRecurrence, Recurrence endRecurrence) { + super(id); + iStandardOffset = standardOffset; + iStartRecurrence = startRecurrence; + iEndRecurrence = endRecurrence; + } + + public String getNameKey(long instant) { + return findMatchingRecurrence(instant).getNameKey(); + } + + public int getOffset(long instant) { + return iStandardOffset + findMatchingRecurrence(instant).getSaveMillis(); + } + + public int getStandardOffset(long instant) { + return iStandardOffset; + } + + public boolean isFixed() { + return false; + } + + public long nextTransition(long instant) { + int standardOffset = iStandardOffset; + Recurrence startRecurrence = iStartRecurrence; + Recurrence endRecurrence = iEndRecurrence; + + long start, end; + + try { + start = startRecurrence.next + (instant, standardOffset, endRecurrence.getSaveMillis()); + if (instant > 0 && start < 0) { + // Overflowed. + start = instant; + } + } catch (IllegalArgumentException e) { + // Overflowed. + start = instant; + } + + try { + end = endRecurrence.next + (instant, standardOffset, startRecurrence.getSaveMillis()); + if (instant > 0 && end < 0) { + // Overflowed. + end = instant; + } + } catch (IllegalArgumentException e) { + // Overflowed. + end = instant; + } + + return (start > end) ? end : start; + } + + public long previousTransition(long instant) { + // Increment in order to handle the case where instant is exactly at + // a transition. + instant++; + + int standardOffset = iStandardOffset; + Recurrence startRecurrence = iStartRecurrence; + Recurrence endRecurrence = iEndRecurrence; + + long start, end; + + try { + start = startRecurrence.previous + (instant, standardOffset, endRecurrence.getSaveMillis()); + if (instant < 0 && start > 0) { + // Overflowed. + start = instant; + } + } catch (IllegalArgumentException e) { + // Overflowed. + start = instant; + } + + try { + end = endRecurrence.previous + (instant, standardOffset, startRecurrence.getSaveMillis()); + if (instant < 0 && end > 0) { + // Overflowed. + end = instant; + } + } catch (IllegalArgumentException e) { + // Overflowed. + end = instant; + } + + return ((start > end) ? start : end) - 1; + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof DSTZone) { + DSTZone other = (DSTZone)obj; + return + getID().equals(other.getID()) && + iStandardOffset == other.iStandardOffset && + iStartRecurrence.equals(other.iStartRecurrence) && + iEndRecurrence.equals(other.iEndRecurrence); + } + return false; + } + + public void writeTo(DataOutput out) throws IOException { + writeMillis(out, iStandardOffset); + iStartRecurrence.writeTo(out); + iEndRecurrence.writeTo(out); + } + + private Recurrence findMatchingRecurrence(long instant) { + int standardOffset = iStandardOffset; + Recurrence startRecurrence = iStartRecurrence; + Recurrence endRecurrence = iEndRecurrence; + + long start, end; + + try { + start = startRecurrence.next + (instant, standardOffset, endRecurrence.getSaveMillis()); + } catch (IllegalArgumentException e) { + // Overflowed. + start = instant; + } + + try { + end = endRecurrence.next + (instant, standardOffset, startRecurrence.getSaveMillis()); + } catch (IllegalArgumentException e) { + // Overflowed. + end = instant; + } + + return (start > end) ? startRecurrence : endRecurrence; + } + } + + private static final class PrecalculatedZone extends DateTimeZone { + private static final long serialVersionUID = 7811976468055766265L; + + static PrecalculatedZone readFrom(DataInput in, String id) throws IOException { + // Read string pool. + int poolSize = in.readUnsignedShort(); + String[] pool = new String[poolSize]; + for (int i=0; i= 0) { + return iNameKeys[i]; + } + i = ~i; + if (i < transitions.length) { + if (i > 0) { + return iNameKeys[i - 1]; + } + return "UTC"; + } + if (iTailZone == null) { + return iNameKeys[i - 1]; + } + return iTailZone.getNameKey(instant); + } + + public int getOffset(long instant) { + long[] transitions = iTransitions; + int i = Arrays.binarySearch(transitions, instant); + if (i >= 0) { + return iWallOffsets[i]; + } + i = ~i; + if (i < transitions.length) { + if (i > 0) { + return iWallOffsets[i - 1]; + } + return 0; + } + if (iTailZone == null) { + return iWallOffsets[i - 1]; + } + return iTailZone.getOffset(instant); + } + + public int getStandardOffset(long instant) { + long[] transitions = iTransitions; + int i = Arrays.binarySearch(transitions, instant); + if (i >= 0) { + return iStandardOffsets[i]; + } + i = ~i; + if (i < transitions.length) { + if (i > 0) { + return iStandardOffsets[i - 1]; + } + return 0; + } + if (iTailZone == null) { + return iStandardOffsets[i - 1]; + } + return iTailZone.getStandardOffset(instant); + } + + public boolean isFixed() { + return false; + } + + public long nextTransition(long instant) { + long[] transitions = iTransitions; + int i = Arrays.binarySearch(transitions, instant); + i = (i >= 0) ? (i + 1) : ~i; + if (i < transitions.length) { + return transitions[i]; + } + if (iTailZone == null) { + return instant; + } + long end = transitions[transitions.length - 1]; + if (instant < end) { + instant = end; + } + return iTailZone.nextTransition(instant); + } + + public long previousTransition(long instant) { + long[] transitions = iTransitions; + int i = Arrays.binarySearch(transitions, instant); + if (i >= 0) { + if (instant > Long.MIN_VALUE) { + return instant - 1; + } + return instant; + } + i = ~i; + if (i < transitions.length) { + if (i > 0) { + long prev = transitions[i - 1]; + if (prev > Long.MIN_VALUE) { + return prev - 1; + } + } + return instant; + } + if (iTailZone != null) { + long prev = iTailZone.previousTransition(instant); + if (prev < instant) { + return prev; + } + } + long prev = transitions[i - 1]; + if (prev > Long.MIN_VALUE) { + return prev - 1; + } + return instant; + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof PrecalculatedZone) { + PrecalculatedZone other = (PrecalculatedZone)obj; + return + getID().equals(other.getID()) && + Arrays.equals(iTransitions, other.iTransitions) && + Arrays.equals(iNameKeys, other.iNameKeys) && + Arrays.equals(iWallOffsets, other.iWallOffsets) && + Arrays.equals(iStandardOffsets, other.iStandardOffsets) && + ((iTailZone == null) + ? (null == other.iTailZone) + : (iTailZone.equals(other.iTailZone))); + } + return false; + } + + public void writeTo(DataOutput out) throws IOException { + int size = iTransitions.length; + + // Create unique string pool. + Set poolSet = new HashSet(); + for (int i=0; i 65535) { + throw new UnsupportedOperationException("String pool is too large"); + } + String[] pool = new String[poolSize]; + Iterator it = poolSet.iterator(); + for (int i=0; it.hasNext(); i++) { + pool[i] = (String)it.next(); + } + + // Write out the pool. + out.writeShort(poolSize); + for (int i=0; i 0) { + double avg = distances / count; + avg /= 24 * 60 * 60 * 1000; + if (avg >= 25) { + // Only bother caching if average distance between + // transitions is at least 25 days. Why 25? + // CachedDateTimeZone is more efficient if the distance + // between transitions is large. With an average of 25, it + // will on average perform about 2 tests per cache + // hit. (49.7 / 25) is approximately 2. + return true; + } + } + + return false; + } + } +} Index: 3rdParty_sources/joda-time/org/joda/time/tz/DefaultNameProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/DefaultNameProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/DefaultNameProvider.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import java.text.DateFormatSymbols; +import java.util.HashMap; +import java.util.Locale; + +/** + * The default name provider acquires localized names from + * {@link DateFormatSymbols java.text.DateFormatSymbols}. + *

+ * DefaultNameProvider is thread-safe and immutable. + * + * @author Brian S O'Neill + */ +public class DefaultNameProvider implements NameProvider { + // locale -> (id -> (nameKey -> [shortName, name])) + private HashMap iByLocaleCache = createCache(); + + public DefaultNameProvider() { + } + + public String getShortName(Locale locale, String id, String nameKey) { + String[] nameSet = getNameSet(locale, id, nameKey); + return nameSet == null ? null : nameSet[0]; + } + + public String getName(Locale locale, String id, String nameKey) { + String[] nameSet = getNameSet(locale, id, nameKey); + return nameSet == null ? null : nameSet[1]; + } + + private synchronized String[] getNameSet(Locale locale, String id, String nameKey) { + if (locale == null || id == null || nameKey == null) { + return null; + } + + HashMap byIdCache = (HashMap)iByLocaleCache.get(locale); + if (byIdCache == null) { + iByLocaleCache.put(locale, byIdCache = createCache()); + } + + HashMap byNameKeyCache = (HashMap)byIdCache.get(id); + if (byNameKeyCache == null) { + byIdCache.put(id, byNameKeyCache = createCache()); + String[][] zoneStrings = new DateFormatSymbols(locale).getZoneStrings(); + for (int i=0; i. For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import org.joda.time.DateTimeZone; + +/** + * Basic DateTimeZone implementation that has a fixed name key and offsets. + *

+ * FixedDateTimeZone is thread-safe and immutable. + * + * @author Brian S O'Neill + */ +public final class FixedDateTimeZone extends DateTimeZone { + + private static final long serialVersionUID = -3513011772763289092L; + + private final String iNameKey; + private final int iWallOffset; + private final int iStandardOffset; + + public FixedDateTimeZone(String id, String nameKey, + int wallOffset, int standardOffset) { + super(id); + iNameKey = nameKey; + iWallOffset = wallOffset; + iStandardOffset = standardOffset; + } + + public String getNameKey(long instant) { + return iNameKey; + } + + public int getOffset(long instant) { + return iWallOffset; + } + + public int getStandardOffset(long instant) { + return iStandardOffset; + } + + public int getOffsetFromLocal(long instantLocal) { + return iWallOffset; + } + + public boolean isFixed() { + return true; + } + + public long nextTransition(long instant) { + return instant; + } + + public long previousTransition(long instant) { + return instant; + } + + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof FixedDateTimeZone) { + FixedDateTimeZone other = (FixedDateTimeZone)obj; + return + getID().equals(other.getID()) && + iStandardOffset == other.iStandardOffset && + iWallOffset == other.iWallOffset; + } + return false; + } +} Index: 3rdParty_sources/joda-time/org/joda/time/tz/NameProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/NameProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/NameProvider.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import java.util.Locale; + +/** + * Service provider factory for localized time zone names. + * + * @author Brian S O'Neill + */ +public interface NameProvider { + /** + * Returns a localized short name, or null if not found. + * + * @param locale locale to use for selecting name set + * @param id time zone id + * @param nameKey time zone name key + */ + String getShortName(Locale locale, String id, String nameKey); + + /** + * Returns a localized name, or null if not found. + * + * @param locale locale to use for selecting name set + * @param id time zone id + * @param nameKey time zone name key + */ + String getName(Locale locale, String id, String nameKey); +} Index: 3rdParty_sources/joda-time/org/joda/time/tz/Provider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/Provider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/Provider.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import java.util.Set; +import org.joda.time.DateTimeZone; + +/** + * Service provider factory for time zones. + * + * @author Brian S O'Neill + */ +public interface Provider { + /** + * Retrieves a DateTimeZone for the given id. All providers must at + * least support id "UTC". + * + * @return null if not found + */ + DateTimeZone getZone(String id); + + /** + * Returns an unmodifiable set of ids. All providers must at least + * support id "UTC". + */ + Set getAvailableIDs(); +} Index: 3rdParty_sources/joda-time/org/joda/time/tz/UTCProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/UTCProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/UTCProvider.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import java.util.Collections; +import java.util.Set; +import org.joda.time.DateTimeZone; + +/** + * Simple time zone provider that supports only UTC. + *

+ * UTCProvider is thread-safe and immutable. + * + * @author Brian S O'Neill + * @since 1.0 + */ +public final class UTCProvider implements Provider { + + /** + * Constructor. + */ + public UTCProvider() { + super(); + } + + /** + * Returns {@link DateTimeZone#UTC UTC} for "UTC", null + * otherwise. + */ + public DateTimeZone getZone(String id) { + if ("UTC".equalsIgnoreCase(id)) { + return DateTimeZone.UTC; + } + return null; + } + + /** + * Returns a singleton collection containing only "UTC". + */ + public Set getAvailableIDs() { + return Collections.singleton("UTC"); + } + +} Index: 3rdParty_sources/joda-time/org/joda/time/tz/ZoneInfoCompiler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/ZoneInfoCompiler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/ZoneInfoCompiler.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,869 @@ +/* + * Joda Software License, Version 1.0 + * + * + * Copyright (c) 2001-2004 Stephen Colebourne. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, + * if any, must include the following acknowledgment: + * "This product includes software developed by the + * Joda project (http://www.joda.org/)." + * Alternately, this acknowledgment may appear in the software itself, + * if and wherever such third-party acknowledgments normally appear. + * + * 4. The name "Joda" must not be used to endorse or promote products + * derived from this software without prior written permission. For + * written permission, please contact licence@joda.org. + * + * 5. Products derived from this software may not be called "Joda", + * nor may "Joda" appear in their name, without prior written + * permission of the Joda project. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE JODA AUTHORS OR THE PROJECT + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Joda project and was originally + * created by Stephen Colebourne . For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TreeMap; + +import org.joda.time.Chronology; +import org.joda.time.DateTime; +import org.joda.time.DateTimeField; +import org.joda.time.DateTimeZone; +import org.joda.time.MutableDateTime; +import org.joda.time.format.DateTimeParser; +import org.joda.time.format.ISODateTimeFormat; +import org.joda.time.chrono.LenientChronology; +import org.joda.time.chrono.ISOChronology; + +/** + * Compiles Olson ZoneInfo database files into binary files for each time zone + * in the database. {@link DateTimeZoneBuilder} is used to construct and encode + * compiled data files. {@link ZoneInfoProvider} loads the encoded files and + * converts them back into {@link DateTimeZone} objects. + *

+ * Although this tool is similar to zic, the binary formats are not + * compatible. The latest Olson database files may be obtained + * here. + *

+ * ZoneInfoCompiler is mutable and not thread-safe, although the main method + * may be safely invoked by multiple threads. + * + * @author Brian S O'Neill + */ +public class ZoneInfoCompiler { + static DateTimeOfYear cStartOfYear; + + static Chronology cLenientISO; + + /** + * Launches the ZoneInfoCompiler tool. + * + *

+     * Usage: java org.joda.time.tz.ZoneInfoCompiler <options> <source files>
+     * where possible options include:
+     *   -src <directory>    Specify where to read source files
+     *   -dst <directory>    Specify where to write generated files
+     * 
+ */ + public static void main(String[] args) throws Exception { + if (args.length == 0) { + printUsage(); + return; + } + + File inputDir = null; + File outputDir = null; + + int i; + for (i=0; i= args.length) { + printUsage(); + return; + } + + File[] sources = new File[args.length - i]; + for (int j=0; i "); + System.out.println("where possible options include:"); + System.out.println(" -src Specify where to read source files"); + System.out.println(" -dst Specify where to write generated files"); + } + + static DateTimeOfYear getStartOfYear() { + if (cStartOfYear == null) { + cStartOfYear = new DateTimeOfYear(); + } + return cStartOfYear; + } + + static Chronology getLenientISOChronology() { + if (cLenientISO == null) { + cLenientISO = LenientChronology.getInstance(ISOChronology.getInstanceUTC()); + } + return cLenientISO; + } + + /** + * @param zimap maps string ids to DateTimeZone objects. + */ + static void writeZoneInfoMap(DataOutputStream dout, Map zimap) throws IOException { + // Build the string pool. + Map idToIndex = new HashMap(zimap.size()); + TreeMap indexToId = new TreeMap(); + + Iterator it = zimap.entrySet().iterator(); + short count = 0; + while (it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + String id = (String)entry.getKey(); + if (!idToIndex.containsKey(id)) { + Short index = new Short(count); + idToIndex.put(id, index); + indexToId.put(index, id); + if (++count == 0) { + throw new InternalError("Too many time zone ids"); + } + } + id = ((DateTimeZone)entry.getValue()).getID(); + if (!idToIndex.containsKey(id)) { + Short index = new Short(count); + idToIndex.put(id, index); + indexToId.put(index, id); + if (++count == 0) { + throw new InternalError("Too many time zone ids"); + } + } + } + + // Write the string pool, ordered by index. + dout.writeShort(indexToId.size()); + it = indexToId.values().iterator(); + while (it.hasNext()) { + dout.writeUTF((String)it.next()); + } + + // Write the mappings. + dout.writeShort(zimap.size()); + it = zimap.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry)it.next(); + String id = (String)entry.getKey(); + dout.writeShort(((Short)idToIndex.get(id)).shortValue()); + id = ((DateTimeZone)entry.getValue()).getID(); + dout.writeShort(((Short)idToIndex.get(id)).shortValue()); + } + } + + /** + * @param zimap gets filled with string id to string id mappings + */ + static void readZoneInfoMap(DataInputStream din, Map zimap) throws IOException { + // Read the string pool. + int size = din.readUnsignedShort(); + String[] pool = new String[size]; + for (int i=0; i end) { + break; + } + + millis = next; + + int nextOffset = tz.getOffset(millis); + String nextKey = tz.getNameKey(millis); + + if (offset == nextOffset + && key.equals(nextKey)) { + System.out.println("*d* Error in " + tz.getID() + " " + + new DateTime(millis, + ISOChronology.getInstanceUTC())); + return false; + } + + if (nextKey == null || (nextKey.length() < 3 && !"??".equals(nextKey))) { + System.out.println("*s* Error in " + tz.getID() + " " + + new DateTime(millis, + ISOChronology.getInstanceUTC()) + + ", nameKey=" + nextKey); + return false; + } + + transitions.add(new Long(millis)); + + offset = nextOffset; + key = nextKey; + } + + // Now verify that reverse transitions match up. + + millis = ISOChronology.getInstanceUTC().year().set(0, 2050); + end = ISOChronology.getInstanceUTC().year().set(0, 1850); + + for (int i=transitions.size(); --i>= 0; ) { + long prev = tz.previousTransition(millis); + if (prev == millis || prev < end) { + break; + } + + millis = prev; + + long trans = ((Long)transitions.get(i)).longValue(); + + if (trans - 1 != millis) { + System.out.println("*r* Error in " + tz.getID() + " " + + new DateTime(millis, + ISOChronology.getInstanceUTC()) + " != " + + new DateTime(trans - 1, + ISOChronology.getInstanceUTC())); + + return false; + } + } + + return true; + } + + // Maps names to RuleSets. + private Map iRuleSets; + + // List of Zone objects. + private List iZones; + + // List String pairs to link. + private List iLinks; + + public ZoneInfoCompiler() { + iRuleSets = new HashMap(); + iZones = new ArrayList(); + iLinks = new ArrayList(); + } + + /** + * Returns a map of ids to DateTimeZones. + * + * @param outputDir optional directory to write compiled data files to + * @param sources optional list of source files to parse + */ + public Map compile(File outputDir, File[] sources) throws IOException { + if (sources != null) { + for (int i=0; i 0) { + System.out.println("Cannot find time zone '" + id + + "' to link alias '" + alias + "' to"); + } + } else { + map.put(alias, tz); + } + } + } + + if (outputDir != null) { + System.out.println("Writing ZoneInfoMap"); + File file = new File(outputDir, "ZoneInfoMap"); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + + OutputStream out = new FileOutputStream(file); + DataOutputStream dout = new DataOutputStream(out); + // Sort and filter out any duplicates that match case. + Map zimap = new TreeMap(String.CASE_INSENSITIVE_ORDER); + zimap.putAll(map); + writeZoneInfoMap(dout, zimap); + dout.close(); + } + + return map; + } + + public void parseDataFile(BufferedReader in) throws IOException { + Zone zone = null; + String line; + while ((line = in.readLine()) != null) { + if (line.length() == 0 || line.charAt(0) == '#') { + continue; + } + + int index = line.indexOf('#'); + if (index >= 0) { + line = line.substring(0, index); + } + + //System.out.println(line); + + StringTokenizer st = new StringTokenizer(line, " \t"); + + if (Character.isWhitespace(line.charAt(0)) && st.hasMoreTokens()) { + if (zone != null) { + // Zone continuation + zone.chain(st); + } + continue; + } else { + if (zone != null) { + iZones.add(zone); + } + zone = null; + } + + if (st.hasMoreTokens()) { + String token = st.nextToken(); + if (token.equalsIgnoreCase("Rule")) { + Rule r = new Rule(st); + RuleSet rs = (RuleSet)iRuleSets.get(r.iName); + if (rs == null) { + rs = new RuleSet(r); + iRuleSets.put(r.iName, rs); + } else { + rs.addRule(r); + } + } else if (token.equalsIgnoreCase("Zone")) { + zone = new Zone(st); + } else if (token.equalsIgnoreCase("Link")) { + iLinks.add(st.nextToken()); + iLinks.add(st.nextToken()); + } else { + System.out.println("Unknown line: " + line); + } + } + } + + if (zone != null) { + iZones.add(zone); + } + } + + private static class DateTimeOfYear { + public final int iMonthOfYear; + public final int iDayOfMonth; + public final int iDayOfWeek; + public final boolean iAdvanceDayOfWeek; + public final int iMillisOfDay; + public final char iZoneChar; + + DateTimeOfYear() { + iMonthOfYear = 1; + iDayOfMonth = 1; + iDayOfWeek = 0; + iAdvanceDayOfWeek = false; + iMillisOfDay = 0; + iZoneChar = 'w'; + } + + DateTimeOfYear(StringTokenizer st) { + int month = 1; + int day = 1; + int dayOfWeek = 0; + int millis = 0; + boolean advance = false; + char zoneChar = 'w'; + + if (st.hasMoreTokens()) { + month = parseMonth(st.nextToken()); + + if (st.hasMoreTokens()) { + String str = st.nextToken(); + if (str.startsWith("last")) { + day = -1; + dayOfWeek = parseDayOfWeek(str.substring(4)); + advance = false; + } else { + try { + day = Integer.parseInt(str); + dayOfWeek = 0; + advance = false; + } catch (NumberFormatException e) { + int index = str.indexOf(">="); + if (index > 0) { + day = Integer.parseInt(str.substring(index + 2)); + dayOfWeek = parseDayOfWeek(str.substring(0, index)); + advance = true; + } else { + index = str.indexOf("<="); + if (index > 0) { + day = Integer.parseInt(str.substring(index + 2)); + dayOfWeek = parseDayOfWeek(str.substring(0, index)); + advance = false; + } else { + throw new IllegalArgumentException(str); + } + } + } + } + + if (st.hasMoreTokens()) { + str = st.nextToken(); + zoneChar = parseZoneChar(str.charAt(str.length() - 1)); + millis = parseTime(str); + } + } + } + + iMonthOfYear = month; + iDayOfMonth = day; + iDayOfWeek = dayOfWeek; + iAdvanceDayOfWeek = advance; + iMillisOfDay = millis; + iZoneChar = zoneChar; + } + + /** + * Adds a recurring savings rule to the builder. + */ + public void addRecurring(DateTimeZoneBuilder builder, String nameKey, + int saveMillis, int fromYear, int toYear) + { + builder.addRecurringSavings(nameKey, saveMillis, + fromYear, toYear, + iZoneChar, + iMonthOfYear, + iDayOfMonth, + iDayOfWeek, + iAdvanceDayOfWeek, + iMillisOfDay); + } + + /** + * Adds a cutover to the builder. + */ + public void addCutover(DateTimeZoneBuilder builder, int year) { + builder.addCutover(year, + iZoneChar, + iMonthOfYear, + iDayOfMonth, + iDayOfWeek, + iAdvanceDayOfWeek, + iMillisOfDay); + } + + public String toString() { + return + "MonthOfYear: " + iMonthOfYear + "\n" + + "DayOfMonth: " + iDayOfMonth + "\n" + + "DayOfWeek: " + iDayOfWeek + "\n" + + "AdvanceDayOfWeek: " + iAdvanceDayOfWeek + "\n" + + "MillisOfDay: " + iMillisOfDay + "\n" + + "ZoneChar: " + iZoneChar + "\n"; + } + } + + private static class Rule { + public final String iName; + public final int iFromYear; + public final int iToYear; + public final String iType; + public final DateTimeOfYear iDateTimeOfYear; + public final int iSaveMillis; + public final String iLetterS; + + Rule(StringTokenizer st) { + iName = st.nextToken().intern(); + iFromYear = parseYear(st.nextToken(), 0); + iToYear = parseYear(st.nextToken(), iFromYear); + if (iToYear < iFromYear) { + throw new IllegalArgumentException(); + } + iType = parseOptional(st.nextToken()); + iDateTimeOfYear = new DateTimeOfYear(st); + iSaveMillis = parseTime(st.nextToken()); + iLetterS = parseOptional(st.nextToken()); + } + + /** + * Adds a recurring savings rule to the builder. + */ + public void addRecurring(DateTimeZoneBuilder builder, String nameFormat) { + String nameKey = formatName(nameFormat); + iDateTimeOfYear.addRecurring + (builder, nameKey, iSaveMillis, iFromYear, iToYear); + } + + private String formatName(String nameFormat) { + int index = nameFormat.indexOf('/'); + if (index > 0) { + if (iSaveMillis == 0) { + // Extract standard name. + return nameFormat.substring(0, index).intern(); + } else { + return nameFormat.substring(index + 1).intern(); + } + } + index = nameFormat.indexOf("%s"); + if (index < 0) { + return nameFormat; + } + String left = nameFormat.substring(0, index); + String right = nameFormat.substring(index + 2); + String name; + if (iLetterS == null) { + name = left.concat(right); + } else { + name = left + iLetterS + right; + } + return name.intern(); + } + + public String toString() { + return + "[Rule]\n" + + "Name: " + iName + "\n" + + "FromYear: " + iFromYear + "\n" + + "ToYear: " + iToYear + "\n" + + "Type: " + iType + "\n" + + iDateTimeOfYear + + "SaveMillis: " + iSaveMillis + "\n" + + "LetterS: " + iLetterS + "\n"; + } + } + + private static class RuleSet { + private List iRules; + + RuleSet(Rule rule) { + iRules = new ArrayList(); + iRules.add(rule); + } + + void addRule(Rule rule) { + if (!(rule.iName.equals(((Rule)iRules.get(0)).iName))) { + throw new IllegalArgumentException("Rule name mismatch"); + } + iRules.add(rule); + } + + /** + * Adds recurring savings rules to the builder. + */ + public void addRecurring(DateTimeZoneBuilder builder, String nameFormat) { + for (int i=0; i. For more + * information on the Joda project, please see . + */ +package org.joda.time.tz; + +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.ref.SoftReference; +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import org.joda.time.DateTimeZone; + +/** + * ZoneInfoProvider loads compiled data files as generated by + * {@link ZoneInfoCompiler}. + *

+ * ZoneInfoProvider is thread-safe and publicly immutable. + * + * @author Brian S O'Neill + */ +public class ZoneInfoProvider implements Provider { + private static Map loadZoneInfoMap(InputStream in) throws IOException { + Map map = new TreeMap(String.CASE_INSENSITIVE_ORDER); + DataInputStream din = new DataInputStream(in); + try { + ZoneInfoCompiler.readZoneInfoMap(din, map); + } finally { + try { + din.close(); + } catch (IOException e) { + } + } + map.put("UTC", new SoftReference(DateTimeZone.UTC)); + return map; + } + + private final File iFileDir; + private final String iResourcePath; + private final ClassLoader iLoader; + + // Maps ids to strings or SoftReferences to DateTimeZones. + private final Map iZoneInfoMap; + + /** + * ZoneInfoProvider searches the given directory for compiled data files. + * + * @throws IOException if directory or map file cannot be read + */ + public ZoneInfoProvider(File fileDir) throws IOException { + if (fileDir == null) { + throw new IllegalArgumentException("No file directory provided"); + } + if (!fileDir.exists()) { + throw new IOException("File directory doesn't exist: " + fileDir); + } + if (!fileDir.isDirectory()) { + throw new IOException("File doesn't refer to a directory: " + fileDir); + } + + iFileDir = fileDir; + iResourcePath = null; + iLoader = null; + + iZoneInfoMap = loadZoneInfoMap(openResource("ZoneInfoMap")); + } + + /** + * ZoneInfoProvider searches the given ClassLoader resource path for + * compiled data files. Resources are loaded from the ClassLoader that + * loaded this class. + * + * @throws IOException if directory or map file cannot be read + */ + public ZoneInfoProvider(String resourcePath) throws IOException { + this(resourcePath, null, false); + } + + /** + * ZoneInfoProvider searches the given ClassLoader resource path for + * compiled data files. + * + * @param loader ClassLoader to load compiled data files from. If null, + * use system ClassLoader. + * @throws IOException if directory or map file cannot be read + */ + public ZoneInfoProvider(String resourcePath, ClassLoader loader) + throws IOException + { + this(resourcePath, loader, true); + } + + /** + * @param favorSystemLoader when true, use the system class loader if + * loader null. When false, use the current class loader if loader is null. + */ + private ZoneInfoProvider(String resourcePath, + ClassLoader loader, boolean favorSystemLoader) + throws IOException + { + if (resourcePath == null) { + throw new IllegalArgumentException("No resource path provided"); + } + if (!resourcePath.endsWith("/")) { + resourcePath += '/'; + } + + iFileDir = null; + iResourcePath = resourcePath; + + if (loader == null && !favorSystemLoader) { + loader = getClass().getClassLoader(); + } + + iLoader = loader; + + iZoneInfoMap = loadZoneInfoMap(openResource("ZoneInfoMap")); + } + + /** + * If an error is thrown while loading zone data, uncaughtException is + * called to log the error and null is returned for this and all future + * requests. + */ + public synchronized DateTimeZone getZone(String id) { + if (id == null) { + return null; + } + + Object obj = iZoneInfoMap.get(id); + if (obj == null) { + return null; + } + + if (id.equals(obj)) { + // Load zone data for the first time. + return loadZoneData(id); + } + + if (obj instanceof SoftReference) { + DateTimeZone tz = (DateTimeZone)((SoftReference)obj).get(); + if (tz != null) { + return tz; + } + // Reference cleared; load data again. + return loadZoneData(id); + } + + // If this point is reached, mapping must link to another. + return getZone((String)obj); + } + + public synchronized Set getAvailableIDs() { + return Collections.unmodifiableSet(iZoneInfoMap.keySet()); + } + + /** + * Called if an exception is thrown from getZone while loading zone + * data. + */ + protected void uncaughtException(Exception e) { + Thread t = Thread.currentThread(); + t.getThreadGroup().uncaughtException(t, e); + } + + private InputStream openResource(String name) throws IOException { + InputStream in; + if (iFileDir != null) { + in = new FileInputStream(new File(iFileDir, name)); + } else { + String path = iResourcePath.concat(name); + if (iLoader != null) { + in = iLoader.getResourceAsStream(path); + } else { + in = ClassLoader.getSystemResourceAsStream(path); + } + if (in == null) { + StringBuffer buf = new StringBuffer(40); + buf.append("Resource not found: \""); + buf.append(path); + buf.append("\" ClassLoader: "); + buf.append(iLoader != null ? iLoader.toString() : "system"); + throw new IOException(buf.toString()); + } + } + return in; + } + + private DateTimeZone loadZoneData(String id) { + InputStream in = null; + try { + in = openResource(id); + DateTimeZone tz = DateTimeZoneBuilder.readFrom(in, id); + iZoneInfoMap.put(id, new SoftReference(tz)); + return tz; + } catch (IOException e) { + uncaughtException(e); + iZoneInfoMap.remove(id); + return null; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException e) { + } + } + } +} Index: 3rdParty_sources/joda-time/org/joda/time/tz/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/package.html 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,70 @@ + + + +org.joda.time.tz package + + + +

+Implementation package supporting the time zones. +

+

+Provides support for implementing time zones. {@link org.joda.time.DateTimeZone} +uses these classes internally, but most applications need not use them directly. +

+ + Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/Readme.txt =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/Readme.txt,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/Readme.txt 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,2 @@ +The data files in this directory were obtained from the public tz database, +http://www.twinsun.com/tz/tz-link.htm, version 2004g. Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/africa =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/africa,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/africa 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,605 @@ +# @(#)africa 7.36 + +# This data is by no means authoritative; if you think you know better, +# go ahead and edit the file (and please send any changes to +# tz@elsie.nci.nih.gov for general use in the future). + +# From Paul Eggert (1999-03-22): +# +# A good source for time zone historical data outside the U.S. is +# Thomas G. Shanks, The International Atlas (5th edition), +# San Diego: ACS Publications, Inc. (1999). +# +# Gwillim Law writes that a good source +# for recent time zone data is the International Air Transport +# Association's Standard Schedules Information Manual (IATA SSIM), +# published semiannually. Law sent in several helpful summaries +# of the IATA's data after 1990. +# +# Except where otherwise noted, Shanks is the source for entries through 1990, +# and IATA SSIM is the source for entries after 1990. +# +# Another source occasionally used is Edward W. Whitman, World Time Differences, +# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), which +# I found in the UCLA library. +# +# A reliable and entertaining source about time zones is +# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997). +# +# Previous editions of this database used WAT, CAT, SAT, and EAT +# for +0:00 through +3:00, respectively, +# but Mark R V Murray reports that +# `SAST' is the official abbreviation for +2:00 in the country of South Africa, +# `CAT' is commonly used for +2:00 in countries north of South Africa, and +# `WAT' is probably the best name for +1:00, as the common phrase for +# the area that includes Nigeria is ``West Africa''. +# He has heard of ``Western Sahara Time'' for +0:00 but can find no reference. +# +# To make things confusing, `WAT' seems to have been used for -1:00 long ago; +# I'd guess that this was because people needed _some_ name for -1:00, +# and at the time, far west Africa was the only major land area in -1:00. +# This usage is now obsolete, as the last use of -1:00 on the African +# mainland seems to have been 1976 in Western Sahara. +# +# To summarize, the following abbreviations seem to have some currency: +# -1:00 WAT West Africa Time (no longer used) +# 0:00 GMT Greenwich Mean Time +# 2:00 CAT Central Africa Time +# 2:00 SAST South Africa Standard Time +# and Murray suggests the following abbreviation: +# 1:00 WAT West Africa Time +# I realize that this leads to `WAT' being used for both -1:00 and 1:00 +# for times before 1976, but this is the best I can think of +# until we get more information. +# +# I invented the following abbreviations; corrections are welcome! +# 2:00 WAST West Africa Summer Time +# 2:30 BEAT British East Africa Time (no longer used) +# 2:44:45 BEAUT British East Africa Unified Time (no longer used) +# 3:00 CAST Central Africa Summer Time (no longer used) +# 3:00 SAST South Africa Summer Time (no longer used) +# 3:00 EAT East Africa Time +# 4:00 EAST East Africa Summer Time (no longer used) + +# Algeria +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Algeria 1916 only - Jun 14 23:00s 1:00 S +Rule Algeria 1916 1919 - Oct Sun<=7 23:00s 0 - +Rule Algeria 1917 only - Mar 24 23:00s 1:00 S +Rule Algeria 1918 only - Mar 9 23:00s 1:00 S +Rule Algeria 1919 only - Mar 1 23:00s 1:00 S +Rule Algeria 1920 only - Feb 14 23:00s 1:00 S +Rule Algeria 1920 only - Oct 23 23:00s 0 - +Rule Algeria 1921 only - Mar 14 23:00s 1:00 S +Rule Algeria 1921 only - Jun 21 23:00s 0 - +Rule Algeria 1939 only - Sep 11 23:00s 1:00 S +Rule Algeria 1939 only - Nov 19 1:00 0 - +Rule Algeria 1944 1945 - Apr Mon<=7 2:00 1:00 S +Rule Algeria 1944 only - Oct 8 2:00 0 - +Rule Algeria 1945 only - Sep 16 1:00 0 - +Rule Algeria 1971 only - Apr 25 23:00s 1:00 S +Rule Algeria 1971 only - Sep 26 23:00s 0 - +Rule Algeria 1977 only - May 6 0:00 1:00 S +Rule Algeria 1977 only - Oct 21 0:00 0 - +Rule Algeria 1978 only - Mar 24 1:00 1:00 S +Rule Algeria 1978 only - Sep 22 3:00 0 - +Rule Algeria 1980 only - Apr 25 0:00 1:00 S +Rule Algeria 1980 only - Oct 31 2:00 0 - +# Shanks gives 0:09 for Paris Mean Time; go with Howse's more precise 0:09:21. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Algiers 0:12:12 - LMT 1891 Mar 15 0:01 + 0:09:21 - PMT 1911 Mar 11 # Paris Mean Time + 0:00 Algeria WE%sT 1940 Feb 25 2:00 + 1:00 Algeria CE%sT 1946 Oct 7 + 0:00 - WET 1956 Jan 29 + 1:00 - CET 1963 Apr 14 + 0:00 Algeria WE%sT 1977 Oct 21 + 1:00 Algeria CE%sT 1979 Oct 26 + 0:00 Algeria WE%sT 1981 May + 1:00 - CET + +# Angola +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Luanda 0:52:56 - LMT 1892 + 0:52:04 - AOT 1911 May 26 # Angola Time + 1:00 - WAT + +# Benin +# Whitman says they switched to 1:00 in 1946, not 1934; go with Shanks. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Porto-Novo 0:10:28 - LMT 1912 + 0:00 - GMT 1934 Feb 26 + 1:00 - WAT + +# Botswana +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Gaborone 1:43:40 - LMT 1885 + 2:00 - CAT 1943 Sep 19 2:00 + 2:00 1:00 CAST 1944 Mar 19 2:00 + 2:00 - CAT + +# Burkina Faso +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Ouagadougou -0:06:04 - LMT 1912 + 0:00 - GMT + +# Burundi +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Bujumbura 1:57:28 - LMT 1890 + 2:00 - CAT + +# Cameroon +# Whitman says they switched to 1:00 in 1920; go with Shanks. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Douala 0:38:48 - LMT 1912 + 1:00 - WAT + +# Cape Verde +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Atlantic/Cape_Verde -1:34:04 - LMT 1907 # Praia + -2:00 - CVT 1942 Sep + -2:00 1:00 CVST 1945 Oct 15 + -2:00 - CVT 1975 Nov 25 2:00 + -1:00 - CVT + +# Central African Republic +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Bangui 1:14:20 - LMT 1912 + 1:00 - WAT + +# Chad +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Ndjamena 1:00:12 - LMT 1912 + 1:00 - WAT 1979 Oct 14 + 1:00 1:00 WAST 1980 Mar 8 + 1:00 - WAT + +# Comoros +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Comoro 2:53:04 - LMT 1911 Jul # Moroni, Gran Comoro + 3:00 - EAT + +# Democratic Republic of Congo +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Kinshasa 1:01:12 - LMT 1897 Nov 9 + 1:00 - WAT +Zone Africa/Lubumbashi 1:49:52 - LMT 1897 Nov 9 + 2:00 - CAT + +# Republic of the Congo +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Brazzaville 1:01:08 - LMT 1912 + 1:00 - WAT + +# Cote D'Ivoire +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Abidjan -0:16:08 - LMT 1912 + 0:00 - GMT + +# Djibouti +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Djibouti 2:52:36 - LMT 1911 Jul + 3:00 - EAT + +############################################################################### + +# Egypt + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Egypt 1940 only - Jul 15 0:00 1:00 S +Rule Egypt 1940 only - Oct 1 0:00 0 - +Rule Egypt 1941 only - Apr 15 0:00 1:00 S +Rule Egypt 1941 only - Sep 16 0:00 0 - +Rule Egypt 1942 1944 - Apr 1 0:00 1:00 S +Rule Egypt 1942 only - Oct 27 0:00 0 - +Rule Egypt 1943 1945 - Nov 1 0:00 0 - +Rule Egypt 1945 only - Apr 16 0:00 1:00 S +Rule Egypt 1957 only - May 10 0:00 1:00 S +Rule Egypt 1957 1958 - Oct 1 0:00 0 - +Rule Egypt 1958 only - May 1 0:00 1:00 S +Rule Egypt 1959 1981 - May 1 1:00 1:00 S +Rule Egypt 1959 1965 - Sep 30 3:00 0 - +Rule Egypt 1966 1994 - Oct 1 3:00 0 - +Rule Egypt 1982 only - Jul 25 1:00 1:00 S +Rule Egypt 1983 only - Jul 12 1:00 1:00 S +Rule Egypt 1984 1988 - May 1 1:00 1:00 S +Rule Egypt 1989 only - May 6 1:00 1:00 S +Rule Egypt 1990 1994 - May 1 1:00 1:00 S +# IATA (after 1990) says transitions are at 0:00. +# Go with IATA starting in 1995, except correct 1995 entry from 09-30 to 09-29. +Rule Egypt 1995 max - Apr lastFri 0:00s 1:00 S +Rule Egypt 1995 max - Sep lastThu 23:00s 0 - + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Cairo 2:05:00 - LMT 1900 Oct + 2:00 Egypt EE%sT + +# Equatorial Guinea +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Malabo 0:35:08 - LMT 1912 + 0:00 - GMT 1963 Dec 15 + 1:00 - WAT + +# Eritrea +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Asmera 2:35:32 - LMT 1870 + 2:35:32 - AMT 1890 # Asmera Mean Time + 2:35:20 - ADMT 1936 May 5 # Adis Dera MT + 3:00 - EAT + +# Ethiopia +# From Paul Eggert (1997-10-05): +# Shanks writes that Ethiopia had six narrowly-spaced time zones between +# 1870 and 1890, and that they merged to 38E50 (2:35:20) in 1890. +# We'll guess that 38E50 is for Adis Dera. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Addis_Ababa 2:34:48 - LMT 1870 + 2:35:20 - ADMT 1936 May 5 # Adis Dera MT + 3:00 - EAT + +# Gabon +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Libreville 0:37:48 - LMT 1912 + 1:00 - WAT + +# Gambia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Banjul -1:06:36 - LMT 1912 + -1:06:36 - BMT 1935 # Banjul Mean Time + -1:00 - WAT 1964 + 0:00 - GMT + +# Ghana +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# Whitman says DST was observed from 1931 to ``the present''; go with Shanks. +Rule Ghana 1936 1942 - Sep 1 0:00 0:20 GHST +Rule Ghana 1936 1942 - Dec 31 0:00 0 GMT +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Accra -0:00:52 - LMT 1918 + 0:00 Ghana %s + +# Guinea +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Conakry -0:54:52 - LMT 1912 + 0:00 - GMT 1934 Feb 26 + -1:00 - WAT 1960 + 0:00 - GMT + +# Guinea-Bissau +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Bissau -1:02:20 - LMT 1911 May 26 + -1:00 - WAT 1975 + 0:00 - GMT + +# Kenya +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Nairobi 2:27:16 - LMT 1928 Jul + 3:00 - EAT 1930 + 2:30 - BEAT 1940 + 2:44:45 - BEAUT 1960 + 3:00 - EAT + +# Lesotho +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Maseru 1:50:00 - LMT 1903 Mar + 2:00 - SAST 1943 Sep 19 2:00 + 2:00 1:00 SAST 1944 Mar 19 2:00 + 2:00 - SAST + +# Liberia +# From Paul Eggert (2001-07-17): +# In 1972 Liberia was the last country to switch +# from a UTC offset that was not a multiple of 15 or 20 minutes. +# Howse reports that it was in honor of their president's birthday. +# Shanks reports the date as May 1, whereas Howse reports Jan; go with Shanks. +# For Liberia before 1972, Shanks reports -0:44, whereas Howse and Whitman +# each report -0:44:30; go with the more precise figure. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Monrovia -0:43:08 - LMT 1882 + -0:43:08 - MMT 1919 Mar # Monrovia Mean Time + -0:44:30 - LRT 1972 May # Liberia Time + 0:00 - GMT + +############################################################################### + +# Libya + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Libya 1951 only - Oct 14 2:00 1:00 S +Rule Libya 1952 only - Jan 1 0:00 0 - +Rule Libya 1953 only - Oct 9 2:00 1:00 S +Rule Libya 1954 only - Jan 1 0:00 0 - +Rule Libya 1955 only - Sep 30 0:00 1:00 S +Rule Libya 1956 only - Jan 1 0:00 0 - +Rule Libya 1982 1984 - Apr 1 0:00 1:00 S +Rule Libya 1982 1985 - Oct 1 0:00 0 - +Rule Libya 1985 only - Apr 6 0:00 1:00 S +Rule Libya 1986 only - Apr 4 0:00 1:00 S +Rule Libya 1986 only - Oct 3 0:00 0 - +Rule Libya 1987 1989 - Apr 1 0:00 1:00 S +Rule Libya 1987 1990 - Oct 1 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Tripoli 0:52:44 - LMT 1920 + 1:00 Libya CE%sT 1959 + 2:00 - EET 1982 + 1:00 Libya CE%sT 1990 May 4 +# The following entries are all from Shanks; +# the IATA SSIM data contain some obvious errors. + 2:00 - EET 1996 Sep 30 + 1:00 - CET 1997 Apr 4 + 1:00 1:00 CEST 1997 Oct 4 + 2:00 - EET + +# Madagascar +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Antananarivo 3:10:04 - LMT 1911 Jul + 3:00 - EAT 1954 Feb 27 23:00s + 3:00 1:00 EAST 1954 May 29 23:00s + 3:00 - EAT + +# Malawi +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Blantyre 2:20:00 - LMT 1903 Mar + 2:00 - CAT + +# Mali +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Bamako -0:32:00 - LMT 1912 + 0:00 - GMT 1934 Feb 26 + -1:00 - WAT 1960 Jun 20 + 0:00 - GMT +# no longer different from Bamako, but too famous to omit +Zone Africa/Timbuktu -0:12:04 - LMT 1912 + 0:00 - GMT + +# Mauritania +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Nouakchott -1:03:48 - LMT 1912 + 0:00 - GMT 1934 Feb 26 + -1:00 - WAT 1960 Nov 28 + 0:00 - GMT + +# Mauritius +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Mauritius 3:50:00 - LMT 1907 # Port Louis + 4:00 - MUT # Mauritius Time +# Agalega Is, Rodriguez +# no information; probably like Indian/Mauritius + +# Mayotte +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Mayotte 3:00:56 - LMT 1911 Jul # Mamoutzou + 3:00 - EAT + +# Morocco +# See the `europe' file for Spanish Morocco (Africa/Ceuta). +# RULE NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Morocco 1939 only - Sep 12 0:00 1:00 S +Rule Morocco 1939 only - Nov 19 0:00 0 - +Rule Morocco 1940 only - Feb 25 0:00 1:00 S +Rule Morocco 1945 only - Nov 18 0:00 0 - +Rule Morocco 1950 only - Jun 11 0:00 1:00 S +Rule Morocco 1950 only - Oct 29 0:00 0 - +Rule Morocco 1967 only - Jun 3 12:00 1:00 S +Rule Morocco 1967 only - Oct 1 0:00 0 - +Rule Morocco 1974 only - Jun 24 0:00 1:00 S +Rule Morocco 1974 only - Sep 1 0:00 0 - +Rule Morocco 1976 1977 - May 1 0:00 1:00 S +Rule Morocco 1976 only - Aug 1 0:00 0 - +Rule Morocco 1977 only - Sep 28 0:00 0 - +Rule Morocco 1978 only - Jun 1 0:00 1:00 S +Rule Morocco 1978 only - Aug 4 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Casablanca -0:30:20 - LMT 1913 Oct 26 + 0:00 Morocco WE%sT 1984 Mar 16 + 1:00 - CET 1986 + 0:00 - WET +# Western Sahara +Zone Africa/El_Aaiun -0:52:48 - LMT 1934 Jan + -1:00 - WAT 1976 Apr 14 + 0:00 - WET + +# Mozambique +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Maputo 2:10:20 - LMT 1903 Mar + 2:00 - CAT + +# Namibia +# The 1994-04-03 transition is from Shanks. +# Shanks reports no DST after 1998-04; go with IATA. +# RULE NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Namibia 1994 max - Sep Sun>=1 2:00 1:00 S +Rule Namibia 1995 max - Apr Sun>=1 2:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Windhoek 1:08:24 - LMT 1892 Feb 8 + 1:30 - SWAT 1903 Mar # SW Africa Time + 2:00 - SAST 1942 Sep 20 2:00 + 2:00 1:00 SAST 1943 Mar 21 2:00 + 2:00 - SAST 1990 Mar 21 # independence + 2:00 - CAT 1994 Apr 3 + 1:00 Namibia WA%sT + +# Niger +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Niamey 0:08:28 - LMT 1912 + -1:00 - WAT 1934 Feb 26 + 0:00 - GMT 1960 + 1:00 - WAT + +# Nigeria +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Lagos 0:13:36 - LMT 1919 Sep + 1:00 - WAT + +# Reunion +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Reunion 3:41:52 - LMT 1911 Jun # Saint-Denis + 4:00 - RET # Reunion Time +# +# Scattered Islands (Iles Eparses) administered from Reunion are as follows. +# The following information about them is taken from +# Iles Eparses (www.outre-mer.gouv.fr/domtom/ile.htm, 1997-07-22, in French; +# no longer available as of 1999-08-17). +# We have no info about their time zone histories. +# +# Bassas da India - uninhabited +# Europa Island - inhabited from 1905 to 1910 by two families +# Glorioso Is - inhabited until at least 1958 +# Juan de Nova - uninhabited +# Tromelin - inhabited until at least 1958 + +# Rwanda +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Kigali 2:00:16 - LMT 1935 Jun + 2:00 - CAT + +# St Helena +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Atlantic/St_Helena -0:22:48 - LMT 1890 # Jamestown + -0:22:48 - JMT 1951 # Jamestown Mean Time + 0:00 - GMT +# The other parts of the St Helena territory are similar: +# Tristan da Cunha: on GMT, say Whitman and the CIA +# Ascension: on GMT, says usno1995 and the CIA +# Gough (scientific station since 1955; sealers wintered previously): +# on GMT, says the CIA +# Inaccessible, Nightingale: no information, but probably GMT + +# Sao Tome and Principe +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Sao_Tome 0:26:56 - LMT 1884 + -0:36:32 - LMT 1912 # Lisbon Mean Time + 0:00 - GMT + +# Senegal +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Dakar -1:09:44 - LMT 1912 + -1:00 - WAT 1941 Jun + 0:00 - GMT + +# Seychelles +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Mahe 3:41:48 - LMT 1906 Jun # Victoria + 4:00 - SCT # Seychelles Time +# From Paul Eggert (2001-05-30): +# Aldabra, Farquhar, and Desroches, originally dependencies of the +# Seychelles, were transferred to the British Indian Ocean Territory +# in 1965 and returned to Seychelles control in 1976. We don't know +# whether this affected their time zone, so omit this for now. +# Possibly the islands were uninhabited. + +# Sierra Leone +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# Whitman gives Mar 31 - Aug 31 for 1931 on; go with Shanks. +Rule SL 1935 1942 - Jun 1 0:00 0:40 SLST +Rule SL 1935 1942 - Oct 1 0:00 0 WAT +Rule SL 1957 1962 - Jun 1 0:00 1:00 SLST +Rule SL 1957 1962 - Sep 1 0:00 0 GMT +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Freetown -0:53:00 - LMT 1882 + -0:53:00 - FMT 1913 Jun # Freetown Mean Time + -1:00 SL %s 1957 + 0:00 SL %s + +# Somalia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Mogadishu 3:01:28 - LMT 1893 Nov + 3:00 - EAT 1931 + 2:30 - BEAT 1957 + 3:00 - EAT + +# South Africa +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule SA 1942 1943 - Sep Sun>=15 2:00 1:00 - +Rule SA 1943 1944 - Mar Sun>=15 2:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Johannesburg 1:52:00 - LMT 1892 Feb 8 + 1:30 - SAST 1903 Mar + 2:00 SA SAST +# Marion and Prince Edward Is +# scientific station since 1947 +# no information + +# Sudan +# +# From +# Sudan News Agency (2000-01-13) +# , also reported by Michael De Beukelaer-Dossche via Steffen Thorsen: +# Clocks will be moved ahead for 60 minutes all over the Sudan as of noon +# Saturday.... This was announced Thursday by Caretaker State Minister for +# Manpower Abdul-Rahman Nur-Eddin. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Sudan 1970 only - May 1 0:00 1:00 S +Rule Sudan 1970 1985 - Oct 15 0:00 0 - +Rule Sudan 1971 only - Apr 30 0:00 1:00 S +Rule Sudan 1972 1985 - Apr lastSun 0:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Khartoum 2:10:08 - LMT 1931 + 2:00 Sudan CA%sT 2000 Jan 15 12:00 + 3:00 - EAT + +# Swaziland +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Mbabane 2:04:24 - LMT 1903 Mar + 2:00 - SAST + +# Tanzania +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Dar_es_Salaam 2:37:08 - LMT 1931 + 3:00 - EAT 1948 + 2:44:45 - BEAUT 1961 + 3:00 - EAT + +# Togo +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Lome 0:04:52 - LMT 1893 + 0:00 - GMT + +# Tunisia +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Tunisia 1939 only - Apr 15 23:00s 1:00 S +Rule Tunisia 1939 only - Nov 18 23:00s 0 - +Rule Tunisia 1940 only - Feb 25 23:00s 1:00 S +Rule Tunisia 1941 only - Oct 6 0:00 0 - +Rule Tunisia 1942 only - Mar 9 0:00 1:00 S +Rule Tunisia 1942 only - Nov 2 3:00 0 - +Rule Tunisia 1943 only - Mar 29 2:00 1:00 S +Rule Tunisia 1943 only - Apr 17 2:00 0 - +Rule Tunisia 1943 only - Apr 25 2:00 1:00 S +Rule Tunisia 1943 only - Oct 4 2:00 0 - +Rule Tunisia 1944 1945 - Apr Mon>=1 2:00 1:00 S +Rule Tunisia 1944 only - Oct 8 0:00 0 - +Rule Tunisia 1945 only - Sep 16 0:00 0 - +Rule Tunisia 1977 only - Apr 30 0:00s 1:00 S +Rule Tunisia 1977 only - Sep 24 0:00s 0 - +Rule Tunisia 1978 only - May 1 0:00s 1:00 S +Rule Tunisia 1978 only - Oct 1 0:00s 0 - +Rule Tunisia 1988 only - Jun 1 0:00s 1:00 S +Rule Tunisia 1988 1990 - Sep lastSun 0:00s 0 - +Rule Tunisia 1989 only - Mar 26 0:00s 1:00 S +Rule Tunisia 1990 only - May 1 0:00s 1:00 S +# Shanks gives 0:09 for Paris Mean Time; go with Howse's more precise 0:09:21. +# Shanks says the 1911 switch occurred on Mar 9; go with Howse's Mar 11. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Tunis 0:40:44 - LMT 1881 May 12 + 0:09:21 - PMT 1911 Mar 11 # Paris Mean Time + 1:00 Tunisia CE%sT + +# Uganda +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Kampala 2:09:40 - LMT 1928 Jul + 3:00 - EAT 1930 + 2:30 - BEAT 1948 + 2:44:45 - BEAUT 1957 + 3:00 - EAT + +# Zambia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Lusaka 1:53:08 - LMT 1903 Mar + 2:00 - CAT + +# Zimbabwe +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Africa/Harare 2:04:12 - LMT 1903 Mar + 2:00 - CAT Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/antarctica =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/antarctica,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/antarctica 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,318 @@ +# @(#)antarctica 7.23 + +# From Paul Eggert (1999-11-15): +# To keep things manageable, we list only locations occupied year-round; see +# +# COMNAP - Stations and Bases +# +# and +# +# Summary of the Peri-Antarctic Islands (1998-07-23) +# +# for information. +# Unless otherwise specified, we have no time zone information. +# +# Except for the French entries, +# I made up all time zone abbreviations mentioned here; corrections welcome! +# FORMAT is `zzz' and GMTOFF is 0 for locations while uninhabited. + +# These rules are stolen from the `europe' file. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule RussAQ 1981 1984 - Apr 1 0:00 1:00 S +Rule RussAQ 1981 1983 - Oct 1 0:00 0 - +Rule RussAQ 1984 1991 - Sep lastSun 2:00s 0 - +Rule RussAQ 1985 1991 - Mar lastSun 2:00s 1:00 S +Rule RussAQ 1992 only - Mar lastSat 23:00 1:00 S +Rule RussAQ 1992 only - Sep lastSat 23:00 0 - +Rule RussAQ 1993 max - Mar lastSun 2:00s 1:00 S +Rule RussAQ 1993 1995 - Sep lastSun 2:00s 0 - +Rule RussAQ 1996 max - Oct lastSun 2:00s 0 - + +# These rules are stolen from the `southamerica' file. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule ArgAQ 1964 1966 - Mar 1 0:00 0 - +Rule ArgAQ 1964 1966 - Oct 15 0:00 1:00 S +Rule ArgAQ 1967 only - Apr 1 0:00 0 - +Rule ArgAQ 1967 1968 - Oct Sun<=7 0:00 1:00 S +Rule ArgAQ 1968 1969 - Apr Sun<=7 0:00 0 - +Rule ArgAQ 1974 only - Jan 23 0:00 1:00 S +Rule ArgAQ 1974 only - May 1 0:00 0 - +Rule ArgAQ 1974 1976 - Oct Sun<=7 0:00 1:00 S +Rule ArgAQ 1975 1977 - Apr Sun<=7 0:00 0 - +Rule ChileAQ 1966 1997 - Oct Sun>=9 0:00 1:00 S +Rule ChileAQ 1967 1998 - Mar Sun>=9 0:00 0 - +Rule ChileAQ 1998 only - Sep 27 0:00 1:00 S +Rule ChileAQ 1999 only - Apr 4 0:00 0 - +Rule ChileAQ 1999 max - Oct Sun>=9 0:00 1:00 S +Rule ChileAQ 2000 max - Mar Sun>=9 0:00 0 - + + +# Argentina - year-round bases +# Belgrano II, Confin Coast, -770227-0343737, since 1972-02-05 +# Esperanza, San Martin Land, -6323-05659, since 1952-12-17 +# Jubany, Potter Peninsula, King George Island, -6414-0602320, since 1982-01 +# Marambio, Seymour I, -6414-05637, since 1969-10-29 +# Orcadas, Laurie I, -6016-04444, since 1904-02-22 +# San Martin, Debenham I, -6807-06708, since 1951-03-21 +# (except 1960-03 / 1976-03-21) + +# Australia - territories +# Heard Island, McDonald Islands (uninhabited) +# previously sealers and scientific personnel wintered +# +# Margaret Turner reports +# (1999-09-30) that they're UTC+5, with no DST; +# presumably this is when they have visitors. +# +# year-round bases +# Casey, Bailey Peninsula, -6617+11032, since 1969 +# Davis, Vestfold Hills, -6835+07759, since 1957-01-13 +# (except 1964-11 - 1969-02) +# Mawson, Holme Bay, -6736+06253, since 1954-02-13 +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Antarctica/Casey 0 - zzz 1969 + 8:00 - WST # Western (Aus) Standard Time +Zone Antarctica/Davis 0 - zzz 1957 Jan 13 + 7:00 - DAVT 1964 Nov # Davis Time + 0 - zzz 1969 Feb + 7:00 - DAVT +Zone Antarctica/Mawson 0 - zzz 1954 Feb 13 + 6:00 - MAWT # Mawson Time +# References: +# +# Casey Weather (1998-02-26) +# +# +# Davis Station, Antarctica (1998-02-26) +# +# +# Mawson Station, Antarctica (1998-02-25) +# + +# Brazil - year-round base +# Ferraz, King George Island, since 1983/4 + +# Chile - year-round bases and towns +# Escudero, South Shetland Is, -621157-0585735, since 1994 +# Frei, King George Island, -6214-05848, since 1969-03-07 +# O'Higgins, Antarctic Peninsula, -6319-05704, since 1948-02 +# Prat, -6230-05941 +# Villa Las Estrellas (a town), King George Island, since 1984-04-09 +# These locations have always used Santiago time; use TZ='America/Santiago'. + +# China - year-round bases +# Great Wall, King George Island, since 1985-02-20 +# Zhongshan, Larsemann Hills, Prydz Bay, since 1989-02-26 + +# France - year-round bases +# +# From Antoine Leca (1997-01-20): +# Time data are from Nicole Pailleau at the IFRTP +# (French Institute for Polar Research and Technology). +# She confirms that French Southern Territories and Terre Adelie bases +# don't observe daylight saving time, even if Terre Adelie supplies came +# from Tasmania. +# +# French Southern Territories with year-round inhabitants +# +# Martin-de-Vivies Base, Amsterdam Island, -374105+0773155, since 1950 +# Alfred-Faure Base, Crozet Islands, -462551+0515152, since 1964 +# Port-aux-Francais, Kerguelen Islands, -492110+0701303, since 1951; +# whaling & sealing station operated 1908/1914, 1920/1929, and 1951/1956 +# +# St Paul Island - near Amsterdam, uninhabited +# fishing stations operated variously 1819/1931 +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Kerguelen 0 - zzz 1950 # Port-aux-Francais + 5:00 - TFT # ISO code TF Time +# +# year-round base in the main continent +# Dumont-d'Urville, Ile des Petrels, -6640+14001, since 1956-11 +# +# Another base at Port-Martin, 50km east, began operation in 1947. +# It was destroyed by fire on 1952-01-14. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Antarctica/DumontDUrville 0 - zzz 1947 + 10:00 - PMT 1952 Jan 14 # Port-Martin Time + 0 - zzz 1956 Nov + 10:00 - DDUT # Dumont-d'Urville Time +# Reference: +# +# Support and Development of Polar Research and Technology (1997-02-03) +# + + +# Germany - year-round base +# Georg von Neumayer + +# India - year-round base +# Dakshin Gangotri + +# Japan - year-round bases +# Dome Fuji +# Syowa +# +# From Hideyuki Suzuki (1999-02-06): +# In all Japanese stations, +0300 is used as the standard time. [See] +# [reference in Japanese] +# and information from KAMO Hiroyasu . +# +# Syowa station, which is the first antarctic station of Japan, +# was established on 1957-01-29. Since Syowa station is still the main +# station of Japan, it's appropriate for the principal location. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Antarctica/Syowa 0 - zzz 1957 Jan 29 + 3:00 - SYOT # Syowa Time +# See: +# +# NIPR Antarctic Research Activities (1999-08-17) +# + +# S Korea - year-round base +# King Sejong, King George Island, since 1988 + +# New Zealand - claims +# Balleny Islands (never inhabited) +# Scott Island (never inhabited) +# +# year-round base +# Scott, Ross Island, since 1957-01, is like Antarctica/McMurdo. +# +# These rules for New Zealand are stolen from the `australasia' file. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule NZAQ 1974 only - Nov 3 2:00s 1:00 D +Rule NZAQ 1975 1988 - Oct lastSun 2:00s 1:00 D +Rule NZAQ 1989 only - Oct 8 2:00s 1:00 D +Rule NZAQ 1990 max - Oct Sun>=1 2:00s 1:00 D +Rule NZAQ 1975 only - Feb 23 2:00s 0 S +Rule NZAQ 1976 1989 - Mar Sun>=1 2:00s 0 S +Rule NZAQ 1990 max - Mar Sun>=15 2:00s 0 S + +# Norway - territories +# Bouvet (never inhabited) +# +# claims +# Peter I Island (never inhabited) + +# Poland - year-round base +# Arctowski, King George Island, -620945-0582745, since 1977 + +# Russia - year-round bases +# Bellingshausen, King George Island, -621159-0585337, since 1968-02-22 +# Mirny, Davis coast, -6633+09301, since 1956-02 +# Molodezhnaya, Alasheyev Bay, year-round from 1962-02 to 1999-07-01 +# Novolazarevskaya, Queen Maud Land, -7046+01150, +# year-round from 1960/61 to 1992 + +# Vostok, since 1957-12-16, temporarily closed 1994-02/1994-11 +# +# From Craig Mundell (1994-12-15): +# Vostok, which is one of the Russian stations, is set on the same +# time as Moscow, Russia. +# +# From Lee Hotz (2001-03-08): +# I queried the folks at Columbia who spent the summer at Vostok and this is +# what they had to say about time there: +# ``in the US Camp (East Camp) we have been on New Zealand (McMurdo) +# time, which is 12 hours ahead of GMT. The Russian Station Vostok was +# 6 hours behind that (although only 2 miles away, i.e. 6 hours ahead +# of GMT). This is a time zone I think two hours east of Moscow. The +# natural time zone is in between the two: 8 hours ahead of GMT.'' +# +# From Paul Eggert (2001-05-04): +# This seems to be hopelessly confusing, so I asked Lee Hotz about it +# in person. He said that some Antartic locations set their local +# time so that noon is the warmest part of the day, and that this +# changes during the year and does not necessarily correspond to mean +# solar noon. So the Vostok time might have been whatever the clocks +# happened to be during their visit. So we still don't really know what time +# it is at Vostok. But we'll guess UTC+6. +# +Zone Antarctica/Vostok 0 - zzz 1957 Dec 16 + 6:00 - VOST # Vostok time + +# S Africa - year-round bases +# Marion Island +# Sanae + +# UK +# +# British Antarctic Territories (BAT) claims +# South Orkney Islands +# scientific station from 1903 +# whaling station at Signy I 1920/1926 +# South Shetland Islands +# +# year-round bases +# Bird Island, South Georgia, -5400-03803, since 1983 +# Deception Island, -6259-06034, whaling station 1912/1931, +# scientific station 1943/1967, +# previously sealers and a scientific expedition wintered by accident, +# and a garrison was deployed briefly +# Halley, Coates Land, -7535-02604, since 1956-01-06 +# Halley is on a moving ice shelf and is periodically relocated +# so that it is never more than 10km from its nominal location. +# Rothera, Adelaide Island, -6734-6808, since 1976-12-01 +# +# From Paul Eggert (2002-10-22) +# says Rothera is -03 all year. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Antarctica/Rothera 0 - zzz 1976 Dec 1 + -3:00 - ROTT # Rothera time + +# Uruguay - year round base +# Artigas, King George Island, -621104-0585107 + +# USA - year-round bases +# +# Palmer, Anvers Island, since 1965 (moved 2 miles in 1968) +# +# From Ethan Dicks (1996-10-06): +# It keeps the same time as Punta Arenas, Chile, because, just like us +# and the South Pole, that's the other end of their supply line.... +# I verified with someone who was there that since 1980, +# Palmer has followed Chile. Prior to that, before the Falklands War, +# Palmer used to be supplied from Argentina. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Antarctica/Palmer 0 - zzz 1965 + -4:00 ArgAQ AR%sT 1969 Oct 5 + -3:00 ArgAQ AR%sT 1982 May + -4:00 ChileAQ CL%sT +# +# +# McMurdo, Ross Island, since 1955-12 +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Antarctica/McMurdo 0 - zzz 1956 + 12:00 NZAQ NZ%sT +# +# Amundsen-Scott, South Pole, continuously occupied since 1956-11-20 +# +# From Paul Eggert (1996-09-03): +# Normally it wouldn't have a separate entry, since it's like the +# larger Antarctica/McMurdo since 1970, but it's too famous to omit. +# +# From Chris Carrier <72157.3334@CompuServe.COM> (1996-06-27): +# Siple, the first commander of the South Pole station, +# stated that he would have liked to have kept GMT at the station, +# but that he found it more convenient to keep GMT+12 +# as supplies for the station were coming from McMurdo Sound, +# which was on GMT+12 because New Zealand was on GMT+12 all year +# at that time (1957). (Source: Siple's book 90 degrees SOUTH.) +# +# From Susan Smith +# http://www.cybertours.com/whs/pole10.html +# (1995-11-13 16:24:56 +1300, no longer available): +# We use the same time as McMurdo does. +# And they use the same time as Christchurch, NZ does.... +# One last quirk about South Pole time. +# All the electric clocks are usually wrong. +# Something about the generators running at 60.1hertz or something +# makes all of the clocks run fast. So every couple of days, +# we have to go around and set them back 5 minutes or so. +# Maybe if we let them run fast all of the time, we'd get to leave here sooner!! +# +Link Antarctica/McMurdo Antarctica/South_Pole Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/asia =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/asia,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/asia 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,1495 @@ +# @(#)asia 7.77 + +# This data is by no means authoritative; if you think you know better, +# go ahead and edit the file (and please send any changes to +# tz@elsie.nci.nih.gov for general use in the future). + +# From Paul Eggert (1999-03-22): +# +# A good source for time zone historical data outside the U.S. is +# Thomas G. Shanks, The International Atlas (5th edition), +# San Diego: ACS Publications, Inc. (1999). +# +# Gwillim Law writes that a good source +# for recent time zone data is the International Air Transport +# Association's Standard Schedules Information Manual (IATA SSIM), +# published semiannually. Law sent in several helpful summaries +# of the IATA's data after 1990. +# +# Except where otherwise noted, Shanks is the source for entries through 1990, +# and IATA SSIM is the source for entries after 1990. +# +# Another source occasionally used is Edward W. Whitman, World Time Differences, +# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), which +# I found in the UCLA library. +# +# A reliable and entertaining source about time zones is +# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997). +# +# I invented the abbreviations marked `*' in the following table; +# the rest are from earlier versions of this file, or from other sources. +# Corrections are welcome! +# std dst +# LMT Local Mean Time +# 2:00 EET EEST Eastern European Time +# 2:00 IST IDT Israel +# 3:00 AST ADT Arabia* +# 3:30 IRST IRDT Iran +# 4:00 GST Gulf* +# 5:30 IST India +# 7:00 ICT Indochina* +# 7:00 WIT west Indonesia +# 8:00 CIT central Indonesia +# 8:00 CST China +# 9:00 CJT Central Japanese Time (1896/1937)* +# 9:00 EIT east Indonesia +# 9:00 JST Japan +# 9:00 KST Korea +# 9:30 CST (Australian) Central Standard Time +# +# See the `europe' file for Russia and Turkey in Asia. + +# From Guy Harris: +# Incorporates data for Singapore from Robert Elz' asia 1.1, as well as +# additional information from Tom Yap, Sun Microsystems Intercontinental +# Technical Support (including a page from the Official Airline Guide - +# Worldwide Edition). The names for time zones are guesses. + +############################################################################### + +# These rules are stolen from the `europe' file. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule EUAsia 1981 max - Mar lastSun 1:00u 1:00 S +Rule EUAsia 1996 max - Oct lastSun 1:00u 0 - +Rule E-EurAsia 1981 max - Mar lastSun 0:00 1:00 S +Rule E-EurAsia 1979 1995 - Sep lastSun 0:00 0 - +Rule E-EurAsia 1996 max - Oct lastSun 0:00 0 - +Rule RussiaAsia 1981 1984 - Apr 1 0:00 1:00 S +Rule RussiaAsia 1981 1983 - Oct 1 0:00 0 - +Rule RussiaAsia 1984 1991 - Sep lastSun 2:00s 0 - +Rule RussiaAsia 1985 1991 - Mar lastSun 2:00s 1:00 S +Rule RussiaAsia 1992 only - Mar lastSat 23:00 1:00 S +Rule RussiaAsia 1992 only - Sep lastSat 23:00 0 - +Rule RussiaAsia 1993 max - Mar lastSun 2:00s 1:00 S +Rule RussiaAsia 1993 1995 - Sep lastSun 2:00s 0 - +Rule RussiaAsia 1996 max - Oct lastSun 2:00s 0 - + +# Afghanistan +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Kabul 4:36:48 - LMT 1890 + 4:00 - AFT 1945 + 4:30 - AFT + +# Armenia +# From Paul Eggert (1999-10-29): +# Shanks has Yerevan switching to 3:00 (with Russian DST) in spring 1991, +# then to 4:00 with no DST in fall 1995, then readopting Russian DST in 1997. +# Go with Shanks, even when he disagrees with others. Edgar Der-Danieliantz +# reported (1996-05-04) that Yerevan probably wouldn't use DST +# in 1996, though it did use DST in 1995. IATA SSIM (1991/1998) reports that +# Armenia switched from 3:00 to 4:00 in 1998 and observed DST after 1991, +# but started switching at 3:00s in 1998. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Yerevan 2:58:00 - LMT 1924 May 2 + 3:00 - YERT 1957 Mar # Yerevan Time + 4:00 RussiaAsia YER%sT 1991 Mar 31 2:00s + 3:00 1:00 YERST 1991 Sep 23 # independence + 3:00 RussiaAsia AM%sT 1995 Sep 24 2:00s + 4:00 - AMT 1997 + 4:00 RussiaAsia AM%sT + +# Azerbaijan +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Azer 1997 max - Mar lastSun 1:00 1:00 S +Rule Azer 1997 max - Oct lastSun 1:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Baku 3:19:24 - LMT 1924 May 2 + 3:00 - BAKT 1957 Mar # Baku Time + 4:00 RussiaAsia BAK%sT 1991 Mar 31 2:00s + 3:00 1:00 BAKST 1991 Aug 30 # independence + 3:00 RussiaAsia AZ%sT 1992 Sep lastSun 2:00s + 4:00 - AZT 1996 # Azerbaijan time + 4:00 EUAsia AZ%sT 1997 + 4:00 Azer AZ%sT + +# Bahrain +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Bahrain 3:22:20 - LMT 1920 # Al Manamah + 4:00 - GST 1972 Jun + 3:00 - AST + +# Bangladesh +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Dhaka 6:01:40 - LMT 1890 + 5:53:20 - HMT 1941 Oct # Howrah Mean Time? + 6:30 - BURT 1942 May 15 # Burma Time + 5:30 - IST 1942 Sep + 6:30 - BURT 1951 Sep 30 + 6:00 - DACT 1971 Mar 26 # Dacca Time + 6:00 - BDT # Bangladesh Time + +# Bhutan +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Thimphu 5:58:36 - LMT 1947 Aug 15 # or Thimbu + 5:30 - IST 1987 Oct + 6:00 - BTT # Bhutan Time + +# British Indian Ocean Territory +# Whitman and the 1995 CIA time zone map say 5:00, but the +# 1997 and later maps say 6:00. Assume the switch occurred in 1996. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Chagos 5:00 - IOT 1996 # BIOT Time + 6:00 - IOT + +# Brunei +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Brunei 7:39:40 - LMT 1926 Mar # Bandar Seri Begawan + 7:30 - BNT 1933 + 8:00 - BNT + +# Burma / Myanmar +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Rangoon 6:24:40 - LMT 1880 # or Yangon + 6:24:36 - RMT 1920 # Rangoon Mean Time? + 6:30 - BURT 1942 May # Burma Time + 9:00 - JST 1945 May 3 + 6:30 - MMT # Myanmar Time + +# Cambodia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Phnom_Penh 6:59:40 - LMT 1906 Jun 9 + 7:06:20 - SMT 1911 Mar 11 0:01 # Saigon MT? + 7:00 - ICT 1912 May + 8:00 - ICT 1931 May + 7:00 - ICT + +# China + +# From Guy Harris: +# People's Republic of China. Yes, they really have only one time zone. + +# From Bob Devine (1988-01-28): +# No they don't. See TIME mag, 1986-02-17 p.52. Even though +# China is across 4 physical time zones, before Feb 1, 1986 only the +# Peking (Bejing) time zone was recognized. Since that date, China +# has two of 'em -- Peking's and Urumqi (named after the capital of +# the Xinjiang Uyghur Autonomous Region). I don't know about DST for it. +# +# . . .I just deleted the DST table and this editor makes it too +# painful to suck in another copy.. So, here is what I have for +# DST start/end dates for Peking's time zone (info from AP): +# +# 1986 May 4 - Sept 14 +# 1987 mid-April - ?? + +# From U. S. Naval Observatory (1989-01-19): +# CHINA 8 H AHEAD OF UTC ALL OF CHINA, INCL TAIWAN +# CHINA 9 H AHEAD OF UTC APR 17 - SEP 10 + +# From Paul Eggert (1995-12-19): +# Shanks writes that China has had a single time zone since 1980 May 1, +# observing summer DST from 1986 through 1991; this contradicts Devine's +# note about Time magazine, though apparently _something_ happened in 1986. +# Go with Shanks for now. I made up names for the other pre-1980 time zones. + +# From Shanks: +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Shang 1940 only - Jun 3 0:00 1:00 D +Rule Shang 1940 1941 - Oct 1 0:00 0 S +Rule Shang 1941 only - Mar 16 0:00 1:00 D +Rule PRC 1949 only - Jan 1 0:00 0 S +Rule PRC 1986 only - May 4 0:00 1:00 D +Rule PRC 1986 1991 - Sep Sun>=11 0:00 0 S +Rule PRC 1987 1991 - Apr Sun>=10 0:00 1:00 D +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# +# From Anthony Fok (2001-12-20): +# BTW, I did some research on-line and found some info regarding these five +# historic timezones from some Taiwan websites. And yes, there are official +# Chinese names for these locales (before 1949): +# Changbai Time ("Long-white Time", Long-white = Heilongjiang area) +Zone Asia/Harbin 8:26:44 - LMT 1928 # or Haerbin + 8:30 - CHAT 1932 Mar # Changbai Time + 8:00 - CST 1940 + 9:00 - CHAT 1966 May + 8:30 - CHAT 1980 May + 8:00 PRC C%sT +# Zhongyuan Time ("Central plain Time") +Zone Asia/Shanghai 8:05:52 - LMT 1928 + 8:00 Shang C%sT 1949 + 8:00 PRC C%sT +# Long-shu Time (probably due to Long and Shu being two names of that area) +Zone Asia/Chongqing 7:06:20 - LMT 1928 # or Chungking + 7:00 - LONT 1980 May # Long-shu Time + 8:00 PRC C%sT +# Xin-zang Time ("Xinjiang-Tibet Time") +Zone Asia/Urumqi 5:50:20 - LMT 1928 # or Urumchi + 6:00 - URUT 1980 May # Urumqi Time + 8:00 PRC C%sT +# Kunlun Time +Zone Asia/Kashgar 5:03:56 - LMT 1928 # or Kashi or Kaxgar + 5:30 - KAST 1940 # Kashgar Time + 5:00 - KAST 1980 May + 8:00 PRC C%sT + +# Hong Kong (Xianggang) +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule HK 1946 only - Apr 20 3:30 1:00 S +Rule HK 1946 only - Dec 1 3:30 0 - +Rule HK 1947 only - Apr 13 3:30 1:00 S +Rule HK 1947 only - Dec 30 3:30 0 - +Rule HK 1948 only - May 2 3:30 1:00 S +Rule HK 1948 1952 - Oct lastSun 3:30 0 - +Rule HK 1949 1953 - Apr Sun>=1 3:30 1:00 S +Rule HK 1953 only - Nov 1 3:30 0 - +Rule HK 1954 1964 - Mar Sun>=18 3:30 1:00 S +Rule HK 1954 only - Oct 31 3:30 0 - +Rule HK 1955 1964 - Nov Sun>=1 3:30 0 - +Rule HK 1965 1977 - Apr Sun>=16 3:30 1:00 S +Rule HK 1965 1977 - Oct Sun>=16 3:30 0 - +Rule HK 1979 1980 - May Sun>=8 3:30 1:00 S +Rule HK 1979 1980 - Oct Sun>=16 3:30 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Hong_Kong 7:36:36 - LMT 1904 Oct 30 + 8:00 HK HK%sT + + +############################################################################### + +# Taiwan + +# Shanks writes that Taiwan observed DST during 1945, when it +# was still controlled by Japan. This is hard to believe, but we don't +# have any other information. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Taiwan 1945 1951 - May 1 0:00 1:00 D +Rule Taiwan 1945 1951 - Oct 1 0:00 0 S +Rule Taiwan 1952 only - Mar 1 0:00 1:00 D +Rule Taiwan 1952 1954 - Nov 1 0:00 0 S +Rule Taiwan 1953 1959 - Apr 1 0:00 1:00 D +Rule Taiwan 1955 1961 - Oct 1 0:00 0 S +Rule Taiwan 1960 1961 - Jun 1 0:00 1:00 D +Rule Taiwan 1974 1975 - Apr 1 0:00 1:00 D +Rule Taiwan 1974 1975 - Oct 1 0:00 0 S +Rule Taiwan 1980 only - Jun 30 0:00 1:00 D +Rule Taiwan 1980 only - Sep 30 0:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Taipei 8:06:00 - LMT 1896 # or Taibei or T'ai-pei + 8:00 Taiwan C%sT + +# Macau (Macao, Aomen) +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Macau 1961 1962 - Mar Sun>=16 3:30 1:00 S +Rule Macau 1961 1964 - Nov Sun>=1 3:30 0 - +Rule Macau 1963 only - Mar Sun>=16 0:00 1:00 S +Rule Macau 1964 only - Mar Sun>=16 3:30 1:00 S +Rule Macau 1965 only - Mar Sun>=16 0:00 1:00 S +Rule Macau 1965 only - Oct 31 0:00 0 - +Rule Macau 1966 1971 - Apr Sun>=16 3:30 1:00 S +Rule Macau 1966 1971 - Oct Sun>=16 3:30 0 - +Rule Macau 1972 1974 - Apr Sun>=15 0:00 1:00 S +Rule Macau 1972 1973 - Oct Sun>=15 0:00 0 - +Rule Macau 1974 1977 - Oct Sun>=15 3:30 0 - +Rule Macau 1975 1977 - Apr Sun>=15 3:30 1:00 S +Rule Macau 1978 1980 - Apr Sun>=15 0:00 1:00 S +Rule Macau 1978 1980 - Oct Sun>=15 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Macau 7:34:20 - LMT 1912 + 8:00 Macau MO%sT 1999 Dec 20 # return to China + 8:00 PRC C%sT + + +############################################################################### + +# Cyprus +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Cyprus 1975 only - Apr 13 0:00 1:00 S +Rule Cyprus 1975 only - Oct 12 0:00 0 - +Rule Cyprus 1976 only - May 15 0:00 1:00 S +Rule Cyprus 1976 only - Oct 11 0:00 0 - +Rule Cyprus 1977 1980 - Apr Sun>=1 0:00 1:00 S +Rule Cyprus 1977 only - Sep 25 0:00 0 - +Rule Cyprus 1978 only - Oct 2 0:00 0 - +Rule Cyprus 1979 1997 - Sep lastSun 0:00 0 - +Rule Cyprus 1981 1998 - Mar lastSun 0:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Nicosia 2:13:28 - LMT 1921 Nov 14 + 2:00 Cyprus EE%sT 1998 Sep + 2:00 EUAsia EE%sT +# IATA SSIM (1998-09) has Cyprus using EU rules for the first time. + +# Classically, Cyprus belongs to Asia; e.g. see Herodotus, Histories, I.72. +# However, for various reasons many users expect to find it under Europe. +Link Asia/Nicosia Europe/Nicosia + +# Georgia +# From Paul Eggert (1994-11-19): +# Today's _Economist_ (p 60) reports that Georgia moved its clocks forward +# an hour recently, due to a law proposed by Zurab Murvanidze, +# an MP who went on a hunger strike for 11 days to force discussion about it! +# We have no details, but we'll guess they didn't move the clocks back in fall. +# +# From Mathew Englander , quoting AP (1996-10-23 13:05-04): +# Instead of putting back clocks at the end of October, Georgia +# will stay on daylight savings time this winter to save energy, +# President Eduard Shevardnadze decreed Wednesday. +# +# From the BBC via Joseph S. Myers (2004-06-27): +# +# Georgia moved closer to Western Europe on Sunday... The former Soviet +# republic has changed its time zone back to that of Moscow. As a result it +# is now just four hours ahead of Greenwich Mean Time, rather than five hours +# ahead. The switch was decreed by the pro-Western president of Georgia, +# Mikhail Saakashvili, who said the change was partly prompted by the process +# of integration into Europe. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Tbilisi 2:59:16 - LMT 1880 + 2:59:16 - TBMT 1924 May 2 # Tbilisi Mean Time + 3:00 - TBIT 1957 Mar # Tbilisi Time + 4:00 RussiaAsia TBI%sT 1991 Mar 31 2:00s + 3:00 1:00 TBIST 1991 Apr 9 # independence + 3:00 RussiaAsia GE%sT 1992 # Georgia Time + 3:00 E-EurAsia GE%sT 1994 Sep lastSun + 4:00 E-EurAsia GE%sT 1996 Oct lastSun + 4:00 1:00 GEST 1997 Mar lastSun + 4:00 E-EurAsia GE%sT 2004 Jun 27 + 3:00 RussiaAsia GE%sT + +# East Timor + +# From Joao Carrascalao, brother of the former governor of East Timor, in +# +# East Timor may be late for its millennium +# (1999-12-26/31): +# Portugal tried to change the time forward in 1974 because the sun +# rises too early but the suggestion raised a lot of problems with the +# Timorese and I still don't think it would work today because it +# conflicts with their way of life. + +# From Paul Eggert (2000-12-04): +# We don't have any record of the above attempt. +# Most likely our records are incomplete, but we have no better data. + +# +# From Manoel de Almeida e Silva, Deputy Spokesman for the UN Secretary-General +# (2000-08-16): +# The Cabinet of the East Timor Transition Administration decided +# today to advance East Timor's time by one hour. The time change, +# which will be permanent, with no seasonal adjustment, will happen at +# midnight on Saturday, September 16. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Dili 8:22:20 - LMT 1912 + 8:00 - TPT 1942 Feb 21 23:00 # E Timor Time + 9:00 - JST 1945 Aug + 9:00 - TPT 1976 May 3 + 8:00 - CIT 2000 Sep 17 00:00 + 9:00 - TPT + +# India +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Calcutta 5:53:28 - LMT 1880 # Kolkata + 5:53:20 - HMT 1941 Oct # Howrah Mean Time? + 6:30 - BURT 1942 May 15 # Burma Time + 5:30 - IST 1942 Sep + 5:30 1:00 IST 1945 Oct 15 + 5:30 - IST +# The following are like Asia/Calcutta: +# Andaman Is +# Lakshadweep (Laccadive, Minicoy and Amindivi Is) +# Nicobar Is + +# Indonesia +# +# From Gwillim Law (2001-05-28), overriding Shanks: +# +# says that Indonesia's time zones changed on 1988-01-01. Looking at some +# time zone maps, I think that must refer to Western Borneo (Kalimantan Barat +# and Kalimantan Tengah) switching from UTC+8 to UTC+7. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Jakarta 7:07:12 - LMT 1867 Aug 10 +# Shanks says the next transition was at 1924 Jan 1 0:13, +# but this must be a typo. + 7:07:12 - JMT 1923 Dec 31 23:47:12 # Jakarta + 7:20 - JAVT 1932 Nov # Java Time + 7:30 - WIT 1942 Mar 23 + 9:00 - JST 1945 Aug + 7:30 - WIT 1948 May + 8:00 - WIT 1950 May + 7:30 - WIT 1964 + 7:00 - WIT +Zone Asia/Pontianak 7:17:20 - LMT 1908 May + 7:17:20 - PMT 1932 Nov # Pontianak MT + 7:30 - WIT 1942 Jan 29 + 9:00 - JST 1945 Aug + 7:30 - WIT 1948 May + 8:00 - WIT 1950 May + 7:30 - WIT 1964 + 8:00 - CIT 1988 Jan 1 + 7:00 - WIT +Zone Asia/Makassar 7:57:36 - LMT 1920 + 7:57:36 - MMT 1932 Nov # Macassar MT + 8:00 - CIT 1942 Feb 9 + 9:00 - JST 1945 Aug + 8:00 - CIT +Zone Asia/Jayapura 9:22:48 - LMT 1932 Nov + 9:00 - EIT 1944 + 9:30 - CST 1964 + 9:00 - EIT + +# Iran + +# From Roozbeh Pournader (2003-03-15): +# This is an English translation of what I just found (originally in Persian). +# The Gregorian dates in brackets are mine: +# +# Official Newspaper No. 13548-1370/6/25 [1991-09-16] +# No. 16760/T233 H 1370/6/10 [1991-09-01] +# +# The Rule About Change of the Official Time of the Country +# +# The Board of Ministers, in the meeting dated 1370/5/23 [1991-08-14], +# based on the suggestion number 2221/D dated 1370/4/22 [1991-07-13] +# of the Country's Organization for Official and Employment Affairs, +# and referring to the law for equating the working hours of workers +# and officers in the whole country dated 1359/4/23 [1980-07-14], and +# for synchronizing the official times of the country, agreed that: +# +# The official time of the country will should move forward one hour +# at the 24[:00] hours of the first day of Farvardin and should return +# to its previous state at the 24[:00] hours of the 30th day of +# Shahrivar. +# +# First Deputy to the President - Hassan Habibi +# +# From personal experience, that agrees with what has been followed +# for at least the last 5 years. Before that, for a few years, the +# date used was the first Thursday night of Farvardin and the last +# Thursday night of Shahrivar, but I can't give exact dates.... +# I have also changed the abbreviations to what is considered correct +# here in Iran, IRST for regular time and IRDT for daylight saving time. + +# From Paul Eggert (2003-03-15) +# Go with Shanks before September 1991, and with Pournader thereafter. +# I used Ed Reingold's cal-persia in GNU Emacs 21.2 to check Persian dates. +# The Persian calendar is based on the sun, and dates after around 2050 +# are approximate; stop after 2037 when 32-bit time_t's overflow. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Iran 1978 1980 - Mar 21 0:00 1:00 D +Rule Iran 1978 only - Oct 21 0:00 0 S +Rule Iran 1979 only - Sep 19 0:00 0 S +Rule Iran 1980 only - Sep 23 0:00 0 S +Rule Iran 1991 only - May 3 0:00 1:00 D +Rule Iran 1992 1995 - Mar 22 0:00 1:00 D +Rule Iran 1991 1995 - Sep 22 0:00 0 S +Rule Iran 1996 only - Mar 21 0:00 1:00 D +Rule Iran 1996 only - Sep 21 0:00 0 S +Rule Iran 1997 1999 - Mar 22 0:00 1:00 D +Rule Iran 1997 1999 - Sep 22 0:00 0 S +Rule Iran 2000 only - Mar 21 0:00 1:00 D +Rule Iran 2000 only - Sep 21 0:00 0 S +Rule Iran 2001 2003 - Mar 22 0:00 1:00 D +Rule Iran 2001 2003 - Sep 22 0:00 0 S +Rule Iran 2004 only - Mar 21 0:00 1:00 D +Rule Iran 2004 only - Sep 21 0:00 0 S +Rule Iran 2005 2007 - Mar 22 0:00 1:00 D +Rule Iran 2005 2007 - Sep 22 0:00 0 S +Rule Iran 2008 only - Mar 21 0:00 1:00 D +Rule Iran 2008 only - Sep 21 0:00 0 S +Rule Iran 2009 2011 - Mar 22 0:00 1:00 D +Rule Iran 2009 2011 - Sep 22 0:00 0 S +Rule Iran 2012 only - Mar 21 0:00 1:00 D +Rule Iran 2012 only - Sep 21 0:00 0 S +Rule Iran 2013 2015 - Mar 22 0:00 1:00 D +Rule Iran 2013 2015 - Sep 22 0:00 0 S +Rule Iran 2016 only - Mar 21 0:00 1:00 D +Rule Iran 2016 only - Sep 21 0:00 0 S +Rule Iran 2017 2019 - Mar 22 0:00 1:00 D +Rule Iran 2017 2019 - Sep 22 0:00 0 S +Rule Iran 2020 only - Mar 21 0:00 1:00 D +Rule Iran 2020 only - Sep 21 0:00 0 S +Rule Iran 2021 2023 - Mar 22 0:00 1:00 D +Rule Iran 2021 2023 - Sep 22 0:00 0 S +Rule Iran 2024 2025 - Mar 21 0:00 1:00 D +Rule Iran 2024 2025 - Sep 21 0:00 0 S +Rule Iran 2026 2027 - Mar 22 0:00 1:00 D +Rule Iran 2026 2027 - Sep 22 0:00 0 S +Rule Iran 2028 2029 - Mar 21 0:00 1:00 D +Rule Iran 2028 2029 - Sep 21 0:00 0 S +Rule Iran 2030 2031 - Mar 22 0:00 1:00 D +Rule Iran 2030 2031 - Sep 22 0:00 0 S +Rule Iran 2032 2033 - Mar 21 0:00 1:00 D +Rule Iran 2032 2033 - Sep 21 0:00 0 S +Rule Iran 2034 2035 - Mar 22 0:00 1:00 D +Rule Iran 2034 2035 - Sep 22 0:00 0 S +Rule Iran 2036 2037 - Mar 21 0:00 1:00 D +Rule Iran 2036 2037 - Sep 21 0:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Tehran 3:25:44 - LMT 1916 + 3:25:44 - TMT 1946 # Tehran Mean Time + 3:30 - IRST 1977 Nov + 4:00 Iran IR%sT 1979 + 3:30 Iran IR%sT + + +# Iraq +# +# From Jonathan Lennox (2000-06-12): +# An article in this week's Economist ("Inside the Saddam-free zone", p. 50 in +# the U.S. edition) on the Iraqi Kurds contains a paragraph: +# "The three northern provinces ... switched their clocks this spring and +# are an hour ahead of Baghdad." +# +# But Rives McDow (2000-06-18) quotes a contact in Iraqi-Kurdistan as follows: +# In the past, some Kurdish nationalists, as a protest to the Iraqi +# Government, did not adhere to daylight saving time. They referred +# to daylight saving as Saddam time. But, as of today, the time zone +# in Iraqi-Kurdistan is on standard time with Baghdad, Iraq. +# +# So we'll ignore the Economist's claim. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Iraq 1982 only - May 1 0:00 1:00 D +Rule Iraq 1982 1984 - Oct 1 0:00 0 S +Rule Iraq 1983 only - Mar 31 0:00 1:00 D +Rule Iraq 1984 1985 - Apr 1 0:00 1:00 D +Rule Iraq 1985 1990 - Sep lastSun 1:00s 0 S +Rule Iraq 1986 1990 - Mar lastSun 1:00s 1:00 D +# IATA SSIM (1991/1996) says Apr 1 12:01am UTC; guess the `:01' is a typo. +# Shanks says Iraq did not observe DST 1992/1997 or 1999 on; ignore this. +Rule Iraq 1991 max - Apr 1 3:00s 1:00 D +Rule Iraq 1991 max - Oct 1 3:00s 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Baghdad 2:57:40 - LMT 1890 + 2:57:36 - BMT 1918 # Baghdad Mean Time? + 3:00 - AST 1982 May + 3:00 Iraq A%sT + + +############################################################################### + +# Israel + +# From Ephraim Silverberg (2001-01-11): +# +# I coined "IST/IDT" circa 1988. Until then there were three +# different abbreviations in use: +# +# JST Jerusalem Standard Time [Danny Braniss, Hebrew University] +# IZT Israel Zonal (sic) Time [Prof. Haim Papo, Technion] +# EEST Eastern Europe Standard Time [used by almost everyone else] +# +# Since timezones should be called by country and not capital cities, +# I ruled out JST. As Israel is in Asia Minor and not Eastern Europe, +# EEST was equally unacceptable. Since "zonal" was not compatible with +# any other timezone abbreviation, I felt that 'IST' was the way to go +# and, indeed, it has received almost universal acceptance in timezone +# settings in Israeli computers. +# +# In any case, I am happy to share timezone abbreviations with India, +# high on my favorite-country list (and not only because my wife's +# family is from India). + +# From Shanks: +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Zion 1940 only - Jun 1 0:00 1:00 D +Rule Zion 1942 1944 - Nov 1 0:00 0 S +Rule Zion 1943 only - Apr 1 2:00 1:00 D +Rule Zion 1944 only - Apr 1 0:00 1:00 D +Rule Zion 1945 only - Apr 16 0:00 1:00 D +Rule Zion 1945 only - Nov 1 2:00 0 S +Rule Zion 1946 only - Apr 16 2:00 1:00 D +Rule Zion 1946 only - Nov 1 0:00 0 S +Rule Zion 1948 only - May 23 0:00 2:00 DD +Rule Zion 1948 only - Sep 1 0:00 1:00 D +Rule Zion 1948 1949 - Nov 1 2:00 0 S +Rule Zion 1949 only - May 1 0:00 1:00 D +Rule Zion 1950 only - Apr 16 0:00 1:00 D +Rule Zion 1950 only - Sep 15 3:00 0 S +Rule Zion 1951 only - Apr 1 0:00 1:00 D +Rule Zion 1951 only - Nov 11 3:00 0 S +Rule Zion 1952 only - Apr 20 2:00 1:00 D +Rule Zion 1952 only - Oct 19 3:00 0 S +Rule Zion 1953 only - Apr 12 2:00 1:00 D +Rule Zion 1953 only - Sep 13 3:00 0 S +Rule Zion 1954 only - Jun 13 0:00 1:00 D +Rule Zion 1954 only - Sep 12 0:00 0 S +Rule Zion 1955 only - Jun 11 2:00 1:00 D +Rule Zion 1955 only - Sep 11 0:00 0 S +Rule Zion 1956 only - Jun 3 0:00 1:00 D +Rule Zion 1956 only - Sep 30 3:00 0 S +Rule Zion 1957 only - Apr 29 2:00 1:00 D +Rule Zion 1957 only - Sep 22 0:00 0 S +Rule Zion 1974 only - Jul 7 0:00 1:00 D +Rule Zion 1974 only - Oct 13 0:00 0 S +Rule Zion 1975 only - Apr 20 0:00 1:00 D +Rule Zion 1975 only - Aug 31 0:00 0 S +Rule Zion 1985 only - Apr 14 0:00 1:00 D +Rule Zion 1985 only - Sep 15 0:00 0 S +Rule Zion 1986 only - May 18 0:00 1:00 D +Rule Zion 1986 only - Sep 7 0:00 0 S +Rule Zion 1987 only - Apr 15 0:00 1:00 D +Rule Zion 1987 only - Sep 13 0:00 0 S +Rule Zion 1988 only - Apr 9 0:00 1:00 D +Rule Zion 1988 only - Sep 3 0:00 0 S + +# From Ephraim Silverberg +# (1997-03-04, 1998-03-16, 1998-12-28, 2000-01-17 and 2000-07-25): + +# According to the Office of the Secretary General of the Ministry of +# Interior, there is NO set rule for Daylight-Savings/Standard time changes. +# One thing is entrenched in law, however: that there must be at least 150 +# days of daylight savings time annually. From 1993-1998, the change to +# daylight savings time was on a Friday morning from midnight IST to +# 1 a.m IDT; up until 1998, the change back to standard time was on a +# Saturday night from midnight daylight savings time to 11 p.m. standard +# time. 1996 is an exception to this rule where the change back to standard +# time took place on Sunday night instead of Saturday night to avoid +# conflicts with the Jewish New Year. In 1999, the change to +# daylight savings time was still on a Friday morning but from +# 2 a.m. IST to 3 a.m. IDT; furthermore, the change back to standard time +# was also on a Friday morning from 2 a.m. IDT to 1 a.m. IST for +# 1999 only. In the year 2000, the change to daylight savings time was +# similar to 1999, but although the change back will be on a Friday, it +# will take place from 1 a.m. IDT to midnight IST. Starting in 2001, all +# changes to/from will take place at 1 a.m. old time, but now there is no +# rule as to what day of the week it will take place in as the start date +# (except in 2003) is the night after the Passover Seder (i.e. the eve +# of the 16th of Nisan in the lunar Hebrew calendar) and the end date +# (except in 2002) is three nights before Yom Kippur [Day of Atonement] +# (the eve of the 7th of Tishrei in the lunar Hebrew calendar). + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Zion 1989 only - Apr 30 0:00 1:00 D +Rule Zion 1989 only - Sep 3 0:00 0 S +Rule Zion 1990 only - Mar 25 0:00 1:00 D +Rule Zion 1990 only - Aug 26 0:00 0 S +Rule Zion 1991 only - Mar 24 0:00 1:00 D +Rule Zion 1991 only - Sep 1 0:00 0 S +Rule Zion 1992 only - Mar 29 0:00 1:00 D +Rule Zion 1992 only - Sep 6 0:00 0 S +Rule Zion 1993 only - Apr 2 0:00 1:00 D +Rule Zion 1993 only - Sep 5 0:00 0 S + +# The dates for 1994-1995 were obtained from Office of the Spokeswoman for the +# Ministry of Interior, Jerusalem, Israel. The spokeswoman can be reached by +# calling the office directly at 972-2-6701447 or 972-2-6701448. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Zion 1994 only - Apr 1 0:00 1:00 D +Rule Zion 1994 only - Aug 28 0:00 0 S +Rule Zion 1995 only - Mar 31 0:00 1:00 D +Rule Zion 1995 only - Sep 3 0:00 0 S + +# The dates for 1996 were determined by the Minister of Interior of the +# time, Haim Ramon. The official announcement regarding 1996-1998 +# (with the dates for 1997-1998 no longer being relevant) can be viewed at: +# +# ftp://ftp.huji.ac.il/pub/tz/announcements/1996-1998.ramon.ps.gz +# +# The dates for 1997-1998 were altered by his successor, Rabbi Eli Suissa. +# +# The official announcements for the years 1997-1999 can be viewed at: +# +# ftp://ftp.huji.ac.il/pub/tz/announcements/YYYY.ps.gz +# +# where YYYY is the relevant year. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Zion 1996 only - Mar 15 0:00 1:00 D +Rule Zion 1996 only - Sep 16 0:00 0 S +Rule Zion 1997 only - Mar 21 0:00 1:00 D +Rule Zion 1997 only - Sep 14 0:00 0 S +Rule Zion 1998 only - Mar 20 0:00 1:00 D +Rule Zion 1998 only - Sep 6 0:00 0 S +Rule Zion 1999 only - Apr 2 2:00 1:00 D +Rule Zion 1999 only - Sep 3 2:00 0 S + +# The Knesset Interior Committee has changed the dates for 2000 for +# the third time in just over a year and have set new dates for the +# years 2001-2004 as well. +# +# The official announcement for the start date of 2000 can be viewed at: +# +# ftp://ftp.huji.ac.il/pub/tz/announcements/2000-start.ps.gz +# +# The official announcement for the end date of 2000 and the dates +# for the years 2001-2004 can be viewed at: +# +# ftp://ftp.huji.ac.il/pub/tz/announcements/2000-2004.ps.gz + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Zion 2000 only - Apr 14 2:00 1:00 D +Rule Zion 2000 only - Oct 6 1:00 0 S +Rule Zion 2001 only - Apr 9 1:00 1:00 D +Rule Zion 2001 only - Sep 24 1:00 0 S +Rule Zion 2002 only - Mar 29 1:00 1:00 D +Rule Zion 2002 only - Oct 7 1:00 0 S +Rule Zion 2003 only - Mar 28 1:00 1:00 D +Rule Zion 2003 only - Oct 3 1:00 0 S +Rule Zion 2004 only - Apr 7 1:00 1:00 D +Rule Zion 2004 only - Sep 22 1:00 0 S + +# From Paul Eggert (2000-07-25): +# Here are guesses for rules after 2004. +# They are probably wrong, but they are more likely than no DST at all. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Zion 2005 max - Apr 1 1:00 1:00 D +Rule Zion 2005 max - Oct 1 1:00 0 S + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Jerusalem 2:20:56 - LMT 1880 + 2:20:40 - JMT 1918 # Jerusalem Mean Time? + 2:00 Zion I%sT + +# From Ephraim Silverberg (2003-03-23): +# +# Minister of Interior Poraz has announced that he will respect the law +# passed in July 2000 (proposed at the time jointly by himself and +# then-MK David Azulai [Shas]) fixing the dates for 2000-2004. Hence, +# the dates for 2003 and 2004 remain unchanged.... +# +# As far as 2005 and beyond, no dates have been set. However, the +# minister has mentioned that he wishes to propose to move Israel's +# timezone in 2005 from GMT+2 to GMT+3 and upon that have DST during +# the summer months (i.e. GMT+4). However, no legislation in this +# direction is expected until the latter part of 2004 which is a long +# time off in terms of Israeli politics. + +# (2004-09-20): +# The latest rumour, however, is that in 2005, when the clock changes to +# Daylight Saving Time (date as yet unknown), the move will be a two-hour leap +# forward (from UTC+0200 to UTC+0400) and then, in the fall, the clock will +# move back only an hour to UTC+0300 thus effectively moving Israel's timezone +# from UTC+0200 to UTC+0300. However, no actual draft has been put before the +# Knesset (Israel's Parliament) though the intention is to do so this +# month [2004-09]. + +# (2004-09-26): +# Even though the draft law for the above did pass the Ministerial Committee +# for Legislative Matters three months ago, it was voted down in today's +# Cabinet meeting. The current suggestion is to keep the current timezone at +# UTC+0200 but have an extended period of Daylight Saving Time (UTC+0300) from +# the beginning of Passover holiday in the spring to after the Tabernacle +# holiday in the fall (i.e. the dates of which are governed by the Hebrew +# calendar but this means at least 184 days of DST). However, this is only a +# suggestion that was raised in today's cabinet meeting and has not yet been +# drafted. + + + +############################################################################### + +# Japan + +# `9:00' and `JST' is from Guy Harris. + +# From Paul Eggert (1995-03-06): +# Today's _Asahi Evening News_ (page 4) reports that Japan had +# daylight saving between 1948 and 1951, but ``the system was discontinued +# because the public believed it would lead to longer working hours.'' +# Shanks writes that daylight saving in Japan during those years was as follows: +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +#Rule Japan 1948 only - May Sun>=1 2:00 1:00 D +#Rule Japan 1948 1951 - Sep Sat>=8 2:00 0 S +#Rule Japan 1949 only - Apr Sun>=1 2:00 1:00 D +#Rule Japan 1950 1951 - May Sun>=1 2:00 1:00 D +# but the only locations using it were US military bases. +# We go with Shanks and omit daylight saving in those years for Asia/Tokyo. + +# From Hideyuki Suzuki (1998-11-09): +# 'Tokyo' usually stands for the former location of Tokyo Astronomical +# Observatory: E 139 44' 40".90 (9h 18m 58s.727), N 35 39' 16".0. +# This data is from 'Rika Nenpyou (Chronological Scientific Tables) 1996' +# edited by National Astronomical Observatory of Japan.... +# JST (Japan Standard Time) has been used since 1888-01-01 00:00 (JST). +# The law is enacted on 1886-07-07. + +# From Hideyuki Suzuki (1998-11-16): +# The ordinance No. 51 (1886) established "standard time" in Japan, +# which stands for the time on E 135 degree. +# In the ordinance No. 167 (1895), "standard time" was renamed to "central +# standard time". And the same ordinance also established "western standard +# time", which stands for the time on E 120 degree.... But "western standard +# time" was abolished in the ordinance No. 529 (1937). In the ordinance No. +# 167, there is no mention regarding for what place western standard time is +# standard.... +# +# I wrote "ordinance" above, but I don't know how to translate. +# In Japanese it's "chokurei", which means ordinance from emperor. + +# Shanks claims JST in use since 1896, and that a few places (e.g. Ishigaki) +# use +0800; go with Suzuki. Guess that all ordinances took effect on Jan 1. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Tokyo 9:18:59 - LMT 1887 Dec 31 15:00u + 9:00 - JST 1896 + 9:00 - CJT 1938 + 9:00 - JST +# Since 1938, all Japanese possessions have been like Asia/Tokyo. + +# Jordan +# +# From +# Jordan Week (1999-07-01) via Steffen Thorsen (1999-09-09): +# Clocks in Jordan were forwarded one hour on Wednesday at midnight, +# in accordance with the government's decision to implement summer time +# all year round. +# +# From +# Jordan Week (1999-09-30) via Steffen Thorsen (1999-11-09): +# Winter time starts today Thursday, 30 September. Clocks will be turned back +# by one hour. This is the latest government decision and it's final! +# The decision was taken because of the increase in working hours in +# government's departments from six to seven hours. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Jordan 1973 only - Jun 6 0:00 1:00 S +Rule Jordan 1973 1975 - Oct 1 0:00 0 - +Rule Jordan 1974 1977 - May 1 0:00 1:00 S +Rule Jordan 1976 only - Nov 1 0:00 0 - +Rule Jordan 1977 only - Oct 1 0:00 0 - +Rule Jordan 1978 only - Apr 30 0:00 1:00 S +Rule Jordan 1978 only - Sep 30 0:00 0 - +Rule Jordan 1985 only - Apr 1 0:00 1:00 S +Rule Jordan 1985 only - Oct 1 0:00 0 - +Rule Jordan 1986 1988 - Apr Fri>=1 0:00 1:00 S +Rule Jordan 1986 1990 - Oct Fri>=1 0:00 0 - +Rule Jordan 1989 only - May 8 0:00 1:00 S +Rule Jordan 1990 only - Apr 27 0:00 1:00 S +Rule Jordan 1991 only - Apr 17 0:00 1:00 S +Rule Jordan 1991 only - Sep 27 0:00 0 - +Rule Jordan 1992 only - Apr 10 0:00 1:00 S +Rule Jordan 1992 1993 - Oct Fri>=1 0:00 0 - +Rule Jordan 1993 1998 - Apr Fri>=1 0:00 1:00 S +Rule Jordan 1994 only - Sep Fri>=15 0:00 0 - +Rule Jordan 1995 1998 - Sep Fri>=15 0:00s 0 - +Rule Jordan 1999 only - Jul 1 0:00s 1:00 S +Rule Jordan 1999 max - Sep lastThu 0:00s 0 - +Rule Jordan 2000 max - Mar lastThu 0:00s 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Amman 2:23:44 - LMT 1931 + 2:00 Jordan EE%sT + +# Kazakhstan +# From Paul Eggert (1996-11-22): +# Andrew Evtichov (1996-04-13) writes that Kazakhstan +# stayed in sync with Moscow after 1990, and that Aqtobe (formerly Aktyubinsk) +# and Aqtau (formerly Shevchenko) are the largest cities in their zones. +# Guess that Aqtau and Aqtobe diverged in 1995, since that's the first time +# IATA SSIM mentions a third time zone in Kazakhstan. +# +# From Paul Eggert (2001-10-18): +# German Iofis, ELSI, Almaty (2001-10-09) reports that Kazakhstan uses +# RussiaAsia rules, instead of switching at 00:00 as the IATA has it. +# Go with Shanks, who has them always using RussiaAsia rules. +# Also go with the following claims of Shanks: +# +# - Kazakhstan did not observe DST in 1991. +# - Qyzylorda switched from +5:00 to +6:00 on 1992-01-19 02:00. +# - Oral switched from +5:00 to +4:00 in spring 1989. +# +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# +# Almaty (formerly Alma-Ata), representing most locations in Kazakhstan +Zone Asia/Almaty 5:07:48 - LMT 1924 May 2 # or Alma-Ata + 5:00 - ALMT 1930 Jun 21 # Alma-Ata Time + 6:00 RussiaAsia ALM%sT 1991 + 6:00 - ALMT 1992 + 6:00 RussiaAsia ALM%sT +# Qyzylorda (aka Kyzylorda, Kizilorda, Kzyl-Orda, etc.) +Zone Asia/Qyzylorda 4:21:52 - LMT 1924 May 2 + 4:00 - KIZT 1930 Jun 21 # Kizilorda Time + 5:00 - KIZT 1981 Apr 1 + 5:00 1:00 KIZST 1981 Oct 1 + 6:00 - KIZT 1982 Apr 1 + 5:00 RussiaAsia KIZ%sT 1991 + 5:00 - KIZT 1991 Dec 16 # independence + 5:00 - QYZT 1992 Jan 19 2:00 + 6:00 RussiaAsia QYZ%sT +# Aqtobe (aka Aktobe, formerly Akt'ubinsk) +Zone Asia/Aqtobe 3:48:40 - LMT 1924 May 2 + 4:00 - AKTT 1930 Jun 21 # Aktyubinsk Time + 5:00 - AKTT 1981 Apr 1 + 5:00 1:00 AKTST 1981 Oct 1 + 6:00 - AKTT 1982 Apr 1 + 5:00 RussiaAsia AKT%sT 1991 + 5:00 - AKTT 1991 Dec 16 # independence + 5:00 RussiaAsia AQT%sT # Aqtobe Time +# Mangghystau +# Aqtau was not founded until 1963, but it represents an inhabited region, +# so include time stamps before 1963. +Zone Asia/Aqtau 3:21:04 - LMT 1924 May 2 + 4:00 - FORT 1930 Jun 21 # Fort Shevchenko T + 5:00 - FORT 1963 + 5:00 - SHET 1981 Oct 1 # Shevchenko Time + 6:00 - SHET 1982 Apr 1 + 5:00 RussiaAsia SHE%sT 1991 + 5:00 - SHET 1991 Dec 16 # independence + 5:00 RussiaAsia AQT%sT 1995 Mar lastSun 2:00 # Aqtau Time + 4:00 RussiaAsia AQT%sT +# West Kazakhstan +Zone Asia/Oral 3:25:24 - LMT 1924 May 2 # or Ural'sk + 4:00 - URAT 1930 Jun 21 # Ural'sk time + 5:00 - URAT 1981 Apr 1 + 5:00 1:00 URAST 1981 Oct 1 + 6:00 - URAT 1982 Apr 1 + 5:00 RussiaAsia URA%sT 1989 Mar 26 2:00 + 4:00 RussiaAsia URA%sT 1991 + 4:00 - URAT 1991 Dec 16 # independence + 4:00 RussiaAsia ORA%sT # Oral Time + +# Kyrgyzstan (Kirgizstan) +# Transitions through 1991 are from Shanks. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Kirgiz 1992 1996 - Apr Sun>=7 0:00s 1:00 S +Rule Kirgiz 1992 1996 - Sep lastSun 0:00 0 - +Rule Kirgiz 1997 max - Mar lastSun 2:30 1:00 S +Rule Kirgiz 1997 max - Oct lastSun 2:30 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Bishkek 4:58:24 - LMT 1924 May 2 + 5:00 - FRUT 1930 Jun 21 # Frunze Time + 6:00 RussiaAsia FRU%sT 1991 Mar 31 2:00s + 5:00 1:00 FRUST 1991 Aug 31 2:00 # independence + 5:00 Kirgiz KG%sT # Kirgizstan Time + +############################################################################### + +# Korea (North and South) + +# From Guy Harris: +# According to someone at the Korean Times in San Francisco, +# Daylight Savings Time was not observed until 1987. He did not know +# at what time of day DST starts or ends. + +# From Shanks: +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule ROK 1960 only - May 15 0:00 1:00 D +Rule ROK 1960 only - Sep 13 0:00 0 S +Rule ROK 1987 1988 - May Sun<=14 0:00 1:00 D +Rule ROK 1987 1988 - Oct Sun<=14 0:00 0 S + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Seoul 8:27:52 - LMT 1890 + 8:30 - KST 1904 Dec + 9:00 - KST 1928 + 8:30 - KST 1932 + 9:00 - KST 1954 Mar 21 + 8:00 ROK K%sT 1961 Aug 10 + 8:30 - KST 1968 Oct + 9:00 ROK K%sT +Zone Asia/Pyongyang 8:23:00 - LMT 1890 + 8:30 - KST 1904 Dec + 9:00 - KST 1928 + 8:30 - KST 1932 + 9:00 - KST 1954 Mar 21 + 8:00 - KST 1961 Aug 10 + 9:00 - KST + +############################################################################### + +# Kuwait +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Kuwait 3:11:56 - LMT 1950 + 3:00 - AST + +# Laos +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Vientiane 6:50:24 - LMT 1906 Jun 9 # or Viangchan + 7:06:20 - SMT 1911 Mar 11 0:01 # Saigon MT? + 7:00 - ICT 1912 May + 8:00 - ICT 1931 May + 7:00 - ICT + +# Lebanon +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Lebanon 1920 only - Mar 28 0:00 1:00 S +Rule Lebanon 1920 only - Oct 25 0:00 0 - +Rule Lebanon 1921 only - Apr 3 0:00 1:00 S +Rule Lebanon 1921 only - Oct 3 0:00 0 - +Rule Lebanon 1922 only - Mar 26 0:00 1:00 S +Rule Lebanon 1922 only - Oct 8 0:00 0 - +Rule Lebanon 1923 only - Apr 22 0:00 1:00 S +Rule Lebanon 1923 only - Sep 16 0:00 0 - +Rule Lebanon 1957 1961 - May 1 0:00 1:00 S +Rule Lebanon 1957 1961 - Oct 1 0:00 0 - +Rule Lebanon 1972 only - Jun 22 0:00 1:00 S +Rule Lebanon 1972 1977 - Oct 1 0:00 0 - +Rule Lebanon 1973 1977 - May 1 0:00 1:00 S +Rule Lebanon 1978 only - Apr 30 0:00 1:00 S +Rule Lebanon 1978 only - Sep 30 0:00 0 - +Rule Lebanon 1984 1987 - May 1 0:00 1:00 S +Rule Lebanon 1984 1991 - Oct 16 0:00 0 - +Rule Lebanon 1988 only - Jun 1 0:00 1:00 S +Rule Lebanon 1989 only - May 10 0:00 1:00 S +Rule Lebanon 1990 1992 - May 1 0:00 1:00 S +Rule Lebanon 1992 only - Oct 4 0:00 0 - +Rule Lebanon 1993 max - Mar lastSun 0:00 1:00 S +Rule Lebanon 1993 1998 - Sep lastSun 0:00 0 - +Rule Lebanon 1999 max - Oct lastSun 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Beirut 2:22:00 - LMT 1880 + 2:00 Lebanon EE%sT + +# Malaysia +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule NBorneo 1935 1941 - Sep 14 0:00 0:20 TS # one-Third Summer +Rule NBorneo 1935 1941 - Dec 14 0:00 0 - +# +# peninsular Malaysia +# The data here are taken from Mok Ly Yng (2003-10-30) +# . +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Kuala_Lumpur 6:46:46 - LMT 1901 Jan 1 + 6:55:25 - SMT 1905 Jun 1 # Singapore M.T. + 7:00 - MALT 1933 Jan 1 # Malaya Time + 7:00 0:20 MALST 1936 Jan 1 + 7:20 - MALT 1941 Sep 1 + 7:30 - MALT 1942 Feb 16 + 9:00 - JST 1945 Sep 12 + 7:30 - MALT 1982 Jan 1 + 8:00 - MYT # Malaysia Time +# Sabah & Sarawak +# From Paul Eggert (2003-11-01): +# The data here are mostly from Shanks, but the 1942, 1945 and 1982 +# transition dates are from Mok Ly Yng. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Kuching 7:21:20 - LMT 1926 Mar + 7:30 - BORT 1933 # Borneo Time + 8:00 NBorneo BOR%sT 1942 Feb 16 + 9:00 - JST 1945 Sep 12 + 8:00 - BORT 1982 Jan 1 + 8:00 - MYT + +# Maldives +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Maldives 4:54:00 - LMT 1880 # Male + 4:54:00 - MMT 1960 # Male Mean Time + 5:00 - MVT # Maldives Time + +# Mongolia + +# Shanks says that Mongolia has three time zones, but usno1995 and the CIA map +# Standard Time Zones of the World (1997-01) +# both say that it has just one. + +# From Oscar van Vlijmen (1999-12-11): +# +# General Information Mongolia +# (1999-09) +# "Time: Mongolia has two time zones. Three westernmost provinces of +# Bayan-Ulgii, Uvs, and Hovd are one hour earlier than the capital city, and +# the rest of the country follows the Ulaanbaatar time, which is UTC/GMT plus +# eight hours." + +# From Rives McDow (1999-12-13): +# Mongolia discontinued the use of daylight savings time in 1999; 1998 +# being the last year it was implemented. The dates of implementation I am +# unsure of, but most probably it was similar to Russia, except for the time +# of implementation may have been different.... +# Some maps in the past have indicated that there was an additional time +# zone in the eastern part of Mongolia, including the provinces of Dornod, +# Suhbaatar, and possibly Khentij. + +# From Paul Eggert (1999-12-15): +# Naming and spelling is tricky in Mongolia. +# We'll use Hovd (also spelled Chovd and Khovd) to represent the west zone; +# the capital of the Hovd province is sometimes called Hovd, sometimes Dund-Us, +# and sometimes Jirgalanta (with variant spellings), but the name Hovd +# is good enough for our purposes. + +# From Rives McDow (2001-05-13): +# In addition to Mongolia starting daylight savings as reported earlier +# (adopted DST on 2001-04-27 02:00 local time, ending 2001-09-28), +# there are three time zones. +# +# Provinces [at 7:00]: Bayan-ulgii, Uvs, Khovd, Zavkhan, Govi-Altai +# Provinces [at 8:00]: Khovsgol, Bulgan, Arkhangai, Khentii, Tov, +# Bayankhongor, Ovorkhangai, Dundgovi, Dornogovi, Omnogovi +# Provinces [at 9:00]: Dornod, Sukhbaatar +# +# [The province of Selenge is omitted from the above lists.] + +# From Ganbold Ts., Ulaanbaatar (2004-04-17): +# Daylight saving occurs at 02:00 local time last Saturday of March. +# It will change back to normal at 02:00 local time last Saturday of +# September.... As I remember this rule was changed in 2001. +# +# From Paul Eggert (2004-04-17): +# For now, assume Rives McDow's informant got confused about Friday vs +# Saturday, and that his 2001 dates should have 1 added to them. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Mongol 1983 1984 - Apr 1 0:00 1:00 S +Rule Mongol 1983 only - Oct 1 0:00 0 - +# IATA SSIM says 1990s switches occurred at 00:00, but Shanks (1995) lists +# them at 02:00s, and McDow says the 2001 switches also occurred at 02:00. +# Also, IATA SSIM (1996-09) says 1996-10-25. Go with Shanks through 1998. +Rule Mongol 1985 1998 - Mar lastSun 2:00s 1:00 S +Rule Mongol 1984 1998 - Sep lastSun 2:00s 0 - +# IATA SSIM (1999-09) says Mongolia no longer observes DST. +Rule Mongol 2001 only - Apr lastSat 2:00 1:00 S +Rule Mongol 2001 max - Sep lastSat 2:00 0 - +Rule Mongol 2002 max - Mar lastSat 2:00 1:00 S + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# Hovd, a.k.a. Chovd, Dund-Us, Dzhargalant, Khovd, Jirgalanta +Zone Asia/Hovd 6:06:36 - LMT 1905 Aug + 6:00 - HOVT 1978 # Hovd Time + 7:00 Mongol HOV%sT +# Ulaanbaatar, a.k.a. Ulan Bataar, Ulan Bator, Urga +Zone Asia/Ulaanbaatar 7:07:32 - LMT 1905 Aug + 7:00 - ULAT 1978 # Ulaanbaatar Time + 8:00 Mongol ULA%sT +# Choibalsan, a.k.a. Bajan Tuemen, Bajan Tumen, Chojbalsan, +# Choybalsan, Sanbejse, Tchoibalsan +Zone Asia/Choibalsan 7:38:00 - LMT 1905 Aug + 7:00 - ULAT 1978 + 8:00 - ULAT 1983 Apr + 9:00 Mongol CHO%sT # Choibalsan Time + +# Nepal +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Katmandu 5:41:16 - LMT 1920 + 5:30 - IST 1986 + 5:45 - NPT # Nepal Time + +# Oman +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Muscat 3:54:20 - LMT 1920 + 4:00 - GST + +# Pakistan + +# From Rives McDow (2002-03-13): +# I have been advised that Pakistan has decided to adopt dst on a +# TRIAL basis for one year, starting 00:01 local time on April 7, 2002 +# and ending at 00:01 local time October 6, 2002. This is what I was +# told, but I believe that the actual time of change may be 00:00; the +# 00:01 was to make it clear which day it was on. + +# From Paul Eggert (2002-03-15): +# Jesper Norgaard found this URL: +# http://www.pak.gov.pk/public/news/app/app06_dec.htm +# (dated 2001-12-06) which says that the Cabinet adopted a scheme "to +# advance the clocks by one hour on the night between the first +# Saturday and Sunday of April and revert to the original position on +# 15th October each year". This agrees with McDow's 04-07 at 00:00, +# but disagrees about the October transition, and makes it sound like +# it's not on a trial basis. Also, the "between the first Saturday +# and Sunday of April" phrase, if taken literally, means that the +# transition takes place at 00:00 on the first Sunday on or after 04-02. + +# From Paul Eggert (2003-02-09): +# DAWN reported on 2002-10-05 +# that 2002 DST ended that day at midnight. Go with McDow for now. + +# From Steffen Thorsen (2003-03-14): +# According to http://www.dawn.com/2003/03/07/top15.htm +# there will be no DST in Pakistan this year: +# +# ISLAMABAD, March 6: Information and Media Development Minister Sheikh +# Rashid Ahmed on Thursday said the cabinet had reversed a previous +# decision to advance clocks by one hour in summer and put them back by +# one hour in winter with the aim of saving light hours and energy. +# +# The minister told a news conference that the experiment had rather +# shown 8 per cent higher consumption of electricity. + + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Pakistan 2002 only - Apr Sun>=2 0:01 1:00 S +Rule Pakistan 2002 only - Oct Sun>=2 0:01 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Karachi 4:28:12 - LMT 1907 + 5:30 - IST 1942 Sep + 5:30 1:00 IST 1945 Oct 15 + 5:30 - IST 1951 Sep 30 + 5:00 - KART 1971 Mar 26 # Karachi Time + 5:00 Pakistan PK%sT # Pakistan Time + +# Palestine + +# From Amos Shapir (1998-02-15): +# +# From 1917 until 1948-05-15, all of Palestine, including the parts now +# known as the Gaza Strip and the West Bank, was under British rule. +# Therefore the rules given for Israel for that period, apply there too... +# +# The Gaza Strip was under Egyptian rule between 1948-05-15 until 1967-06-05 +# (except a short occupation by Israel from 1956-11 till 1957-03, but no +# time zone was affected then). It was never formally annexed to Egypt, +# though. +# +# The rest of Palestine was under Jordanian rule at that time, formally +# annexed in 1950 as the West Bank (and the word "Trans" was dropped from +# the country's previous name of "the Hashemite Kingdom of the +# Trans-Jordan"). So the rules for Jordan for that time apply. Major +# towns in that area are Nablus (Shchem), El-Halil (Hebron), Ramallah, and +# East Jerusalem. +# +# Both areas were occupied by Israel in June 1967, but not annexed (except +# for East Jerusalem). They were on Israel time since then; there might +# have been a Military Governor's order about time zones, but I'm not aware +# of any (such orders may have been issued semi-annually whenever summer +# time was in effect, but maybe the legal aspect of time was just neglected). +# +# The Palestinian Authority was established in 1993, and got hold of most +# towns in the West Bank and Gaza by 1995. I know that in order to +# demonstrate...independence, they have been switching to +# summer time and back on a different schedule than Israel's, but I don't +# know when this was started, or what algorithm is used (most likely the +# Jordanian one). +# +# To summarize, the table should probably look something like that: +# +# Area \ when | 1918-1947 | 1948-1967 | 1967-1995 | 1996- +# ------------+-----------+-----------+-----------+----------- +# Israel | Zion | Zion | Zion | Zion +# West bank | Zion | Jordan | Zion | Jordan +# Gaza | Zion | Egypt | Zion | Jordan +# +# I guess more info may be available from the PA's web page (if/when they +# have one). + +# From Paul Eggert (1998-02-25): +# Shanks writes that Gaza did not observe DST until 1957, but we'll go +# with Shapir and assume that it observed DST from 1940 through 1947, +# and that it used Jordanian rules starting in 1996. +# We don't yet need a separate entry for the West Bank, since +# the only differences between it and Gaza that we know about +# occurred before our cutoff date of 1970. +# However, as we get more information, we may need to add entries +# for parts of the West Bank as they transitioned from Israel's rules +# to Palestine's rules. If you have more info about this, please +# send it to tz@elsie.nci.nih.gov for incorporation into future editions. + +# From IINS News Service - Israel - 1998-03-23 10:38:07 Israel time, +# forwarded by Ephraim Silverberg: +# +# Despite the fact that Israel changed over to daylight savings time +# last week, the PLO Authority (PA) has decided not to turn its clocks +# one-hour forward at this time. As a sign of independence from Israeli rule, +# the PA has decided to implement DST in April. + +# From Paul Eggert (1999-09-20): +# Daoud Kuttab writes in +# +# Holiday havoc +# (Jerusalem Post, 1999-04-22) that +# the Palestinian National Authority changed to DST on 1999-04-15. +# I vaguely recall that they switch back in October (sorry, forgot the source). +# For now, let's assume that the spring switch was at 24:00, +# and that they switch at 0:00 on the 3rd Fridays of April and October. + +# The rules for Egypt are stolen from the `africa' file. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule EgyptAsia 1957 only - May 10 0:00 1:00 S +Rule EgyptAsia 1957 1958 - Oct 1 0:00 0 - +Rule EgyptAsia 1958 only - May 1 0:00 1:00 S +Rule EgyptAsia 1959 1967 - May 1 1:00 1:00 S +Rule EgyptAsia 1959 1965 - Sep 30 3:00 0 - +Rule EgyptAsia 1966 only - Oct 1 3:00 0 - + +Rule Palestine 1999 max - Apr Fri>=15 0:00 1:00 S +Rule Palestine 1999 max - Oct Fri>=15 0:00 0 - + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Gaza 2:17:52 - LMT 1900 Oct + 2:00 Zion EET 1948 May 15 + 2:00 EgyptAsia EE%sT 1967 Jun 5 + 2:00 Zion I%sT 1996 + 2:00 Jordan EE%sT 1999 + 2:00 Palestine EE%sT + +# Paracel Is +# no information + +# Philippines +# On 1844-08-16, Narciso Claveria, governor-general of the +# Philippines, issued a proclamation announcing that 1844-12-30 was to +# be immediately followed by 1845-01-01. Robert H. van Gent has a +# transcript of the decree in . +# The rest of this data is from Shanks. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Phil 1936 only - Nov 1 0:00 1:00 S +Rule Phil 1937 only - Feb 1 0:00 0 - +Rule Phil 1954 only - Apr 12 0:00 1:00 S +Rule Phil 1954 only - Jul 1 0:00 0 - +Rule Phil 1978 only - Mar 22 0:00 1:00 S +Rule Phil 1978 only - Sep 21 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Manila -15:56:00 - LMT 1844 Dec 31 + 8:04:00 - LMT 1899 May 11 + 8:00 Phil PH%sT 1942 May + 9:00 - JST 1944 Nov + 8:00 Phil PH%sT + +# Qatar +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Qatar 3:26:08 - LMT 1920 # Al Dawhah / Doha + 4:00 - GST 1972 Jun + 3:00 - AST + +# Saudi Arabia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Riyadh 3:06:52 - LMT 1950 + 3:00 - AST + +# Singapore +# The data here are taken from Mok Ly Yng (2003-10-30) +# . +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Singapore 6:55:25 - LMT 1901 Jan 1 + 6:55:25 - SMT 1905 Jun 1 # Singapore M.T. + 7:00 - MALT 1933 Jan 1 # Malaya Time + 7:00 0:20 MALST 1936 Jan 1 + 7:20 - MALT 1941 Sep 1 + 7:30 - MALT 1942 Feb 16 + 9:00 - JST 1945 Sep 12 + 7:30 - MALT 1965 Aug 9 # independence + 7:30 - SGT 1982 Jan 1 # Singapore Time + 8:00 - SGT + +# Spratly Is +# no information + +# Sri Lanka +# From Paul Eggert (1996-09-03): +# "Sri Lanka advances clock by an hour to avoid blackout" +# (www.virtual-pc.com/lankaweb/news/items/240596-2.html, 1996-05-24, +# no longer available as of 1999-08-17) +# reported ``the country's standard time will be put forward by one hour at +# midnight Friday (1830 GMT) `in the light of the present power crisis'.'' +# +# From Dharmasiri Senanayake, Sri Lanka Media Minister (1996-10-24), as quoted +# by Shamindra in +# +# Daily News - Hot News Section (1996-10-26) +# : +# With effect from 12.30 a.m. on 26th October 1996 +# Sri Lanka will be six (06) hours ahead of GMT. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Colombo 5:19:24 - LMT 1880 + 5:19:32 - MMT 1906 # Moratuwa Mean Time + 5:30 - IST 1942 Jan 5 + 5:30 0:30 IHST 1942 Sep + 5:30 1:00 IST 1945 Oct 16 2:00 + 5:30 - IST 1996 May 25 0:00 + 6:30 - LKT 1996 Oct 26 0:30 + 6:00 - LKT + +# Syria +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Syria 1920 1923 - Apr Sun>=15 2:00 1:00 S +Rule Syria 1920 1923 - Oct Sun>=1 2:00 0 - +Rule Syria 1962 only - Apr 29 2:00 1:00 S +Rule Syria 1962 only - Oct 1 2:00 0 - +Rule Syria 1963 1965 - May 1 2:00 1:00 S +Rule Syria 1963 only - Sep 30 2:00 0 - +Rule Syria 1964 only - Oct 1 2:00 0 - +Rule Syria 1965 only - Sep 30 2:00 0 - +Rule Syria 1966 only - Apr 24 2:00 1:00 S +Rule Syria 1966 1976 - Oct 1 2:00 0 - +Rule Syria 1967 1978 - May 1 2:00 1:00 S +Rule Syria 1977 1978 - Sep 1 2:00 0 - +Rule Syria 1983 1984 - Apr 9 2:00 1:00 S +Rule Syria 1983 1984 - Oct 1 2:00 0 - +Rule Syria 1986 only - Feb 16 2:00 1:00 S +Rule Syria 1986 only - Oct 9 2:00 0 - +Rule Syria 1987 only - Mar 1 2:00 1:00 S +Rule Syria 1987 1988 - Oct 31 2:00 0 - +Rule Syria 1988 only - Mar 15 2:00 1:00 S +Rule Syria 1989 only - Mar 31 2:00 1:00 S +Rule Syria 1989 only - Oct 1 2:00 0 - +Rule Syria 1990 only - Apr 1 2:00 1:00 S +Rule Syria 1990 only - Sep 30 2:00 0 - +Rule Syria 1991 only - Apr 1 0:00 1:00 S +Rule Syria 1991 1992 - Oct 1 0:00 0 - +Rule Syria 1992 only - Apr 8 0:00 1:00 S +Rule Syria 1993 only - Mar 26 0:00 1:00 S +Rule Syria 1993 only - Sep 25 0:00 0 - +# IATA SSIM (1998-02) says 1998-04-02; +# (1998-09) says 1999-03-29 and 1999-09-29; (1999-02) says 1999-04-02, +# 2000-04-02, and 2001-04-02; (1999-09) says 2000-03-31 and 2001-03-31; +# ignore all these claims and go with Shanks. +Rule Syria 1994 1996 - Apr 1 0:00 1:00 S +Rule Syria 1994 max - Oct 1 0:00 0 - +Rule Syria 1997 1998 - Mar lastMon 0:00 1:00 S +Rule Syria 1999 max - Apr 1 0:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Damascus 2:25:12 - LMT 1920 # Dimashq + 2:00 Syria EE%sT + +# Tajikistan +# From Shanks. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Dushanbe 4:35:12 - LMT 1924 May 2 + 5:00 - DUST 1930 Jun 21 # Dushanbe Time + 6:00 RussiaAsia DUS%sT 1991 Mar 31 2:00s + 5:00 1:00 DUSST 1991 Sep 9 2:00s + 5:00 - TJT # Tajikistan Time + +# Thailand +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Bangkok 6:42:04 - LMT 1880 + 6:42:04 - BMT 1920 Apr # Bangkok Mean Time + 7:00 - ICT + +# Turkmenistan +# From Shanks. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Ashgabat 3:53:32 - LMT 1924 May 2 # or Ashkhabad + 4:00 - ASHT 1930 Jun 21 # Ashkhabad Time + 5:00 RussiaAsia ASH%sT 1991 Mar 31 2:00 + 4:00 RussiaAsia ASH%sT 1991 Oct 27 # independence + 4:00 RussiaAsia TM%sT 1992 Jan 19 2:00 + 5:00 - TMT + +# United Arab Emirates +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Dubai 3:41:12 - LMT 1920 + 4:00 - GST + +# Uzbekistan +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Samarkand 4:27:12 - LMT 1924 May 2 + 4:00 - SAMT 1930 Jun 21 # Samarkand Time + 5:00 - SAMT 1981 Apr 1 + 5:00 1:00 SAMST 1981 Oct 1 + 6:00 RussiaAsia TAS%sT 1991 Mar 31 2:00 # Tashkent Time + 5:00 RussiaAsia TAS%sT 1991 Sep 1 # independence + 5:00 RussiaAsia UZ%sT 1992 + 5:00 RussiaAsia UZ%sT 1993 + 5:00 - UZT +Zone Asia/Tashkent 4:37:12 - LMT 1924 May 2 + 5:00 - TAST 1930 Jun 21 # Tashkent Time + 6:00 RussiaAsia TAS%sT 1991 Mar 31 2:00s + 5:00 RussiaAsia TAS%sT 1991 Sep 1 # independence + 5:00 RussiaAsia UZ%sT 1992 + 5:00 RussiaAsia UZ%sT 1993 + 5:00 - UZT + +# Vietnam +# From Paul Eggert (1993-11-18): +# Saigon's official name is Thanh-Pho Ho Chi Minh, but it's too long. +# We'll stick with the traditional name for now. +# From Shanks: +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Saigon 7:06:40 - LMT 1906 Jun 9 + 7:06:20 - SMT 1911 Mar 11 0:01 # Saigon MT? + 7:00 - ICT 1912 May + 8:00 - ICT 1931 May + 7:00 - ICT + +# Yemen +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Asia/Aden 3:00:48 - LMT 1950 + 3:00 - AST Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/australasia =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/australasia,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/australasia 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,1338 @@ +# @(#)australasia 7.69 +# This file also includes Pacific islands. + +# Notes are at the end of this file + +############################################################################### + +# Australia + +# Please see the notes below for the controversy about "EST" versus "AEST" etc. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Aus 1917 only - Jan 1 0:01 1:00 - +Rule Aus 1917 only - Mar 25 2:00 0 - +Rule Aus 1942 only - Jan 1 2:00 1:00 - +Rule Aus 1942 only - Mar 29 2:00 0 - +Rule Aus 1942 only - Sep 27 2:00 1:00 - +Rule Aus 1943 1944 - Mar lastSun 2:00 0 - +Rule Aus 1943 only - Oct 3 2:00 1:00 - +# Go with Whitman and the Australian National Standards Commission, which +# says W Australia didn't use DST in 1943/1944. Ignore Whitman's claim that +# 1944/1945 was just like 1943/1944. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# Northern Territory +Zone Australia/Darwin 8:43:20 - LMT 1895 Feb + 9:00 - CST 1899 May + 9:30 Aus CST +# Western Australia +Zone Australia/Perth 7:43:24 - LMT 1895 Dec + 8:00 Aus WST 1943 Jul + 8:00 - WST 1974 Oct lastSun 2:00s + 8:00 1:00 WST 1975 Mar Sun>=1 2:00s + 8:00 - WST 1983 Oct lastSun 2:00s + 8:00 1:00 WST 1984 Mar Sun>=1 2:00s + 8:00 - WST 1991 Nov 17 2:00s + 8:00 1:00 WST 1992 Mar Sun>=1 2:00s + 8:00 - WST +# Queensland +# +# From Alex Livingston (1996-11-01): +# I have heard or read more than once that some resort islands off the coast +# of Queensland chose to keep observing daylight-saving time even after +# Queensland ceased to. +# +# From Paul Eggert (1996-11-22): +# IATA SSIM (1993-02/1994-09) say that the Holiday Islands (Hayman, Lindeman, +# Hamilton) observed DST for two years after the rest of Queensland stopped. +# Hamilton is the largest, but there is also a Hamilton in Victoria, +# so use Lindeman. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule AQ 1971 only - Oct lastSun 2:00s 1:00 - +Rule AQ 1972 only - Feb lastSun 2:00s 0 - +Rule AQ 1989 1991 - Oct lastSun 2:00s 1:00 - +Rule AQ 1990 1992 - Mar Sun>=1 2:00s 0 - +Rule Holiday 1992 1993 - Oct lastSun 2:00s 1:00 - +Rule Holiday 1993 1994 - Mar Sun>=1 2:00s 0 - +Zone Australia/Brisbane 10:12:08 - LMT 1895 + 10:00 Aus EST 1971 + 10:00 AQ EST +Zone Australia/Lindeman 9:55:56 - LMT 1895 + 10:00 Aus EST 1971 + 10:00 AQ EST 1992 Jul + 10:00 Holiday EST + +# South Australia +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule AS 1971 1985 - Oct lastSun 2:00s 1:00 - +Rule AS 1986 only - Oct 19 2:00s 1:00 - +Rule AS 1987 max - Oct lastSun 2:00s 1:00 - +Rule AS 1972 only - Feb 27 2:00s 0 - +Rule AS 1973 1985 - Mar Sun>=1 2:00s 0 - +Rule AS 1986 1989 - Mar Sun>=15 2:00s 0 - +Rule AS 1990 only - Mar Sun>=18 2:00s 0 - +Rule AS 1991 only - Mar Sun>=1 2:00s 0 - +Rule AS 1992 only - Mar Sun>=18 2:00s 0 - +Rule AS 1993 only - Mar Sun>=1 2:00s 0 - +Rule AS 1994 only - Mar Sun>=18 2:00s 0 - +Rule AS 1995 max - Mar lastSun 2:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Australia/Adelaide 9:14:20 - LMT 1895 Feb + 9:00 - CST 1899 May + 9:30 Aus CST 1971 + 9:30 AS CST + +# Tasmania +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule AT 1967 only - Oct Sun>=1 2:00s 1:00 - +Rule AT 1968 only - Mar lastSun 2:00s 0 - +Rule AT 1968 1985 - Oct lastSun 2:00s 1:00 - +Rule AT 1969 1971 - Mar Sun>=8 2:00s 0 - +Rule AT 1972 only - Feb lastSun 2:00s 0 - +Rule AT 1973 1981 - Mar Sun>=1 2:00s 0 - +Rule AT 1982 1983 - Mar lastSun 2:00s 0 - +Rule AT 1984 1986 - Mar Sun>=1 2:00s 0 - +Rule AT 1986 only - Oct Sun>=15 2:00s 1:00 - +Rule AT 1987 1990 - Mar Sun>=15 2:00s 0 - +Rule AT 1987 only - Oct Sun>=22 2:00s 1:00 - +Rule AT 1988 1990 - Oct lastSun 2:00s 1:00 - +Rule AT 1991 1999 - Oct Sun>=1 2:00s 1:00 - +Rule AT 1991 max - Mar lastSun 2:00s 0 - +Rule AT 2000 only - Aug lastSun 2:00s 1:00 - +Rule AT 2001 max - Oct Sun>=1 2:00s 1:00 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Australia/Hobart 9:49:16 - LMT 1895 Sep + 10:00 - EST 1916 Oct 1 2:00 + 10:00 1:00 EST 1917 Feb + 10:00 Aus EST 1967 + 10:00 AT EST + +# Victoria +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule AV 1971 1985 - Oct lastSun 2:00s 1:00 - +Rule AV 1972 only - Feb lastSun 2:00s 0 - +Rule AV 1973 1985 - Mar Sun>=1 2:00s 0 - +Rule AV 1986 1990 - Mar Sun>=15 2:00s 0 - +Rule AV 1986 1987 - Oct Sun>=15 2:00s 1:00 - +Rule AV 1988 1999 - Oct lastSun 2:00s 1:00 - +Rule AV 1991 1994 - Mar Sun>=1 2:00s 0 - +Rule AV 1995 max - Mar lastSun 2:00s 0 - +Rule AV 2000 only - Aug lastSun 2:00s 1:00 - +Rule AV 2001 max - Oct lastSun 2:00s 1:00 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Australia/Melbourne 9:39:52 - LMT 1895 Feb + 10:00 Aus EST 1971 + 10:00 AV EST + +# New South Wales +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule AN 1971 1985 - Oct lastSun 2:00s 1:00 - +Rule AN 1972 only - Feb 27 2:00s 0 - +Rule AN 1973 1981 - Mar Sun>=1 2:00s 0 - +Rule AN 1982 only - Apr Sun>=1 2:00s 0 - +Rule AN 1983 1985 - Mar Sun>=1 2:00s 0 - +Rule AN 1986 1989 - Mar Sun>=15 2:00s 0 - +Rule AN 1986 only - Oct 19 2:00s 1:00 - +Rule AN 1987 1999 - Oct lastSun 2:00s 1:00 - +Rule AN 1990 1995 - Mar Sun>=1 2:00s 0 - +Rule AN 1996 max - Mar lastSun 2:00s 0 - +Rule AN 2000 only - Aug lastSun 2:00s 1:00 - +Rule AN 2001 max - Oct lastSun 2:00s 1:00 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Australia/Sydney 10:04:52 - LMT 1895 Feb + 10:00 Aus EST 1971 + 10:00 AN EST +Zone Australia/Broken_Hill 9:25:48 - LMT 1895 Feb + 10:00 - EST 1896 Aug 23 + 9:00 - CST 1899 May + 9:30 Aus CST 1971 + 9:30 AN CST 2000 + 9:30 AS CST + +# Lord Howe Island +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule LH 1981 1984 - Oct lastSun 2:00 1:00 - +Rule LH 1982 1985 - Mar Sun>=1 2:00 0 - +Rule LH 1985 only - Oct lastSun 2:00 0:30 - +Rule LH 1986 1989 - Mar Sun>=15 2:00 0 - +Rule LH 1986 only - Oct 19 2:00 0:30 - +Rule LH 1987 1999 - Oct lastSun 2:00 0:30 - +Rule LH 1990 1995 - Mar Sun>=1 2:00 0 - +Rule LH 1996 max - Mar lastSun 2:00 0 - +Rule LH 2000 only - Aug lastSun 2:00 0:30 - +Rule LH 2001 max - Oct lastSun 2:00 0:30 - +Zone Australia/Lord_Howe 10:36:20 - LMT 1895 Feb + 10:00 - EST 1981 Mar + 10:30 LH LHST + +# Australian miscellany +# +# Ashmore Is, Cartier +# no indigenous inhabitants; only seasonal caretakers +# like Australia/Perth, says Turner +# +# Coral Sea Is +# no indigenous inhabitants; only meteorologists +# no information +# +# Macquarie +# permanent occupation (scientific station) since 1948; +# sealing and penguin oil station operated 1888/1917 +# like Australia/Hobart, says Turner + +# Christmas +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Christmas 7:02:52 - LMT 1895 Feb + 7:00 - CXT # Christmas Island Time + +# Cook Is +# From Shanks: +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Cook 1978 only - Nov 12 0:00 0:30 HS +Rule Cook 1979 1991 - Mar Sun>=1 0:00 0 - +Rule Cook 1979 1990 - Oct lastSun 0:00 0:30 HS +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Rarotonga -10:39:04 - LMT 1901 # Avarua + -10:30 - CKT 1978 Nov 12 # Cook Is Time + -10:00 Cook CK%sT + +# Cocos +# From USNO (1989): +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Indian/Cocos 6:30 - CCT # Cocos Islands Time + +# Fiji +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Fiji 1998 1999 - Nov Sun>=1 2:00 1:00 S +Rule Fiji 1999 2000 - Feb lastSun 3:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Fiji 11:53:40 - LMT 1915 Oct 26 # Suva + 12:00 Fiji FJ%sT # Fiji Time + +# French Polynesia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Gambier -8:59:48 - LMT 1912 Oct # Rikitea + -9:00 - GAMT # Gambier Time +Zone Pacific/Marquesas -9:18:00 - LMT 1912 Oct + -9:30 - MART # Marquesas Time +Zone Pacific/Tahiti -9:58:16 - LMT 1912 Oct # Papeete + -10:00 - TAHT # Tahiti Time +# Clipperton (near North America) is administered from French Polynesia; +# it is uninhabited. + +# Guam +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Guam -14:21:00 - LMT 1844 Dec 31 + 9:39:00 - LMT 1901 # Agana + 10:00 - GST 2000 Dec 23 # Guam + 10:00 - ChST # Chamorro Standard Time + +# Kiribati +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Tarawa 11:32:04 - LMT 1901 # Bairiki + 12:00 - GILT # Gilbert Is Time +Zone Pacific/Enderbury -11:24:20 - LMT 1901 + -12:00 - PHOT 1979 Oct # Phoenix Is Time + -11:00 - PHOT 1995 + 13:00 - PHOT +Zone Pacific/Kiritimati -10:29:20 - LMT 1901 + -10:40 - LINT 1979 Oct # Line Is Time + -10:00 - LINT 1995 + 14:00 - LINT + +# N Mariana Is +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Saipan -14:17:00 - LMT 1844 Dec 31 + 9:43:00 - LMT 1901 + 9:00 - MPT 1969 Oct # N Mariana Is Time + 10:00 - MPT 2000 Dec 23 + 10:00 - ChST # Chamorro Standard Time + +# Marshall Is +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Majuro 11:24:48 - LMT 1901 + 11:00 - MHT 1969 Oct # Marshall Islands Time + 12:00 - MHT +Zone Pacific/Kwajalein 11:09:20 - LMT 1901 + 11:00 - MHT 1969 Oct + -12:00 - KWAT 1993 Aug 20 # Kwajalein Time + 12:00 - MHT + +# Micronesia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Yap 9:12:32 - LMT 1901 # Colonia + 9:00 - YAPT 1969 Oct # Yap Time + 10:00 - YAPT +Zone Pacific/Truk 10:07:08 - LMT 1901 + 10:00 - TRUT # Truk Time +Zone Pacific/Ponape 10:32:52 - LMT 1901 # Kolonia + 11:00 - PONT # Ponape Time +Zone Pacific/Kosrae 10:51:56 - LMT 1901 + 11:00 - KOST 1969 Oct # Kosrae Time + 12:00 - KOST 1999 + 11:00 - KOST + +# Nauru +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Nauru 11:07:40 - LMT 1921 Jan 15 # Uaobe + 11:30 - NRT 1942 Mar 15 # Nauru Time + 9:00 - JST 1944 Aug 15 + 11:30 - NRT 1979 May + 12:00 - NRT + +# New Caledonia +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule NC 1977 1978 - Dec Sun>=1 0:00 1:00 S +Rule NC 1978 1979 - Feb 27 0:00 0 - +Rule NC 1996 only - Dec 1 2:00s 1:00 S +# Shanks says the following was at 2:00; go with IATA. +Rule NC 1997 only - Mar 2 2:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Noumea 11:05:48 - LMT 1912 Jan 13 + 11:00 NC NC%sT + + +############################################################################### + +# New Zealand + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule NZ 1927 only - Nov 6 2:00 1:00 S +Rule NZ 1928 only - Mar 4 2:00 0 M +Rule NZ 1928 1933 - Oct Sun>=8 2:00 0:30 S +Rule NZ 1929 1933 - Mar Sun>=15 2:00 0 M +Rule NZ 1934 1940 - Apr lastSun 2:00 0 M +Rule NZ 1934 1940 - Sep lastSun 2:00 0:30 S +Rule NZ 1946 only - Jan 1 0:00 0 S +# Since 1957 Chatham has been 45 minutes ahead of NZ, but there's no +# convenient notation for this so we must duplicate the Rule lines. +Rule NZ 1974 only - Nov Sun>=1 2:00s 1:00 D +Rule Chatham 1974 only - Nov Sun>=1 2:45s 1:00 D +Rule NZ 1975 only - Feb lastSun 2:00s 0 S +Rule Chatham 1975 only - Feb lastSun 2:45s 0 S +Rule NZ 1975 1988 - Oct lastSun 2:00s 1:00 D +Rule Chatham 1975 1988 - Oct lastSun 2:45s 1:00 D +Rule NZ 1976 1989 - Mar Sun>=1 2:00s 0 S +Rule Chatham 1976 1989 - Mar Sun>=1 2:45s 0 S +Rule NZ 1989 only - Oct Sun>=8 2:00s 1:00 D +Rule Chatham 1989 only - Oct Sun>=8 2:45s 1:00 D +Rule NZ 1990 max - Oct Sun>=1 2:00s 1:00 D +Rule Chatham 1990 max - Oct Sun>=1 2:45s 1:00 D +Rule NZ 1990 max - Mar Sun>=15 2:00s 0 S +Rule Chatham 1990 max - Mar Sun>=15 2:45s 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Auckland 11:39:04 - LMT 1868 Nov 2 + 11:30 NZ NZ%sT 1946 Jan 1 + 12:00 NZ NZ%sT +Zone Pacific/Chatham 12:13:48 - LMT 1957 Jan 1 + 12:45 Chatham CHA%sT + + +# Auckland Is +# uninhabited; Maori and Moriori, colonial settlers, pastoralists, sealers, +# and scientific personnel have wintered + +# Campbell I +# minor whaling stations operated 1909/1914 +# scientific station operated 1941/1995; +# previously whalers, sealers, pastoralists, and scientific personnel wintered +# was probably like Pacific/Auckland + +############################################################################### + + +# Niue +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Niue -11:19:40 - LMT 1901 # Alofi + -11:20 - NUT 1951 # Niue Time + -11:30 - NUT 1978 Oct 1 + -11:00 - NUT + +# Norfolk +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Norfolk 11:11:52 - LMT 1901 # Kingston + 11:12 - NMT 1951 # Norfolk Mean Time + 11:30 - NFT # Norfolk Time + +# Palau (Belau) +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Palau 8:57:56 - LMT 1901 # Koror + 9:00 - PWT # Palau Time + +# Papua New Guinea +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Port_Moresby 9:48:40 - LMT 1880 + 9:48:32 - PMMT 1895 # Port Moresby Mean Time + 10:00 - PGT # Papua New Guinea Time + +# Pitcairn +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Pitcairn -8:40:20 - LMT 1901 # Adamstown + -8:30 - PNT 1998 Apr 27 00:00 + -8:00 - PST # Pitcairn Standard Time + +# American Samoa +Zone Pacific/Pago_Pago 12:37:12 - LMT 1879 Jul 5 + -11:22:48 - LMT 1911 + -11:30 - SAMT 1950 # Samoa Time + -11:00 - NST 1967 Apr # N=Nome + -11:00 - BST 1983 Nov 30 # B=Bering + -11:00 - SST # S=Samoa + +# W Samoa +Zone Pacific/Apia 12:33:04 - LMT 1879 Jul 5 + -11:26:56 - LMT 1911 + -11:30 - SAMT 1950 # Samoa Time + -11:00 - WST # W Samoa Time + +# Solomon Is +# excludes Bougainville, for which see Papua New Guinea +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Guadalcanal 10:39:48 - LMT 1912 Oct # Honiara + 11:00 - SBT # Solomon Is Time + +# Tokelau Is +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Fakaofo -11:24:56 - LMT 1901 + -10:00 - TKT # Tokelau Time + +# Tonga +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Tonga 1999 only - Oct 7 2:00s 1:00 S +Rule Tonga 2000 only - Mar 19 2:00s 0 - +Rule Tonga 2000 2001 - Nov Sun>=1 2:00 1:00 S +Rule Tonga 2001 2002 - Jan lastSun 2:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Tongatapu 12:19:20 - LMT 1901 + 12:20 - TOT 1941 # Tonga Time + 13:00 - TOT 1999 + 13:00 Tonga TO%sT + +# Tuvalu +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Funafuti 11:56:52 - LMT 1901 + 12:00 - TVT # Tuvalu Time + + +# US minor outlying islands + +# Howland, Baker +# uninhabited since World War II +# no information; was probably like Pacific/Pago_Pago + +# Jarvis +# uninhabited since 1958 +# no information; was probably like Pacific/Kiritimati + +# Johnston +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Johnston -10:00 - HST + +# Kingman +# uninhabited + +# Midway +Zone Pacific/Midway -11:49:28 - LMT 1901 + -11:00 - NST 1956 Jun 3 + -11:00 1:00 NDT 1956 Sep 2 + -11:00 - NST 1967 Apr # N=Nome + -11:00 - BST 1983 Nov 30 # B=Bering + -11:00 - SST # S=Samoa + +# Palmyra +# uninhabited since World War II; was probably like Pacific/Kiritimati + +# Wake +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Wake 11:06:28 - LMT 1901 + 12:00 - WAKT # Wake Time + + +# Vanuatu +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Vanuatu 1983 only - Sep 25 0:00 1:00 S +Rule Vanuatu 1984 1991 - Mar Sun>=23 0:00 0 - +Rule Vanuatu 1984 only - Oct 23 0:00 1:00 S +Rule Vanuatu 1985 1991 - Sep Sun>=23 0:00 1:00 S +Rule Vanuatu 1992 1993 - Jan Sun>=23 0:00 0 - +Rule Vanuatu 1992 only - Oct Sun>=23 0:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Efate 11:13:16 - LMT 1912 Jan 13 # Vila + 11:00 Vanuatu VU%sT # Vanuatu Time + +# Wallis and Futuna +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Pacific/Wallis 12:15:20 - LMT 1901 + 12:00 - WFT # Wallis & Futuna Time + +############################################################################### + +# NOTES + +# This data is by no means authoritative; if you think you know better, +# go ahead and edit the file (and please send any changes to +# tz@elsie.nci.nih.gov for general use in the future). + +# From Paul Eggert (1999-10-29): +# A good source for time zone historical data outside the U.S. is +# Thomas G. Shanks, The International Atlas (5th edition), +# San Diego: ACS Publications, Inc. (1999). +# +# Gwillim Law writes that a good source +# for recent time zone data is the International Air Transport +# Association's Standard Schedules Information Manual (IATA SSIM), +# published semiannually. Law sent in several helpful summaries +# of the IATA's data after 1990. +# +# Except where otherwise noted, Shanks is the source for entries through 1990, +# and IATA SSIM is the source for entries after 1990. +# +# Another source occasionally used is Edward W. Whitman, World Time Differences, +# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), which +# I found in the UCLA library. +# +# A reliable and entertaining source about time zones is +# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997). +# +# I invented the abbreviations marked `*' in the following table; +# the rest are from earlier versions of this file, or from other sources. +# Corrections are welcome! +# std dst +# LMT Local Mean Time +# 8:00 WST WST Western Australia +# 9:00 JST Japan +# 9:30 CST CST Central Australia +# 10:00 EST EST Eastern Australia +# 10:00 ChST Chamorro +# 10:30 LHST LHST Lord Howe* +# 11:30 NZMT NZST New Zealand through 1945 +# 12:00 NZST NZDT New Zealand 1946-present +# 12:45 CHAST CHADT Chatham* +# -11:00 SST Samoa +# -10:00 HST Hawaii +# - 8:00 PST Pitcairn* +# +# See the `northamerica' file for Hawaii. +# See the `southamerica' file for Easter I and the Galapagos Is. + +############################################################################### + +# Australia + +# +# Australia's Daylight Saving Times +# , by Margaret Turner, summarizes daylight saving issues in Australia. + +# From John Mackin (1991-03-06): +# We in Australia have _never_ referred to DST as `daylight' time. +# It is called `summer' time. Now by a happy coincidence, `summer' +# and `standard' happen to start with the same letter; hence, the +# abbreviation does _not_ change... +# The legislation does not actually define abbreviations, at least +# in this State, but the abbreviation is just commonly taken to be the +# initials of the phrase, and the legislation here uniformly uses +# the phrase `summer time' and does not use the phrase `daylight +# time'. +# Announcers on the Commonwealth radio network, the ABC (for Australian +# Broadcasting Commission), use the phrases `Eastern Standard Time' +# or `Eastern Summer Time'. (Note, though, that as I say in the +# current australasia file, there is really no such thing.) Announcers +# on its overseas service, Radio Australia, use the same phrases +# prefixed by the word `Australian' when referring to local times; +# time announcements on that service, naturally enough, are made in UTC. + +# From Arthur David Olson (1992-03-08): +# Given the above, what's chosen for year-round use is: +# CST for any place operating at a GMTOFF of 9:30 +# WST for any place operating at a GMTOFF of 8:00 +# EST for any place operating at a GMTOFF of 10:00 + +# From Paul Eggert (2001-04-05), summarizing a long discussion about "EST" +# versus "AEST" etc.: +# +# I see the following points of dispute: +# +# * How important are unique time zone abbreviations? +# +# Here I tend to agree with the point (most recently made by Chris +# Newman) that unique abbreviations should not be essential for proper +# operation of software. We have other instances of ambiguity +# (e.g. "IST" denoting both "Israel Standard Time" and "Indian +# Standard Time"), and they are not likely to go away any time soon. +# In the old days, some software mistakenly relied on unique +# abbreviations, but this is becoming less true with time, and I don't +# think it's that important to cater to such software these days. +# +# On the other hand, there is another motivation for unambiguous +# abbreviations: it cuts down on human confusion. This is +# particularly true for Australia, where "EST" can mean one thing for +# time T and a different thing for time T plus 1 second. +# +# * Does the relevant legislation indicate which abbreviations should be used? +# +# Here I tend to think that things are a mess, just as they are in +# many other countries. We Americans are currently disagreeing about +# which abbreviation to use for the newly legislated Chamorro Standard +# Time, for example. +# +# Personally, I would prefer to use common practice; I would like to +# refer to legislation only for examples of common practice, or as a +# tiebreaker. +# +# * Do Australians more often use "Eastern Daylight Time" or "Eastern +# Summer Time"? Do they typically prefix the time zone names with +# the word "Australian"? +# +# My own impression is that both "Daylight Time" and "Summer Time" are +# common and are widely understood, but that "Summer Time" is more +# popular; and that the leading "A" is also common but is omitted more +# often than not. I just used AltaVista advanced search and got the +# following count of page hits: +# +# 1,103 "Eastern Summer Time" AND domain:au +# 971 "Australian Eastern Summer Time" AND domain:au +# 613 "Eastern Daylight Time" AND domain:au +# 127 "Australian Eastern Daylight Time" AND domain:au +# +# Here "Summer" seems quite a bit more popular than "Daylight", +# particularly when we know the time zone is Australian and not US, +# say. The "Australian" prefix seems to be popular for Eastern Summer +# Time, but unpopular for Eastern Daylight Time. +# +# For abbreviations, tools like AltaVista are less useful because of +# ambiguity. Many hits are not really time zones, unfortunately, and +# many hits denote US time zones and not Australian ones. But here +# are the hit counts anyway: +# +# 161,304 "EST" and domain:au +# 25,156 "EDT" and domain:au +# 18,263 "AEST" and domain:au +# 10,416 "AEDT" and domain:au +# +# 14,538 "CST" and domain:au +# 5,728 "CDT" and domain:au +# 176 "ACST" and domain:au +# 29 "ACDT" and domain:au +# +# 7,539 "WST" and domain:au +# 68 "AWST" and domain:au +# +# This data suggest that Australians tend to omit the "A" prefix in +# practice. The situation for "ST" versus "DT" is less clear, given +# the ambiguities involved. +# +# * How do Australians feel about the abbreviations in the tz database? +# +# If you just count Australians on this list, I count 2 in favor and 3 +# against. One of the "against" votes (David Keegel) counseled delay, +# saying that both AEST/AEDT and EST/EST are widely used and +# understood in Australia. + +# From Paul Eggert (1995-12-19): +# Shanks reports 2:00 for all autumn changes in Australia and New Zealand. +# Mark Prior writes that his newspaper +# reports that NSW's fall 1995 change will occur at 2:00, +# but Robert Elz says it's been 3:00 in Victoria since 1970 +# and perhaps the newspaper's `2:00' is referring to standard time. +# For now we'll continue to assume 2:00s for changes since 1960. + +# From Eric Ulevik (1998-01-05): +# +# Here are some URLs to Australian time legislation. These URLs are stable, +# and should probably be included in the data file. There are probably more +# relevant entries in this database. +# +# NSW (including LHI and Broken Hill): +# +# Standard Time Act 1987 (updated 1995-04-04) +# +# ACT +# +# Standard Time and Summer Time Act 1972 +# +# SA +# +# Standard Time Act, 1898 +# + +# Northern Territory + +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# # The NORTHERN TERRITORY.. [ Courtesy N.T. Dept of the Chief Minister ] +# # [ Nov 1990 ] +# # N.T. have never utilised any DST due to sub-tropical/tropical location. +# ... +# Zone Australia/North 9:30 - CST + +# From Bradley White (1991-03-04): +# A recent excerpt from an Australian newspaper... +# the Northern Territory do[es] not have daylight saving. + +# Western Australia + +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# # The state of WESTERN AUSTRALIA.. [ Courtesy W.A. dept Premier+Cabinet ] +# # [ Nov 1990 ] +# # W.A. suffers from a great deal of public and political opposition to +# # DST in principle. A bill is brought before parliament in most years, but +# # usually defeated either in the upper house, or in party caucus +# # before reaching parliament. +# ... +# Zone Australia/West 8:00 AW %sST +# ... +# Rule AW 1974 only - Oct lastSun 2:00 1:00 D +# Rule AW 1975 only - Mar Sun>=1 3:00 0 W +# Rule AW 1983 only - Oct lastSun 2:00 1:00 D +# Rule AW 1984 only - Mar Sun>=1 3:00 0 W + +# From Bradley White (1991-03-04): +# A recent excerpt from an Australian newspaper... +# Western Australia...do[es] not have daylight saving. + +# From John D. Newman via Bradley White (1991-11-02): +# Western Australia is still on "winter time". Some DH in Sydney +# rang me at home a few days ago at 6.00am. (He had just arrived at +# work at 9.00am.) +# W.A. is switching to Summer Time on Nov 17th just to confuse +# everybody again. + +# From Arthur David Olson (1992-03-08): +# The 1992 ending date used in the rules is a best guess; +# it matches what was used in the past. + +# +# The Australian Bureau of Meteorology FAQ +# (1999-09-27) writes that Giles Meteorological Station uses +# South Australian time even though it's located in Western Australia. + +# Queensland +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# # The state of QUEENSLAND.. [ Courtesy Qld. Dept Premier Econ&Trade Devel ] +# # [ Dec 1990 ] +# ... +# Zone Australia/Queensland 10:00 AQ %sST +# ... +# Rule AQ 1971 only - Oct lastSun 2:00 1:00 D +# Rule AQ 1972 only - Feb lastSun 3:00 0 E +# Rule AQ 1989 max - Oct lastSun 2:00 1:00 D +# Rule AQ 1990 max - Mar Sun>=1 3:00 0 E + +# From Bradley White (1989-12-24): +# "Australia/Queensland" now observes daylight time (i.e. from +# October 1989). + +# From Bradley White (1991-03-04): +# A recent excerpt from an Australian newspaper... +# ...Queensland...[has] agreed to end daylight saving +# at 3am tomorrow (March 3)... + +# From John Mackin (1991-03-06): +# I can certainly confirm for my part that Daylight Saving in NSW did in fact +# end on Sunday, 3 March. I don't know at what hour, though. (It surprised +# me.) + +# From Bradley White (1992-03-08): +# ...there was recently a referendum in Queensland which resulted +# in the experimental daylight saving system being abandoned. So, ... +# ... +# Rule QLD 1989 1991 - Oct lastSun 2:00 1:00 D +# Rule QLD 1990 1992 - Mar Sun>=1 3:00 0 S +# ... + +# From Arthur David Olson (1992-03-08): +# The chosen rules the union of the 1971/1972 change and the 1989-1992 changes. + +# From Rives McDow (2002-04-09): +# The most interesting region I have found consists of three towns on the +# southern coast of Australia, population 10 at last report, along with +# 50,000 sheep, about 100 kilometers long and 40 kilometers into the +# continent. The primary town is Madura, with the other towns being +# Mundrabilla and Eucla. According to the sheriff of Madura, the +# residents got tired of having to change the time so often, as they are +# located in a strip overlapping the border of South Australia and Western +# Australia. South Australia observes daylight saving time; Western +# Australia does not. The two states are one and a half hours apart. The +# residents decided to forget about this nonsense of changing the clock so +# much and set the local time 20 hours and 45 minutes from the +# international date line, or right in the middle of the time of South +# Australia and Western Australia. As it only affects about 10 people and +# tourists staying at the Madura Motel, it has never really made as big an +# impact as Broken Hill. However, as tourist visiting there or anyone +# calling the local sheriff will attest, they do keep time in this way. +# +# From Paul Eggert (2002-04-09): +# This is confirmed by the section entitled +# "What's the deal with time zones???" in +# , +# which says a few other things: +# +# * Border Village, SA also is 45 minutes ahead of Perth. +# * The locals call this time zone "central W.A. Time" (presumably "CWAT"). +# * The locals also call Western Australia time "Perth time". +# +# It's not clear from context whether everyone in Western Australia +# knows of this naming convention, or whether it's just the people in +# this subregion. + +# South Australia, Tasmania, Victoria + +# From Arthur David Olson (1992-03-08): +# The rules from version 7.1 follow. +# There are lots of differences between these rules and +# the Shepherd et al. rules. Since the Shepherd et al. rules +# and Bradley White's newspaper article are in agreement on +# current DST ending dates, no worries. +# +# Rule Oz 1971 1985 - Oct lastSun 2:00 1:00 - +# Rule Oz 1986 max - Oct Sun<=24 2:00 1:00 - +# Rule Oz 1972 only - Feb 27 3:00 0 - +# Rule Oz 1973 1986 - Mar Sun>=1 3:00 0 - +# Rule Oz 1987 max - Mar Sun<=21 3:00 0 - +# Zone Australia/Tasmania 10:00 Oz EST +# Zone Australia/South 9:30 Oz CST +# Zone Australia/Victoria 10:00 Oz EST 1985 Oct lastSun 2:00 +# 10:00 1:00 EST 1986 Mar Sun<=21 3:00 +# 10:00 Oz EST + +# From Robert Elz (1991-03-06): +# I believe that the current start date for DST is "lastSun" in Oct... +# that changed Oct 89. That is, we're back to the +# original rule, and that rule currently applies in all the states +# that have dst, incl Qld. (Certainly it was true in Vic). +# The file I'm including says that happened in 1988, I think +# that's incorrect, but I'm not 100% certain. + +# South Australia + +# From Bradley White (1991-03-04): +# A recent excerpt from an Australian newspaper... +# ...South Australia...[has] agreed to end daylight saving +# at 3am tomorrow (March 3)... + +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# # The state of SOUTH AUSTRALIA....[ Courtesy of S.A. Dept of Labour ] +# # [ Nov 1990 ] +# ... +# Zone Australia/South 9:30 AS %sST +# ... +# Rule AS 1971 max - Oct lastSun 2:00 1:00 D +# Rule AS 1972 1985 - Mar Sun>=1 3:00 0 C +# Rule AS 1986 1990 - Mar Sun<=21 3:00 0 C +# Rule AS 1991 max - Mar Sun>=1 3:00 0 C + +# From Bradley White (1992-03-11): +# Recent correspondence with a friend in Adelaide +# contained the following exchange: "Due to the Adelaide Festival, +# South Australia delays setting back our clocks for a few weeks." + +# From Robert Elz (1992-03-13): +# I heard that apparently (or at least, it appears that) +# South Aus will have an extra 3 weeks daylight saving every even +# numbered year (from 1990). That's when the Adelaide Festival +# is on... + +# From Robert Elz (1992-03-16, 00:57:07 +1000): +# DST didn't end in Adelaide today (yesterday).... +# But whether it's "4th Sunday" or "2nd last Sunday" I have no idea whatever... +# (it's just as likely to be "the Sunday we pick for this year"...). + +# From Bradley White (1994-04-11): +# If Sun, 15 March, 1992 was at +1030 as kre asserts, but yet Sun, 20 March, +# 1994 was at +0930 as John Connolly's customer seems to assert, then I can +# only conclude that the actual rule is more complicated.... + +# From John Warburton (1994-10-07): +# The new Daylight Savings dates for South Australia ... +# was gazetted in the Government Hansard on Sep 26 1994.... +# start on last Sunday in October and end in last sunday in March. + +# Tasmania + +# The rules for 1967 through 1991 were reported by George Shepherd +# via Simon Woodhead via Robert Elz (1991-03-06): +# # The state of TASMANIA.. [Courtesy Tasmanian Dept of Premier + Cabinet ] +# # [ Nov 1990 ] + +# From Bill Hart via Guy Harris (1991-10-10): +# Oh yes, the new daylight savings rules are uniquely tasmanian, we have +# 6 weeks a year now when we are out of sync with the rest of Australia +# (but nothing new about that). + +# From Alex Livingston (1999-10-04): +# I heard on the ABC (Australian Broadcasting Corporation) radio news on the +# (long) weekend that Tasmania, which usually goes its own way in this regard, +# has decided to join with most of NSW, the ACT, and most of Victoria +# (Australia) and start daylight saving on the last Sunday in August in 2000 +# instead of the first Sunday in October. + +# Sim Alam (2000-07-03) reported a legal citation for the 2000/2001 rules: +# http://www.thelaw.tas.gov.au/fragview/42++1968+GS3A@EN+2000070300 + +# Victoria + +# The rules for 1971 through 1991 were reported by George Shepherd +# via Simon Woodhead via Robert Elz (1991-03-06): +# # The state of VICTORIA.. [ Courtesy of Vic. Dept of Premier + Cabinet ] +# # [ Nov 1990 ] + +# From Scott Harrington (2001-08-29): +# On KQED's "City Arts and Lectures" program last night I heard an +# interesting story about daylight savings time. Dr. John Heilbron was +# discussing his book "The Sun in the Church: Cathedrals as Solar +# Observatories"[1], and in particular the Shrine of Remembrance[2] located +# in Melbourne, Australia. +# +# Apparently the shrine's main purpose is a beam of sunlight which +# illuminates a special spot on the floor at the 11th hour of the 11th day +# of the 11th month (Remembrance Day) every year in memory of Australia's +# fallen WWI soldiers. And if you go there on Nov. 11, at 11am local time, +# you will indeed see the sunbeam illuminate the special spot at the +# expected time. +# +# However, that is only because of some special mirror contraption that had +# to be employed, since due to daylight savings time, the true solar time of +# the remembrance moment occurs one hour later (or earlier?). Perhaps +# someone with more information on this jury-rig can tell us more. +# +# [1] http://www.hup.harvard.edu/catalog/HEISUN.html +# [2] http://www.shrine.org.au + +# New South Wales + +# From Arthur David Olson: +# New South Wales and subjurisdictions have their own ideas of a fun time. +# Based on law library research by John Mackin (john@basser.cs.su.oz), +# who notes: +# In Australia, time is not legislated federally, but rather by the +# individual states. Thus, while such terms as ``Eastern Standard Time'' +# [I mean, of course, Australian EST, not any other kind] are in common +# use, _they have NO REAL MEANING_, as they are not defined in the +# legislation. This is very important to understand. +# I have researched New South Wales time only... + +# From Paul Eggert (1999-09-27): +# The Information Service of the Australian National Standards Commission +# +# Daylight Saving +# page (1995-04) has an excellent overall history of Australian DST. +# The Community Relations Division of the NSW Attorney General's Department +# publishes a history of daylight saving in NSW. See: +# +# Lawlink NSW: Daylight Saving in New South Wales +# + +# From Eric Ulevik (1999-05-26): +# DST will start in NSW on the last Sunday of August, rather than the usual +# October in 2000. [See: Matthew Moore, +# +# Two months more daylight saving +# +# Sydney Morning Herald (1999-05-26).] + +# From Paul Eggert (1999-09-27): +# See the following official NSW source: +# +# Daylight Saving in New South Wales. +# +# +# Narrabri Shire (NSW) council has announced it will ignore the extension of +# daylight saving next year. See: +# +# Narrabri Council to ignore daylight saving +# (1999-07-22). For now, we'll wait to see if this really happens. +# +# Victoria will following NSW. See: +# +# Vic to extend daylight saving +# (1999-07-28). +# +# However, South Australia rejected the DST request. See: +# +# South Australia rejects Olympics daylight savings request +# (1999-07-19). +# +# Queensland also will not observe DST for the Olympics. See: +# +# Qld says no to daylight savings for Olympics +# (1999-06-01), which quotes Queensland Premier Peter Beattie as saying +# ``Look you've got to remember in my family when this came up last time +# I voted for it, my wife voted against it and she said to me it's all very +# well for you, you don't have to worry about getting the children out of +# bed, getting them to school, getting them to sleep at night. +# I've been through all this argument domestically...my wife rules.'' +# +# Broken Hill will stick with South Australian time in 2000. See: +# +# Broken Hill to be behind the times +# (1999-07-21). + +# IATA SSIM (1998-09) says that the spring 2000 change for Australian +# Capital Territory, New South Wales except Lord Howe Island and Broken +# Hill, and Victoria will be August 27, presumably due to the Sydney Olympics. + +# From Eric Ulevik, referring to Sydney's Sun Herald (2000-08-13), page 29: +# The Queensland Premier Peter Beattie is encouraging northern NSW +# towns to use Queensland time. + +# Yancowinna + +# From John Mackin (1989-01-04): +# `Broken Hill' means the County of Yancowinna. + +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# # YANCOWINNA.. [ Confirmation courtesy of Broken Hill Postmaster ] +# # [ Dec 1990 ] +# ... +# # Yancowinna uses Central Standard Time, despite [its] location on the +# # New South Wales side of the S.A. border. Most business and social dealings +# # are with CST zones, therefore CST is legislated by local government +# # although the switch to Summer Time occurs in line with N.S.W. There have +# # been years when this did not apply, but the historical data is not +# # presently available. +# Zone Australia/Yancowinna 9:30 AY %sST +# ... +# Rule AY 1971 1985 - Oct lastSun 2:00 1:00 D +# Rule AY 1972 only - Feb lastSun 3:00 0 C +# [followed by other Rules] + +# Lord Howe Island + +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# LHI... [ Courtesy of Pauline Van Winsen.. pauline@Aus ] +# [ Dec 1990 ] +# Lord Howe Island is located off the New South Wales coast, and is half an +# hour ahead of NSW time. + +# From James Lonergan, Secretary, Lord Howe Island Board (2000-01-27): +# Lord Howe Island summer time in 2000/2001 will commence on the same +# date as the rest of NSW (i.e. 2000-08-27). For your information the +# Lord Howe Island Board (controlling authority for the Island) is +# seeking the community's views on various options for summer time +# arrangements on the Island, e.g. advance clocks by 1 full hour +# instead of only 30 minutes. Dependant on the wishes of residents +# the Board may approach the NSW government to change the existing +# arrangements. The starting date for summer time on the Island will +# however always coincide with the rest of NSW. + +# From James Lonergan, Secretary, Lord Howe Island Board (2000-10-25): +# Lord Howe Island advances clocks by 30 minutes during DST in NSW and retards +# clocks by 30 minutes when DST finishes. Since DST was most recently +# introduced in NSW, the "changeover" time on the Island has been 02:00 as +# shown on clocks on LHI. I guess this means that for 30 minutes at the start +# of DST, LHI is actually 1 hour ahead of the rest of NSW. + +# From Paul Eggert (2001-02-09): +# For Lord Howe dates we use Shanks through 1989, and Lonergan thereafter. +# For times we use Lonergan. + +############################################################################### + +# New Zealand + +# From Mark Davies (1990-10-03): +# the 1989/90 year was a trial of an extended "daylight saving" period. +# This trial was deemed successful and the extended period adopted for +# subsequent years (with the addition of a further week at the start). +# source -- phone call to Ministry of Internal Affairs Head Office. + +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# # The Country of New Zealand (Australia's east island -) Gee they hate that! +# # or is Australia the west island of N.Z. +# # [ courtesy of Geoff Tribble.. Geofft@Aus.. Auckland N.Z. ] +# # [ Nov 1990 ] +# ... +# Rule NZ 1974 1988 - Oct lastSun 2:00 1:00 D +# Rule NZ 1989 max - Oct Sun>=1 2:00 1:00 D +# Rule NZ 1975 1989 - Mar Sun>=1 3:00 0 S +# Rule NZ 1990 max - Mar lastSun 3:00 0 S +# ... +# Zone NZ 12:00 NZ NZ%sT # New Zealand +# Zone NZ-CHAT 12:45 - NZ-CHAT # Chatham Island + +# From Arthur David Olson (1992-03-08): +# The chosen rules use the Davies October 8 values for the start of DST in 1989 +# rather than the October 1 value. + +# From Paul Eggert (1995-12-19); +# Shanks reports 2:00 for all autumn changes in Australia and New Zealand. +# Robert Uzgalis writes that the New Zealand Daylight +# Savings Time Order in Council dated 1990-06-18 specifies 2:00 standard +# time on both the first Sunday in October and the third Sunday in March. +# As with Australia, we'll assume the tradition is 2:00s, not 2:00. +# +# From Paul Eggert (2003-05-26): +# The Department of Internal Affairs (DIA) maintains a brief history, +# as does Carol Squires; see tz-link.htm for the full references. +# Use these sources in preference to Shanks. +# +# For Chatham, IATA SSIM (1991/1999) gives the NZ rules but with +# transitions at 2:45 local standard time; this confirms that Chatham +# is always exactly 45 minutes ahead of Auckland. + +############################################################################### + + +# Fiji + +# Howse writes (p 153) that in 1879 the British governor of Fiji +# enacted an ordinance standardizing the islands on Antipodean Time +# instead of the American system (which was one day behind). + +# From Rives McDow (1998-10-08): +# Fiji will introduce DST effective 0200 local time, 1998-11-01 +# until 0300 local time 1999-02-28. Each year the DST period will +# be from the first Sunday in November until the last Sunday in February. + +# From Paul Eggert (2000-01-08): +# IATA SSIM (1999-09) says DST ends 0100 local time. Go with McDow. + +# From the BBC World Service (1998-10-31 11:32 UTC): +# The Fijiian government says the main reasons for the time change is to +# improve productivity and reduce road accidents. But correspondents say it +# also hopes the move will boost Fiji's ability to compete with other pacific +# islands in the effort to attract tourists to witness the dawning of the new +# millenium. + +# http://www.fiji.gov.fj/press/2000_09/2000_09_13-05.shtml (2000-09-13) +# reports that Fiji has discontinued DST. + +# Johnston + +# Johnston data is from usno1995. + + +# Kiribati + +# From Paul Eggert (1996-01-22): +# Today's _Wall Street Journal_ (page 1) reports that Kiribati +# ``declared it the same day throught the country as of Jan. 1, 1995'' +# as part of the competition to be first into the 21st century. + + +# Kwajalein + +# In comp.risks 14.87 (26 August 1993), Peter Neumann writes: +# I wonder what happened in Kwajalein, where there was NO Friday, +# 1993-08-20. Thursday night at midnight Kwajalein switched sides with +# respect to the International Date Line, to rejoin its fellow islands, +# going from 11:59 p.m. Thursday to 12:00 m. Saturday in a blink. + + +# N Mariana Is, Guam + +# Howse writes (p 153) ``The Spaniards, on the other hand, reached the +# Philippines and the Ladrones from America,'' and implies that the Ladrones +# (now called the Marianas) kept American date for quite some time. +# For now, we assume the Ladrones switched at the same time as the Philippines; +# see Asia/Manila. + +# US Public Law 106-564 (2000-12-23) made UTC+10 the official standard time, +# under the name "Chamorro Standard Time". There is no official abbreviation, +# but Congressman Robert A. Underwood, author of the bill that became law, +# wrote in a press release (2000-12-27) that he will seek the use of "ChST". + + +# Micronesia + +# Alan Eugene Davis writes (1996-03-16), +# ``I am certain, having lived there for the past decade, that "Truk" +# (now properly known as Chuuk) ... is in the time zone GMT+10.'' +# +# Shanks writes that Truk switched from UTC+10 to UTC+11 on 1978-10-01; +# ignore this for now. + +# From Paul Eggert (1999-10-29): +# The Federated States of Micronesia Visitors Board writes in +# +# The Federated States of Micronesia - Visitor Information +# (1999-01-26) +# that Truk and Yap are UTC+10, and Ponape and Kosrae are UTC+11. +# We don't know when Kosrae switched from UTC+12; assume January 1 for now. + + +# Midway + +# From Charles T O'Connor, KMTH DJ (1956), +# quoted in the KTMH section of the Radio Heritage Collection +# (2002-12-31): +# For the past two months we've been on what is known as Daylight +# Saving Time. This time has put us on air at 5am in the morning, +# your time down there in New Zealand. Starting September 2, 1956 +# we'll again go back to Standard Time. This'll mean that we'll go to +# air at 6am your time. +# +# From Paul Eggert (2003-03-23): +# We don't know the date of that quote, but we'll guess they +# started DST on June 3. Possibly DST was observed other years +# in Midway, but we have no record of it. + + +# Pitcairn + +# From Rives McDow (1999-11-08): +# A Proclamation was signed by the Governor of Pitcairn on the 27th March 1998 +# with regard to Pitcairn Standard Time. The Proclamation is as follows. +# +# The local time for general purposes in the Islands shall be +# Co-ordinated Universal time minus 8 hours and shall be known +# as Pitcairn Standard Time. +# +# ... I have also seen Pitcairn listed as UTC minus 9 hours in several +# references, and can only assume that this was an error in interpretation +# somehow in light of this proclamation. + +# From Rives McDow (1999-11-09): +# The Proclamation regarding Pitcairn time came into effect on 27 April 1998 +# ... at midnight. + +# From Howie Phelps (1999-11-10), who talked to a Pitcairner via shortwave: +# Betty Christian told me yesterday that their local time is the same as +# Pacific Standard Time. They used to be 1/2 hour different from us here in +# Sacramento but it was changed a couple of years ago. + + +# Samoa + +# Howse writes (p 153, citing p 10 of the 1883-11-18 New York Herald) +# that in 1879 the King of Samoa decided to change +# ``the date in his kingdom from the Antipodean to the American system, +# ordaining -- by a masterpiece of diplomatic flattery -- that +# the Fourth of July should be celebrated twice in that year.'' + + +# Tonga + +# From Paul Eggert (1996-01-22): +# Today's _Wall Street Journal_ (p 1) reports that ``Tonga has been plotting +# to sneak ahead of [New Zealanders] by introducing daylight-saving time.'' +# Since Kiribati has moved the Date Line it's not clear what Tonga will do. + +# Don Mundell writes in the 1997-02-20 Tonga Chronicle +# +# How Tonga became `The Land where Time Begins' +# : + +# Until 1941 Tonga maintained a standard time 50 minutes ahead of NZST +# 12 hours and 20 minutes ahead of GMT. When New Zealand adjusted its +# standard time in 1940s, Tonga had the choice of subtracting from its +# local time to come on the same standard time as New Zealand or of +# advancing its time to maintain the differential of 13 degrees +# (approximately 50 minutes ahead of New Zealand time). +# +# Because His Majesty King Taufa'ahau Tupou IV, then Crown Prince +# Tungi, preferred to ensure Tonga's title as the land where time +# begins, the Legislative Assembly approved the latter change. +# +# But some of the older, more conservative members from the outer +# islands objected. "If at midnight on Dec. 31, we move ahead 40 +# minutes, as your Royal Highness wishes, what becomes of the 40 +# minutes we have lost?" +# +# The Crown Prince, presented an unanswerable argument: "Remember that +# on the World Day of Prayer, you would be the first people on Earth +# to say your prayers in the morning." + +# From Paul Eggert (1999-08-12): +# Shanks says the transition was on 1968-10-01; go with Mundell. + +# From Eric Ulevik (1999-05-03): +# Tonga's director of tourism, who is also secretary of the National Millenium +# Committee, has a plan to get Tonga back in front. +# He has proposed a one-off move to tropical daylight saving for Tonga from +# October to March, which has won approval in principle from the Tongan +# Government. + +# From Steffen Thorsen [straen@thorsen.priv.no] (1999-09-09): +# * Tonga will introduce DST in November +# +# I was given this link by John Letts : +# +# http://news.bbc.co.uk/hi/english/world/asia-pacific/newsid_424000/424764.stm +# +# +# I have not been able to find exact dates for the transition in November +# yet. By reading this article it seems like Fiji will be 14 hours ahead +# of UTC as well, but as far as I know Fiji will only be 13 hours ahead +# (12 + 1 hour DST). + +# From Arthur David Olson [arthur_david_olson@nih.gov] (1999-09-20): +# According to (1999-10-29): +# A good source for time zone historical data outside the U.S. is +# Thomas G. Shanks, The International Atlas (5th edition), +# San Diego: ACS Publications, Inc. (1999). +# +# Gwillim Law writes that a good source +# for recent time zone data is the International Air Transport +# Association's Standard Schedules Information Manual (IATA SSIM), +# published semiannually. Law sent in several helpful summaries +# of the IATA's data after 1990. +# +# Except where otherwise noted, Shanks is the source for entries through 1991, +# and IATA SSIM is the source for entries afterwards. +# +# Other sources occasionally used include: +# +# Edward W. Whitman, World Time Differences, +# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), +# which I found in the UCLA library. +# +# +# William Willett, The Waste of Daylight, 19th edition +# (1914-03) +# +# Brazil's Departamento Servico da Hora (DSH), +# +# History of Summer Time +# (1998-09-21, in Portuguese) + +# +# I invented the abbreviations marked `*' in the following table; +# the rest are from earlier versions of this file, or from other sources. +# Corrections are welcome! +# std dst 2dst +# LMT Local Mean Time +# -4:00 AST ADT Atlantic +# -3:00 WGT WGST Western Greenland* +# -1:00 EGT EGST Eastern Greenland* +# 0:00 GMT BST BDST Greenwich, British Summer +# 0:00 GMT IST Greenwich, Irish Summer +# 0:00 WET WEST WEMT Western Europe +# 0:19:32.13 AMT NST Amsterdam, Netherlands Summer (1835-1937)* +# 0:20 NET NEST Netherlands (1937-1940)* +# 1:00 CET CEST CEMT Central Europe +# 1:00:14 SET Swedish (1879-1899)* +# 2:00 EET EEST Eastern Europe +# 3:00 MSK MSD Moscow +# +# A reliable and entertaining source about time zones, especially in Britain, +# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997). + +# From Peter Ilieve (1994-12-04), +# The original six [EU members]: Belgium, France, (West) Germany, Italy, +# Luxembourg, the Netherlands. +# Plus, from 1 Jan 73: Denmark, Ireland, United Kingdom. +# Plus, from 1 Jan 81: Greece. +# Plus, from 1 Jan 86: Spain, Portugal. +# Plus, from 1 Jan 95: Austria, Finland, Sweden. (Norway negotiated terms for +# entry but in a referendum on 28 Nov 94 the people voted No by 52.2% to 47.8% +# on a turnout of 88.6%. This was almost the same result as Norway's previous +# referendum in 1972, they are the only country to have said No twice. +# Referendums in the other three countries voted Yes.) +# ... +# Estonia ... uses EU dates but not at 01:00 GMT, they use midnight GMT. +# I don't think they know yet what they will do from 1996 onwards. +# ... +# There shouldn't be any [current members who are not using EU rules]. +# A Directive has the force of law, member states are obliged to enact +# national law to implement it. The only contentious issue was the +# different end date for the UK and Ireland, and this was always allowed +# in the Directive. + + +############################################################################### + +# Britain (United Kingdom) and Ireland (Eire) + +# From Peter Ilieve (1994-07-06): +# +# On 17 Jan 1994 the Independent, a UK quality newspaper, had a piece about +# historical vistas along the Thames in west London. There was a photo +# and a sketch map showing some of the sightlines involved. One paragraph +# of the text said: +# +# `An old stone obelisk marking a forgotten terrestrial meridian stands +# beside the river at Kew. In the 18th century, before time and longitude +# was standardised by the Royal Observatory in Greenwich, scholars observed +# this stone and the movement of stars from Kew Observatory nearby. They +# made their calculations and set the time for the Horse Guards and Parliament, +# but now the stone is obscured by scrubwood and can only be seen by walking +# along the towpath within a few yards of it.' +# +# I have a one inch to one mile map of London and my estimate of the stone's +# position is 51 deg. 28' 30" N, 0 deg. 18' 45" W. The longitude should +# be within about +-2". The Ordnance Survey grid reference is TQ172761. +# +# [This yields GMTOFF = -0:01:15 for London LMT in the 18th century.] + +# From Paul Eggert (1993-11-18): +# +# Howse writes that Britain was the first country to use standard time. +# The railways cared most about the inconsistencies of local mean time, +# and it was they who forced a uniform time on the country. +# The original idea was credited to Dr. William Hyde Wollaston (1766-1828) +# and was popularized by Abraham Follett Osler (1808-1903). +# The first railway to adopt London time was the Great Western Railway +# in November 1840; other railways followed suit, and by 1847 most +# (though not all) railways used London time. On 1847-09-22 the +# Railway Clearing House, an industry standards body, recommended that GMT be +# adopted at all stations as soon as the General Post Office permitted it. +# The transition occurred on 12-01 for the L&NW, the Caledonian, +# and presumably other railways; the January 1848 Bradshaw's lists many +# railways as using GMT. By 1855 the vast majority of public +# clocks in Britain were set to GMT (though some, like the great clock +# on Tom Tower at Christ Church, Oxford, were fitted with two minute hands, +# one for local time and one for GMT). The last major holdout was the legal +# system, which stubbornly stuck to local time for many years, leading +# to oddities like polls opening at 08:13 and closing at 16:13. +# The legal system finally switched to GMT when the Statutes (Definition +# of Time) Act took effect; it received the Royal Assent on 1880-08-02. +# +# In the tables below, we condense this complicated story into a single +# transition date for London, namely 1847-12-01. We don't know as much +# about Dublin, so we use 1880-08-02, the legal transition time. + +# From Paul Eggert (2003-09-27): +# Summer Time was first seriously proposed by William Willett (1857-1915), +# a London builder and member of the Royal Astronomical Society +# who circulated a pamphlet ``The Waste of Daylight'' (1907) +# that proposed advancing clocks 20 minutes on each of four Sundays in April, +# and retarding them by the same amount on four Sundays in September. +# A bill was drafted in 1909 and introduced in Parliament several times, +# but it met with ridicule and opposition, especially from farming interests. +# Later editions of the pamphlet proposed one-hour summer time, and +# it was eventually adopted as a wartime measure in 1916. +# See: Summer Time Arrives Early, The Times (2000-05-18). +# A monument to Willett was unveiled on 1927-05-21, in an open space in +# a 45-acre wood near Chislehurst, Kent that was purchased by popular +# subscription and open to the public. On the south face of the monolith, +# designed by G. W. Miller, is the the William Willett Memorial Sundial, +# which is permanently set to Summer Time. + +# From Winston Churchill (1934-04-28): +# It is one of the paradoxes of history that we should owe the boon of +# summer time, which gives every year to the people of this country +# between 160 and 170 hours more daylight leisure, to a war which +# plunged Europe into darkness for four years, and shook the +# foundations of civilization throughout the world. +# -- +# "A Silent Toast to William Willett", Pictorial Weekly +# + +# From Paul Eggert (1996-09-03): +# The OED Supplement says that the English originally said ``Daylight Saving'' +# when they were debating the adoption of DST in 1908; but by 1916 this +# term appears only in quotes taken from DST's opponents, whereas the +# proponents (who eventually won the argument) are quoted as using ``Summer''. + +# From Arthur David Olson (1989-01-19): +# +# A source at the British Information Office in New York avers that it's +# known as "British" Summer Time in all parts of the United Kingdom. + +# Date: 4 Jan 89 08:57:25 GMT (Wed) +# From: Jonathan Leffler +# [British Summer Time] is fixed annually by Act of Parliament. +# If you can predict what Parliament will do, you should be in +# politics making a fortune, not computing. + +# From Chris Carrier <72157.3334@CompuServe.COM> (1996-06-14): +# I remember reading in various wartime issues of the London Times the +# acronym BDST for British Double Summer Time. Look for the published +# time of sunrise and sunset in The Times, when BDST was in effect, and +# if you find a zone reference it will say, "All times B.D.S.T." + +# From Joseph S. Myers (1999-09-02): +# ... some military cables (WO 219/4100 - this is a copy from the +# main SHAEF archives held in the US National Archives, SHAEF/5252/8/516) +# agree that the usage is BDST (this appears in a message dated 17 Feb 1945). + +# From Joseph S. Myers (2000-10-03): +# On 18th April 1941, Sir Stephen Tallents of the BBC wrote to Sir +# Alexander Maxwell of the Home Office asking whether there was any +# official designation; the reply of the 21st was that there wasn't +# but he couldn't think of anything better than the "Double British +# Summer Time" that the BBC had been using informally. +# http://student.cusu.cam.ac.uk/~jsm28/british-time/bbc-19410418.png +# http://student.cusu.cam.ac.uk/~jsm28/british-time/ho-19410421.png + +# From Sir Alexander Maxwell in the above-mentioned letter (1941-04-21): +# [N]o official designation has as far as I know been adopted for the time +# which is to be introduced in May.... +# I cannot think of anything better than "Double British Summer Time" +# which could not be said to run counter to any official description. + +# From Paul Eggert (2000-10-02): +# Howse writes (p 157) `DBST' too, but `BDST' seems to have been common +# and follows the more usual convention of putting the location name first, +# so we use `BDST'. + +# Peter Ilieve (1998-04-19) described at length +# the history of summer time legislation in the United Kingdom. +# Since 1998 Joseph S. Myers has been updating +# and extending this list, which can be found in +# +# History of legal time in Britain +# + +# From Joseph S. Myers (1998-01-06): +# +# The legal time in the UK outside of summer time is definitely GMT, not UTC; +# see Lord Tanlaw's speech +# +# (Lords Hansard 11 June 1997 columns 964 to 976) +# . + +# From Paul Eggert (2001-07-18): +# +# For lack of other data, we'll follow Shanks for Eire in 1940-1948. +# +# Given Ilieve and Myers's data, the following claims by Shanks are incorrect: +# * Wales did not switch from GMT to daylight saving time until +# 1921 Apr 3, when they began to conform with the rest of Great Britain. +# Actually, Wales was identical after 1880. +# * Eire had two transitions on 1916 Oct 1. +# It actually just had one transition. +# * Northern Ireland used single daylight saving time throughout WW II. +# Actually, it conformed to Britain. +# * GB-Eire changed standard time to 1 hour ahead of GMT on 1968-02-18. +# Actually, that date saw the usual switch to summer time. +# Standard time was not changed until 1968-10-27 (the clocks didn't change). +# +# Here is another incorrect claim by Shanks: +# * Jersey, Guernsey, and the Isle of Man did not switch from GMT +# to daylight saving time until 1921 Apr 3, when they began to +# conform with Great Britain. +# S.R.&O. 1916, No. 382 and HO 45/10811/312364 (quoted above) say otherwise. +# +# The following claim by Shanks is possible though doubtful; +# we'll ignore it for now. +# * Dublin's 1971-10-31 switch was at 02:00, even though London's was 03:00. +# +# +# Whitman says Dublin Mean Time was -0:25:21, which is more precise than Shanks. +# Perhaps this was Dunsink Observatory Time, as Dunsink Observatory +# (8 km NW of Dublin's center) seemingly was to Dublin as Greenwich was +# to London. For example: +# +# "Timeball on the ballast office is down. Dunsink time." +# -- James Joyce, Ulysses + +# From Paul Eggert (1999-03-28): +# Clive Feather (, 1997-03-31) +# reports that Folkestone (Cheriton) Shuttle Terminal uses Concession Time +# (CT), equivalent to French civil time. +# Julian Hill (, 1998-09-30) reports that +# trains between Dollands Moor (the freight facility next door) +# and Frethun run in CT. +# My admittedly uninformed guess is that the terminal has two authorities, +# the French concession operators and the British civil authorities, +# and that the time depends on who you're talking to. +# If, say, the British police were called to the station for some reason, +# I would expect the official police report to use GMT/BST and not CET/CEST. +# This is a borderline case, but for now let's stick to GMT/BST. + +# From an anonymous contributor (1996-06-02): +# The law governing time in Ireland is under Statutory Instrument SI 395/94, +# which gives force to European Union 7th Council Directive # 94/21/EC. +# Under this directive, the Minister for Justice in Ireland makes appropriate +# regulations. I spoke this morning with the Secretary of the Department of +# Justice (tel +353 1 678 9711) who confirmed to me that the correct name is +# "Irish Summer Time", abbreviated to "IST". + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# Summer Time Act, 1916 +Rule GB-Eire 1916 only - May 21 2:00s 1:00 BST +Rule GB-Eire 1916 only - Oct 1 2:00s 0 GMT +# S.R.&O. 1917, No. 358 +Rule GB-Eire 1917 only - Apr 8 2:00s 1:00 BST +Rule GB-Eire 1917 only - Sep 17 2:00s 0 GMT +# S.R.&O. 1918, No. 274 +Rule GB-Eire 1918 only - Mar 24 2:00s 1:00 BST +Rule GB-Eire 1918 only - Sep 30 2:00s 0 GMT +# S.R.&O. 1919, No. 297 +Rule GB-Eire 1919 only - Mar 30 2:00s 1:00 BST +Rule GB-Eire 1919 only - Sep 29 2:00s 0 GMT +# S.R.&O. 1920, No. 458 +Rule GB-Eire 1920 only - Mar 28 2:00s 1:00 BST +# S.R.&O. 1920, No. 1844 +Rule GB-Eire 1920 only - Oct 25 2:00s 0 GMT +# S.R.&O. 1921, No. 363 +Rule GB-Eire 1921 only - Apr 3 2:00s 1:00 BST +Rule GB-Eire 1921 only - Oct 3 2:00s 0 GMT +# S.R.&O. 1922, No. 264 +Rule GB-Eire 1922 only - Mar 26 2:00s 1:00 BST +Rule GB-Eire 1922 only - Oct 8 2:00s 0 GMT +# The Summer Time Act, 1922 +Rule GB-Eire 1923 only - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1923 1924 - Sep Sun>=16 2:00s 0 GMT +Rule GB-Eire 1924 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1925 1926 - Apr Sun>=16 2:00s 1:00 BST +# The Summer Time Act, 1925 +Rule GB-Eire 1925 1938 - Oct Sun>=2 2:00s 0 GMT +Rule GB-Eire 1927 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1928 1929 - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1930 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1931 1932 - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1933 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1934 only - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1935 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1936 1937 - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1938 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1939 only - Apr Sun>=16 2:00s 1:00 BST +# S.R.&O. 1939, No. 1379 +Rule GB-Eire 1939 only - Nov Sun>=16 2:00s 0 GMT +# S.R.&O. 1940, No. 172 and No. 1883 +Rule GB-Eire 1940 only - Feb Sun>=23 2:00s 1:00 BST +# S.R.&O. 1941, No. 476 +Rule GB-Eire 1941 only - May Sun>=2 1:00s 2:00 BDST +Rule GB-Eire 1941 1943 - Aug Sun>=9 1:00s 1:00 BST +# S.R.&O. 1942, No. 506 +Rule GB-Eire 1942 1944 - Apr Sun>=2 1:00s 2:00 BDST +# S.R.&O. 1944, No. 932 +Rule GB-Eire 1944 only - Sep Sun>=16 1:00s 1:00 BST +# S.R.&O. 1945, No. 312 +Rule GB-Eire 1945 only - Apr Mon>=2 1:00s 2:00 BDST +Rule GB-Eire 1945 only - Jul Sun>=9 1:00s 1:00 BST +# S.R.&O. 1945, No. 1208 +Rule GB-Eire 1945 1946 - Oct Sun>=2 2:00s 0 GMT +Rule GB-Eire 1946 only - Apr Sun>=9 2:00s 1:00 BST +# The Summer Time Act, 1947 +Rule GB-Eire 1947 only - Mar 16 2:00s 1:00 BST +Rule GB-Eire 1947 only - Apr 13 1:00s 2:00 BDST +Rule GB-Eire 1947 only - Aug 10 1:00s 1:00 BST +Rule GB-Eire 1947 only - Nov 2 2:00s 0 GMT +# Summer Time Order, 1948 (S.I. 1948/495) +Rule GB-Eire 1948 only - Mar 14 2:00s 1:00 BST +Rule GB-Eire 1948 only - Oct 31 2:00s 0 GMT +# Summer Time Order, 1949 (S.I. 1949/373) +Rule GB-Eire 1949 only - Apr 3 2:00s 1:00 BST +Rule GB-Eire 1949 only - Oct 30 2:00s 0 GMT +# Summer Time Order, 1950 (S.I. 1950/518) +# Summer Time Order, 1951 (S.I. 1951/430) +# Summer Time Order, 1952 (S.I. 1952/451) +Rule GB-Eire 1950 1952 - Apr Sun>=14 2:00s 1:00 BST +Rule GB-Eire 1950 1952 - Oct Sun>=21 2:00s 0 GMT +# revert to the rules of the Summer Time Act, 1925 +Rule GB-Eire 1953 only - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1953 1960 - Oct Sun>=2 2:00s 0 GMT +Rule GB-Eire 1954 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1955 1956 - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1957 only - Apr Sun>=9 2:00s 1:00 BST +Rule GB-Eire 1958 1959 - Apr Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1960 only - Apr Sun>=9 2:00s 1:00 BST +# Summer Time Order, 1961 (S.I. 1961/71) +# Summer Time (1962) Order, 1961 (S.I. 1961/2465) +# Summer Time Order, 1963 (S.I. 1963/81) +Rule GB-Eire 1961 1963 - Mar lastSun 2:00s 1:00 BST +Rule GB-Eire 1961 1968 - Oct Sun>=23 2:00s 0 GMT +# Summer Time (1964) Order, 1963 (S.I. 1963/2101) +# Summer Time Order, 1964 (S.I. 1964/1201) +# Summer Time Order, 1967 (S.I. 1967/1148) +Rule GB-Eire 1964 1967 - Mar Sun>=19 2:00s 1:00 BST +# Summer Time Order, 1968 (S.I. 1968/117) +Rule GB-Eire 1968 only - Feb 18 2:00s 1:00 BST +# The British Standard Time Act, 1968 +# (no summer time) +# The Summer Time Act, 1972 +Rule GB-Eire 1972 1980 - Mar Sun>=16 2:00s 1:00 BST +Rule GB-Eire 1972 1980 - Oct Sun>=23 2:00s 0 GMT +# Summer Time Order, 1980 (S.I. 1980/1089) +# Summer Time Order, 1982 (S.I. 1982/1673) +# Summer Time Order, 1986 (S.I. 1986/223) +# Summer Time Order, 1988 (S.I. 1988/931) +Rule GB-Eire 1981 1995 - Mar lastSun 1:00u 1:00 BST +Rule GB-Eire 1981 1989 - Oct Sun>=23 1:00u 0 GMT +# Summer Time Order, 1989 (S.I. 1989/985) +# Summer Time Order, 1992 (S.I. 1992/1729) +# Summer Time Order 1994 (S.I. 1994/2798) +Rule GB-Eire 1990 1995 - Oct Sun>=22 1:00u 0 GMT +# Summer Time Order 1997 (S.I. 1997/2982) +# See EU for rules starting in 1996. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/London -0:01:15 - LMT 1847 Dec 1 + 0:00 GB-Eire %s 1968 Oct 27 + 1:00 - BST 1971 Oct 31 2:00u + 0:00 GB-Eire %s 1996 + 0:00 EU GMT/BST +Zone Europe/Belfast -0:23:40 - LMT 1880 Aug 2 + -0:25:21 - DMT 1916 May 21 2:00 # Dublin/Dunsink MT + -0:25:21 1:00 IST 1916 Oct 1 2:00s # Irish Summer Time + 0:00 GB-Eire %s 1968 Oct 27 + 1:00 - BST 1971 Oct 31 2:00u + 0:00 GB-Eire %s 1996 + 0:00 EU GMT/BST +Zone Europe/Dublin -0:25:00 - LMT 1880 Aug 2 + -0:25:21 - DMT 1916 May 21 2:00 + -0:25:21 1:00 IST 1916 Oct 1 2:00s + 0:00 GB-Eire %s 1921 Dec 6 # independence + 0:00 GB-Eire GMT/IST 1940 Feb 25 2:00 + 0:00 1:00 IST 1946 Oct 6 2:00 + 0:00 - GMT 1947 Mar 16 2:00 + 0:00 1:00 IST 1947 Nov 2 2:00 + 0:00 - GMT 1948 Apr 18 2:00 + 0:00 GB-Eire GMT/IST 1968 Oct 27 + 1:00 - IST 1971 Oct 31 2:00u + 0:00 GB-Eire GMT/IST 1996 + 0:00 EU GMT/IST + +############################################################################### + +# Continental Europe + +# EU rules are for the European Union, previously known as the EC, EEC, +# Common Market, etc. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule EU 1977 1980 - Apr Sun>=1 1:00u 1:00 S +Rule EU 1977 only - Sep lastSun 1:00u 0 - +Rule EU 1978 only - Oct 1 1:00u 0 - +Rule EU 1979 1995 - Sep lastSun 1:00u 0 - +Rule EU 1981 max - Mar lastSun 1:00u 1:00 S +Rule EU 1996 max - Oct lastSun 1:00u 0 - +# The most recent directive covers the years starting in 2002. See: +# + +# W-Eur differs from EU only in that W-Eur uses standard time. +Rule W-Eur 1977 1980 - Apr Sun>=1 1:00s 1:00 S +Rule W-Eur 1977 only - Sep lastSun 1:00s 0 - +Rule W-Eur 1978 only - Oct 1 1:00s 0 - +Rule W-Eur 1979 1995 - Sep lastSun 1:00s 0 - +Rule W-Eur 1981 max - Mar lastSun 1:00s 1:00 S +Rule W-Eur 1996 max - Oct lastSun 1:00s 0 - + +# Older C-Eur rules are for convenience in the tables. +# From 1977 on, C-Eur differs from EU only in that C-Eur uses standard time. +Rule C-Eur 1916 only - Apr 30 23:00 1:00 S +Rule C-Eur 1916 only - Oct 1 1:00 0 - +Rule C-Eur 1917 1918 - Apr Mon>=15 2:00s 1:00 S +Rule C-Eur 1917 1918 - Sep Mon>=15 2:00s 0 - +Rule C-Eur 1940 only - Apr 1 2:00s 1:00 S +Rule C-Eur 1942 only - Nov 2 2:00s 0 - +Rule C-Eur 1943 only - Mar 29 2:00s 1:00 S +Rule C-Eur 1943 only - Oct 4 2:00s 0 - +Rule C-Eur 1944 only - Apr 3 2:00s 1:00 S +# Whitman gives 1944 Oct 7; go with Shanks. +Rule C-Eur 1944 only - Oct 2 2:00s 0 - +Rule C-Eur 1977 1980 - Apr Sun>=1 2:00s 1:00 S +Rule C-Eur 1977 only - Sep lastSun 2:00s 0 - +Rule C-Eur 1978 only - Oct 1 2:00s 0 - +Rule C-Eur 1979 1995 - Sep lastSun 2:00s 0 - +Rule C-Eur 1981 max - Mar lastSun 2:00s 1:00 S +Rule C-Eur 1996 max - Oct lastSun 2:00s 0 - + +# E-Eur differs from EU only in that E-Eur switches at midnight local time. +Rule E-Eur 1977 1980 - Apr Sun>=1 0:00 1:00 S +Rule E-Eur 1977 only - Sep lastSun 0:00 0 - +Rule E-Eur 1978 only - Oct 1 0:00 0 - +Rule E-Eur 1979 1995 - Sep lastSun 0:00 0 - +Rule E-Eur 1981 max - Mar lastSun 0:00 1:00 S +Rule E-Eur 1996 max - Oct lastSun 0:00 0 - + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Russia 1917 only - Jul 1 23:00 1:00 MST # Moscow Summer Time +Rule Russia 1917 only - Dec 28 0:00 0 MMT # Moscow Mean Time +Rule Russia 1918 only - May 31 22:00 2:00 MDST # Moscow Double Summer Time +Rule Russia 1918 only - Sep 16 1:00 1:00 MST +Rule Russia 1919 only - May 31 23:00 2:00 MDST +Rule Russia 1919 only - Jul 1 2:00 1:00 S +Rule Russia 1919 only - Aug 16 0:00 0 - +Rule Russia 1921 only - Feb 14 23:00 1:00 S +Rule Russia 1921 only - Mar 20 23:00 2:00 M # Midsummer +Rule Russia 1921 only - Sep 1 0:00 1:00 S +Rule Russia 1921 only - Oct 1 0:00 0 - +# Act No.925 of the Council of Ministers of the USSR (1980-10-24): +Rule Russia 1981 1984 - Apr 1 0:00 1:00 S +Rule Russia 1981 1983 - Oct 1 0:00 0 - +# Act No.967 of the Council of Ministers of the USSR (1984-09-13), repeated in +# Act No.227 of the Council of Ministers of the USSR (1989-03-14): +Rule Russia 1984 1991 - Sep lastSun 2:00s 0 - +Rule Russia 1985 1991 - Mar lastSun 2:00s 1:00 S +# +Rule Russia 1992 only - Mar lastSat 23:00 1:00 S +Rule Russia 1992 only - Sep lastSat 23:00 0 - +Rule Russia 1993 max - Mar lastSun 2:00s 1:00 S +Rule Russia 1993 1995 - Sep lastSun 2:00s 0 - +Rule Russia 1996 max - Oct lastSun 2:00s 0 - + +# These are for backward compatibility with older versions. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone WET 0:00 EU WE%sT +Zone CET 1:00 C-Eur CE%sT +Zone MET 1:00 C-Eur ME%sT +Zone EET 2:00 EU EE%sT + +# Previous editions of this database used abbreviations like MET DST +# for Central European Summer Time, but this didn't agree with common usage. + +# From Markus Kuhn (1996-07-12): +# The official German names ... are +# +# Mitteleuropaeische Zeit (MEZ) = UTC+01:00 +# Mitteleuropaeische Sommerzeit (MESZ) = UTC+02:00 +# +# as defined in the German Time Act (Gesetz ueber die Zeitbestimmung (ZeitG), +# 1978-07-25, Bundesgesetzblatt, Jahrgang 1978, Teil I, S. 1110-1111).... +# I wrote ... to the German Federal Physical-Technical Institution +# +# Physikalisch-Technische Bundesanstalt (PTB) +# Laboratorium 4.41 "Zeiteinheit" +# Postfach 3345 +# D-38023 Braunschweig +# phone: +49 531 592-0 +# +# ... I received today an answer letter from Dr. Peter Hetzel, head of the PTB +# department for time and frequency transmission. He explained that the +# PTB translates MEZ and MESZ into English as +# +# Central European Time (CET) = UTC+01:00 +# Central European Summer Time (CEST) = UTC+02:00 + + +# Albania +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Albania 1940 only - Jun 16 0:00 1:00 S +Rule Albania 1942 only - Nov 2 3:00 0 - +Rule Albania 1943 only - Mar 29 2:00 1:00 S +Rule Albania 1943 only - Apr 10 3:00 0 - +Rule Albania 1974 only - May 4 0:00 1:00 S +Rule Albania 1974 only - Oct 2 0:00 0 - +Rule Albania 1975 only - May 1 0:00 1:00 S +Rule Albania 1975 only - Oct 2 0:00 0 - +Rule Albania 1976 only - May 2 0:00 1:00 S +Rule Albania 1976 only - Oct 3 0:00 0 - +Rule Albania 1977 only - May 8 0:00 1:00 S +Rule Albania 1977 only - Oct 2 0:00 0 - +Rule Albania 1978 only - May 6 0:00 1:00 S +Rule Albania 1978 only - Oct 1 0:00 0 - +Rule Albania 1979 only - May 5 0:00 1:00 S +Rule Albania 1979 only - Sep 30 0:00 0 - +Rule Albania 1980 only - May 3 0:00 1:00 S +Rule Albania 1980 only - Oct 4 0:00 0 - +Rule Albania 1981 only - Apr 26 0:00 1:00 S +Rule Albania 1981 only - Sep 27 0:00 0 - +Rule Albania 1982 only - May 2 0:00 1:00 S +Rule Albania 1982 only - Oct 3 0:00 0 - +Rule Albania 1983 only - Apr 18 0:00 1:00 S +Rule Albania 1983 only - Oct 1 0:00 0 - +Rule Albania 1984 only - Apr 1 0:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Tirane 1:19:20 - LMT 1914 + 1:00 - CET 1940 Jun 16 + 1:00 Albania CE%sT 1984 Jul + 1:00 EU CE%sT + +# Andorra +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Andorra 0:06:04 - LMT 1901 + 0:00 - WET 1946 Sep 30 + 1:00 - CET 1985 Mar 31 2:00 + 1:00 EU CE%sT + +# Austria + +# From Paul Eggert (2003-02-28): Shanks gives 1918-06-16 and +# 1945-11-18, but the Austrian Federal Office of Metrology and +# Surveying (BEV) gives 1918-09-16 and for Vienna gives the "alleged" +# date of 1945-04-12 with no time. For the 1980-04-06 transition +# Shanks gives 02:00, the BEV 00:00. Go with the BEV, and guess 02:00 +# for 1945-04-12. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Austria 1920 only - Apr 5 2:00s 1:00 S +Rule Austria 1920 only - Sep 13 2:00s 0 - +Rule Austria 1946 only - Apr 14 2:00s 1:00 S +Rule Austria 1946 1948 - Oct Sun>=1 2:00s 0 - +Rule Austria 1947 only - Apr 6 2:00s 1:00 S +Rule Austria 1948 only - Apr 18 2:00s 1:00 S +Rule Austria 1980 only - Apr 6 0:00 1:00 S +Rule Austria 1980 only - Sep 28 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Vienna 1:05:20 - LMT 1893 Apr + 1:00 C-Eur CE%sT 1920 + 1:00 Austria CE%sT 1940 Apr 1 2:00s + 1:00 C-Eur CE%sT 1945 Apr 2 2:00s + 1:00 1:00 CEST 1945 Apr 12 2:00s + 1:00 - CET 1946 + 1:00 Austria CE%sT 1981 + 1:00 EU CE%sT + +# Belarus +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Minsk 1:50:16 - LMT 1880 + 1:50 - MMT 1924 May 2 # Minsk Mean Time + 2:00 - EET 1930 Jun 21 + 3:00 - MSK 1941 Jun 28 + 1:00 C-Eur CE%sT 1944 Jul 3 + 3:00 Russia MSK/MSD 1990 + 3:00 - MSK 1991 Mar 31 2:00s + 2:00 1:00 EEST 1991 Sep 29 2:00s + 2:00 - EET 1992 Mar 29 0:00s + 2:00 1:00 EEST 1992 Sep 27 0:00s + 2:00 Russia EE%sT + +# Belgium +# +# From Paul Eggert (1997-07-02): +# Entries from 1918 through 1991 are taken from: +# Annuaire de L'Observatoire Royal de Belgique, +# Avenue Circulaire, 3, B-1180 BRUXELLES, CLVIIe annee, 1991 +# (Imprimerie HAYEZ, s.p.r.l., Rue Fin, 4, 1080 BRUXELLES, MCMXC), +# pp 8-9. +# LMT before 1892 was 0:17:30, according to the official journal of Belgium: +# Moniteur Belge, Samedi 30 Avril 1892, N.121. +# Thanks to Pascal Delmoitie for these references. +# The 1918 rules are listed for completeness; they apply to unoccupied Belgium. +# Assume Brussels switched to WET in 1918 when the armistice took effect. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Belgium 1918 only - Mar 9 0:00s 1:00 S +Rule Belgium 1918 1919 - Oct Sat>=1 23:00s 0 - +Rule Belgium 1919 only - Mar 1 23:00s 1:00 S +Rule Belgium 1920 only - Feb 14 23:00s 1:00 S +Rule Belgium 1920 only - Oct 23 23:00s 0 - +Rule Belgium 1921 only - Mar 14 23:00s 1:00 S +Rule Belgium 1921 only - Oct 25 23:00s 0 - +Rule Belgium 1922 only - Mar 25 23:00s 1:00 S +Rule Belgium 1922 1927 - Oct Sat>=1 23:00s 0 - +Rule Belgium 1923 only - Apr 21 23:00s 1:00 S +Rule Belgium 1924 only - Mar 29 23:00s 1:00 S +Rule Belgium 1925 only - Apr 4 23:00s 1:00 S +# DSH writes that a royal decree of 1926-02-22 specified the Sun following 3rd +# Sat in Apr (except if it's Easter, in which case it's one Sunday earlier), +# to Sun following 1st Sat in Oct, and that a royal decree of 1928-09-15 +# changed the transition times to 02:00 GMT. +Rule Belgium 1926 only - Apr 17 23:00s 1:00 S +Rule Belgium 1927 only - Apr 9 23:00s 1:00 S +Rule Belgium 1928 only - Apr 14 23:00s 1:00 S +Rule Belgium 1928 1938 - Oct Sun>=2 2:00s 0 - +Rule Belgium 1929 only - Apr 21 2:00s 1:00 S +Rule Belgium 1930 only - Apr 13 2:00s 1:00 S +Rule Belgium 1931 only - Apr 19 2:00s 1:00 S +Rule Belgium 1932 only - Apr 3 2:00s 1:00 S +Rule Belgium 1933 only - Mar 26 2:00s 1:00 S +Rule Belgium 1934 only - Apr 8 2:00s 1:00 S +Rule Belgium 1935 only - Mar 31 2:00s 1:00 S +Rule Belgium 1936 only - Apr 19 2:00s 1:00 S +Rule Belgium 1937 only - Apr 4 2:00s 1:00 S +Rule Belgium 1938 only - Mar 27 2:00s 1:00 S +Rule Belgium 1939 only - Apr 16 2:00s 1:00 S +Rule Belgium 1939 only - Nov 19 2:00s 0 - +Rule Belgium 1940 only - Feb 25 2:00s 1:00 S +Rule Belgium 1944 only - Sep 17 2:00s 0 - +Rule Belgium 1945 only - Apr 2 2:00s 1:00 S +Rule Belgium 1945 only - Sep 16 2:00s 0 - +Rule Belgium 1946 only - May 19 2:00s 1:00 S +Rule Belgium 1946 only - Oct 7 2:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Brussels 0:17:30 - LMT 1880 + 0:17:30 - BMT 1892 May 1 12:00 # Brussels MT + 0:00 - WET 1914 Nov 8 + 1:00 - CET 1916 May 1 0:00 + 1:00 C-Eur CE%sT 1918 Nov 11 11:00u + 0:00 Belgium WE%sT 1940 May 20 2:00s + 1:00 C-Eur CE%sT 1944 Sep 3 + 1:00 Belgium CE%sT 1977 + 1:00 EU CE%sT + +# Bosnia and Herzegovina +# see Serbia and Montenegro + +# Bulgaria +# +# From Plamen Simenov via Steffen Thorsen (1999-09-09): +# A document of Government of Bulgaria (No.94/1997) says: +# EET --> EETDST is in 03:00 Local time in last Sunday of March ... +# EETDST --> EET is in 04:00 Local time in last Sunday of October +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Bulg 1979 only - Mar 31 23:00 1:00 S +Rule Bulg 1979 only - Oct 1 1:00 0 - +Rule Bulg 1980 1982 - Apr Sat<=7 23:00 1:00 S +Rule Bulg 1980 only - Sep 29 1:00 0 - +Rule Bulg 1981 only - Sep 27 2:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Sofia 1:33:16 - LMT 1880 + 1:56:56 - IMT 1894 Nov 30 # Istanbul MT? + 2:00 - EET 1942 Nov 2 3:00 + 1:00 C-Eur CE%sT 1945 Apr 2 3:00 + 2:00 - EET 1979 Mar 31 23:00 + 2:00 Bulg EE%sT 1982 Sep 26 2:00 + 2:00 C-Eur EE%sT 1991 + 2:00 E-Eur EE%sT 1997 + 2:00 EU EE%sT + +# Croatia +# see Serbia and Montenegro + +# Cyprus +# Please see the `asia' file for Asia/Nicosia. + +# Czech Republic +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Czech 1945 only - Apr 8 2:00s 1:00 S +Rule Czech 1945 only - Nov 18 2:00s 0 - +Rule Czech 1946 only - May 6 2:00s 1:00 S +Rule Czech 1946 1949 - Oct Sun>=1 2:00s 0 - +Rule Czech 1947 only - Apr 20 2:00s 1:00 S +Rule Czech 1948 only - Apr 18 2:00s 1:00 S +Rule Czech 1949 only - Apr 9 2:00s 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Prague 0:57:44 - LMT 1850 + 0:57:44 - PMT 1891 Oct # Prague Mean Time + 1:00 C-Eur CE%sT 1944 Sep 17 2:00s + 1:00 Czech CE%sT 1979 + 1:00 EU CE%sT + +# Denmark, Faeroe Islands, and Greenland +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Denmark 1916 only - May 14 23:00 1:00 S +Rule Denmark 1916 only - Sep 30 23:00 0 - +Rule Denmark 1940 only - May 15 0:00 1:00 S +Rule Denmark 1945 only - Apr 2 2:00s 1:00 S +Rule Denmark 1945 only - Aug 15 2:00s 0 - +Rule Denmark 1946 only - May 1 2:00s 1:00 S +Rule Denmark 1946 only - Sep 1 2:00s 0 - +Rule Denmark 1947 only - May 4 2:00s 1:00 S +Rule Denmark 1947 only - Aug 10 2:00s 0 - +Rule Denmark 1948 only - May 9 2:00s 1:00 S +Rule Denmark 1948 only - Aug 8 2:00s 0 - +# Whitman also gives 1949 Apr 9 to 1949 Oct 1, and disagrees in minor ways +# about many of the above dates; go with Shanks. +# +# For 1894, Shanks says Jan, Whitman Apr; go with Whitman. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Copenhagen 0:50:20 - LMT 1890 + 0:50:20 - CMT 1894 Apr # Copenhagen Mean Time + 1:00 Denmark CE%sT 1942 Nov 2 2:00s + 1:00 C-Eur CE%sT 1945 Apr 2 2:00 + 1:00 Denmark CE%sT 1980 + 1:00 EU CE%sT +Zone Atlantic/Faeroe -0:27:04 - LMT 1908 Jan 11 # Torshavn + 0:00 - WET 1981 + 0:00 EU WE%sT +# +# From Paul Eggert (1996-11-22): +# Greenland joined the EU as part of Denmark, obtained home rule on 1979-05-01, +# and left the EU on 1985-02-01. It therefore should have been using EU +# rules at least through 1984. Shanks says Scoresbysund and Godthab +# used C-Eur rules after 1980, but IATA SSIM (1991/1996) says they use EU +# rules since at least 1991. Assume EU rules since 1980. + +# From Gwillin Law (2001-06-06), citing +# (2001-03-15), +# and with translations corrected by Steffen Thorsen: +# +# Greenland has four local times, and the relation to UTC +# is according to the following time line: +# +# The military zone near Thule UTC-4 +# Standard Greenland time UTC-3 +# Scoresbysund UTC-1 +# Danmarkshavn UTC +# +# In the military area near Thule and in Danmarkshavn DST will not be +# introduced. + +# From Rives McDow (2001-11-01): +# +# I correspond regularly with the Dansk Polarcenter, and wrote them at +# the time to clarify the situation in Thule. Unfortunately, I have +# not heard back from them regarding my recent letter. [But I have +# info from earlier correspondence.] +# +# According to the center, a very small local time zone around Thule +# Air Base keeps the time according to UTC-4, implementing daylight +# savings using North America rules, changing the time at 02:00 local time.... +# +# The east coast of Greenland north of the community of Scoresbysund +# uses UTC in the same way as in Iceland, year round, with no dst. +# There are just a few stations on this coast, including the +# Danmarkshavn ICAO weather station mentioned in your September 29th +# email. The other stations are two sledge patrol stations in +# Mestersvig and Daneborg, the air force base at Station Nord, and the +# DPC research station at Zackenberg. +# +# Scoresbysund and two small villages nearby keep time UTC-1 and use +# the same daylight savings time period as in West Greenland (Godthab). +# +# The rest of Greenland, including Godthab (this area, although it +# includes central Greenland, is known as west Greenland), keeps time +# UTC-3, with daylight savings methods according to European rules. +# +# It is common procedure to use UTC 0 in the wilderness of East and +# North Greenland, because it is mainly Icelandic aircraft operators +# maintaining traffic in these areas. However, the official status of +# this area is that it sticks with Godthab time. This area might be +# considered a dual time zone in some respects because of this. + +# From Rives McDow (2001-11-19): +# I heard back from someone stationed at Thule; the time change took place +# there at 2:00 AM. + +# From Paul Eggert (2001-11-19): +# The 1997 CIA map shows Danmarkshavn on GMT; the 1995 map as like Godthab. +# For lack of better info, assume they were like Godthab before 1996. +# startkart.no says Thule does not observe DST, but this is clearly an error, +# so go with Shanks for all Thule transitions. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Thule 1991 1992 - Mar lastSun 2:00 1:00 D +Rule Thule 1991 1992 - Sep lastSun 2:00 0 S +Rule Thule 1993 max - Apr Sun>=1 2:00 1:00 D +Rule Thule 1993 max - Oct lastSun 2:00 0 S +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Danmarkshavn -1:14:40 - LMT 1916 Jul 28 + -3:00 - WGT 1980 Apr 6 2:00 + -3:00 EU WG%sT 1996 + 0:00 - GMT +Zone America/Scoresbysund -1:29:00 - LMT 1916 Jul 28 # Ittoqqortoormiit + -2:00 - CGT 1980 Apr 6 2:00 + -2:00 C-Eur CG%sT 1981 Mar 29 + -1:00 EU EG%sT +Zone America/Godthab -3:26:56 - LMT 1916 Jul 28 # Nuuk + -3:00 - WGT 1980 Apr 6 2:00 + -3:00 EU WG%sT +Zone America/Thule -4:35:08 - LMT 1916 Jul 28 # Pituffik air base + -4:00 Thule A%sT + +# Estonia +# From Peter Ilieve (1994-10-15): +# A relative in Tallinn confirms the accuracy of the data for 1989 onwards +# [through 1994] and gives the legal authority for it, +# a regulation of the Government of Estonia, No. 111 of 1989.... +# +# From Peter Ilieve (1996-10-28): +# [IATA SSIM (1992/1996) claims that the Baltic republics switch at 01:00s, +# but a relative confirms that Estonia still switches at 02:00s, writing:] +# ``I do not [know] exactly but there are some little different +# (confusing) rules for International Air and Railway Transport Schedules +# conversion in Sunday connected with end of summer time in Estonia.... +# A discussion is running about the summer time efficiency and effect on +# human physiology. It seems that Estonia maybe will not change to +# summer time next spring.'' + +# From Peter Ilieve (1998-11-04), heavily edited: +# +# The 1998-09-22 Estonian time law +# +# refers to the Eighth Directive and cites the association agreement between +# the EU and Estonia, ratified by the Estonian law (RT II 1995, 22--27, 120). +# +# I also asked [my relative] whether they use any standard abbreviation +# for their standard and summer times. He says no, they use "suveaeg" +# (summer time) and "talveaeg" (winter time). + +# From The Baltic Times (1999-09-09) +# via Steffen Thorsen: +# This year will mark the last time Estonia shifts to summer time, +# a council of the ruling coalition announced Sept. 6.... +# But what this could mean for Estonia's chances of joining the European +# Union are still unclear. In 1994, the EU declared summer time compulsory +# for all member states until 2001. Brussels has yet to decide what to do +# after that. + +# From Mart Oruaas (2000-01-29): +# Regulation no. 301 (1999-10-12) obsoletes previous regulation +# no. 206 (1998-09-22) and thus sticks Estonia to +02:00 GMT for all +# the year round. The regulation is effective 1999-11-01. + +# From Toomas Soome (2002-02-21): +# The Estonian government has changed once again timezone politics. +# Now we are using again EU rules. +# +# From Urmet Jaanes (2002-03-28): +# The legislative reference is Government decree No. 84 on 2002-02-21. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Tallinn 1:39:00 - LMT 1880 + 1:39:00 - TMT 1918 Feb # Tallinn Mean Time + 1:00 C-Eur CE%sT 1919 Jul + 1:39:00 - TMT 1921 May + 2:00 - EET 1940 Aug 6 + 3:00 - MSK 1941 Sep 15 + 1:00 C-Eur CE%sT 1944 Sep 22 + 3:00 Russia MSK/MSD 1989 Mar 26 2:00s + 2:00 1:00 EEST 1989 Sep 24 2:00s + 2:00 C-Eur EE%sT 1998 Sep 22 + 2:00 EU EE%sT 1999 Nov 1 + 2:00 - EET 2002 Feb 21 + 2:00 EU EE%sT + +# Finland +# +# From Hannu Strang (25 Sep 1994 06:03:37 UTC): +# Well, here in Helsinki we're just changing from summer time to regular one, +# and it's supposed to change at 4am... +# +# From Paul Eggert (25 Sep 1994): +# Shanks says Finland has switched at 02:00 standard time since 1981. +# Go with Strang instead. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Finland 1942 only - Apr 3 0:00 1:00 S +Rule Finland 1942 only - Oct 3 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Helsinki 1:39:52 - LMT 1878 May 31 + 1:39:52 - HMT 1921 May # Helsinki Mean Time + 2:00 Finland EE%sT 1981 Mar 29 2:00 + 2:00 EU EE%sT + +# Aaland Is +Link Europe/Helsinki Europe/Mariehamn + + +# France + +# From Ciro Discepolo (2000-12-20): +# +# Henri Le Corre, Regimes Horaires pour le monde entier, Editions +# Traditionnelles - Paris 2 books, 1993 +# +# Gabriel, Traite de l'heure dans le monde, Guy Tredaniel editeur, +# Paris, 1991 +# +# Francoise Gauquelin, Problemes de l'heure resolus en astrologie, +# Guy tredaniel, Paris 1987 + + +# +# Shanks seems to use `24:00' ambiguously; we resolve it with Whitman. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule France 1916 only - Jun 14 23:00s 1:00 S +Rule France 1916 1919 - Oct Sun>=1 23:00s 0 - +Rule France 1917 only - Mar 24 23:00s 1:00 S +Rule France 1918 only - Mar 9 23:00s 1:00 S +Rule France 1919 only - Mar 1 23:00s 1:00 S +Rule France 1920 only - Feb 14 23:00s 1:00 S +Rule France 1920 only - Oct 23 23:00s 0 - +Rule France 1921 only - Mar 14 23:00s 1:00 S +Rule France 1921 only - Oct 25 23:00s 0 - +Rule France 1922 only - Mar 25 23:00s 1:00 S +# DSH writes that a law of 1923-05-24 specified 3rd Sat in Apr at 23:00 to 1st +# Sat in Oct at 24:00; and that in 1930, because of Easter, the transitions +# were Apr 12 and Oct 5. Go with Shanks. +Rule France 1922 1938 - Oct Sat>=1 23:00s 0 - +Rule France 1923 only - May 26 23:00s 1:00 S +Rule France 1924 only - Mar 29 23:00s 1:00 S +Rule France 1925 only - Apr 4 23:00s 1:00 S +Rule France 1926 only - Apr 17 23:00s 1:00 S +Rule France 1927 only - Apr 9 23:00s 1:00 S +Rule France 1928 only - Apr 14 23:00s 1:00 S +Rule France 1929 only - Apr 20 23:00s 1:00 S +Rule France 1930 only - Apr 12 23:00s 1:00 S +Rule France 1931 only - Apr 18 23:00s 1:00 S +Rule France 1932 only - Apr 2 23:00s 1:00 S +Rule France 1933 only - Mar 25 23:00s 1:00 S +Rule France 1934 only - Apr 7 23:00s 1:00 S +Rule France 1935 only - Mar 30 23:00s 1:00 S +Rule France 1936 only - Apr 18 23:00s 1:00 S +Rule France 1937 only - Apr 3 23:00s 1:00 S +Rule France 1938 only - Mar 26 23:00s 1:00 S +Rule France 1939 only - Apr 15 23:00s 1:00 S +Rule France 1939 only - Nov 18 23:00s 0 - +Rule France 1940 only - Feb 25 2:00 1:00 S +# The French rules for 1941-1944 were not used in Paris, but Shanks writes +# that they were used in Monaco and in many French locations. +# Le Corre writes that the upper limit of the free zone was Arneguy, Orthez, +# Mont-de-Marsan, Bazas, Langon, Lamotte-Montravel, Marouil, La +# Rochefoucault, Champagne-Mouton, La Roche-Posay, La Haye-Decartes, +# Loches, Montrichard, Vierzon, Bourges, Moulins, Digoin, +# Paray-le-Monial, Montceau-les-Mines, Chalons-sur-Saone, Arbois, +# Dole, Morez, St-Claude, and Collognes (Haute-Savioe). +Rule France 1941 only - May 5 0:00 2:00 M # Midsummer +# Shanks says this transition occurred at Oct 6 1:00, +# but go with Denis.Excoffier@ens.fr (1997-12-12), +# who quotes the Ephemerides Astronomiques for 1998 from Bureau des Longitudes +# as saying 5/10/41 22hUT. +Rule France 1941 only - Oct 6 0:00 1:00 S +Rule France 1942 only - Mar 9 0:00 2:00 M +Rule France 1942 only - Nov 2 3:00 1:00 S +Rule France 1943 only - Mar 29 2:00 2:00 M +Rule France 1943 only - Oct 4 3:00 1:00 S +Rule France 1944 only - Apr 3 2:00 2:00 M +Rule France 1944 only - Oct 8 1:00 1:00 S +Rule France 1945 only - Apr 2 2:00 2:00 M +Rule France 1945 only - Sep 16 3:00 0 - +# Shanks gives Mar 28 2:00 and Sep 26 3:00; +# go with Excoffier's 28/3/76 0hUT and 25/9/76 23hUT. +Rule France 1976 only - Mar 28 1:00 1:00 S +Rule France 1976 only - Sep 26 1:00 0 - +# Shanks gives 0:09 for Paris Mean Time, and Whitman gives 0:09:05, +# but Howse quotes the actual French legislation as saying 0:09:21. +# Go with Howse. Howse writes that the time in France was officially based +# on PMT-0:09:21 until 1978-08-09, when the time base finally switched to UTC. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Paris 0:09:21 - LMT 1891 Mar 15 0:01 + 0:09:21 - PMT 1911 Mar 11 0:01 # Paris MT +# Shanks gives 1940 Jun 14 0:00; go with Excoffier and Le Corre. + 0:00 France WE%sT 1940 Jun 14 23:00 +# Le Corre says Paris stuck with occupied-France time after the liberation; +# go with Shanks. + 1:00 C-Eur CE%sT 1944 Aug 25 + 0:00 France WE%sT 1945 Sep 16 3:00 + 1:00 France CE%sT 1977 + 1:00 EU CE%sT + +# Germany + +# From Markus Kuhn (1998-09-29): +# The German time zone web site by the Physikalisch-Technische +# Bundesanstalt contains DST information back to 1916. +# [See tz-link.htm for the URL.] + +# From Joerg Schilling (2002-10-23): +# In 1945, Berlin was switched to Moscow Summer time (GMT+4) by +# General [Nikolai] Bersarin. + +# From Paul Eggert (2003-03-08): +# +# says that Bersarin issued an order to use Moscow time on May 20. +# However, Moscow did not observe daylight saving in 1945, so +# this was equivalent to CEMT (GMT+3), not GMT+4. + + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Germany 1945 only - Apr 2 2:00s 1:00 S +Rule Germany 1945 only - May 24 2:00 2:00 M # Midsummer +Rule Germany 1945 only - Sep 24 3:00 1:00 S +Rule Germany 1945 only - Nov 18 2:00s 0 - +Rule Germany 1946 only - Apr 14 2:00s 1:00 S +Rule Germany 1946 only - Oct 7 2:00s 0 - +Rule Germany 1947 1949 - Oct Sun>=1 2:00s 0 - +Rule Germany 1947 only - Apr 6 2:00s 1:00 S +Rule Germany 1947 only - May 11 2:00s 2:00 M +Rule Germany 1947 only - Jun 29 3:00 1:00 S +Rule Germany 1948 only - Apr 18 2:00s 1:00 S +Rule Germany 1949 only - Apr 10 2:00s 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Berlin 0:53:28 - LMT 1893 Apr + 1:00 C-Eur CE%sT 1945 Apr 2 2:00 + 1:00 Germany CE%sT 1980 + 1:00 EU CE%sT + +# Georgia +# Please see the "asia" file for Asia/Tbilisi. +# Herodotus (Histories, IV.45) says Georgia north of the Phasis (now Rioni) +# is in Europe. Our reference location Tbilisi is in the Asian part. + +# Gibraltar +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Gibraltar -0:21:24 - LMT 1880 Aug 2 + 0:00 GB-Eire %s 1957 Apr 14 2:00 + 1:00 - CET 1982 + 1:00 EU CE%sT + +# Greece +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# Whitman gives 1932 Jul 5 - Nov 1; go with Shanks. +Rule Greece 1932 only - Jul 7 0:00 1:00 S +Rule Greece 1932 only - Sep 1 0:00 0 - +# Whitman gives 1941 Apr 25 - ?; go with Shanks. +Rule Greece 1941 only - Apr 7 0:00 1:00 S +# Whitman gives 1942 Feb 2 - ?; go with Shanks. +Rule Greece 1942 only - Nov 2 3:00 0 - +Rule Greece 1943 only - Mar 30 0:00 1:00 S +Rule Greece 1943 only - Oct 4 0:00 0 - +# Whitman gives 1944 Oct 3 - Oct 31; go with Shanks. +Rule Greece 1952 only - Jul 1 0:00 1:00 S +Rule Greece 1952 only - Nov 2 0:00 0 - +Rule Greece 1975 only - Apr 12 0:00s 1:00 S +Rule Greece 1975 only - Nov 26 0:00s 0 - +Rule Greece 1976 only - Apr 11 2:00s 1:00 S +Rule Greece 1976 only - Oct 10 2:00s 0 - +Rule Greece 1977 1978 - Apr Sun>=1 2:00s 1:00 S +Rule Greece 1977 only - Sep 26 2:00s 0 - +Rule Greece 1978 only - Sep 24 4:00 0 - +Rule Greece 1979 only - Apr 1 9:00 1:00 S +Rule Greece 1979 only - Sep 29 2:00 0 - +Rule Greece 1980 only - Apr 1 0:00 1:00 S +Rule Greece 1980 only - Sep 28 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Athens 1:34:52 - LMT 1895 Sep 14 + 1:34:52 - AMT 1916 Jul 28 0:01 # Athens MT + 2:00 Greece EE%sT 1941 Apr 30 + 1:00 Greece CE%sT 1944 Apr 4 + 2:00 Greece EE%sT 1981 + # Shanks says they switched to C-Eur in 1981; + # go with EU instead, since Greece joined it on Jan 1. + 2:00 EU EE%sT + +# Hungary +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Hungary 1918 only - Apr 1 3:00 1:00 S +Rule Hungary 1918 only - Sep 29 3:00 0 - +Rule Hungary 1919 only - Apr 15 3:00 1:00 S +Rule Hungary 1919 only - Sep 15 3:00 0 - +Rule Hungary 1920 only - Apr 5 3:00 1:00 S +Rule Hungary 1920 only - Sep 30 3:00 0 - +Rule Hungary 1945 only - May 1 23:00 1:00 S +Rule Hungary 1945 only - Nov 3 0:00 0 - +Rule Hungary 1946 only - Mar 31 2:00s 1:00 S +Rule Hungary 1946 1949 - Oct Sun>=1 2:00s 0 - +Rule Hungary 1947 1949 - Apr Sun>=4 2:00s 1:00 S +Rule Hungary 1950 only - Apr 17 2:00s 1:00 S +Rule Hungary 1950 only - Oct 23 2:00s 0 - +Rule Hungary 1954 1955 - May 23 0:00 1:00 S +Rule Hungary 1954 1955 - Oct 3 0:00 0 - +Rule Hungary 1956 only - Jun Sun>=1 0:00 1:00 S +Rule Hungary 1956 only - Sep lastSun 0:00 0 - +Rule Hungary 1957 only - Jun Sun>=1 1:00 1:00 S +Rule Hungary 1957 only - Sep lastSun 3:00 0 - +Rule Hungary 1980 only - Apr 6 1:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Budapest 1:16:20 - LMT 1890 Oct + 1:00 C-Eur CE%sT 1918 + 1:00 Hungary CE%sT 1941 Apr 6 2:00 + 1:00 C-Eur CE%sT 1945 May 1 23:00 + 1:00 Hungary CE%sT 1980 Sep 28 2:00s + 1:00 EU CE%sT + +# Iceland +# +# From Adam David (1993-11-06): +# The name of the timezone in Iceland for system / mail / news purposes is GMT. +# +# (1993-12-05): +# This material is paraphrased from the 1988 edition of the University of +# Iceland Almanak. +# +# From January 1st, 1908 the whole of Iceland was standardised at 1 hour +# behind GMT. Previously, local mean solar time was used in different parts +# of Iceland, the almanak had been based on Reykjavik mean solar time which +# was 1 hour and 28 minutes behind GMT. +# +# "first day of winter" referred to [below] means the first day of the 26 weeks +# of winter, according to the old icelandic calendar that dates back to the +# time the norsemen first settled Iceland. The first day of winter is always +# Saturday, but is not dependent on the Julian or Gregorian calendars. +# +# (1993-12-10): +# I have a reference from the Oxford Icelandic-English dictionary for the +# beginning of winter, which ties it to the ecclesiastical calendar (and thus +# to the julian/gregorian calendar) over the period in question. +# the winter begins on the Saturday next before St. Luke's day +# (old style), or on St. Luke's day, if a Saturday. +# St. Luke's day ought to be traceable from ecclesiastical sources. "old style" +# might be a reference to the Julian calendar as opposed to Gregorian, or it +# might mean something else (???). +# +# From Paul Eggert (1999-10-29): +# The Iceland Almanak, Shanks and Whitman disagree on many points. +# We go with the Almanak, except for one claim from Shanks, namely that +# Reykavik was 21W57 from 1837 to 1908, local mean time before that. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Iceland 1917 1918 - Feb 19 23:00 1:00 S +Rule Iceland 1917 only - Oct 21 1:00 0 - +Rule Iceland 1918 only - Nov 16 1:00 0 - +Rule Iceland 1939 only - Apr 29 23:00 1:00 S +Rule Iceland 1939 only - Nov 29 2:00 0 - +Rule Iceland 1940 only - Feb 25 2:00 1:00 S +Rule Iceland 1940 only - Nov 3 2:00 0 - +Rule Iceland 1941 only - Mar 2 1:00s 1:00 S +Rule Iceland 1941 only - Nov 2 1:00s 0 - +Rule Iceland 1942 only - Mar 8 1:00s 1:00 S +Rule Iceland 1942 only - Oct 25 1:00s 0 - +# 1943-1946 - first Sunday in March until first Sunday in winter +Rule Iceland 1943 1946 - Mar Sun>=1 1:00s 1:00 S +Rule Iceland 1943 1948 - Oct Sun>=22 1:00s 0 - +# 1947-1967 - first Sunday in April until first Sunday in winter +Rule Iceland 1947 1967 - Apr Sun>=1 1:00s 1:00 S +# 1949 Oct transition delayed by 1 week +Rule Iceland 1949 only - Oct 30 1:00s 0 - +Rule Iceland 1950 1966 - Oct Sun>=22 1:00s 0 - +Rule Iceland 1967 only - Oct 29 1:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Atlantic/Reykjavik -1:27:24 - LMT 1837 + -1:27:48 - RMT 1908 # Reykjavik Mean Time? + -1:00 Iceland IS%sT 1968 Apr 7 1:00s + 0:00 - GMT + +# Italy +# +# From Paul Eggert (2001-03-06): +# Sicily and Sardinia each had their own time zones from 1866 to 1893, +# called Palermo Time (+00:53:28) and Cagliari Time (+00:36:32). +# During World War II, German-controlled Italy used German time. +# But these events all occurred before the 1970 cutoff, +# so record only the time in Rome. +# +# From Paul Eggert (1996-05-06): +# For Italian DST we have three sources: Shanks, Whitman, and F. Pollastri +# +# Day-light Saving Time in Italy (1996-03-14) +# +# (`FP' below), taken from an Italian National Electrotechnical Institute +# publication. When the three sources disagree, guess who's right, as follows: +# +# year FP Shanks (S) Whitman (W) Go with: +# 1916 06-03 06-03 24:00 06-03 00:00 FP & W +# 09-30 09-30 24:00 09-30 01:00 FP; guess 24:00s +# 1917 04-01 03-31 24:00 03-31 00:00 FP & S +# 09-30 09-29 24:00 09-30 01:00 FP & W +# 1918 03-09 03-09 24:00 03-09 00:00 FP & S +# 10-06 10-05 24:00 10-06 01:00 FP & W +# 1919 03-01 03-01 24:00 03-01 00:00 FP & S +# 10-04 10-04 24:00 10-04 01:00 FP; guess 24:00s +# 1920 03-20 03-20 24:00 03-20 00:00 FP & S +# 09-18 09-18 24:00 10-01 01:00 FP; guess 24:00s +# 1944 04-02 04-03 02:00 S (see C-Eur) +# 09-16 10-02 03:00 FP; guess 24:00s +# 1945 09-14 09-16 24:00 FP; guess 24:00s +# 1970 05-21 05-31 00:00 S +# 09-20 09-27 00:00 S +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Italy 1916 only - Jun 3 0:00s 1:00 S +Rule Italy 1916 only - Oct 1 0:00s 0 - +Rule Italy 1917 only - Apr 1 0:00s 1:00 S +Rule Italy 1917 only - Sep 30 0:00s 0 - +Rule Italy 1918 only - Mar 10 0:00s 1:00 S +Rule Italy 1918 1919 - Oct Sun>=1 0:00s 0 - +Rule Italy 1919 only - Mar 2 0:00s 1:00 S +Rule Italy 1920 only - Mar 21 0:00s 1:00 S +Rule Italy 1920 only - Sep 19 0:00s 0 - +Rule Italy 1940 only - Jun 15 0:00s 1:00 S +Rule Italy 1944 only - Sep 17 0:00s 0 - +Rule Italy 1945 only - Apr 2 2:00 1:00 S +Rule Italy 1945 only - Sep 15 0:00s 0 - +Rule Italy 1946 only - Mar 17 2:00s 1:00 S +Rule Italy 1946 only - Oct 6 2:00s 0 - +Rule Italy 1947 only - Mar 16 0:00s 1:00 S +Rule Italy 1947 only - Oct 5 0:00s 0 - +Rule Italy 1948 only - Feb 29 2:00s 1:00 S +Rule Italy 1948 only - Oct 3 2:00s 0 - +Rule Italy 1966 1968 - May Sun>=22 0:00 1:00 S +Rule Italy 1966 1969 - Sep Sun>=22 0:00 0 - +Rule Italy 1969 only - Jun 1 0:00 1:00 S +Rule Italy 1970 only - May 31 0:00 1:00 S +Rule Italy 1970 only - Sep lastSun 0:00 0 - +Rule Italy 1971 1972 - May Sun>=22 0:00 1:00 S +Rule Italy 1971 only - Sep lastSun 1:00 0 - +Rule Italy 1972 only - Oct 1 0:00 0 - +Rule Italy 1973 only - Jun 3 0:00 1:00 S +Rule Italy 1973 1974 - Sep lastSun 0:00 0 - +Rule Italy 1974 only - May 26 0:00 1:00 S +Rule Italy 1975 only - Jun 1 0:00s 1:00 S +Rule Italy 1975 1977 - Sep lastSun 0:00s 0 - +Rule Italy 1976 only - May 30 0:00s 1:00 S +Rule Italy 1977 1979 - May Sun>=22 0:00s 1:00 S +Rule Italy 1978 only - Oct 1 0:00s 0 - +Rule Italy 1979 only - Sep 30 0:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Rome 0:49:56 - LMT 1866 Sep 22 + 0:49:56 - RMT 1893 Nov # Rome Mean Time + 1:00 Italy CE%sT 1942 Nov 2 2:00s + 1:00 C-Eur CE%sT 1944 Jul + 1:00 Italy CE%sT 1980 + 1:00 EU CE%sT + +Link Europe/Rome Europe/Vatican +Link Europe/Rome Europe/San_Marino + +# Latvia + +# From Liene Kanepe (1998-09-17): + +# I asked about this matter Scientific Secretary of the Institute of Astronomy +# of The University of Latvia Dr. paed Mr. Ilgonis Vilks. I also searched the +# correct data in juridical acts and I found some juridical documents about +# changes in the counting of time in Latvia from 1981.... +# +# Act No.35 of the Council of Ministers of Latvian SSR of 1981-01-22 ... +# according to the Act No.925 of the Council of Ministers of USSR of 1980-10-24 +# ...: all year round the time of 2nd time zone + 1 hour, in addition turning +# the hands of the clock 1 hour forward on 1 April at 00:00 (GMT 31 March 21:00) +# and 1 hour backward on the 1 October at 00:00 (GMT 30 September 20:00). +# +# Act No.592 of the Council of Ministers of Latvian SSR of 1984-09-24 ... +# according to the Act No.967 of the Council of Ministers of USSR of 1984-09-13 +# ...: all year round the time of 2nd time zone + 1 hour, in addition turning +# the hands of the clock 1 hour forward on the last Sunday of March at 02:00 +# (GMT 23:00 on the previous day) and 1 hour backward on the last Sunday of +# September at 03:00 (GMT 23:00 on the previous day). +# +# Act No.81 of the Council of Ministers of Latvian SSR of 1989-03-22 ... +# according to the Act No.227 of the Council of Ministers of USSR of 1989-03-14 +# ...: since the last Sunday of March 1989 in Lithuanian SSR, Latvian SSR, +# Estonian SSR and Kaliningrad region of Russian Federation all year round the +# time of 2nd time zone (Moscow time minus one hour). On the territory of Latvia +# transition to summer time is performed on the last Sunday of March at 02:00 +# (GMT 00:00), turning the hands of the clock 1 hour forward. The end of +# daylight saving time is performed on the last Sunday of September at 03:00 +# (GMT 00:00), turning the hands of the clock 1 hour backward. Exception is +# 1989-03-26, when we must not turn the hands of the clock.... +# +# The Regulations of the Cabinet of Ministers of the Republic of Latvia of +# 1997-01-21 on transition to Summer time ... established the same order of +# daylight savings time settings as in the States of the European Union. + +# From Andrei Ivanov (2000-03-06): +# This year Latvia will not switch to Daylight Savings Time (as specified in +# +# The Regulations of the Cabinet of Ministers of the Rep. of Latvia of +# 29-Feb-2000 (#79), in Latvian for subscribers only). + +# +# From RFE/RL Newsline (2001-01-03), noted after a heads-up by Rives McDow: +# +# The Latvian government on 2 January decided that the country will +# institute daylight-saving time this spring, LETA reported. +# Last February the three Baltic states decided not to turn back their +# clocks one hour in the spring.... +# Minister of Economy Aigars Kalvitis noted that Latvia had too few +# daylight hours and thus decided to comply with a draft European +# Commission directive that provides for instituting daylight-saving +# time in EU countries between 2002 and 2006. The Latvian government +# urged Lithuania and Estonia to adopt a similar time policy, but it +# appears that they will not do so.... + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Latvia 1989 1996 - Mar lastSun 2:00s 1:00 S +Rule Latvia 1989 1996 - Sep lastSun 2:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Riga 1:36:24 - LMT 1880 + 1:36:24 - RMT 1918 Apr 15 2:00 #Riga Mean Time + 1:36:24 1:00 LST 1918 Sep 16 3:00 #Latvian Summer + 1:36:24 - RMT 1919 Apr 1 2:00 + 1:36:24 1:00 LST 1919 May 22 3:00 + 1:36:24 - RMT 1926 May 11 + 2:00 - EET 1940 Aug 5 + 3:00 - MSK 1941 Jul + 1:00 C-Eur CE%sT 1944 Oct 13 + 3:00 Russia MSK/MSD 1989 Mar lastSun 2:00s + 2:00 1:00 EEST 1989 Sep lastSun 2:00s + 2:00 Latvia EE%sT 1997 Jan 21 + 2:00 EU EE%sT 2000 Feb 29 + 2:00 - EET 2001 Jan 2 + 2:00 EU EE%sT + +# Liechtenstein +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Vaduz 0:38:04 - LMT 1894 Jun + 1:00 - CET 1981 + 1:00 EU CE%sT + +# Lithuania + +# From Paul Eggert (1996-11-22): +# IATA SSIM (1992/1996) says Lithuania uses W-Eur rules, but since it is +# known to be wrong about Estonia and Latvia, assume it's wrong here too. + +# From Marius Gedminas (1998-08-07): +# I would like to inform that in this year Lithuanian time zone +# (Europe/Vilnius) was changed. + +# From ELTA No. 972 (2582) (1999-09-29), +# via Steffen Thorsen: +# Lithuania has shifted back to the second time zone (GMT plus two hours) +# to be valid here starting from October 31, +# as decided by the national government on Wednesday.... +# The Lithuanian government also announced plans to consider a +# motion to give up shifting to summer time in spring, as it was +# already done by Estonia. + +# From the +# Fact File, Lithuanian State Department of Tourism +# (2000-03-27): Local time is GMT+2 hours ..., no daylight saving. + +# From a user via Klaus Marten (2003-02-07): +# As a candidate for membership of the European Union, Lithuania will +# observe Summer Time in 2003, changing its clocks at the times laid +# down in EU Directive 2000/84 of 19.I.01 (i.e. at the same times as its +# neighbour Latvia). The text of the Lithuanian government Order of +# 7.XI.02 to this effect can be found at +# http://www.lrvk.lt/nut/11/n1749.htm + + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Vilnius 1:41:16 - LMT 1880 + 1:24:00 - WMT 1917 # Warsaw Mean Time + 1:35:36 - KMT 1919 Oct 10 # Kaunas Mean Time + 1:00 - CET 1920 Jul 12 + 2:00 - EET 1920 Oct 9 + 1:00 - CET 1940 Aug 3 + 3:00 - MSK 1941 Jun 24 + 1:00 C-Eur CE%sT 1944 Aug + 3:00 Russia MSK/MSD 1991 Mar 31 2:00s + 2:00 1:00 EEST 1991 Sep 29 2:00s + 2:00 C-Eur EE%sT 1998 + 2:00 - EET 1998 Mar 29 1:00u + 1:00 EU CE%sT 1999 Oct 31 1:00u + 2:00 - EET 2003 Jan 1 + 2:00 EU EE%sT + +# Luxembourg +# Whitman disagrees with most of these dates in minor ways; go with Shanks. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Lux 1916 only - May 14 23:00 1:00 S +Rule Lux 1916 only - Oct 1 1:00 0 - +Rule Lux 1917 only - Apr 28 23:00 1:00 S +Rule Lux 1917 only - Sep 17 1:00 0 - +Rule Lux 1918 only - Apr Mon>=15 2:00s 1:00 S +Rule Lux 1918 only - Sep Mon>=15 2:00s 0 - +Rule Lux 1919 only - Mar 1 23:00 1:00 S +Rule Lux 1919 only - Oct 5 3:00 0 - +Rule Lux 1920 only - Feb 14 23:00 1:00 S +Rule Lux 1920 only - Oct 24 2:00 0 - +Rule Lux 1921 only - Mar 14 23:00 1:00 S +Rule Lux 1921 only - Oct 26 2:00 0 - +Rule Lux 1922 only - Mar 25 23:00 1:00 S +Rule Lux 1922 only - Oct Sun>=2 1:00 0 - +Rule Lux 1923 only - Apr 21 23:00 1:00 S +Rule Lux 1923 only - Oct Sun>=2 2:00 0 - +Rule Lux 1924 only - Mar 29 23:00 1:00 S +Rule Lux 1924 1928 - Oct Sun>=2 1:00 0 - +Rule Lux 1925 only - Apr 5 23:00 1:00 S +Rule Lux 1926 only - Apr 17 23:00 1:00 S +Rule Lux 1927 only - Apr 9 23:00 1:00 S +Rule Lux 1928 only - Apr 14 23:00 1:00 S +Rule Lux 1929 only - Apr 20 23:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Luxembourg 0:24:36 - LMT 1904 Jun + 1:00 Lux CE%sT 1918 Nov 25 + 0:00 Lux WE%sT 1929 Oct 6 2:00s + 0:00 Belgium WE%sT 1940 May 14 3:00 + 1:00 C-Eur WE%sT 1944 Sep 18 3:00 + 1:00 Belgium CE%sT 1977 + 1:00 EU CE%sT + +# Macedonia +# see Serbia and Montenegro + +# Malta +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Malta 1973 only - Mar 31 0:00s 1:00 S +Rule Malta 1973 only - Sep 29 0:00s 0 - +Rule Malta 1974 only - Apr 21 0:00s 1:00 S +Rule Malta 1974 only - Sep 16 0:00s 0 - +Rule Malta 1975 1979 - Apr Sun>=15 2:00 1:00 S +Rule Malta 1975 1980 - Sep Sun>=15 2:00 0 - +Rule Malta 1980 only - Mar 31 2:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Malta 0:58:04 - LMT 1893 Nov 2 # Valletta + 1:00 Italy CE%sT 1942 Nov 2 2:00s + 1:00 C-Eur CE%sT 1945 Apr 2 2:00s + 1:00 Italy CE%sT 1973 Mar 31 + 1:00 Malta CE%sT 1981 + 1:00 EU CE%sT + +# Moldova + +# From Paul Eggert (2001-02-11): +# A previous version of this database followed Shanks, who writes that +# Tiraspol switched to Moscow time on 1992-01-19 at 02:00. +# However, this is most likely an error, as Moldova declared independence +# on 1991-08-27 (the 1992-01-19 date is that of a Russian decree). +# In early 1992 there was large-scale interethnic violence in the area +# and it's possible that some Russophones continued to observe Moscow time. +# But moldavizolit@tirastel.md and mk@tirastel.md separately reported via +# Jesper Norgaard that as of 2001-01-24 Tiraspol was like Chisinau. +# The Tiraspol entry has therefore been removed for now. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Chisinau 1:55:20 - LMT 1880 + 1:55 - CMT 1918 Feb 15 # Chisinau MT + 1:44:24 - BMT 1931 Jul 24 # Bucharest MT + 2:00 Romania EE%sT 1940 Aug 15 + 2:00 1:00 EEST 1941 Jul 17 + 1:00 C-Eur CE%sT 1944 Aug 24 + 3:00 Russia MSK/MSD 1990 + 3:00 - MSK 1990 May 6 + 2:00 - EET 1991 + 2:00 Russia EE%sT 1992 + 2:00 E-Eur EE%sT 1997 +# See Romania commentary for the guessed 1997 transition to EU rules. + 2:00 EU EE%sT + +# Monaco +# Shanks gives 0:09 for Paris Mean Time; go with Howse's more precise 0:09:21. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Monaco 0:29:32 - LMT 1891 Mar 15 + 0:09:21 - PMT 1911 Mar 11 # Paris Mean Time + 0:00 France WE%sT 1945 Sep 16 3:00 + 1:00 France CE%sT 1977 + 1:00 EU CE%sT + +# Netherlands + +# Howse writes that the Netherlands' railways used GMT between 1892 and 1940, +# but for other purposes the Netherlands used Amsterdam mean time. + +# However, Robert H. van Gent writes (2001-04-01): +# Howse's statement is only correct up to 1909. From 1909-05-01 (00:00:00 +# Amsterdam mean time) onwards, the whole of the Netherlands (including +# the Dutch railways) was required by law to observe Amsterdam mean time +# (19 minutes 32.13 seconds ahead of GMT). This had already been the +# common practice (except for the railways) for many decades but it was +# not until 1909 when the Dutch government finally defined this by law. +# On 1937-07-01 this was changed to 20 minutes (exactly) ahead of GMT and +# was generally known as Dutch Time ("Nederlandse Tijd"). +# +# (2001-04-08): +# 1892-05-01 was the date when the Dutch railways were by law required to +# observe GMT while the remainder of the Netherlands adhered to the common +# practice of following Amsterdam mean time. +# +# (2001-04-09): +# In 1835 the authorities of the province of North Holland requested the +# municipal authorities of the towns and cities in the province to observe +# Amsterdam mean time but I do not know in how many cases this request was +# actually followed. +# +# From 1852 onwards the Dutch telegraph offices were by law required to +# observe Amsterdam mean time. As the time signals from the observatory of +# Leiden were also distributed by the telegraph system, I assume that most +# places linked up with the telegraph (and railway) system automatically +# adopted Amsterdam mean time. +# +# Although the early Dutch railway companies initially observed a variety +# of times, most of them had adopted Amsterdam mean time by 1858 but it +# was not until 1866 when they were all required by law to observe +# Amsterdam mean time. + +# The data before 1945 are taken from +# . + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Neth 1916 only - May 1 0:00 1:00 NST # Netherlands Summer Time +Rule Neth 1916 only - Oct 1 0:00 0 AMT # Amsterdam Mean Time +Rule Neth 1917 only - Apr 16 2:00s 1:00 NST +Rule Neth 1917 only - Sep 17 2:00s 0 AMT +Rule Neth 1918 1921 - Apr Mon>=1 2:00s 1:00 NST +Rule Neth 1918 1921 - Sep lastMon 2:00s 0 AMT +Rule Neth 1922 only - Mar lastSun 2:00s 1:00 NST +Rule Neth 1922 1936 - Oct Sun>=2 2:00s 0 AMT +Rule Neth 1923 only - Jun Fri>=1 2:00s 1:00 NST +Rule Neth 1924 only - Mar lastSun 2:00s 1:00 NST +Rule Neth 1925 only - Jun Fri>=1 2:00s 1:00 NST +# From 1926 through 1939 DST began 05-15, except that it was delayed by a week +# in years when 05-15 fell in the Pentecost weekend. +Rule Neth 1926 1931 - May 15 2:00s 1:00 NST +Rule Neth 1932 only - May 22 2:00s 1:00 NST +Rule Neth 1933 1936 - May 15 2:00s 1:00 NST +Rule Neth 1937 only - May 22 2:00s 1:00 NST +Rule Neth 1937 only - Jul 1 0:00 1:00 S +Rule Neth 1937 1939 - Oct Sun>=2 2:00s 0 - +Rule Neth 1938 1939 - May 15 2:00s 1:00 S +Rule Neth 1945 only - Apr 2 2:00s 1:00 S +Rule Neth 1945 only - Sep 16 2:00s 0 - +# +# Amsterdam Mean Time was +00:19:32.13 exactly, but the .13 is omitted +# below because the current format requires GMTOFF to be an integer. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Amsterdam 0:19:32 - LMT 1835 + 0:19:32 Neth %s 1937 Jul 1 + 0:20 Neth NE%sT 1940 May 16 0:00 # Dutch Time + 1:00 C-Eur CE%sT 1945 Apr 2 2:00 + 1:00 Neth CE%sT 1977 + 1:00 EU CE%sT + +# Norway +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# Whitman gives 1916 May 21 - 1916 Oct 21; go with Shanks. +Rule Norway 1916 only - May 22 1:00 1:00 S +Rule Norway 1916 only - Sep 30 0:00 0 - +# Whitman says DST observed 1935-08-11/1942-11-01, then 1943-03-29/10-04, +# 1944-04-03/10-02, and 1945-04-01/10-01; go with Shanks. +Rule Norway 1945 only - Apr 2 2:00s 1:00 S +Rule Norway 1945 only - Oct 1 2:00s 0 - +Rule Norway 1959 1964 - Mar Sun>=15 2:00s 1:00 S +Rule Norway 1959 1965 - Sep Sun>=15 2:00s 0 - +Rule Norway 1965 only - Apr 25 2:00s 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Oslo 0:43:00 - LMT 1895 Jan 1 + 1:00 Norway CE%sT 1940 Aug 10 23:00 + 1:00 C-Eur CE%sT 1945 Apr 2 2:00 + 1:00 Norway CE%sT 1980 + 1:00 EU CE%sT + +# Svalbard & Jan Mayen + +# From Steffen Thorsen (2001-05-01): +# Although I could not find it explicitly, it seems that Jan Mayen and +# Svalbard have been using the same time as Norway at least since the +# time they were declared as parts of Norway. Svalbard was declared +# as a part of Norway by law of 1925-07-17 no 11, section 4 and Jan +# Mayen by law of 1930-02-27 no 2, section 2. (From +# http://www.lovdata.no/all/nl-19250717-011.html and +# http://www.lovdata.no/all/nl-19300227-002.html). The law/regulation +# for normal/standard time in Norway is from 1894-06-29 no 1 (came +# into operation on 1895-01-01) and Svalbard/Jan Mayen seem to be a +# part of this law since 1925/1930. (From +# http://www.lovdata.no/all/nl-18940629-001.html ) I have not been +# able to find if Jan Mayen used a different time zone (e.g. -0100) +# before 1930. Jan Mayen has only been "inhabitated" since 1921 by +# Norwegian meteorologists and maybe used the same time as Norway ever +# since 1921. Svalbard (Arctic/Longyearbyen) has been inhabited since +# before 1895, and therefore probably changed the local time somewhere +# between 1895 and 1925 (inclusive). + +# From Paul Eggert (2001-05-01): +# +# Actually, Jan Mayen was never occupied by Germany during World War II, +# so it must have diverged from Oslo time during the war, as Oslo was +# keeping Berlin time. +# +# says that the meteorologists +# burned down their station in 1940 and left the island, but returned in +# 1941 with a small Norwegian garrison and continued operations despite +# frequent air ttacks from Germans. In 1943 the Americans established a +# radiolocating station on the island, called "Atlantic City". Possibly +# the UTC offset changed during the war, but I think it unlikely that +# Jan Mayen used German daylight-saving rules. +# +# Svalbard is more complicated, as it was raided in August 1941 by an +# Allied party that evacuated the civilian population to England (says +# ). The Svalbard FAQ +# says that the Germans were +# expelled on 1942-05-14. However, small parties of Germans did return, +# and according to Wilhelm Dege's book "War North of 80" (1954) +# +# the German armed forces at the Svalbard weather station code-named +# Haudegen did not surrender to the Allies until September 1945. +# +# All these events predate our cutoff date of 1970. Unless we can +# come up with more definitive info about the timekeeping during the +# war years it's probably best just do do the following for now: +Link Europe/Oslo Arctic/Longyearbyen +Link Europe/Oslo Atlantic/Jan_Mayen + +# Poland +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Poland 1918 1919 - Sep 16 2:00s 0 - +Rule Poland 1919 only - Apr 15 2:00s 1:00 S +# Whitman gives 1944 Nov 30; go with Shanks. +Rule Poland 1944 only - Oct 4 2:00 0 - +# For 1944-1948 Whitman gives the previous day; go with Shanks. +Rule Poland 1945 only - Apr 29 0:00 1:00 S +Rule Poland 1945 only - Nov 1 0:00 0 - +Rule Poland 1946 only - Apr 14 0:00 1:00 S +Rule Poland 1946 only - Sep 7 0:00 0 - +Rule Poland 1947 only - May 4 0:00 1:00 S +Rule Poland 1947 1948 - Oct Sun>=1 0:00 0 - +Rule Poland 1948 only - Apr 18 0:00 1:00 S +# Whitman also gives 1949 Apr 9 - 1949 Oct 1; go with Shanks. +Rule Poland 1957 only - Jun 2 1:00s 1:00 S +Rule Poland 1957 1958 - Sep lastSun 1:00s 0 - +Rule Poland 1958 only - Mar 30 1:00s 1:00 S +Rule Poland 1959 only - May 31 1:00s 1:00 S +Rule Poland 1959 1961 - Oct Sun>=1 1:00s 0 - +Rule Poland 1960 only - Apr 3 1:00s 1:00 S +Rule Poland 1961 1964 - May Sun>=25 1:00s 1:00 S +Rule Poland 1962 1964 - Sep lastSun 1:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Warsaw 1:24:00 - LMT 1880 + 1:24:00 - WMT 1915 Aug 5 # Warsaw Mean Time + 1:00 C-Eur CE%sT 1918 Sep 16 3:00 + 2:00 Poland EE%sT 1922 Jun + 1:00 Poland CE%sT 1940 Jun 23 2:00 + 1:00 C-Eur CE%sT 1944 Oct + 1:00 Poland CE%sT 1977 Apr 3 1:00 + 1:00 W-Eur CE%sT 1999 +# IATA SSIM (1991/1996) gives EU rules, but the _The Warsaw Voice_ +# +# http://www.warsawvoice.com/pl/v361/NewsInBrief.shtml (1995-09-24) +# +# says the autumn 1995 switch was at 02:00. +# Stick with W-Eur for now. +# +# From Marcin.Kasperski@softax.com.pl (1999-06-10): +# According to my colleagues someone recently decided, that Poland would +# follow European Union regulations, so - I think - the matter is not +# worth further discussion. +# +# From Paul Eggert (1999-06-10): +# Kasperski also writes that the government futzed with the rules in 1997 +# or 1998 but he doesn't remember the details. Assume they switched to +# EU rules in 1999. + 1:00 EU CE%sT + +# Portugal +# +# From Rui Pedro Salgueiro (1992-11-12): +# Portugal has recently (September, 27) changed timezone +# (from WET to MET or CET) to harmonize with EEC. +# +# Martin Bruckmann (1996-02-29) reports via Peter Ilieve +# that Portugal is reverting to 0:00 by not moving its clocks this spring. +# The new Prime Minister was fed up with getting up in the dark in the winter. +# +# From Paul Eggert (1996-11-12): +# IATA SSIM (1991-09) reports several 1991-09 and 1992-09 transitions +# at 02:00u, not 01:00u. Assume that these are typos. +# IATA SSIM (1991/1992) reports that the Azores were at -1:00. +# IATA SSIM (1993-02) says +0:00; later issues (through 1996-09) say -1:00. +# Guess that the Azores changed to EU rules in 1992 (since that's when Portugal +# harmonized with the EU), and that they stayed +0:00 that winter. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# DSH writes that despite Decree 1,469 (1915), the change to the clocks was not +# done every year, depending on what Spain did, because of railroad schedules. +# Go with Shanks. +Rule Port 1916 only - Jun 17 23:00 1:00 S +# Whitman gives 1916 Oct 31; go with Shanks. +Rule Port 1916 only - Nov 1 1:00 0 - +Rule Port 1917 only - Feb 28 23:00s 1:00 S +Rule Port 1917 1921 - Oct 14 23:00s 0 - +Rule Port 1918 only - Mar 1 23:00s 1:00 S +Rule Port 1919 only - Feb 28 23:00s 1:00 S +Rule Port 1920 only - Feb 29 23:00s 1:00 S +Rule Port 1921 only - Feb 28 23:00s 1:00 S +Rule Port 1924 only - Apr 16 23:00s 1:00 S +Rule Port 1924 only - Oct 14 23:00s 0 - +Rule Port 1926 only - Apr 17 23:00s 1:00 S +Rule Port 1926 1929 - Oct Sat>=1 23:00s 0 - +Rule Port 1927 only - Apr 9 23:00s 1:00 S +Rule Port 1928 only - Apr 14 23:00s 1:00 S +Rule Port 1929 only - Apr 20 23:00s 1:00 S +Rule Port 1931 only - Apr 18 23:00s 1:00 S +# Whitman gives 1931 Oct 8; go with Shanks. +Rule Port 1931 1932 - Oct Sat>=1 23:00s 0 - +Rule Port 1932 only - Apr 2 23:00s 1:00 S +# Shanks gives 1934 Apr 4; go with Whitman. +Rule Port 1934 only - Apr 7 23:00s 1:00 S +# Whitman gives 1934 Oct 5; go with Shanks. +Rule Port 1934 1938 - Oct Sat>=1 23:00s 0 - +# Shanks gives 1935 Apr 30; go with Whitman. +Rule Port 1935 only - Mar 30 23:00s 1:00 S +Rule Port 1936 only - Apr 18 23:00s 1:00 S +# Whitman gives 1937 Apr 2; go with Shanks. +Rule Port 1937 only - Apr 3 23:00s 1:00 S +Rule Port 1938 only - Mar 26 23:00s 1:00 S +Rule Port 1939 only - Apr 15 23:00s 1:00 S +# Whitman gives 1939 Oct 7; go with Shanks. +Rule Port 1939 only - Nov 18 23:00s 0 - +Rule Port 1940 only - Feb 24 23:00s 1:00 S +# Shanks gives 1940 Oct 7; go with Whitman. +Rule Port 1940 1941 - Oct 5 23:00s 0 - +Rule Port 1941 only - Apr 5 23:00s 1:00 S +Rule Port 1942 1945 - Mar Sat>=8 23:00s 1:00 S +Rule Port 1942 only - Apr 25 22:00s 2:00 M # Midsummer +Rule Port 1942 only - Aug 15 22:00s 1:00 S +Rule Port 1942 1945 - Oct Sat>=24 23:00s 0 - +Rule Port 1943 only - Apr 17 22:00s 2:00 M +Rule Port 1943 1945 - Aug Sat>=25 22:00s 1:00 S +Rule Port 1944 1945 - Apr Sat>=21 22:00s 2:00 M +Rule Port 1946 only - Apr Sat>=1 23:00s 1:00 S +Rule Port 1946 only - Oct Sat>=1 23:00s 0 - +Rule Port 1947 1949 - Apr Sun>=1 2:00s 1:00 S +Rule Port 1947 1949 - Oct Sun>=1 2:00s 0 - +# Shanks says DST was observed in 1950; go with Whitman. +# Whitman gives Oct lastSun for 1952 on; go with Shanks. +Rule Port 1951 1965 - Apr Sun>=1 2:00s 1:00 S +Rule Port 1951 1965 - Oct Sun>=1 2:00s 0 - +Rule Port 1977 only - Mar 27 0:00s 1:00 S +Rule Port 1977 only - Sep 25 0:00s 0 - +Rule Port 1978 1979 - Apr Sun>=1 0:00s 1:00 S +Rule Port 1978 only - Oct 1 0:00s 0 - +Rule Port 1979 1982 - Sep lastSun 1:00s 0 - +Rule Port 1980 only - Mar lastSun 0:00s 1:00 S +Rule Port 1981 1982 - Mar lastSun 1:00s 1:00 S +Rule Port 1983 only - Mar lastSun 2:00s 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# Shanks says that the transition from LMT to WET occurred 1911-05-24; +# Willett says 1912-01-01. Go with Willett. +Zone Europe/Lisbon -0:36:32 - LMT 1884 + -0:36:32 - LMT 1912 Jan 1 # Lisbon Mean Time + 0:00 Port WE%sT 1966 Apr 3 2:00 + 1:00 - CET 1976 Sep 26 1:00 + 0:00 Port WE%sT 1983 Sep 25 1:00s + 0:00 W-Eur WE%sT 1992 Sep 27 1:00s + 1:00 EU CE%sT 1996 Mar 31 1:00u + 0:00 EU WE%sT +Zone Atlantic/Azores -1:42:40 - LMT 1884 # Ponta Delgada + -1:54:32 - HMT 1911 May 24 # Horta Mean Time + -2:00 Port AZO%sT 1966 Apr 3 2:00 # Azores Time + -1:00 Port AZO%sT 1983 Sep 25 1:00s + -1:00 W-Eur AZO%sT 1992 Sep 27 1:00s + 0:00 EU WE%sT 1993 Mar 28 1:00u + -1:00 EU AZO%sT +Zone Atlantic/Madeira -1:07:36 - LMT 1884 # Funchal + -1:07:36 - FMT 1911 May 24 # Funchal Mean Time + -1:00 Port MAD%sT 1966 Apr 3 2:00 # Madeira Time + 0:00 Port WE%sT 1983 Sep 25 1:00s + 0:00 EU WE%sT + +# Romania +# +# From Paul Eggert (1999-10-07): +# +# Nine O'clock (1998-10-23) reports that the switch occurred at +# 04:00 local time in fall 1998. For lack of better info, +# assume that Romania and Moldova switched to EU rules in 1997, +# the same year as Bulgaria. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Romania 1932 only - May 21 0:00s 1:00 S +Rule Romania 1932 1939 - Oct Sun>=1 0:00s 0 - +Rule Romania 1933 1939 - Apr Sun>=2 0:00s 1:00 S +Rule Romania 1979 only - May 27 0:00 1:00 S +Rule Romania 1979 only - Sep lastSun 0:00 0 - +Rule Romania 1980 only - Apr 5 23:00 1:00 S +Rule Romania 1980 only - Sep lastSun 1:00 0 - +Rule Romania 1991 1993 - Mar lastSun 0:00s 1:00 S +Rule Romania 1991 1993 - Sep lastSun 0:00s 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Bucharest 1:44:24 - LMT 1891 Oct + 1:44:24 - BMT 1931 Jul 24 # Bucharest MT + 2:00 Romania EE%sT 1981 Mar 29 2:00s + 2:00 C-Eur EE%sT 1991 + 2:00 Romania EE%sT 1994 + 2:00 E-Eur EE%sT 1997 + 2:00 EU EE%sT + +# Russia + +# From Paul Eggert (1999-11-12): +# Except for Moscow after 1919-07-01, I invented the time zone abbreviations. +# Moscow time zone abbreviations after 1919-07-01, and Moscow rules after 1991, +# are from Andrey A. Chernov. The rest is from Shanks, except we follow +# Chernov's report that 1992 DST transitions were Sat 23:00, not Sun 02:00s. +# +# From Stanislaw A. Kuzikowski (1994-06-29): +# But now it is some months since Novosibirsk is 3 hours ahead of Moscow! +# I do not know why they have decided to make this change; +# as far as I remember it was done exactly during winter->summer switching +# so we (Novosibirsk) simply did not switch. +# +# From Andrey A. Chernov (1996-10-04): +# `MSK' and `MSD' were born and used initially on Moscow computers with +# UNIX-like OSes by several developer groups (e.g. Demos group, Kiae group).... +# The next step was the UUCP network, the Relcom predecessor +# (used mainly for mail), and MSK/MSD was actively used there. +# +# From Chris Carrier <72157.3334@CompuServe.COM> (1996-10-30): +# According to a friend of mine who rode the Trans-Siberian Railroad from +# Moscow to Irkutsk in 1995, public air and rail transport in Russia ... +# still follows Moscow time, no matter where in Russia it is located. +# +# For Grozny, Chechnya, we have the following story from +# John Daniszewski, "Scavengers in the Rubble", Los Angeles Times (2001-02-07): +# News--often false--is spread by word of mouth. A rumor that it was +# time to move the clocks back put this whole city out of sync with +# the rest of Russia for two weeks--even soldiers stationed here began +# enforcing curfew at the wrong time. +# +# From Gwillim Law (2001-06-05): +# There's considerable evidence that Sakhalin Island used to be in +# UTC+11, and has changed to UTC+10, in this decade. I start with the +# SSIM, which listed Yuzhno-Sakhalinsk in zone RU10 along with Magadan +# until February 1997, and then in RU9 with Khabarovsk and Vladivostok +# since September 1997.... Although the Kuril Islands are +# administratively part of Sakhalin oblast', they appear to have +# remained on UTC+11 along with Magadan. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# +# Kaliningradskaya oblast'. +Zone Europe/Kaliningrad 1:22:00 - LMT 1893 Apr + 1:00 C-Eur CE%sT 1945 + 2:00 Poland CE%sT 1946 + 3:00 Russia MSK/MSD 1991 Mar 31 2:00s + 2:00 Russia EE%sT +# +# From Oscar van Vlijmen (2001-08-25): [This region consists of] +# Respublika Adygeya, Arkhangel'skaya oblast', Astrakhanskaya oblast', +# Belgorodskaya oblast', Bryanskaya oblast', Vladimirskaya oblast', +# Volgogradskaya oblast', Vologodskaya oblast', Voronezhskaya oblast', +# Respublika Dagestan, Ivanovskaya oblast', Respublika Ingushetiya, +# Kabarbino-Balkarskaya Respublika, Respublika Kalmykiya, +# Kalyzhskaya oblast', Respublika Karachaevo-Cherkessiya, +# Respublika Kareliya, Kirovskaya oblast', Respublika Komi, +# Kostromskaya oblast', Krasnodarskij kraj, Kurskaya oblast', +# Leningradskaya oblast', Lipetskaya oblast', Respublika Marij El, +# Respublika Mordoviya, Moskva, Moskovskaya oblast', +# Murmanskaya oblast', Nenetskij avtonomnyj okrug, +# Nizhegorodskaya oblast', Novgorodskaya oblast', Orlovskaya oblast', +# Penzenskaya oblast', Pskovskaya oblast', Rostovskaya oblast', +# Ryazanskaya oblast', Sankt-Peterburg, Saratovskaya oblast', +# Respublika Severnaya Osetiya, Smolenskaya oblast', +# Stavropol'skij kraj, Tambovskaya oblast', Respublika Tatarstan, +# Tverskaya oblast', Tyl'skaya oblast', Ul'yanovskaya oblast', +# Chechenskaya Respublika, Chuvashskaya oblast', +# Yaroslavskaya oblast' +Zone Europe/Moscow 2:30:20 - LMT 1880 + 2:30 - MMT 1916 Jul 3 # Moscow Mean Time + 2:30:48 Russia %s 1919 Jul 1 2:00 + 3:00 Russia MSK/MSD 1922 Oct + 2:00 - EET 1930 Jun 21 + 3:00 Russia MSK/MSD 1991 Mar 31 2:00s + 2:00 Russia EE%sT 1992 Jan 19 2:00s + 3:00 Russia MSK/MSD +# +# From Oscar van Vlijmen (2001-08-25): [This region consists of] +# Samarskaya oblast', Udmyrtskaya respublika +Zone Europe/Samara 3:20:36 - LMT 1919 Jul 1 2:00 + 3:00 - KUYT 1930 Jun 21 # Kuybyshev + 4:00 Russia KUY%sT 1989 Mar 26 2:00s + 3:00 Russia KUY%sT 1991 Mar 31 2:00s + 2:00 Russia KUY%sT 1991 Sep 29 2:00s + 3:00 - KUYT 1991 Oct 20 3:00 + 4:00 Russia SAM%sT # Samara Time +# +# From Oscar van Vlijmen (2001-08-25): [This region consists of] +# Respublika Bashkortostan, Komi-Permyatskij avtonomnyj okrug, +# Kurganskaya oblast', Orenburgskaya oblast', Permskaya oblast', +# Sverdlovskaya oblast', Tyumenskaya oblast', +# Khanty-Manskijskij avtonomnyj okrug, Chelyabinskaya oblast', +# Yamalo-Nenetskij avtonomnyj okrug. +Zone Asia/Yekaterinburg 4:02:24 - LMT 1919 Jul 15 4:00 + 4:00 - SVET 1930 Jun 21 # Sverdlovsk Time + 5:00 Russia SVE%sT 1991 Mar 31 2:00s + 4:00 Russia SVE%sT 1992 Jan 19 2:00s + 5:00 Russia YEK%sT # Yekaterinburg Time +# +# From Oscar van Vlijmen (2001-08-25): [This region consists of] +# Respublika Altaj, Altajskij kraj, Omskaya oblast'. +Zone Asia/Omsk 4:53:36 - LMT 1919 Nov 14 + 5:00 - OMST 1930 Jun 21 # Omsk TIme + 6:00 Russia OMS%sT 1991 Mar 31 2:00s + 5:00 Russia OMS%sT 1992 Jan 19 2:00s + 6:00 Russia OMS%sT +# +# Novosibirskaya oblast'. +Zone Asia/Novosibirsk 5:31:40 - LMT 1919 Dec 14 6:00 + 6:00 - NOVT 1930 Jun 21 # Novosibirsk Time + 7:00 Russia NOV%sT 1991 Mar 31 2:00s + 6:00 Russia NOV%sT 1992 Jan 19 2:00s + 7:00 Russia NOV%sT 1993 May 23 # says Shanks + 6:00 Russia NOV%sT +# +# From Oscar van Vlijmen (2001-08-25): [This region consists of] +# Kemerovskaya oblast', Krasnoyarskij kraj, +# Tajmyrskij (Dolgano-Nenetskij) avtonomnyj okrug, Tomskaya oblast', +# Respublika Tuva, Respublika Khakasiya, Evenkijskij avtonomnyj okrug. +Zone Asia/Krasnoyarsk 6:11:20 - LMT 1920 Jan 6 + 6:00 - KRAT 1930 Jun 21 # Krasnoyarsk Time + 7:00 Russia KRA%sT 1991 Mar 31 2:00s + 6:00 Russia KRA%sT 1992 Jan 19 2:00s + 7:00 Russia KRA%sT +# +# From Oscar van Vlijmen (2001-08-25): [This region consists of] +# Respublika Buryatiya, Irkutskaya oblast', +# Ust'-Ordynskij Buryatskij avtonomnyj okrug. +Zone Asia/Irkutsk 6:57:20 - LMT 1880 + 6:57:20 - IMT 1920 Jan 25 # Irkutsk Mean Time + 7:00 - IRKT 1930 Jun 21 # Irkutsk Time + 8:00 Russia IRK%sT 1991 Mar 31 2:00s + 7:00 Russia IRK%sT 1992 Jan 19 2:00s + 8:00 Russia IRK%sT +# +# From Oscar van Vlijmen (2003-10-18): [This region consists of] +# Aginskij Buryatskij avtonomnyj okrug, Amurskaya oblast', +# [parts of] Respublika Sakha (Yakutiya), Chitinskaya oblast'. +# The Sakha districts are: Aldanskij, Amginskij, Anabarskij, +# Bulunskij, Verkhnekolymskij, Verkhnevilyujskij, Vilyujskij, Gornyj, +# Zhiganskij, Kobyajskij, Lenskij, Megino-Kangalasskij, Mirninskij, +# Namskij, Nyurbinskij, Olenekskij, Olekminskij, Srednekolymskij, +# Suntarskij, Tattinskij, Ust'-Aldanskij, Khangalasskij, +# Churapchinskij, Eveno-Bytantajskij. +Zone Asia/Yakutsk 8:38:40 - LMT 1919 Dec 15 + 8:00 - YAKT 1930 Jun 21 # Yakutsk Time + 9:00 Russia YAK%sT 1991 Mar 31 2:00s + 8:00 Russia YAK%sT 1992 Jan 19 2:00s + 9:00 Russia YAK%sT +# +# From Oscar van Vlijmen (2003-10-18): [This region consists of] +# Evrejskaya avtonomnaya oblast', Khabarovskij kraj, Primorskij kraj, +# [parts of] Respublika Sakha (Yakutiya). +# The Sakha districts are: Verkhoyanskij, Tomponskij, Ust'-Majskij, +# Ust'-Yanskij. +Zone Asia/Vladivostok 8:47:44 - LMT 1922 Nov 15 + 9:00 - VLAT 1930 Jun 21 # Vladivostok Time + 10:00 Russia VLA%sT 1991 Mar 31 2:00s + 9:00 Russia VLA%sST 1992 Jan 19 2:00s + 10:00 Russia VLA%sT +# +# Sakhalinskaya oblast'. +# The Zone name should be Yuzhno-Sakhalinsk, but that's too long. +Zone Asia/Sakhalin 9:30:48 - LMT 1905 Aug 23 + 9:00 - CJT 1938 + 9:00 - JST 1945 Aug 25 + 11:00 Russia SAK%sT 1991 Mar 31 2:00s # Sakhalin T. + 10:00 Russia SAK%sT 1992 Jan 19 2:00s + 11:00 Russia SAK%sT 1997 Mar lastSun 2:00s + 10:00 Russia SAK%sT +# +# From Oscar van Vlijmen (2003-10-18): [This region consists of] +# Magadanskaya oblast', Respublika Sakha (Yakutiya). +# Probably also: Kuril Islands. +# The Sakha districts are: Abyjskij, Allaikhovskij, Momskij, +# Nizhnekolymskij, Ojmyakonskij. +Zone Asia/Magadan 10:03:12 - LMT 1924 May 2 + 10:00 - MAGT 1930 Jun 21 # Magadan Time + 11:00 Russia MAG%sT 1991 Mar 31 2:00s + 10:00 Russia MAG%sT 1992 Jan 19 2:00s + 11:00 Russia MAG%sT +# +# From Oscar van Vlijmen (2001-08-25): [This region consists of] +# Kamchatskaya oblast', Koryakskij avtonomnyj okrug. +# +# The Zone name should be Asia/Petropavlovsk-Kamchatski, but that's too long. +Zone Asia/Kamchatka 10:34:36 - LMT 1922 Nov 10 + 11:00 - PETT 1930 Jun 21 # P-K Time + 12:00 Russia PET%sT 1991 Mar 31 2:00s + 11:00 Russia PET%sT 1992 Jan 19 2:00s + 12:00 Russia PET%sT +# +# Chukotskij avtonomnyj okrug +Zone Asia/Anadyr 11:49:56 - LMT 1924 May 2 + 12:00 - ANAT 1930 Jun 21 # Anadyr Time + 13:00 Russia ANA%sT 1982 Apr 1 0:00s + 12:00 Russia ANA%sT 1991 Mar 31 2:00s + 11:00 Russia ANA%sT 1992 Jan 19 2:00s + 12:00 Russia ANA%sT + +# Serbia and Montenegro +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Belgrade 1:22:00 - LMT 1884 + 1:00 - CET 1941 Apr 18 23:00 + 1:00 C-Eur CE%sT 1945 May 8 2:00s + 1:00 1:00 CEST 1945 Sep 16 2:00s +# Metod Kozelj reports that the legal date of +# transition to EU rules was 1982-11-27, for all of Yugoslavia at the time. +# Shanks doesn't give as much detail, so go with Kozelj. + 1:00 - CET 1982 Nov 27 + 1:00 EU CE%sT +Link Europe/Belgrade Europe/Ljubljana # Slovenia +Link Europe/Belgrade Europe/Sarajevo # Bosnia and Herzegovina +Link Europe/Belgrade Europe/Skopje # Macedonia +Link Europe/Belgrade Europe/Zagreb # Croatia + +# Slovakia +Link Europe/Prague Europe/Bratislava + +# Slovenia +# see Serbia and Montenegro + +# Spain +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# For 1917-1919 Whitman gives Apr Sat>=1 - Oct Sat>=1; go with Shanks. +Rule Spain 1917 only - May 5 23:00s 1:00 S +Rule Spain 1917 1919 - Oct 6 23:00s 0 - +Rule Spain 1918 only - Apr 15 23:00s 1:00 S +Rule Spain 1919 only - Apr 5 23:00s 1:00 S +# Whitman gives 1921 Feb 28 - Oct 14; go with Shanks. +Rule Spain 1924 only - Apr 16 23:00s 1:00 S +# Whitman gives 1924 Oct 14; go with Shanks. +Rule Spain 1924 only - Oct 4 23:00s 0 - +Rule Spain 1926 only - Apr 17 23:00s 1:00 S +# Whitman says no DST in 1929; go with Shanks. +Rule Spain 1926 1929 - Oct Sat>=1 23:00s 0 - +Rule Spain 1927 only - Apr 9 23:00s 1:00 S +Rule Spain 1928 only - Apr 14 23:00s 1:00 S +Rule Spain 1929 only - Apr 20 23:00s 1:00 S +# Whitman gives 1937 Jun 16, 1938 Apr 16, 1940 Apr 13; go with Shanks. +Rule Spain 1937 only - May 22 23:00s 1:00 S +Rule Spain 1937 1939 - Oct Sat>=1 23:00s 0 - +Rule Spain 1938 only - Mar 22 23:00s 1:00 S +Rule Spain 1939 only - Apr 15 23:00s 1:00 S +Rule Spain 1940 only - Mar 16 23:00s 1:00 S +# Whitman says no DST 1942-1945; go with Shanks. +Rule Spain 1942 only - May 2 22:00s 2:00 M # Midsummer +Rule Spain 1942 only - Sep 1 22:00s 1:00 S +Rule Spain 1943 1946 - Apr Sat>=13 22:00s 2:00 M +Rule Spain 1943 only - Oct 3 22:00s 1:00 S +Rule Spain 1944 only - Oct 10 22:00s 1:00 S +Rule Spain 1945 only - Sep 30 1:00 1:00 S +Rule Spain 1946 only - Sep 30 0:00 0 - +Rule Spain 1949 only - Apr 30 23:00 1:00 S +Rule Spain 1949 only - Sep 30 1:00 0 - +Rule Spain 1974 1975 - Apr Sat>=13 23:00 1:00 S +Rule Spain 1974 1975 - Oct Sun>=1 1:00 0 - +Rule Spain 1976 only - Mar 27 23:00 1:00 S +Rule Spain 1976 1977 - Sep lastSun 1:00 0 - +Rule Spain 1977 1978 - Apr 2 23:00 1:00 S +Rule Spain 1978 only - Oct 1 1:00 0 - +# The following rules are copied from Morocco from 1967 through 1978. +Rule SpainAfrica 1967 only - Jun 3 12:00 1:00 S +Rule SpainAfrica 1967 only - Oct 1 0:00 0 - +Rule SpainAfrica 1974 only - Jun 24 0:00 1:00 S +Rule SpainAfrica 1974 only - Sep 1 0:00 0 - +Rule SpainAfrica 1976 1977 - May 1 0:00 1:00 S +Rule SpainAfrica 1976 only - Aug 1 0:00 0 - +Rule SpainAfrica 1977 only - Sep 28 0:00 0 - +Rule SpainAfrica 1978 only - Jun 1 0:00 1:00 S +Rule SpainAfrica 1978 only - Aug 4 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Madrid -0:14:44 - LMT 1901 + 0:00 Spain WE%sT 1946 Sep 30 + 1:00 Spain CE%sT 1979 + 1:00 EU CE%sT +Zone Africa/Ceuta -0:21:16 - LMT 1901 + 0:00 - WET 1918 May 6 23:00 + 0:00 1:00 WEST 1918 Oct 7 23:00 + 0:00 - WET 1924 + 0:00 Spain WE%sT 1929 + 0:00 SpainAfrica WE%sT 1984 Mar 16 + 1:00 - CET 1986 + 1:00 EU CE%sT +Zone Atlantic/Canary -1:01:36 - LMT 1922 Mar # Las Palmas de Gran C. + -1:00 - CANT 1946 Sep 30 1:00 # Canaries Time + 0:00 - WET 1980 Apr 6 0:00s + 0:00 1:00 WEST 1980 Sep 28 0:00s + 0:00 EU WE%sT +# IATA SSIM (1996-09) says the Canaries switch at 2:00u, not 1:00u. +# Ignore this for now, as the Canaries are part of the EU. + +# Sweden + +# From Ivan Nilsson (2001-04-13), superseding Shanks: +# +# The law "Svensk forfattningssamling 1878, no 14" about standard time in 1879: +# From the beginning of 1879 (that is 01-01 00:00) the time for all +# places in the country is "the mean solar time for the meridian at +# three degrees, or twelve minutes of time, to the west of the +# meridian of the Observatory of Stockholm". The law is dated 1878-05-31. +# +# The observatory at that time had the meridian 18 degrees 03' 30" +# eastern longitude = 01:12:14 in time. Less 12 minutes gives the +# national standard time as 01:00:14 ahead of GMT.... +# +# About the beginning of CET in Sweden. The lawtext ("Svensk +# forfattningssamling 1899, no 44") states, that "from the beginning +# of 1900... ... the same as the mean solar time for the meridian at +# the distance of one hour of time from the meridian of the English +# observatory at Greenwich, or at 12 minutes 14 seconds to the west +# from the meridian of the Observatory of Stockholm". The law is dated +# 1899-06-16. In short: At 1900-01-01 00:00:00 the new standard time +# in Sweden is 01:00:00 ahead of GMT. +# +# 1916: The lawtext ("Svensk forfattningssamling 1916, no 124") states +# that "1916-05-15 is considered to begin one hour earlier". It is +# pretty obvious that at 05-14 23:00 the clocks are set to 05-15 00:00.... +# Further the law says, that "1916-09-30 is considered to end one hour later". +# +# The laws regulating [DST] are available on the site of the Swedish +# Parliament beginning with 1985 - the laws regulating 1980/1984 are +# not available on the site (to my knowledge they are only available +# in Swedish): (type +# "sommartid" without the quotes in the field "Fritext" and then click +# the Sok-button). +# +# (2001-05-13): +# +# I have now found a newspaper stating that at 1916-10-01 01:00 +# summertime the church-clocks etc were set back one hour to show +# 1916-10-01 00:00 standard time. The article also reports that some +# people thought the switch to standard time would take place already +# at 1916-10-01 00:00 summer time, but they had to wait for another +# hour before the event took place. +# +# Source: The newspaper "Dagens Nyheter", 1916-10-01, page 7 upper left. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Stockholm 1:12:12 - LMT 1879 Jan 1 + 1:00:14 - SET 1900 Jan 1 # Swedish Time + 1:00 - CET 1916 May 14 23:00 + 1:00 1:00 CEST 1916 Oct 1 01:00 + 1:00 - CET 1980 + 1:00 EU CE%sT + +# Switzerland +# From Howse: +# By the end of the 18th century clocks and watches became commonplace +# and their performance improved enormously. Communities began to keep +# mean time in preference to apparent time -- Geneva from 1780 .... +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# From Whitman (who writes ``Midnight?''): +Rule Swiss 1940 only - Nov 2 0:00 1:00 S +Rule Swiss 1940 only - Dec 31 0:00 0 - +# From Shanks: +Rule Swiss 1941 1942 - May Sun>=1 2:00 1:00 S +Rule Swiss 1941 1942 - Oct Sun>=1 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Zurich 0:34:08 - LMT 1848 Sep 12 + 0:29:44 - BMT 1894 Jun # Bern Mean Time + 1:00 Swiss CE%sT 1981 + 1:00 EU CE%sT + +# Turkey +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Turkey 1916 only - May 1 0:00 1:00 S +Rule Turkey 1916 only - Oct 1 0:00 0 - +Rule Turkey 1920 only - Mar 28 0:00 1:00 S +Rule Turkey 1920 only - Oct 25 0:00 0 - +Rule Turkey 1921 only - Apr 3 0:00 1:00 S +Rule Turkey 1921 only - Oct 3 0:00 0 - +Rule Turkey 1922 only - Mar 26 0:00 1:00 S +Rule Turkey 1922 only - Oct 8 0:00 0 - +# Whitman gives 1923 Apr 28 - Sep 16 and no DST in 1924-1925; go with Shanks. +Rule Turkey 1924 only - May 13 0:00 1:00 S +Rule Turkey 1924 1925 - Oct 1 0:00 0 - +Rule Turkey 1925 only - May 1 0:00 1:00 S +Rule Turkey 1940 only - Jun 30 0:00 1:00 S +Rule Turkey 1940 only - Oct 5 0:00 0 - +Rule Turkey 1940 only - Dec 1 0:00 1:00 S +Rule Turkey 1941 only - Sep 21 0:00 0 - +Rule Turkey 1942 only - Apr 1 0:00 1:00 S +# Whitman omits the next two transition and gives 1945 Oct 1; go with Shanks. +Rule Turkey 1942 only - Nov 1 0:00 0 - +Rule Turkey 1945 only - Apr 2 0:00 1:00 S +Rule Turkey 1945 only - Oct 8 0:00 0 - +Rule Turkey 1946 only - Jun 1 0:00 1:00 S +Rule Turkey 1946 only - Oct 1 0:00 0 - +Rule Turkey 1947 1948 - Apr Sun>=16 0:00 1:00 S +Rule Turkey 1947 1950 - Oct Sun>=2 0:00 0 - +Rule Turkey 1949 only - Apr 10 0:00 1:00 S +Rule Turkey 1950 only - Apr 19 0:00 1:00 S +Rule Turkey 1951 only - Apr 22 0:00 1:00 S +Rule Turkey 1951 only - Oct 8 0:00 0 - +Rule Turkey 1962 only - Jul 15 0:00 1:00 S +Rule Turkey 1962 only - Oct 8 0:00 0 - +Rule Turkey 1964 only - May 15 0:00 1:00 S +Rule Turkey 1964 only - Oct 1 0:00 0 - +Rule Turkey 1970 1972 - May Sun>=2 0:00 1:00 S +Rule Turkey 1970 1972 - Oct Sun>=2 0:00 0 - +Rule Turkey 1973 only - Jun 3 1:00 1:00 S +Rule Turkey 1973 only - Nov 4 3:00 0 - +Rule Turkey 1974 only - Mar 31 2:00 1:00 S +Rule Turkey 1974 only - Nov 3 5:00 0 - +Rule Turkey 1975 only - Mar 30 0:00 1:00 S +Rule Turkey 1975 1976 - Oct lastSun 0:00 0 - +Rule Turkey 1976 only - Jun 1 0:00 1:00 S +Rule Turkey 1977 1978 - Apr Sun>=1 0:00 1:00 S +Rule Turkey 1977 only - Oct 16 0:00 0 - +Rule Turkey 1979 1980 - Apr Sun>=1 3:00 1:00 S +Rule Turkey 1979 1982 - Oct Mon>=11 0:00 0 - +Rule Turkey 1981 1982 - Mar lastSun 3:00 1:00 S +Rule Turkey 1983 only - Jul 31 0:00 1:00 S +Rule Turkey 1983 only - Oct 2 0:00 0 - +Rule Turkey 1985 only - Apr 20 0:00 1:00 S +Rule Turkey 1985 only - Sep 28 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Europe/Istanbul 1:55:52 - LMT 1880 + 1:56:56 - IMT 1910 Oct # Istanbul Mean Time? + 2:00 Turkey EE%sT 1978 Oct 15 + 3:00 Turkey TR%sT 1985 Apr 20 # Turkey Time + 2:00 Turkey EE%sT 1986 + 2:00 C-Eur EE%sT 1991 + 2:00 EU EE%sT +Link Europe/Istanbul Asia/Istanbul # Istanbul is in both continents. + +# Ukraine +# +# From Igor Karpov, who works for the Ukranian Ministry of Justice, +# via Garrett Wollman (2003-01-27): +# BTW, I've found the official document on this matter. It's goverment +# regulations number 509, May 13, 1996. In my poor translation it says: +# "Time in Ukraine is set to second timezone (Kiev time). Each last Sunday +# of March at 3am the time is changing to 4am and each last Sunday of +# October the time at 4am is changing to 3am" + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# Most of Ukraine since 1970 has been like Kiev. +Zone Europe/Kiev 2:02:04 - LMT 1880 + 2:02:04 - KMT 1924 May 2 # Kiev Mean Time + 2:00 - EET 1930 Jun 21 + 3:00 - MSK 1941 Sep 20 + 1:00 C-Eur CE%sT 1943 Nov 6 + 3:00 Russia MSK/MSD 1990 + 3:00 - MSK 1990 Jul 1 2:00 + 2:00 - EET 1992 + 2:00 E-Eur EE%sT 1995 + 2:00 EU EE%sT +# Ruthenia used CET 1990/1991. +Zone Europe/Uzhgorod 1:29:12 - LMT 1890 Oct + 1:00 - CET 1940 + 1:00 C-Eur CE%sT 1944 Oct + 1:00 1:00 CEST 1944 Oct 26 + 1:00 - CET 1945 Jun 29 + 3:00 Russia MSK/MSD 1990 + 3:00 - MSK 1990 Jul 1 2:00 + 1:00 - CET 1991 Mar 31 3:00 + 2:00 - EET 1992 + 2:00 E-Eur EE%sT 1995 + 2:00 EU EE%sT +# Zaporozh'ye and eastern Lugansk oblasts observed DST 1990/1991. +# Zaporozh'ye has an apostrophe, but Posix file names can't have apostrophes. +Zone Europe/Zaporozhye 2:20:40 - LMT 1880 + 2:20 - CUT 1924 May 2 # Central Ukraine T + 2:00 - EET 1930 Jun 21 + 3:00 - MSK 1941 Aug 25 + 1:00 C-Eur CE%sT 1943 Oct 25 + 3:00 Russia MSK/MSD 1991 Mar 31 2:00 + 2:00 E-Eur EE%sT 1995 + 2:00 EU EE%sT +# Central Crimea used Moscow time 1994/1997. +Zone Europe/Simferopol 2:16:24 - LMT 1880 + 2:16 - SMT 1924 May 2 # Simferopol Mean T + 2:00 - EET 1930 Jun 21 + 3:00 - MSK 1941 Nov + 1:00 C-Eur CE%sT 1944 Apr 13 + 3:00 Russia MSK/MSD 1990 + 3:00 - MSK 1990 Jul 1 2:00 + 2:00 - EET 1992 +# From Paul Eggert (1999-11-12): +# The _Economist_ (1994-05-28, p 45) reports that central Crimea switched +# from Kiev to Moscow time sometime after the January 1994 elections. +# Shanks says ``date of change uncertain'', but implies that it happened +# sometime between the 1994 DST switches. For now, guess it changed in May. + 2:00 E-Eur EE%sT 1994 May +# From IATA SSIM (1994/1997), which also says that Kerch is still like Kiev. + 3:00 E-Eur MSK/MSD 1996 Mar 31 3:00s + 3:00 1:00 MSD 1996 Oct 27 3:00s +# IATA SSIM (1997-09) says Crimea switched to EET/EEST. +# Assume it happened in March by not changing the clocks. + 3:00 Russia MSK/MSD 1997 + 3:00 - MSK 1997 Mar lastSun 1:00u + 2:00 EU EE%sT + +############################################################################### + +# One source shows that Bulgaria, Cyprus, Finland, and Greece observe DST from +# the last Sunday in March to the last Sunday in September in 1986. +# The source shows Romania changing a day later than everybody else. +# +# According to Bernard Sieloff's source, Poland is in the MET time zone but +# uses the WE DST rules. The Western USSR uses EET+1 and ME DST rules. +# Bernard Sieloff's source claims Romania switches on the same day, but at +# 00:00 standard time (i.e., 01:00 DST). It also claims that Turkey +# switches on the same day, but switches on at 01:00 standard time +# and off at 00:00 standard time (i.e., 01:00 DST) + +# ... +# Date: Wed, 28 Jan 87 16:56:27 -0100 +# From: seismo!mcvax!cgcha!wtho (Tom Hofmann) +# Message-Id: <8701281556.AA22174@cgcha.uucp> +# ... +# +# ...the European time rules are...standardized since 1981, when +# most European coun[tr]ies started DST. Before that year, only +# a few countries (UK, France, Italy) had DST, each according +# to own national rules. In 1981, however, DST started on +# 'Apr firstSun', and not on 'Mar lastSun' as in the following +# years... +# But also since 1981 there are some more national exceptions +# than listed in 'europe': Switzerland, for example, joined DST +# one year later, Denmark ended DST on 'Oct 1' instead of 'Sep +# lastSun' in 1981---I don't know how they handle now. +# +# Finally, DST ist always from 'Apr 1' to 'Oct 1' in the +# Soviet Union (as far as I know). +# +# Tom Hofmann, Scientific Computer Center, CIBA-GEIGY AG, +# 4002 Basle, Switzerland +# UUCP: ...!mcvax!cernvax!cgcha!wtho + +# ... +# Date: Wed, 4 Feb 87 22:35:22 +0100 +# From: seismo!mcvax!cwi.nl!dik (Dik T. Winter) +# ... +# +# The information from Tom Hofmann is (as far as I know) not entirely correct. +# After a request from chongo at amdahl I tried to retrieve all information +# about DST in Europe. I was able to find all from about 1969. +# +# ...standardization on DST in Europe started in about 1977 with switches on +# first Sunday in April and last Sunday in September... +# In 1981 UK joined Europe insofar that +# the starting day for both shifted to last Sunday in March. And from 1982 +# the whole of Europe used DST, with switch dates April 1 and October 1 in +# the Sov[i]et Union. In 1985 the SU reverted to standard Europe[a]n switch +# dates... +# +# It should also be remembered that time-zones are not constants; e.g. +# Portugal switched in 1976 from MET (or CET) to WET with DST... +# Note also that though there were rules for switch dates not +# all countries abided to these dates, and many individual deviations +# occurred, though not since 1982 I believe. Another note: it is always +# assumed that DST is 1 hour ahead of normal time, this need not be the +# case; at least in the Netherlands there have been times when DST was 2 hours +# in advance of normal time. +# +# ... +# dik t. winter, cwi, amsterdam, nederland +# INTERNET : dik@cwi.nl +# BITNET/EARN: dik@mcvax + +# From Bob Devine (1988-01-28): +# ... +# Greece: Last Sunday in April to last Sunday in September (iffy on dates). +# Since 1978. Change at midnight. +# ... +# Monaco: has same DST as France. +# ... Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/northamerica =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/northamerica,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/northamerica 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,1985 @@ +# @(#)northamerica 7.70 +# also includes Central America and the Caribbean + +# This data is by no means authoritative; if you think you know better, +# go ahead and edit the file (and please send any changes to +# tz@elsie.nci.nih.gov for general use in the future). + +# From Paul Eggert (1999-03-22): +# A reliable and entertaining source about time zones is +# Derek Howse, Greenwich time and longitude, Philip Wilson Publishers (1997). + +############################################################################### + +# United States + +# From Paul Eggert (1999-03-31): +# Howse writes (pp 121-125) that time zones were invented by +# Professor Charles Ferdinand Dowd (1825-1904), +# Principal of Temple Grove Ladies' Seminary (Saratoga Springs, NY). +# His pamphlet ``A System of National Time for Railroads'' (1870) +# was the result of his proposals at the Convention of Railroad Trunk Lines +# in New York City (1869-10). His 1870 proposal was based on Washington, DC, +# but in 1872-05 he moved the proposed origin to Greenwich. +# His proposal was adopted by the railroads on 1883-11-18 at 12:00, +# and the most of the country soon followed suit. + +# From Paul Eggert (1995-12-19): +# A good source for time zone historical data in the US is +# Thomas G. Shanks, The American Atlas (5th edition), +# San Diego: ACS Publications, Inc. (1991). +# Make sure you have the errata sheet; the book is somewhat useless without it. +# It is the source for the US and Puerto Rico entries below. + +# From Paul Eggert (2001-03-06): +# Daylight Saving Time was first suggested as a joke by Benjamin Franklin +# in his whimsical essay ``An Economical Project for Diminishing the Cost +# of Light'' published in the Journal de Paris (1784-04-26). +# Not everyone is happy with the results: +# +# I don't really care how time is reckoned so long as there is some +# agreement about it, but I object to being told that I am saving +# daylight when my reason tells me that I am doing nothing of the kind. +# I even object to the implication that I am wasting something +# valuable if I stay in bed after the sun has risen. As an admirer +# of moonlight I resent the bossy insistence of those who want to +# reduce my time for enjoying it. At the back of the Daylight Saving +# scheme I detect the bony, blue-fingered hand of Puritanism, eager +# to push people into bed earlier, and get them up earlier, to make +# them healthy, wealthy and wise in spite of themselves. +# +# -- Robertson Davies, The Diary of Samuel Marchbanks (1947), XIX, Sunday +# +# For more about the first ten years of DST in the United States, see +# Robert Garland's +# Ten years of daylight saving from the Pittsburgh standpoint +# (Carnegie Library of Pittsburgh, 1927). +# +# Shanks says that DST was called "War Time" in the US in 1918 and 1919. +# However, DST was imposed by the Standard Time Act of 1918, which +# was the first nationwide legal time standard, and apparently +# time was just called "Standard Time" or "Daylight Saving Time". + +# From Arthur David Olson: +# US Daylight Saving Time ended on the last Sunday of *October* in 1974. +# See, for example, the front page of the Saturday, 1974-10-26 +# and Sunday, 1974-10-27 editions of the Washington Post. + +# From Arthur David Olson: +# Before the Uniform Time Act of 1966 took effect in 1967, observance of +# Daylight Saving Time in the US was by local option, except during wartime. + +# From Arthur David Olson (2000-09-25): +# Last night I heard part of a rebroadcast of a 1945 Arch Oboler radio drama. +# In the introduction, Oboler spoke of "Eastern Peace Time." +# An AltaVista search turned up +# : +# "When the time is announced over the radio now, it is 'Eastern Peace +# Time' instead of the old familiar 'Eastern War Time.' Peace is wonderful." +# (August 1945) by way of confirmation. + +# From Joseph Gallant , citing +# George H. Douglas, _The Early Days of Radio Broadcasting_ (1987): +# At 7 P.M. (Eastern War Time) [on 1945-08-14], the networks were set +# to switch to London for Attlee's address, but the American people +# never got to hear his speech live. According to one press account, +# CBS' Bob Trout was first to announce the word of Japan's surrender, +# but a few seconds later, NBC, ABC and Mutual also flashed the word +# of surrender, all of whom interrupting the bells of Big Ben in +# London which were to precede Mr. Attlee's speech. + +# From Paul Eggert (2003-02-09): It was Robert St John, not Bob Trout. From +# Myrna Oliver's obituary of St John on page B16 of today's Los Angeles Times: +# +# ... a war-weary U.S. clung to radios, awaiting word of Japan's surrender. +# Any announcement from Asia would reach St. John's New York newsroom on a +# wire service teletype machine, which had prescribed signals for major news. +# Associated Press, for example, would ring five bells before spewing out +# typed copy of an important story, and 10 bells for news "of transcendental +# importance." +# +# On Aug. 14, stalling while talking steadily into the NBC networks' open +# microphone, St. John heard five bells and waited only to hear a sixth bell, +# before announcing confidently: "Ladies and gentlemen, World War II is over. +# The Japanese have agreed to our surrender terms." +# +# He had scored a 20-second scoop on other broadcasters. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule US 1918 1919 - Mar lastSun 2:00 1:00 D +Rule US 1918 1919 - Oct lastSun 2:00 0 S +Rule US 1942 only - Feb 9 2:00 1:00 W # War +Rule US 1945 only - Aug 14 23:00u 1:00 P # Peace +Rule US 1945 only - Sep 30 2:00 0 S +Rule US 1967 max - Oct lastSun 2:00 0 S +Rule US 1967 1973 - Apr lastSun 2:00 1:00 D +Rule US 1974 only - Jan 6 2:00 1:00 D +Rule US 1975 only - Feb 23 2:00 1:00 D +Rule US 1976 1986 - Apr lastSun 2:00 1:00 D +Rule US 1987 max - Apr Sun>=1 2:00 1:00 D +# +# H.R.177 +# (introduced 1999-01-06) would change April to March in the above rule. + +# From Bob Devine (1988-01-28): +# ...Alaska (and Hawaii) had the timezone names changed in 1967. +# old new +# Pacific Standard Time(PST) -same- +# Yukon Standard Time(YST) -same- +# Central Alaska S.T. (CAT) Alaska-Hawaii St[an]dard Time (AHST) +# Nome Standard Time (NT) Bering Standard Time (BST) +# +# ...Alaska's timezone lines were redrawn in 1983 to give only 2 tz. +# The YST zone now covers nearly all of the state, AHST just part +# of the Aleutian islands. No DST. + +# From Paul Eggert (1995-12-19): +# The tables below use `NST', not `NT', for Nome Standard Time. +# I invented `CAWT' for Central Alaska War Time. + +# From U. S. Naval Observatory (1989-01-19): +# USA EASTERN 5 H BEHIND UTC NEW YORK, WASHINGTON +# USA EASTERN 4 H BEHIND UTC APR 3 - OCT 30 +# USA CENTRAL 6 H BEHIND UTC CHICAGO, HOUSTON +# USA CENTRAL 5 H BEHIND UTC APR 3 - OCT 30 +# USA MOUNTAIN 7 H BEHIND UTC DENVER +# USA MOUNTAIN 6 H BEHIND UTC APR 3 - OCT 30 +# USA PACIFIC 8 H BEHIND UTC L.A., SAN FRANCISCO +# USA PACIFIC 7 H BEHIND UTC APR 3 - OCT 30 +# USA ALASKA STD 9 H BEHIND UTC MOST OF ALASKA (AKST) +# USA ALASKA STD 8 H BEHIND UTC APR 3 - OCT 30 (AKDT) +# USA ALEUTIAN 10 H BEHIND UTC ISLANDS WEST OF 170W +# USA - " - 9 H BEHIND UTC APR 3 - OCT 30 +# USA HAWAII 10 H BEHIND UTC +# USA BERING 11 H BEHIND UTC SAMOA, MIDWAY + +# From Arthur David Olson (1989-01-21): +# The above dates are for 1988. +# Note the "AKST" and "AKDT" abbreviations, the claim that there's +# no DST in Samoa, and the claim that there is DST in Alaska and the +# Aleutians. + +# From Arthur David Olson (1988-02-13): +# Legal standard time zone names, from United States Code (1982 Edition and +# Supplement III), Title 15, Chapter 6, Section 260 and forward. First, names +# up to 1967-04-01 (when most provisions of the Uniform Time Act of 1966 +# took effect), as explained in sections 263 and 261: +# (none) +# United States standard eastern time +# United States standard mountain time +# United States standard central time +# United States standard Pacific time +# (none) +# United States standard Alaska time +# (none) +# Next, names from 1967-04-01 until 1983-11-30 (the date for +# public law 98-181): +# Atlantic standard time +# eastern standard time +# central standard time +# mountain standard time +# Pacific standard time +# Yukon standard time +# Alaska-Hawaii standard time +# Bering standard time +# And after 1983-11-30: +# Atlantic standard time +# eastern standard time +# central standard time +# mountain standard time +# Pacific standard time +# Alaska standard time +# Hawaii-Aleutian standard time +# Samoa standard time +# The law doesn't give abbreviations. +# +# From Paul Eggert (2000-01-08), following a heads-up from Rives McDow: +# Public law 106-564 (2000-12-23) introduced the abbreviation +# "Chamorro Standard Time" for time in Guam and the Northern Marianas. +# See the file "australasia". + + +# US eastern time, represented by New York + +# Connecticut, Delaware, District of Columbia, most of Florida, +# Georgia, southeast Indiana (Clark, Dearborn, Floyd, Harrison, and +# Ohio counties), eastern Kentucky, Maine, Maryland, Massachusetts, +# New Hampshire, New Jersey, New York, North Carolina, Ohio, +# Pennsylvania, Rhode Island, South Carolina, eastern Tennessee, +# Vermont, Virginia, West Virginia + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule NYC 1920 only - Mar lastSun 2:00 1:00 D +Rule NYC 1920 only - Oct lastSun 2:00 0 S +Rule NYC 1921 1966 - Apr lastSun 2:00 1:00 D +Rule NYC 1921 1954 - Sep lastSun 2:00 0 S +Rule NYC 1955 1966 - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/New_York -4:56:02 - LMT 1883 Nov 18 12:00 + -5:00 US E%sT 1920 + -5:00 NYC E%sT 1942 + -5:00 US E%sT 1946 + -5:00 NYC E%sT 1967 + -5:00 US E%sT + +# US central time, represented by Chicago + +# Alabama, Arkansas, Florida panhandle (Bay, Calhoun, Escambia, +# Gulf, Holmes, Jackson, Okaloosa, Santa Rosa, Walton, and +# Washington counties), Illinois, western Indiana +# (Gibson, Jasper, Lake, LaPorte, Newton, Porter, Posey, Spencer, +# Vanderburgh, and Warrick counties), Iowa, most of Kansas, western +# Kentucky, Louisiana, Minnesota, Mississippi, Missouri, eastern +# Nebraska, eastern North Dakota, Oklahoma, eastern South Dakota, +# western Tennessee, most of Texas, Wisconsin + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Chicago 1920 only - Jun 13 2:00 1:00 D +Rule Chicago 1920 1921 - Oct lastSun 2:00 0 S +Rule Chicago 1921 only - Mar lastSun 2:00 1:00 D +Rule Chicago 1922 1966 - Apr lastSun 2:00 1:00 D +Rule Chicago 1922 1954 - Sep lastSun 2:00 0 S +Rule Chicago 1955 1966 - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Chicago -5:50:36 - LMT 1883 Nov 18 12:00 + -6:00 US C%sT 1920 + -6:00 Chicago C%sT 1936 Mar 1 2:00 + -5:00 - EST 1936 Nov 15 2:00 + -6:00 Chicago C%sT 1942 + -6:00 US C%sT 1946 + -6:00 Chicago C%sT 1967 + -6:00 US C%sT +# Oliver County, ND switched from mountain to central time on 1992-10-25. +Zone America/North_Dakota/Center -6:45:12 - LMT 1883 Nov 18 12:00 + -7:00 US M%sT 1992 Oct 25 02:00 + -6:00 US C%sT + +# US mountain time, represented by Denver +# +# Colorado, far western Kansas, Montana, western +# Nebraska, Nevada border (Jackpot, Owyhee, and Mountain City), +# New Mexico, southwestern North Dakota, far eastern Oregon, +# western South Dakota, far western Texas (El Paso County, Hudspeth County, +# and Pine Springs and Nickel Creek in Culberson County), Utah, Wyoming +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Denver 1920 1921 - Mar lastSun 2:00 1:00 D +Rule Denver 1920 only - Oct lastSun 2:00 0 S +Rule Denver 1921 only - May 22 2:00 0 S +Rule Denver 1965 1966 - Apr lastSun 2:00 1:00 D +Rule Denver 1965 1966 - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Denver -6:59:56 - LMT 1883 Nov 18 12:00 + -7:00 US M%sT 1920 + -7:00 Denver M%sT 1942 + -7:00 US M%sT 1946 + -7:00 Denver M%sT 1967 + -7:00 US M%sT + +# US Pacific time, represented by Los Angeles +# +# California, northern Idaho (Benewah, Bonner, Boundary, Clearwater, +# Idaho, Kootenai, Latah, Lewis, Nez Perce, and Shoshone counties), +# most of Nevada, most of Oregon, and Washington +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule CA 1948 only - Mar 14 2:00 1:00 D +Rule CA 1949 only - Jan 1 2:00 0 S +Rule CA 1950 1966 - Apr lastSun 2:00 1:00 D +Rule CA 1950 1961 - Sep lastSun 2:00 0 S +Rule CA 1962 1966 - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Los_Angeles -7:52:58 - LMT 1883 Nov 18 12:00 + -8:00 US P%sT 1946 + -8:00 CA P%sT 1967 + -8:00 US P%sT + +# Alaska +# AK%sT is the modern abbreviation for -9:00 per USNO. +# +# From Paul Eggert (2001-05-30): +# Howse writes that Alaska switched from the Julian to the Gregorian calendar, +# and from east-of-GMT to west-of-GMT days, when the US bought it from Russia. +# This was on 1867-10-18, a Friday; the previous day was 1867-10-06 Julian, +# also a Friday. Include only the time zone part of this transition, +# ignoring the switch from Julian to Gregorian, since we can't represent +# the Julian calendar. +# +# As far as we know, none of the exact locations mentioned below were +# permanently inhabited in 1867 by anyone using either calendar. +# (Yakutat was colonized by the Russians in 1799, but the settlement +# was destroyed in 1805 by a Yakutat-kon war party.) However, there +# were nearby inhabitants in some cases and for our purposes perhaps +# it's best to simply use the official transition. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Juneau 15:02:19 - LMT 1867 Oct 18 + -8:57:41 - LMT 1900 Aug 20 12:00 + -8:00 - PST 1942 + -8:00 US P%sT 1946 + -8:00 - PST 1969 + -8:00 US P%sT 1983 Oct 30 2:00 + -9:00 US Y%sT 1983 Nov 30 + -9:00 US AK%sT +Zone America/Yakutat 14:41:05 - LMT 1867 Oct 18 + -9:18:55 - LMT 1900 Aug 20 12:00 + -9:00 - YST 1942 + -9:00 US Y%sT 1946 + -9:00 - YST 1969 + -9:00 US Y%sT 1983 Nov 30 + -9:00 US AK%sT +Zone America/Anchorage 14:00:24 - LMT 1867 Oct 18 + -9:59:36 - LMT 1900 Aug 20 12:00 + -10:00 - CAT 1942 + -10:00 US CAT/CAWT 1946 + -10:00 - CAT 1967 Apr + -10:00 - AHST 1969 + -10:00 US AH%sT 1983 Oct 30 2:00 + -9:00 US Y%sT 1983 Nov 30 + -9:00 US AK%sT +Zone America/Nome 12:58:21 - LMT 1867 Oct 18 + -11:01:38 - LMT 1900 Aug 20 12:00 + -11:00 - NST 1942 + -11:00 US N%sT 1946 + -11:00 - NST 1967 Apr + -11:00 - BST 1969 + -11:00 US B%sT 1983 Oct 30 2:00 + -9:00 US Y%sT 1983 Nov 30 + -9:00 US AK%sT +Zone America/Adak 12:13:21 - LMT 1867 Oct 18 + -11:46:38 - LMT 1900 Aug 20 12:00 + -11:00 - NST 1942 + -11:00 US N%sT 1946 + -11:00 - NST 1967 Apr + -11:00 - BST 1969 + -11:00 US B%sT 1983 Oct 30 2:00 + -10:00 US AH%sT 1983 Nov 30 + -10:00 US HA%sT +# Shanks writes that part of southwest Alaska (e.g. Aniak) +# switched from -11:00 to -10:00 on 1968-09-22 at 02:00, +# and another part (e.g. Akiak) made the same switch five weeks later. +# These switches don't quite make our 1970 cutoff. + +# Hawaii +# +# From Arthur David Olson: +# And then there's Hawaii. +# DST was observed for one day in 1933; +# standard time was changed by half an hour in 1947; +# it's always standard as of 1986. +# +# From Paul Eggert: +# Shanks says the 1933 experiment lasted for three weeks. Go with Shanks. +# +Zone Pacific/Honolulu -10:31:26 - LMT 1900 Jan 1 12:00 + -10:30 - HST 1933 Apr 30 2:00 + -10:30 1:00 HDT 1933 May 21 2:00 + -10:30 US H%sT 1947 Jun 8 2:00 + -10:00 - HST + +# Now we turn to US areas that have diverged from the consensus since 1970. + +# Arizona mostly uses MST. + +# From Paul Eggert (2002-10-20): +# +# The information in the rest of this paragraph is derived from the +# +# Daylight Saving Time web page (2002-01-23) maintained by the +# Arizona State Library, Archives and Public Records. +# Between 1944-01-01 and 1944-04-01 the State of Arizona used standard +# time, but by federal law railroads, airlines, bus lines, military +# personnel, and some engaged in interstate commerce continued to +# observe war (i.e., daylight saving) time. The 1944-03-17 Phoenix +# Gazette says that was the date the law changed, and that 04-01 was +# the date the state's clocks would change. In 1945 the State of +# Arizona used standard time all year, again with exceptions only as +# mandated by federal law. Arizona observed DST in 1967, but Arizona +# Laws 1968, ch. 183 (effective 1968-03-21) repealed DST. +# +# Shanks says the 1944 experiment came to an end on 1944-03-17. +# Go with the Arizona State Library instead. + +Zone America/Phoenix -7:28:18 - LMT 1883 Nov 18 12:00 + -7:00 US M%sT 1944 Jan 1 00:01 + -7:00 - MST 1944 Apr 1 00:01 + -7:00 US M%sT 1944 Oct 1 00:01 + -7:00 - MST 1967 + -7:00 US M%sT 1968 Mar 21 + -7:00 - MST +# From Arthur David Olson (1988-02-13): +# A writer from the Inter Tribal Council of Arizona, Inc., +# notes in private correspondence dated 1987-12-28 that "Presently, only the +# Navajo Nation participates in the Daylight Saving Time policy, due to its +# large size and location in three states." (The "only" means that other +# tribal nations don't use DST.) + +Link America/Denver America/Shiprock + +# Southern Idaho (Ada, Adams, Bannock, Bear Lake, Bingham, Blaine, +# Boise, Bonneville, Butte, Camas, Canyon, Caribou, Cassia, Clark, +# Custer, Elmore, Franklin, Fremont, Gem, Gooding, Jefferson, Jerome, +# Lemhi, Lincoln, Madison, Minidoka, Oneida, Owyhee, Payette, Power, +# Teton, Twin Falls, Valley, Washington counties) and eastern Oregon +# switched four weeks late in 1974. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Boise -7:44:49 - LMT 1883 Nov 18 12:00 + -8:00 US P%sT 1923 May 13 2:00 + -7:00 US M%sT 1974 + -7:00 - MST 1974 Feb 3 2:00 + -7:00 US M%sT + +# Indiana +# +# For a map of Indiana's time zone regions, see: +# +# What time is it in Indiana? +# (1999-04-06) +# +# From Paul Eggert (1995-12-19): +# Indiana generally observes either EST all year, or CST/CDT, +# but areas near Cincinnati and Louisville use those cities' timekeeping +# and in 1969 and 1970 the whole state observed daylight time; +# and there are other exceptions as noted below. +# Shanks partitions Indiana into 345 regions, each with its own time history, +# and writes ``Even newspaper reports present contradictory information.'' +# Fortunately, most of the complexity occurred before our cutoff date of 1970. +# +# Since 1970, EST-only Indiana has been like America/Indianapolis, +# with exceptions noted below for Crawford, Starke, and Switzerland counties. +# The parts of Indiana not listed below have been like America/Chicago, +# America/Louisville, or America/New_York. +# +# Other than Indianapolis, the Indiana place names are so nondescript +# that they would be ambiguous if we left them at the `America' level. +# So we reluctantly put them all in a subdirectory `America/Indiana'. +# +# Most of EST-only Indiana last observed DST in 1970. + +# From Paul Eggert (2001-03-06), following a tip by Markus Kuhn: +# Pam Belluck reported in the New York Times (2001-01-31) that the +# Indiana Legislature is considering a bill to adopt DST statewide. +# Her article mentioned Vevay, whose post office observes a different +# time zone from Danner's Hardware across the street. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Indianapolis 1941 only - Jun 22 2:00 1:00 D +Rule Indianapolis 1941 1954 - Sep lastSun 2:00 0 S +Rule Indianapolis 1946 1954 - Apr lastSun 2:00 1:00 D +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Indianapolis -5:44:38 - LMT 1883 Nov 18 12:00 + -6:00 US C%sT 1920 + -6:00 Indianapolis C%sT 1942 + -6:00 US C%sT 1946 + -6:00 Indianapolis C%sT 1955 Apr 24 2:00 + -5:00 - EST 1957 Sep 29 2:00 + -6:00 - CST 1958 Apr 27 2:00 + -5:00 - EST 1969 + -5:00 US E%sT 1971 + -5:00 - EST +Link America/Indianapolis America/Indiana/Indianapolis +# +# Part of Crawford County, Indiana, last observed DST in 1975, +# and left its clocks alone in 1974. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Marengo 1951 only - Apr lastSun 2:00 1:00 D +Rule Marengo 1951 only - Sep lastSun 2:00 0 S +Rule Marengo 1954 1960 - Apr lastSun 2:00 1:00 D +Rule Marengo 1954 1960 - Sep lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Indiana/Marengo -5:45:23 - LMT 1883 Nov 18 12:00 + -6:00 US C%sT 1951 + -6:00 Marengo C%sT 1961 Apr 30 2:00 + -5:00 - EST 1969 + -5:00 US E%sT 1974 Jan 6 2:00 + -6:00 1:00 CDT 1974 Oct 27 2:00 + -5:00 US E%sT 1976 + -5:00 - EST +# +# Starke County, Indiana +# From Arthur David Olson (1991-10-28): +# An article on page A3 of the Sunday, 1991-10-27 Washington Post +# notes that Starke County switched from Central time to Eastern time as of +# 1991-10-27. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Starke 1947 1961 - Apr lastSun 2:00 1:00 D +Rule Starke 1947 1954 - Sep lastSun 2:00 0 S +Rule Starke 1955 1956 - Oct lastSun 2:00 0 S +Rule Starke 1957 1958 - Sep lastSun 2:00 0 S +Rule Starke 1959 1961 - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Indiana/Knox -5:46:30 - LMT 1883 Nov 18 12:00 + -6:00 US C%sT 1947 + -6:00 Starke C%sT 1962 Apr 29 2:00 + -5:00 - EST 1963 Oct 27 2:00 + -6:00 US C%sT 1991 Oct 27 2:00 + -5:00 - EST +# +# Switzerland County, Indiana, last observed DST in 1972. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Indiana/Vevay -5:40:16 - LMT 1883 Nov 18 12:00 + -6:00 US C%sT 1954 Apr 25 2:00 + -5:00 - EST 1969 + -5:00 US E%sT 1973 + -5:00 - EST + +# Part of Kentucky left its clocks alone in 1974. +# This also includes a part of Indiana immediately adjacent to Louisville. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Louisville 1921 only - May 1 2:00 1:00 D +Rule Louisville 1921 only - Sep 1 2:00 0 S +Rule Louisville 1941 1961 - Apr lastSun 2:00 1:00 D +Rule Louisville 1941 only - Sep lastSun 2:00 0 S +Rule Louisville 1946 only - Jun 2 2:00 0 S +Rule Louisville 1950 1955 - Sep lastSun 2:00 0 S +Rule Louisville 1956 1960 - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Louisville -5:43:02 - LMT 1883 Nov 18 12:00 + -6:00 US C%sT 1921 + -6:00 Louisville C%sT 1942 + -6:00 US C%sT 1946 + -6:00 Louisville C%sT 1961 Jul 23 2:00 + -5:00 - EST 1968 + -5:00 US E%sT 1974 Jan 6 2:00 + -6:00 1:00 CDT 1974 Oct 27 2:00 + -5:00 US E%sT +Link America/Louisville America/Kentucky/Louisville +# +# Wayne, Clinton, and Russell Counties, Kentucky +# +# From +# +# Lake Cumberland LIFE +# (1999-01-29) via WKYM-101.7: +# Clinton County has joined Wayne County in asking the DoT to change from +# the Central to the Eastern time zone.... The Wayne County government made +# the same request in December. And while Russell County officials have not +# taken action, the majority of respondents to a poll conducted there in +# August indicated they would like to change to "fast time" also. +# The three Lake Cumberland counties are the farthest east of any U.S. +# location in the Central time zone. +# +# From Rich Wales (2000-08-29): +# After prolonged debate, and despite continuing deep differences of opinion, +# Wayne County (central Kentucky) is switching from Central (-0600) to Eastern +# (-0500) time. They won't "fall back" this year. See Sara Shipley, +# The difference an hour makes, Nando Times (2000-08-29 15:33 -0400). +# +# From Paul Eggert (2001-07-16): +# The final rule was published in the +# +# Federal Register 65, 160 (2000-08-17), page 50154-50158. +# +# +Zone America/Kentucky/Monticello -5:39:24 - LMT 1883 Nov 18 12:00 + -6:00 US C%sT 1946 + -6:00 - CST 1968 + -6:00 US C%sT 2000 Oct 29 2:00 + -5:00 US E%sT + + +# From Rives McDow (2000-08-30): +# Here ... are all the changes in the US since 1985. +# Kearny County, KS (put all of county on central; +# previously split between MST and CST) ... 1990-10 +# Starke County, IN (from CST to EST) ... 1991-10 +# Oliver County, ND (from MST to CST) ... 1992-10 +# West Wendover, NV (from PST TO MST) ... 1999-10 +# Wayne County, KY (from CST to EST) ... 2000-10 +# +# From Paul Eggert (2001-07-17): +# We don't know where the line used to be within Kearny County, KS, +# so omit that change for now. +# See America/Indiana/Knox for the Starke County, IN change. +# See America/North_Dakota/Center for the Oliver County, ND change. +# West Wendover, NV officially switched from Pacific to mountain time on +# 1999-10-31. See the +# +# Federal Register 64, 203 (1999-10-21), page 56705-56707. +# +# However, the Federal Register says that West Wendover already operated +# on mountain time, and the rule merely made this official; +# hence a separate tz entry is not needed. + +# Michigan +# +# From Bob Devine (1988-01-28): +# Michigan didn't observe DST from 1968 to 1973. +# +# From Paul Eggert (1999-03-31): +# Shanks writes that Michigan started using standard time on 1885-09-18, +# but Howse writes (pp 124-125, referring to Popular Astronomy, 1901-01) +# that Detroit kept +# +# local time until 1900 when the City Council decreed that clocks should +# be put back twenty-eight minutes to Central Standard Time. Half the +# city obeyed, half refused. After considerable debate, the decision +# was rescinded and the city reverted to Sun time. A derisive offer to +# erect a sundial in front of the city hall was referred to the +# Committee on Sewers. Then, in 1905, Central time was adopted +# by city vote. +# +# This story is too entertaining to be false, so go with Howse over Shanks. +# +# From Paul Eggert (2001-03-06): +# Garland (1927) writes ``Cleveland and Detroit advanced their clocks +# one hour in 1914.'' This change is not in Shanks. We have no more +# info, so omit this for now. +# +# Most of Michigan observed DST from 1973 on, but was a bit late in 1975. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Detroit 1948 only - Apr lastSun 2:00 1:00 D +Rule Detroit 1948 only - Sep lastSun 2:00 0 S +Rule Detroit 1967 only - Jun 14 2:00 1:00 D +Rule Detroit 1967 only - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Detroit -5:32:11 - LMT 1905 + -6:00 - CST 1915 May 15 2:00 + -5:00 - EST 1942 + -5:00 US E%sT 1946 + -5:00 Detroit E%sT 1973 + -5:00 US E%sT 1975 + -5:00 - EST 1975 Apr 27 2:00 + -5:00 US E%sT +# +# The Michigan border with Wisconsin switched from EST to CST/CDT in 1973. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER +Rule Menominee 1946 only - Apr lastSun 2:00 1:00 D +Rule Menominee 1946 only - Sep lastSun 2:00 0 S +Rule Menominee 1966 only - Apr lastSun 2:00 1:00 D +Rule Menominee 1966 only - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Menominee -5:50:27 - LMT 1885 Sep 18 12:00 + -6:00 US C%sT 1946 + -6:00 Menominee C%sT 1969 Apr 27 2:00 + -5:00 - EST 1973 Apr 29 2:00 + -6:00 US C%sT + +# Navassa +# administered by the US Fish and Wildlife Service +# claimed by US under the provisions of the 1856 Guano Islands Act +# also claimed by Haiti +# occupied 1857/1900 by the Navassa Phosphate Co +# US lighthouse 1917/1996-09 +# currently uninhabited +# see Mark Fineman, ``An Isle Rich in Guano and Discord'', +# _Los Angeles Times_ (1998-11-10), A1, A10; it cites +# Jimmy Skaggs, _The Great Guano Rush_ (1994). + +# Old names, for S5 users + +# Link LINK-FROM LINK-TO +Link America/New_York EST5EDT +Link America/Chicago CST6CDT +Link America/Denver MST7MDT +Link America/Los_Angeles PST8PDT +Link America/Indianapolis EST +Link America/Phoenix MST +Link Pacific/Honolulu HST + +################################################################################ + + +# From Paul Eggert (1999-10-29): +# A good source for time zone historical data outside the US is +# Thomas G. Shanks, The International Atlas (5th edition), +# San Diego: ACS Publications, Inc. (1999). +# +# Gwillim Law writes that a good source +# for recent time zone data is the International Air Transport +# Association's Standard Schedules Information Manual (IATA SSIM), +# published semiannually. Law sent in several helpful summaries +# of the IATA's data after 1990. +# +# Except where otherwise noted, Shanks is the source for entries through 1990, +# and IATA SSIM is the source for entries after 1990. +# +# Other sources occasionally used include: +# +# Edward W. Whitman, World Time Differences, +# Whitman Publishing Co, 2 Niagara Av, Ealing, London (undated), +# which I found in the UCLA library. +# +# +# William Willett, The Waste of Daylight, 19th edition +# (1914-03) +# +# See the `europe' file for Greenland. + +# Canada + +# From Alain LaBont (1994-11-14): +# I post here the time zone abbreviations standardized in Canada +# for both English and French in the CAN/CSA-Z234.4-89 standard.... +# +# UTC Standard time Daylight savings time +# offset French English French English +# -2:30 - - HAT NDT +# -3 - - HAA ADT +# -3:30 HNT NST - - +# -4 HNA AST HAE EDT +# -5 HNE EST HAC CDT +# -6 HNC CST HAR MDT +# -7 HNR MST HAP PDT +# -8 HNP PST HAY YDT +# -9 HNY YST - - +# +# HN: Heure Normale ST: Standard Time +# HA: Heure Avance DT: Daylight saving Time +# +# A: de l'Atlantique Atlantic +# C: du Centre Central +# E: de l'Est Eastern +# M: Mountain +# N: Newfoundland +# P: du Pacifique Pacific +# R: des Rocheuses +# T: de Terre-Neuve +# Y: du Yukon Yukon +# +# From Paul Eggert (1994-11-22): +# Alas, this sort of thing must be handled by localization software. + +# Unless otherwise specified, the data for Canada are all from Shanks. + +# From Paul Eggert (2000-10-02): +# H. David Matthews and Mary Vincent's map +# +# "It's about TIME", _Canadian Geographic_ (September-October 1998) +# contains detailed boundaries for regions observing nonstandard +# time and daylight saving time arrangements in Canada circa 1998. +# +# INMS, the Institute for National Measurement Standards in Ottawa, has +# +# information about standard and daylight saving time zones in Canada. +# (updated periodically). +# Its unofficial information is often taken from Matthews and Vincent. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Canada 1918 only - Apr 14 2:00 1:00 D +Rule Canada 1918 only - Oct 31 2:00 0 S +Rule Canada 1942 only - Feb 9 2:00 1:00 W # War +Rule Canada 1945 only - Aug 14 23:00u 1:00 P # Peace +Rule Canada 1945 only - Sep 30 2:00 0 S +Rule Canada 1974 1986 - Apr lastSun 2:00 1:00 D +Rule Canada 1974 max - Oct lastSun 2:00 0 S +Rule Canada 1987 max - Apr Sun>=1 2:00 1:00 D + + +# Newfoundland (and far southeast Labrador) + +# From Paul Eggert (2000-10-02): +# Matthews and Vincent (1998) write that Labrador should use NST/NDT, +# but the only part of Labrador that follows the rules is the +# southeast corner, including Port Hope Simpson and Mary's Harbour, +# but excluding, say, Black Tickle. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule StJohns 1917 only - Apr 8 2:00 1:00 D +Rule StJohns 1917 only - Sep 17 2:00 0 S +# Whitman gives 1919 Apr 5 and 1920 Apr 5; go with Shanks. +Rule StJohns 1919 only - May 5 23:00 1:00 D +Rule StJohns 1919 only - Aug 12 23:00 0 S +# For 1931-1935 Whitman gives Apr same date; go with Shanks. +Rule StJohns 1920 1935 - May Sun>=1 23:00 1:00 D +Rule StJohns 1920 1935 - Oct lastSun 23:00 0 S +# For 1936-1941 Whitman gives May Sun>=8 and Oct Sun>=1; go with Shanks. +Rule StJohns 1936 1941 - May Mon>=9 0:00 1:00 D +Rule StJohns 1936 1941 - Oct Mon>=2 0:00 0 S +# Whitman gives the following transitions: +# 1942 03-01/12-31, 1943 05-30/09-05, 1944 07-10/09-02, 1945 01-01/10-07 +# but go with Shanks and assume they used Canadian rules. +# For 1946-9 Whitman gives May 5,4,9,1 - Oct 1,5,3,2, and for 1950 he gives +# Apr 30 - Sep 24; go with Shanks. +Rule StJohns 1946 1950 - May Sun>=8 2:00 1:00 D +Rule StJohns 1946 1950 - Oct Sun>=2 2:00 0 S +Rule StJohns 1951 1986 - Apr lastSun 2:00 1:00 D +Rule StJohns 1951 1959 - Sep lastSun 2:00 0 S +Rule StJohns 1960 1986 - Oct lastSun 2:00 0 S +# From Paul Eggert (2000-10-02): +# INMS (2000-09-12) says that, since 1988 at least, Newfoundland switches +# at 00:01 local time. For now, assume it started in 1987. +Rule StJohns 1987 only - Apr Sun>=1 0:01 1:00 D +Rule StJohns 1987 max - Oct lastSun 0:01 0 S +Rule StJohns 1988 only - Apr Sun>=1 0:01 2:00 DD +Rule StJohns 1989 max - Apr Sun>=1 0:01 1:00 D +# St John's has an apostrophe, but Posix file names can't have apostrophes. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/St_Johns -3:30:52 - LMT 1884 + -3:30:52 StJohns N%sT 1918 + -3:30:52 Canada N%sT 1919 + -3:30:52 StJohns N%sT 1935 Mar 30 + -3:30 StJohns N%sT 1942 May 11 + -3:30 Canada N%sT 1946 + -3:30 StJohns N%sT + +# most of east Labrador + +# The name `Happy Valley-Goose Bay' is too long; use `Goose Bay'. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Goose_Bay -4:01:40 - LMT 1884 # Happy Valley-Goose Bay + -3:30:52 - NST 1918 + -3:30:52 Canada N%sT 1919 + -3:30:52 - NST 1935 Mar 30 + -3:30 - NST 1936 + -3:30 StJohns N%sT 1942 May 11 + -3:30 Canada N%sT 1946 + -3:30 StJohns N%sT 1966 Mar 15 2:00 + -4:00 StJohns A%sT + + +# west Labrador, New Brunswick, Nova Scotia, Prince Edward I + +# From Paul Eggert (1996-06-12): +# Shanks writes that since 1970 most of this region has been like Halifax. +# Many locales did not observe peacetime DST until 1972; +# Glace Bay, NS is the largest that we know of. +# Shanks also writes that Liverpool, NS was the only town in Canada to observe +# DST in 1971 but not 1970; for now we'll assume this is a typo. + +# From Paul Eggert (2000-10-02): +# INMS (2000-09-12) says that, since 1988 at least, New Brunswick switches +# at 00:01 local time. FIXME: verify and create a new Zone for this. + + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Halifax 1916 only - Apr 1 0:00 1:00 D +Rule Halifax 1916 only - Oct 1 0:00 0 S +Rule Halifax 1920 only - May 9 0:00 1:00 D +Rule Halifax 1920 only - Aug 29 0:00 0 S +Rule Halifax 1921 only - May 6 0:00 1:00 D +Rule Halifax 1921 1922 - Sep 5 0:00 0 S +Rule Halifax 1922 only - Apr 30 0:00 1:00 D +Rule Halifax 1923 1925 - May Sun>=1 0:00 1:00 D +Rule Halifax 1923 only - Sep 4 0:00 0 S +Rule Halifax 1924 only - Sep 15 0:00 0 S +Rule Halifax 1925 only - Sep 28 0:00 0 S +Rule Halifax 1926 only - May 16 0:00 1:00 D +Rule Halifax 1926 only - Sep 13 0:00 0 S +Rule Halifax 1927 only - May 1 0:00 1:00 D +Rule Halifax 1927 only - Sep 26 0:00 0 S +Rule Halifax 1928 1931 - May Sun>=8 0:00 1:00 D +Rule Halifax 1928 only - Sep 9 0:00 0 S +Rule Halifax 1929 only - Sep 3 0:00 0 S +Rule Halifax 1930 only - Sep 15 0:00 0 S +Rule Halifax 1931 1932 - Sep Mon>=24 0:00 0 S +Rule Halifax 1932 only - May 1 0:00 1:00 D +Rule Halifax 1933 only - Apr 30 0:00 1:00 D +Rule Halifax 1933 only - Oct 2 0:00 0 S +Rule Halifax 1934 only - May 20 0:00 1:00 D +Rule Halifax 1934 only - Sep 16 0:00 0 S +Rule Halifax 1935 only - Jun 2 0:00 1:00 D +Rule Halifax 1935 only - Sep 30 0:00 0 S +Rule Halifax 1936 only - Jun 1 0:00 1:00 D +Rule Halifax 1936 only - Sep 14 0:00 0 S +Rule Halifax 1937 1938 - May Sun>=1 0:00 1:00 D +Rule Halifax 1937 1941 - Sep Mon>=24 0:00 0 S +Rule Halifax 1939 only - May 28 0:00 1:00 D +Rule Halifax 1940 1941 - May Sun>=1 0:00 1:00 D +Rule Halifax 1946 1949 - Sep lastSun 2:00 0 S +Rule Halifax 1946 1949 - Apr lastSun 2:00 1:00 D +Rule Halifax 1951 1954 - Sep lastSun 2:00 0 S +Rule Halifax 1951 1954 - Apr lastSun 2:00 1:00 D +Rule Halifax 1956 1959 - Sep lastSun 2:00 0 S +Rule Halifax 1956 1959 - Apr lastSun 2:00 1:00 D +Rule Halifax 1962 1973 - Apr lastSun 2:00 1:00 D +Rule Halifax 1962 1973 - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Halifax -4:14:24 - LMT 1902 Jun 15 + -4:00 Halifax A%sT 1918 + -4:00 Canada A%sT 1919 + -4:00 Halifax A%sT 1942 Feb 9 2:00s + -4:00 Canada A%sT 1946 + -4:00 Halifax A%sT 1974 + -4:00 Canada A%sT +Zone America/Glace_Bay -3:59:48 - LMT 1902 Jun 15 + -4:00 Canada A%sT 1953 + -4:00 Halifax A%sT 1954 + -4:00 - AST 1972 + -4:00 Halifax A%sT 1974 + -4:00 Canada A%sT + + +# Ontario, Quebec + +# From Paul Eggert (1996-06-12): +# Shanks writes that since 1970 most of Ontario has been like Toronto, +# and most of Quebec has been like Montreal. +# Thunder Bay skipped DST in 1973. +# Many smaller locales did not observe peacetime DST until 1974; +# Nipigon (EST) and Rainy River (CST) are the largest that we know of. +# Far west Ontario is like Winnipeg; far east Quebec is like Halifax. + +# From Mark Brader (2003-07-26): +# [According to the Toronto Star] Orillia, Ontario, adopted DST +# effective Saturday, 1912-06-22, 22:00; the article mentions that +# Port Arthur (now part of Thunder Bay, Ontario) as well as Moose Jaw +# have already done so. In Orillia DST was to run until Saturday, +# 1912-08-31 (no time mentioned), but it was met with considerable +# hostility from certain segments of the public, and was revoked after +# only two weeks -- I copied it as Saturday, 1912-07-07, 22:00, but +# presumably that should be -07-06. (1912-06-19, -07-12; also letters +# earlier in June). +# +# Kenora, Ontario, was to abandon DST on 1914-06-01 (-05-21). + +# From Paul Eggert (1997-10-17): +# Mark Brader writes that an article in the 1997-10-14 Toronto Star +# says that Atikokan, Ontario currently does not observe DST, +# but will vote on 11-10 whether to use EST/EDT. +# He also writes that the +# +# Ontario Time Act (1990, Chapter T.9) +# +# says that Ontario east of 90W uses EST/EDT, and west of 90W uses CST/CDT. +# Officially Atikokan is therefore on CST/CDT, and most likely this report +# concerns a non-official time observed as a matter of local practice. +# For what it's worth, Shanks says that Atikokan has agreed with +# Rainy River ever since standard time was introduced. + +# From Paul Eggert (2000-10-02): +# Matthews and Vincent (1998) write that Atikokan, Pickle Lake, and +# New Osnaburgh observe CST all year, that Big Trout Lake observes +# CST/CDT, and that Upsala and Shebandowan observe EST/EDT, all in +# violation of the official Ontario rules. +# They also write that Quebec east of the -63 meridian is supposed to +# observe AST, but residents as far east as Natashquan use EST/EDT, +# and residents east of Natashquan use AST. +# We probably need Zones for far east Quebec and for Atikokan, +# but we don't know when their practices started. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Mont 1917 only - Mar 25 2:00 1:00 D +Rule Mont 1917 only - Apr 24 0:00 0 S +Rule Mont 1919 only - Mar 31 2:30 1:00 D +Rule Mont 1919 only - Oct 25 2:30 0 S +Rule Mont 1920 only - May 2 2:30 1:00 D +Rule Mont 1920 1922 - Oct Sun>=1 2:30 0 S +Rule Mont 1921 only - May 1 2:00 1:00 D +Rule Mont 1922 only - Apr 30 2:00 1:00 D +Rule Mont 1924 only - May 17 2:00 1:00 D +Rule Mont 1924 1926 - Sep lastSun 2:30 0 S +Rule Mont 1925 1926 - May Sun>=1 2:00 1:00 D +# The 1927-to-1937 rules can be expressed more simply as +# Rule Mont 1927 1937 - Apr lastSat 24:00 1:00 D +# Rule Mont 1927 1937 - Sep lastSat 24:00 0 S +# The rules below avoid use of 24:00 +# (which pre-1998 versions of zic cannot handle). +Rule Mont 1927 only - May 1 0:00 1:00 D +Rule Mont 1927 1932 - Sep lastSun 0:00 0 S +Rule Mont 1928 1931 - Apr lastSun 0:00 1:00 D +Rule Mont 1932 only - May 1 0:00 1:00 D +Rule Mont 1933 1940 - Apr lastSun 0:00 1:00 D +Rule Mont 1933 only - Oct 1 0:00 0 S +Rule Mont 1934 1939 - Sep lastSun 0:00 0 S +Rule Mont 1946 1973 - Apr lastSun 2:00 1:00 D +Rule Mont 1945 1948 - Sep lastSun 2:00 0 S +Rule Mont 1949 1950 - Oct lastSun 2:00 0 S +Rule Mont 1951 1956 - Sep lastSun 2:00 0 S +Rule Mont 1957 1973 - Oct lastSun 2:00 0 S + +Rule Toronto 1919 only - Mar 30 23:30 1:00 D +Rule Toronto 1919 only - Oct 26 0:00 0 S +Rule Toronto 1920 only - May 2 2:00 1:00 D +Rule Toronto 1920 only - Sep 26 0:00 0 S +Rule Toronto 1921 only - May 15 2:00 1:00 D +Rule Toronto 1921 only - Sep 15 2:00 0 S +Rule Toronto 1922 1923 - May Sun>=8 2:00 1:00 D +# Shanks says 1923-09-19; assume it's a typo and that "-16" was meant. +Rule Toronto 1922 1926 - Sep Sun>=15 2:00 0 S +Rule Toronto 1924 1927 - May Sun>=1 2:00 1:00 D +# The 1927-to-1939 rules can be expressed more simply as +# Rule Toronto 1927 1937 - Sep Sun>=25 2:00 0 S +# Rule Toronto 1928 1937 - Apr Sun>=25 2:00 1:00 D +# Rule Toronto 1938 1940 - Apr lastSun 2:00 1:00 D +# Rule Toronto 1938 1939 - Sep lastSun 2:00 0 S +# The rules below avoid use of Sun>=25 +# (which pre-2004 versions of zic cannot handle). +Rule Toronto 1927 1932 - Sep lastSun 2:00 0 S +Rule Toronto 1928 1931 - Apr lastSun 2:00 1:00 D +Rule Toronto 1932 only - May 1 2:00 1:00 D +Rule Toronto 1933 1940 - Apr lastSun 2:00 1:00 D +Rule Toronto 1933 only - Oct 1 2:00 0 S +Rule Toronto 1934 1939 - Sep lastSun 2:00 0 S +Rule Toronto 1945 1946 - Sep lastSun 2:00 0 S +Rule Toronto 1946 only - Apr lastSun 2:00 1:00 D +Rule Toronto 1947 1949 - Apr lastSun 0:00 1:00 D +Rule Toronto 1947 1948 - Sep lastSun 0:00 0 S +Rule Toronto 1949 only - Nov lastSun 0:00 0 S +Rule Toronto 1950 1973 - Apr lastSun 2:00 1:00 D +Rule Toronto 1950 only - Nov lastSun 2:00 0 S +Rule Toronto 1951 1956 - Sep lastSun 2:00 0 S +# Shanks says Toronto ended DST a week early in 1971, namely on 1971-10-24, +# but Mark Brader wrote (2003-05-31) that he checked the 1971-10-30 issue +# of the Toronto Star, and it said that DST ended 1971-10-31 as usual. +Rule Toronto 1957 1973 - Oct lastSun 2:00 0 S + +# From Paul Eggert (2003-07-27): +# Willett (1914-03) writes (p. 17) "In the Cities of Fort William, and +# Port Arthur, Ontario, the principle of the Bill has been in +# operation for the past three years, and in the City of Moose Jaw, +# Saskatchewan, for one year." + +# From David Bryan via Tory Tronrud, Director/Curator, +# Thunder Bay Museum (2003-11-12): +# There is some suggestion, however, that, by-law or not, daylight +# savings time was being practiced in Fort William and Port Arthur +# before 1909.... [I]n 1910, the line between the Eastern and Central +# Time Zones was permanently moved about two hundred miles west to +# include the Thunder Bay area.... When Canada adopted daylight +# savings time in 1916, Fort William and Port Arthur, having done so +# already, did not change their clocks.... During the Second World +# War,... [t]he cities agreed to implement DST during the summer +# months for the remainder of the war years. + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Montreal -4:54:16 - LMT 1884 + -5:00 Mont E%sT 1918 + -5:00 Canada E%sT 1919 + -5:00 Mont E%sT 1942 Feb 9 2:00s + -5:00 Canada E%sT 1946 + -5:00 Mont E%sT 1974 + -5:00 Canada E%sT +Zone America/Toronto -5:17:32 - LMT 1895 + -5:00 Canada E%sT 1919 + -5:00 Toronto E%sT 1942 Feb 9 2:00s + -5:00 Canada E%sT 1946 + -5:00 Toronto E%sT 1974 + -5:00 Canada E%sT +Zone America/Thunder_Bay -5:57:00 - LMT 1895 + -6:00 - CST 1910 + -5:00 - EST 1942 + -5:00 Canada E%sT 1970 + -5:00 Mont E%sT 1973 + -5:00 - EST 1974 + -5:00 Canada E%sT +Zone America/Nipigon -5:53:04 - LMT 1895 + -5:00 Canada E%sT 1940 Sep 29 + -5:00 1:00 EDT 1942 Feb 9 2:00s + -5:00 Canada E%sT +Zone America/Rainy_River -6:17:56 - LMT 1895 + -6:00 Canada C%sT 1940 Sep 29 + -6:00 1:00 CDT 1942 Feb 9 2:00s + -6:00 Canada C%sT + + +# Manitoba + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Winn 1916 only - Apr 23 0:00 1:00 D +Rule Winn 1916 only - Sep 17 0:00 0 S +Rule Winn 1918 only - Apr 14 2:00 1:00 D +Rule Winn 1918 only - Oct 31 2:00 0 S +Rule Winn 1937 only - May 16 2:00 1:00 D +Rule Winn 1937 only - Sep 26 2:00 0 S +Rule Winn 1942 only - Feb 9 2:00 1:00 W # War +Rule Winn 1945 only - Aug 14 23:00u 1:00 P # Peace +Rule Winn 1945 only - Sep lastSun 2:00 0 S +Rule Winn 1946 only - May 12 2:00 1:00 D +Rule Winn 1946 only - Oct 13 2:00 0 S +Rule Winn 1947 1949 - Apr lastSun 2:00 1:00 D +Rule Winn 1947 1949 - Sep lastSun 2:00 0 S +Rule Winn 1950 only - May 1 2:00 1:00 D +Rule Winn 1950 only - Sep 30 2:00 0 S +Rule Winn 1951 1960 - Apr lastSun 2:00 1:00 D +Rule Winn 1951 1958 - Sep lastSun 2:00 0 S +Rule Winn 1959 only - Oct lastSun 2:00 0 S +Rule Winn 1960 only - Sep lastSun 2:00 0 S +Rule Winn 1963 only - Apr lastSun 2:00 1:00 D +Rule Winn 1963 only - Sep 22 2:00 0 S +Rule Winn 1966 1986 - Apr lastSun 2:00 1:00 D +Rule Winn 1966 1986 - Oct lastSun 2:00 0 S +Rule Winn 1987 max - Apr Sun>=1 2:00 1:00 D +# From Paul Eggert (2000-10-02): +# INMS (2000-09-12) says that, since 1988 at least, Manitoba switches from +# DST at 03:00 local time. For now, assume it started in 1987. +Rule Winn 1987 max - Oct lastSun 2:00s 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Winnipeg -6:28:36 - LMT 1887 Jul 16 + -6:00 Winn C%sT + + +# Saskatchewan + +# From Mark Brader (2003-07-26): +# The first actual adoption of DST in Canada was at the municipal +# level. As the [Toronto] Star put it (1912-06-07), "While people +# elsewhere have long been talking of legislation to save daylight, +# the city of Moose Jaw [Saskatchewan] has acted on its own hook." +# DST in Moose Jaw began on Saturday, 1912-06-01 (no time mentioned: +# presumably late evening, as below), and would run until "the end of +# the summer". The discrepancy between municipal time and railroad +# time was noted. + +# From Paul Eggert (2003-07-27): +# Willett (1914-03) notes that DST "has been in operation ... in the +# City of Moose Jaw, Saskatchewan, for one year." + +# From Paul Eggert (2000-10-02): +# Shanks writes that since 1970 most of this region has been like Regina. +# Some western towns (e.g. Swift Current) switched from MST/MDT to CST in 1972. +# Other western towns (e.g. Lloydminster) are like Edmonton. +# Matthews and Vincent (1998) write that Denare Beach and Creighton +# are like Winnipeg, in violation of Saskatchewan law. + +# From W. Jones (1992-11-06): +# The. . .below is based on information I got from our law library, the +# provincial archives, and the provincial Community Services department. +# A precise history would require digging through newspaper archives, and +# since you didn't say what you wanted, I didn't bother. +# +# Saskatchewan is split by a time zone meridian (105W) and over the years +# the boundary became pretty ragged as communities near it reevaluated +# their affiliations in one direction or the other. In 1965 a provincial +# referendum favoured legislating common time practices. +# +# On 15 April 1966 the Time Act (c. T-14, Revised Statutes of +# Saskatchewan 1978) was proclaimed, and established that the eastern +# part of Saskatchewan would use CST year round, that districts in +# northwest Saskatchewan would by default follow CST but could opt to +# follow Mountain Time rules (thus 1 hour difference in the winter and +# zero in the summer), and that districts in southwest Saskatchewan would +# by default follow MT but could opt to follow CST. +# +# It took a few years for the dust to settle (I know one story of a town +# on one time zone having its school in another, such that a mom had to +# serve her family lunch in two shifts), but presently it seems that only +# a few towns on the border with Alberta (e.g. Lloydminster) follow MT +# rules any more; all other districts appear to have used CST year round +# since sometime in the 1960s. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Regina 1918 only - Apr 14 2:00 1:00 D +Rule Regina 1918 only - Oct 31 2:00 0 S +Rule Regina 1930 1934 - May Sun>=1 0:00 1:00 D +Rule Regina 1930 1934 - Oct Sun>=1 0:00 0 S +Rule Regina 1937 1941 - Apr Sun>=8 0:00 1:00 D +Rule Regina 1937 only - Oct Sun>=8 0:00 0 S +Rule Regina 1938 only - Oct Sun>=1 0:00 0 S +Rule Regina 1939 1941 - Oct Sun>=8 0:00 0 S +Rule Regina 1942 only - Feb 9 2:00 1:00 W # War +Rule Regina 1945 only - Aug 14 23:00u 1:00 P # Peace +Rule Regina 1945 only - Sep lastSun 2:00 0 S +Rule Regina 1946 only - Apr Sun>=8 2:00 1:00 D +Rule Regina 1946 only - Oct Sun>=8 2:00 0 S +Rule Regina 1947 1957 - Apr lastSun 2:00 1:00 D +Rule Regina 1947 1957 - Sep lastSun 2:00 0 S +Rule Regina 1959 only - Apr lastSun 2:00 1:00 D +Rule Regina 1959 only - Oct lastSun 2:00 0 S +# +Rule Swift 1957 only - Apr lastSun 2:00 1:00 D +Rule Swift 1957 only - Oct lastSun 2:00 0 S +Rule Swift 1959 1961 - Apr lastSun 2:00 1:00 D +Rule Swift 1959 only - Oct lastSun 2:00 0 S +Rule Swift 1960 1961 - Sep lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Regina -6:58:36 - LMT 1905 Sep + -7:00 Regina M%sT 1960 Apr lastSun 2:00 + -6:00 - CST +Zone America/Swift_Current -7:11:20 - LMT 1905 Sep + -7:00 Canada M%sT 1946 Apr lastSun 2:00 + -7:00 Regina M%sT 1950 + -7:00 Swift M%sT 1972 Apr lastSun 2:00 + -6:00 - CST + + +# Alberta + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Edm 1918 1919 - Apr Sun>=8 2:00 1:00 D +Rule Edm 1918 only - Oct 31 2:00 0 S +Rule Edm 1919 only - May 27 2:00 0 S +Rule Edm 1920 1923 - Apr lastSun 2:00 1:00 D +Rule Edm 1920 only - Oct lastSun 2:00 0 S +Rule Edm 1921 1923 - Sep lastSun 2:00 0 S +Rule Edm 1942 only - Feb 9 2:00 1:00 W # War +Rule Edm 1945 only - Aug 14 23:00u 1:00 P # Peace +Rule Edm 1945 only - Sep lastSun 2:00 0 S +Rule Edm 1947 only - Apr lastSun 2:00 1:00 D +Rule Edm 1947 only - Sep lastSun 2:00 0 S +Rule Edm 1967 only - Apr lastSun 2:00 1:00 D +Rule Edm 1967 only - Oct lastSun 2:00 0 S +Rule Edm 1969 only - Apr lastSun 2:00 1:00 D +Rule Edm 1969 only - Oct lastSun 2:00 0 S +Rule Edm 1972 1986 - Apr lastSun 2:00 1:00 D +Rule Edm 1972 max - Oct lastSun 2:00 0 S +Rule Edm 1987 max - Apr Sun>=1 2:00 1:00 D +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Edmonton -7:33:52 - LMT 1906 Sep + -7:00 Edm M%sT + + +# British Columbia + +# From Paul Eggert (2000-10-02): +# Shanks writes that since 1970 most of this region has been like Vancouver. +# Dawson Creek uses MST. Much of east BC is like Edmonton. +# Matthews and Vincent (1998) write that Creston is like Dawson Creek. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Vanc 1918 only - Apr 14 2:00 1:00 D +Rule Vanc 1918 only - Oct 31 2:00 0 S +Rule Vanc 1942 only - Feb 9 2:00 1:00 W # War +Rule Vanc 1945 only - Aug 14 23:00u 1:00 P # Peace +Rule Vanc 1945 only - Sep 30 2:00 0 S +Rule Vanc 1946 1986 - Apr lastSun 2:00 1:00 D +Rule Vanc 1946 only - Oct 13 2:00 0 S +Rule Vanc 1947 1961 - Sep lastSun 2:00 0 S +Rule Vanc 1962 max - Oct lastSun 2:00 0 S +Rule Vanc 1987 max - Apr Sun>=1 2:00 1:00 D +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Vancouver -8:12:28 - LMT 1884 + -8:00 Vanc P%sT +Zone America/Dawson_Creek -8:00:56 - LMT 1884 + -8:00 Canada P%sT 1947 + -8:00 Vanc P%sT 1972 Aug 30 2:00 + -7:00 - MST + + +# Northwest Territories, Nunavut, Yukon + +# From Paul Eggert (1999-10-29): +# Dawson switched to PST in 1973. Inuvik switched to MST in 1979. +# Mathew Englander (1996-10-07) gives the following refs: +# * 1967. Paragraph 28(34)(g) of the Interpretation Act, S.C. 1967-68, +# c. 7 defines Yukon standard time as UTC-9. This is still valid; +# see Interpretation Act, R.S.C. 1985, c. I-21, s. 35(1). +# * C.O. 1973/214 switched Yukon to PST on 1973-10-28 00:00. +# * O.I.C. 1980/02 established DST. +# * O.I.C. 1987/056 changed DST to Apr firstSun 2:00 to Oct lastSun 2:00. +# Shanks says Yukon's 1973-10-28 switch was at 2:00; go with Englander. + +# From Rives McDow (1999-09-04): +# Nunavut ... moved ... to incorporate the whole territory into one time zone. +# +# Nunavut moves to single time zone Oct. 31 +# +# +# From Antoine Leca (1999-09-06): +# We then need to create a new timezone for the Kitikmeot region of Nunavut +# to differentiate it from the Yellowknife region. + +# From Paul Eggert (1999-09-20): +# +# Basic Facts: The New Territory +# (1999) reports that Pangnirtung operates on eastern time, +# and that Coral Harbour does not observe DST. We don't know when +# Pangnirtung switched to eastern time; we'll guess 1995. +# We'll ignore the claim about Coral Harbour for now, +# since we have no further info. + +# From Rives McDow (1999-11-08): +# On October 31, when the rest of Nunavut went to Central time, +# Pangnirtung wobbled. Here is the result of their wobble: +# +# The following businesses and organizations in Pangnirtung use Central Time: +# +# First Air, Power Corp, Nunavut Construction, Health Center, RCMP, +# Eastern Arctic National Parks, A & D Specialist +# +# The following businesses and organizations in Pangnirtung use Eastern Time: +# +# Hamlet office, All other businesses, Both schools, Airport operator +# +# This has made for an interesting situation there, which warranted the news. +# No one there that I spoke with seems concerned, or has plans to +# change the local methods of keeping time, as it evidently does not +# really interfere with any activities or make things difficult locally. +# They plan to celebrate New Year's turn-over twice, one hour apart, +# so it appears that the situation will last at least that long. +# The Nunavut Intergovernmental Affairs hopes that they will "come to +# their senses", but the locals evidently don't see any problem with +# the current state of affairs. + +# From Michaela Rodrigue, writing in the +# +# Nunatsiaq News (1999-11-19): +# Clyde River, Pangnirtung and Sanikiluaq now operate with two time zones, +# central - or Nunavut time - for government offices, and eastern time +# for municipal offices and schools.... Igloolik [was similar but then] +# made the switch to central time on Saturday, Nov. 6. + +# From Paul Eggert (2000-10-02): +# Matthews and Vincent (1998) say the following, but we lack histories +# for these potential new Zones. +# +# The Canadian Forces station at Alert uses Eastern Time while the +# handful of residents at the Eureka weather station [in the Central +# zone] skip daylight savings. Baffin Island, which is crossed by the +# Central, Eastern and Atlantic Time zones only uses Eastern Time. +# Gjoa Haven, Taloyoak and Pelly Bay all use Mountain instead of +# Central Time and Southampton Island [in the Central zone] is not +# required to use daylight savings. + +# From +# +# Nunavut now has two time zones +# (2000-11-10): +# The Nunavut government would allow its employees in Kugluktuk and +# Cambridge Bay to operate on central time year-round, putting them +# one hour behind the rest of Nunavut for six months during the winter. +# At the end of October the two communities had rebelled against +# Nunavut's unified time zone, refusing to shift to eastern time with +# the rest of the territory for the winter. Cambridge Bay remained on +# central time, while Kugluktuk, even farther west, reverted to +# mountain time, which they had used before the advent of Nunavut's +# unified time zone in 1999. +# +# From Rives McDow (2001-01-20), quoting the Nunavut government: +# The preceding decision came into effect at midnight, Saturday Nov 4, 2000. + +# From Paul Eggert (2000-12-04): +# Let's just keep track of the official times for now. + +# From Rives McDow (2001-03-07): +# The premier of Nunavut has issued a ministerial statement advising +# that effective 2001-04-01, the territory of Nunavut will revert +# back to three time zones (mountain, central, and eastern). Of the +# cities in Nunavut, Coral Harbor is the only one that I know of that +# has said it will not observe dst, staying on EST year round. I'm +# checking for more info, and will get back to you if I come up with +# more. +# [Also see (2001-03-09).] + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule NT_YK 1918 only - Apr 14 2:00 1:00 D +Rule NT_YK 1918 only - Oct 27 2:00 0 S +Rule NT_YK 1919 only - May 25 2:00 1:00 D +Rule NT_YK 1919 only - Nov 1 0:00 0 S +Rule NT_YK 1942 only - Feb 9 2:00 1:00 W # War +Rule NT_YK 1945 only - Aug 14 23:00u 1:00 P # Peace +Rule NT_YK 1945 only - Sep 30 2:00 0 S +Rule NT_YK 1965 only - Apr lastSun 0:00 2:00 DD +Rule NT_YK 1965 only - Oct lastSun 2:00 0 S +Rule NT_YK 1980 1986 - Apr lastSun 2:00 1:00 D +Rule NT_YK 1980 max - Oct lastSun 2:00 0 S +Rule NT_YK 1987 max - Apr Sun>=1 2:00 1:00 D +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Pangnirtung -4:22:56 - LMT 1884 + -4:00 NT_YK A%sT 1995 Apr Sun>=1 2:00 + -5:00 Canada E%sT 1999 Oct 31 2:00 + -6:00 Canada C%sT 2000 Oct 29 2:00 + -5:00 Canada E%sT +Zone America/Iqaluit -4:33:52 - LMT 1884 # Frobisher Bay before 1987 + -5:00 NT_YK E%sT 1999 Oct 31 2:00 + -6:00 Canada C%sT 2000 Oct 29 2:00 + -5:00 Canada E%sT +Zone America/Rankin_Inlet -6:08:40 - LMT 1884 + -6:00 NT_YK C%sT 2000 Oct 29 2:00 + -5:00 - EST 2001 Apr 1 3:00 + -6:00 Canada C%sT +Zone America/Cambridge_Bay -7:00:20 - LMT 1884 + -7:00 NT_YK M%sT 1999 Oct 31 2:00 + -6:00 Canada C%sT 2000 Oct 29 2:00 + -5:00 - EST 2000 Nov 5 0:00 + -6:00 - CST 2001 Apr 1 3:00 + -7:00 Canada M%sT +Zone America/Yellowknife -7:37:24 - LMT 1884 + -7:00 NT_YK M%sT +Zone America/Inuvik -8:54:00 - LMT 1884 + -8:00 NT_YK P%sT 1979 Apr lastSun 2:00 + -7:00 NT_YK M%sT +Zone America/Whitehorse -9:00:12 - LMT 1900 Aug 20 + -9:00 NT_YK Y%sT 1966 Jul 1 2:00 + -8:00 NT_YK P%sT +Zone America/Dawson -9:17:40 - LMT 1900 Aug 20 + -9:00 NT_YK Y%sT 1973 Oct 28 0:00 + -8:00 NT_YK P%sT + + +############################################################################### + +# Mexico + +# From Paul Eggert (2001-03-05): +# The Investigation and Analysis Service of the +# Mexican Library of Congress (MLoC) has published a +# +# history of Mexican local time (in Spanish) +# . +# +# Here are the discrepancies between Shanks and the MLoC. +# (In all cases we go with the MLoC.) +# Shanks reports that Baja was at -8:00 in 1922/1923. +# Shanks says the 1930 transition in Baja was 1930-11-16. +# Shanks reports no DST during summer 1931. +# Shanks reports a transition at 1032-03-30 23:00, not 1932-04-01. +# Shanks does not report transitions for Baja in 1945 or 1948. +# Shanks reports southern Mexico transitions on 1981-12-01, not 12-23. +# Shanks says Quintana Roo switched to -6:00 on 1982-12-02, and to -5:00 +# on 1997-10-26 at 02:00. + +# From Gwillim Law (2001-02-20): +# There are some other discrepancies between the Decrees page and the +# tz database. I think they can best be explained by supposing that +# the researchers who prepared the Decrees page failed to find some of +# the relevant documents. + +# From Paul Eggert (2000-07-26): +# Shanks gives 1942-04-01 instead of 1942-04-24, and omits the 1981 +# and 1988 DST experiments. Go with spin.com.mx. + +# From Alan Perry (1996-02-15): +# A guy from our Mexico subsidiary finally found the Presidential Decree +# outlining the timezone changes in Mexico. +# +# ------------- Begin Forwarded Message ------------- +# +# I finally got my hands on the Official Presidential Decree that sets up the +# rules for the DST changes. The rules are: +# +# 1. The country is divided in 3 timezones: +# - Baja California Norte (the Mexico/BajaNorte TZ) +# - Baja California Sur, Nayarit, Sinaloa and Sonora (the Mexico/BajaSur TZ) +# - The rest of the country (the Mexico/General TZ) +# +# 2. From the first Sunday in April at 2:00 AM to the last Sunday in October +# at 2:00 AM, the times in each zone are as follows: +# BajaNorte: GMT+7 +# BajaSur: GMT+6 +# General: GMT+5 +# +# 3. The rest of the year, the times are as follows: +# BajaNorte: GMT+8 +# BajaSur: GMT+7 +# General: GMT+6 +# +# The Decree was published in Mexico's Official Newspaper on January 4th. +# +# -------------- End Forwarded Message -------------- +# From Paul Eggert (1996-06-12): +# For an English translation of the decree, see +# +# ``Diario Oficial: Time Zone Changeover'' (1996-01-04). +# + +# From Rives McDow (1998-10-08): +# The State of Quintana Roo has reverted back to central STD and DST times +# (i.e. UTC -0600 and -0500 as of 1998-08-02). + +# From Rives McDow (2000-01-10): +# Effective April 4, 1999 at 2:00 AM local time, Sonora changed to the time +# zone 5 hours from the International Date Line, and will not observe daylight +# savings time so as to stay on the same time zone as the southern part of +# Arizona year round. + +# From Jesper Norgaard, translating +# (2001-01-17): +# In Oaxaca, the 55.000 teachers from the Section 22 of the National +# Syndicate of Education Workers, refuse to apply daylight saving each +# year, so that the more than 10,000 schools work at normal hour the +# whole year. + +# From Gwillim Law (2001-01-19): +# ... says +# (translated):... +# January 17, 2000 - The Energy Secretary, Ernesto Martens, announced +# that Summer Time will be reduced from seven to five months, starting +# this year.... +# +# [translated], says "summer time will ... take effect on the first Sunday +# in May, and end on the last Sunday of September. + +# From Arthur David Olson (2001-01-25): +# The 2001-01-24 traditional Washington Post contained the page one +# story "Timely Issue Divides Mexicans."... +# http://www.washingtonpost.com/wp-dyn/articles/A37383-2001Jan23.html +# ... Mexico City Mayor Lopez Obrador "...is threatening to keep +# Mexico City and its 20 million residents on a different time than +# the rest of the country..." In particular, Lopez Obrador would abolish +# observation of Daylight Saving Time. + +# +# Official statute published by the Energy Department +# (2001-02-01) shows Baja and Chihauhua as still using US DST rules, +# and Sonora with no DST. This was reported by Jesper Norgaard (2001-02-03). + +# From Paul Eggert (2001-03-03): +# +# +# James F. Smith writes in today's LA Times +# +# * Sonora will continue to observe standard time. +# * Last week Mexico City's mayor Andres Manuel Lopez Obrador decreed that +# the Federal District will not adopt DST. +# * 4 of 16 district leaders announced they'll ignore the decree. +# * The decree does not affect federal-controlled facilities including +# the airport, banks, hospitals, and schools. +# +# For now we'll assume that the Federal District will bow to federal rules. + +# From Jesper Norgaard (2001-04-01): +# I found some references to the Mexican application of daylight +# saving, which modifies what I had already sent you, stating earlier +# that a number of northern Mexican states would go on daylight +# saving. The modification reverts this to only cover Baja California +# (Norte), while all other states (except Sonora, who has no daylight +# saving all year) will follow the original decree of president +# Vicente Fox, starting daylight saving May 6, 2001 and ending +# September 30, 2001. +# References: "Diario de Monterrey" +# Palabra (2001-03-31) + +# From Reuters (2001-09-04): +# Mexico's Supreme Court on Tuesday declared that daylight savings was +# unconstitutional in Mexico City, creating the possibility the +# capital will be in a different time zone from the rest of the nation +# next year.... The Supreme Court's ruling takes effect at 2:00 +# a.m. (0800 GMT) on Sept. 30, when Mexico is scheduled to revert to +# standard time. "This is so residents of the Federal District are not +# subject to unexpected time changes," a statement from the court said. + +# From Jesper Norgaard Welen (2002-03-12): +# ... consulting my local grocery store(!) and my coworkers, they all insisted +# that a new decision had been made to reinstate US style DST in Mexico.... +# http://www.conae.gob.mx/ahorro/horaver2001_m1_2002.html (2002-02-20) +# confirms this. Sonora as usual is the only state where DST is not applied. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Mexico 1939 only - Feb 5 0:00 1:00 D +Rule Mexico 1939 only - Jun 25 0:00 0 S +Rule Mexico 1940 only - Dec 9 0:00 1:00 D +Rule Mexico 1941 only - Apr 1 0:00 0 S +Rule Mexico 1943 only - Dec 16 0:00 1:00 W # War +Rule Mexico 1944 only - May 1 0:00 0 S +Rule Mexico 1950 only - Feb 12 0:00 1:00 D +Rule Mexico 1950 only - Jul 30 0:00 0 S +Rule Mexico 1996 2000 - Apr Sun>=1 2:00 1:00 D +Rule Mexico 1996 2000 - Oct lastSun 2:00 0 S +Rule Mexico 2001 only - May Sun>=1 2:00 1:00 D +Rule Mexico 2001 only - Sep lastSun 2:00 0 S +Rule Mexico 2002 max - Apr Sun>=1 2:00 1:00 D +Rule Mexico 2002 max - Oct lastSun 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# Quintana Roo +Zone America/Cancun -5:47:04 - LMT 1922 Jan 1 0:12:56 + -6:00 - CST 1981 Dec 23 + -5:00 Mexico E%sT 1998 Aug 2 2:00 + -6:00 Mexico C%sT +# Campeche, Yucatan +Zone America/Merida -5:58:28 - LMT 1922 Jan 1 0:01:32 + -6:00 - CST 1981 Dec 23 + -5:00 - EST 1982 Dec 2 + -6:00 Mexico C%sT +# Coahuila, Durango, Nuevo Leon, Tamaulipas +Zone America/Monterrey -6:41:16 - LMT 1921 Dec 31 23:18:44 + -6:00 - CST 1988 + -6:00 US C%sT 1989 + -6:00 Mexico C%sT +# Central Mexico +Zone America/Mexico_City -6:36:36 - LMT 1922 Jan 1 0:23:24 + -7:00 - MST 1927 Jun 10 23:00 + -6:00 - CST 1930 Nov 15 + -7:00 - MST 1931 May 1 23:00 + -6:00 - CST 1931 Oct + -7:00 - MST 1932 Apr 1 + -6:00 Mexico C%sT 2001 Sep 30 02:00 + -6:00 - CST 2002 Feb 20 + -6:00 Mexico C%sT +# Chihuahua +Zone America/Chihuahua -7:04:20 - LMT 1921 Dec 31 23:55:40 + -7:00 - MST 1927 Jun 10 23:00 + -6:00 - CST 1930 Nov 15 + -7:00 - MST 1931 May 1 23:00 + -6:00 - CST 1931 Oct + -7:00 - MST 1932 Apr 1 + -6:00 - CST 1996 + -6:00 Mexico C%sT 1998 + -6:00 - CST 1998 Apr Sun>=1 3:00 + -7:00 Mexico M%sT +# Sonora +Zone America/Hermosillo -7:23:52 - LMT 1921 Dec 31 23:36:08 + -7:00 - MST 1927 Jun 10 23:00 + -6:00 - CST 1930 Nov 15 + -7:00 - MST 1931 May 1 23:00 + -6:00 - CST 1931 Oct + -7:00 - MST 1932 Apr 1 + -6:00 - CST 1942 Apr 24 + -7:00 - MST 1949 Jan 14 + -8:00 - PST 1970 + -7:00 Mexico M%sT 1999 + -7:00 - MST +# Baja California Sur, Nayarit, Sinaloa +Zone America/Mazatlan -7:05:40 - LMT 1921 Dec 31 23:54:20 + -7:00 - MST 1927 Jun 10 23:00 + -6:00 - CST 1930 Nov 15 + -7:00 - MST 1931 May 1 23:00 + -6:00 - CST 1931 Oct + -7:00 - MST 1932 Apr 1 + -6:00 - CST 1942 Apr 24 + -7:00 - MST 1949 Jan 14 + -8:00 - PST 1970 + -7:00 Mexico M%sT +# Baja California +Zone America/Tijuana -7:48:04 - LMT 1922 Jan 1 0:11:56 + -7:00 - MST 1924 + -8:00 - PST 1927 Jun 10 23:00 + -7:00 - MST 1930 Nov 15 + -8:00 - PST 1931 Apr 1 + -8:00 1:00 PDT 1931 Sep 30 + -8:00 - PST 1942 Apr 24 + -8:00 1:00 PWT 1945 Nov 12 + -8:00 - PST 1948 Apr 5 + -8:00 1:00 PDT 1949 Jan 14 + -8:00 - PST 1954 + -8:00 CA P%sT 1961 + -8:00 - PST 1976 + -8:00 US P%sT 1996 + -8:00 Mexico P%sT 2001 + -8:00 US P%sT 2002 Feb 20 + -8:00 Mexico P%sT +# From Paul Eggert (2001-03-05): +# Formerly there was an America/Ensenada zone, which differed from +# America/Tijuana only in that it did not observe DST from 1976 +# through 1995. This was as per Shanks. However, Guy Harris reports +# that the 1987 OAG says "Only Ensenada, Mexicale, San Felipe and +# Tijuana observe DST," which contradicts Shanks but does imply that +# DST-observance was a town-by-town matter back then. This concerns +# data after 1970 so most likely there should be at least one Zone +# other than America/Tijuana for Baja, but it's not clear yet what its +# name or contents should be. +# +# Revillagigedo Is +# no information + +############################################################################### + +# Anguilla +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Anguilla -4:12:16 - LMT 1912 Mar 2 + -4:00 - AST + +# Antigua and Barbuda +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Antigua -4:07:12 - LMT 1912 Mar 2 + -5:00 - EST 1951 + -4:00 - AST + +# Bahamas +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Bahamas 1964 max - Oct lastSun 2:00 0 S +Rule Bahamas 1964 1986 - Apr lastSun 2:00 1:00 D +Rule Bahamas 1987 max - Apr Sun>=1 2:00 1:00 D +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Nassau -5:09:24 - LMT 1912 Mar 2 + -5:00 Bahamas E%sT + +# Barbados +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Barb 1977 only - Jun 12 2:00 1:00 D +Rule Barb 1977 1978 - Oct Sun>=1 2:00 0 S +Rule Barb 1978 1980 - Apr Sun>=15 2:00 1:00 D +Rule Barb 1979 only - Sep 30 2:00 0 S +Rule Barb 1980 only - Sep 25 2:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Barbados -3:58:28 - LMT 1924 # Bridgetown + -3:58:28 - BMT 1932 # Bridgetown Mean Time + -4:00 Barb A%sT + +# Belize +# Whitman entirely disagrees with Shanks; go with Shanks. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Belize 1918 1942 - Oct Sun>=2 0:00 0:30 HD +Rule Belize 1919 1943 - Feb Sun>=9 0:00 0 S +Rule Belize 1973 only - Dec 5 0:00 1:00 D +Rule Belize 1974 only - Feb 9 0:00 0 S +Rule Belize 1982 only - Dec 18 0:00 1:00 D +Rule Belize 1983 only - Feb 12 0:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Belize -5:52:48 - LMT 1912 Apr + -6:00 Belize C%sT + +# Bermuda +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Atlantic/Bermuda -4:19:04 - LMT 1930 Jan 1 2:00 # Hamilton + -4:00 - AST 1974 Apr 28 2:00 + -4:00 Bahamas A%sT + +# Cayman Is +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Cayman -5:25:32 - LMT 1890 # Georgetown + -5:07:12 - KMT 1912 Feb # Kingston Mean Time + -5:00 - EST + +# Costa Rica +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule CR 1979 1980 - Feb lastSun 0:00 1:00 D +Rule CR 1979 1980 - Jun Sun>=1 0:00 0 S +Rule CR 1991 1992 - Jan Sat>=15 0:00 1:00 D +# IATA SSIM (1991-09) says the following was at 1:00; go with Shanks. +Rule CR 1991 only - Jul 1 0:00 0 S +Rule CR 1992 only - Mar 15 0:00 0 S +# There are too many San Joses elsewhere, so we'll use `Costa Rica'. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Costa_Rica -5:36:20 - LMT 1890 # San Jose + -5:36:20 - SJMT 1921 Jan 15 # San Jose Mean Time + -6:00 CR C%sT +# Coco +# no information; probably like America/Costa_Rica + +# Cuba + +# From Arthur David Olson (1999-03-29): +# The 1999-03-28 exhibition baseball game held in Havana, Cuba, between +# the Cuban National Team and the Baltimore Orioles was carried live on +# the Orioles Radio Network, including affiliate WTOP in Washington, DC. +# During the game, play-by-play announcer Jim Hunter noted that +# "We'll be losing two hours of sleep...Cuba switched to Daylight Saving +# Time today." (The "two hour" remark referred to losing one hour of +# sleep on 1999-03-28--when the announcers were in Cuba as it switched +# to DST--and one more hour on 1999-04-04--when the announcers will have +# returned to Baltimore, which switches on that date.) + +# From Evert van der Veer via Steffen Thorsen (2004-10-28): +# Cuba is not going back to standard time this year. +# From Paul Eggert (2004-10-28): +# http://www.granma.cu/ingles/2004/septiembre/juev30/41medid-i.html +# says that it's due to a problem at the Antonio Guiteras +# thermoelectric plant, and says "This October there will be no return +# to normal hours (after daylight saving time)". +# For now, let's assume that it's a one-year temporary measure. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Cuba 1928 only - Jun 10 0:00 1:00 D +Rule Cuba 1928 only - Oct 10 0:00 0 S +Rule Cuba 1940 1942 - Jun Sun>=1 0:00 1:00 D +Rule Cuba 1940 1942 - Sep Sun>=1 0:00 0 S +Rule Cuba 1945 1946 - Jun Sun>=1 0:00 1:00 D +Rule Cuba 1945 1946 - Sep Sun>=1 0:00 0 S +Rule Cuba 1965 only - Jun 1 0:00 1:00 D +Rule Cuba 1965 only - Sep 30 0:00 0 S +Rule Cuba 1966 only - May 29 0:00 1:00 D +Rule Cuba 1966 only - Oct 2 0:00 0 S +Rule Cuba 1967 only - Apr 8 0:00 1:00 D +Rule Cuba 1967 1968 - Sep Sun>=8 0:00 0 S +Rule Cuba 1968 only - Apr 14 0:00 1:00 D +Rule Cuba 1969 1977 - Apr lastSun 0:00 1:00 D +Rule Cuba 1969 1971 - Oct lastSun 0:00 0 S +Rule Cuba 1972 1974 - Oct 8 0:00 0 S +Rule Cuba 1975 1977 - Oct lastSun 0:00 0 S +Rule Cuba 1978 only - May 7 0:00 1:00 D +Rule Cuba 1978 1990 - Oct Sun>=8 0:00 0 S +Rule Cuba 1979 1980 - Mar Sun>=15 0:00 1:00 D +Rule Cuba 1981 1985 - May Sun>=5 0:00 1:00 D +Rule Cuba 1986 1989 - Mar Sun>=14 0:00 1:00 D +Rule Cuba 1990 1997 - Apr Sun>=1 0:00 1:00 D +Rule Cuba 1991 1995 - Oct Sun>=8 0:00s 0 S +Rule Cuba 1996 only - Oct 6 0:00s 0 S +Rule Cuba 1997 only - Oct 12 0:00s 0 S +Rule Cuba 1998 1999 - Mar lastSun 0:00s 1:00 D +Rule Cuba 1998 2003 - Oct lastSun 0:00s 0 S +Rule Cuba 2000 max - Apr Sun>=1 0:00s 1:00 D +Rule Cuba 2005 max - Oct lastSun 0:00s 0 S + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Havana -5:29:28 - LMT 1890 + -5:29:36 - HMT 1925 Jul 19 12:00 # Havana MT + -5:00 Cuba C%sT + +# Dominica +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Dominica -4:05:36 - LMT 1911 Jul 1 0:01 # Roseau + -4:00 - AST + +# Dominican Republic + +# From Steffen Thorsen (2000-10-30): +# Enrique Morales reported to me that the Dominican Republic has changed the +# time zone to Eastern Standard Time as of Sunday 29 at 2 am.... +# http://www.listin.com.do/antes/261000/republica/princi.html + +# From Paul Eggert (2000-12-04): +# That URL (2000-10-26, in Spanish) says they planned to use US-style DST. + +# From Rives McDow (2000-12-01): +# Dominican Republic changed its mind and presidential decree on Tuesday, +# November 28, 2000, with a new decree. On Sunday, December 3 at 1:00 AM the +# Dominican Republic will be reverting to 8 hours from the International Date +# Line, and will not be using DST in the foreseeable future. The reason they +# decided to use DST was to be in synch with Puerto Rico, who was also going +# to implement DST. When Puerto Rico didn't implement DST, the president +# decided to revert. + + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule DR 1966 only - Oct 30 0:00 1:00 D +Rule DR 1967 only - Feb 28 0:00 0 S +Rule DR 1969 1973 - Oct lastSun 0:00 0:30 HD +Rule DR 1970 only - Feb 21 0:00 0 S +Rule DR 1971 only - Jan 20 0:00 0 S +Rule DR 1972 1974 - Jan 21 0:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Santo_Domingo -4:39:36 - LMT 1890 + -4:40 - SDMT 1933 Apr 1 12:00 # S. Dom. MT + -5:00 DR E%sT 1974 Oct 27 + -4:00 - AST 2000 Oct 29 02:00 + -5:00 US E%sT 2000 Dec 3 01:00 + -4:00 - AST + +# El Salvador +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Salv 1987 1988 - May Sun>=1 0:00 1:00 D +Rule Salv 1987 1988 - Sep lastSun 0:00 0 S +# There are too many San Salvadors elsewhere, so use America/El_Salvador +# instead of America/San_Salvador. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/El_Salvador -5:56:48 - LMT 1921 # San Salvador + -6:00 Salv C%sT + +# Grenada +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Grenada -4:07:00 - LMT 1911 Jul # St George's + -4:00 - AST + +# Guadeloupe +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Guadeloupe -4:06:08 - LMT 1911 Jun 8 # Pointe a Pitre + -4:00 - AST + +# Guatemala +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Guat 1973 only - Nov 25 0:00 1:00 D +Rule Guat 1974 only - Feb 24 0:00 0 S +Rule Guat 1983 only - May 21 0:00 1:00 D +Rule Guat 1983 only - Sep 22 0:00 0 S +Rule Guat 1991 only - Mar 23 0:00 1:00 D +Rule Guat 1991 only - Sep 7 0:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Guatemala -6:02:04 - LMT 1918 Oct 5 + -6:00 Guat C%sT + +# Haiti +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Haiti 1983 only - May 8 0:00 1:00 D +Rule Haiti 1984 1987 - Apr lastSun 0:00 1:00 D +Rule Haiti 1983 1987 - Oct lastSun 0:00 0 S +# Shanks says AT is 2:00, but IATA SSIM (1991/1997) says 1:00s. Go with IATA. +Rule Haiti 1988 1997 - Apr Sun>=1 1:00s 1:00 D +Rule Haiti 1988 1997 - Oct lastSun 1:00s 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Port-au-Prince -4:49:20 - LMT 1890 + -4:49 - PPMT 1917 Jan 24 12:00 # P-a-P MT + -5:00 Haiti E%sT + +# Honduras +# Shanks says 1921 Jan 1; go with Whitman's more precise Apr 1. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Tegucigalpa -5:48:52 - LMT 1921 Apr + -6:00 Salv C%sT +# +# Great Swan I ceded by US to Honduras in 1972 + +# Jamaica + +# From Bob Devine (1988-01-28): +# Follows US rules. + +# From U. S. Naval Observatory (1989-01-19): +# JAMAICA 5 H BEHIND UTC + +# From Shanks: +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Jamaica -5:07:12 - LMT 1890 # Kingston + -5:07:12 - KMT 1912 Feb # Kingston Mean Time + -5:00 - EST 1974 Apr 28 2:00 + -5:00 US E%sT 1984 + -5:00 - EST + +# Martinique +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Martinique -4:04:20 - LMT 1890 # Fort-de-France + -4:04:20 - FFMT 1911 May # Fort-de-France MT + -4:00 - AST 1980 Apr 6 + -4:00 1:00 ADT 1980 Sep 28 + -4:00 - AST + +# Montserrat +# From Paul Eggert (1997-08-31): +# Recent volcanic eruptions have forced evacuation of Plymouth, the capital. +# Luckily, Olveston, the current de facto capital, has the same longitude. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Montserrat -4:08:52 - LMT 1911 Jul 1 0:01 # Olveston + -4:00 - AST + +# Nicaragua +# +# From Steffen Thorsen (1998-12-29): +# Nicaragua seems to be back at -6:00 but I have not been able to find when +# they changed from -5:00. +# +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Nic 1979 1980 - Mar Sun>=16 0:00 1:00 D +Rule Nic 1979 1980 - Jun Mon>=23 0:00 0 S +Rule Nic 1992 only - Jan 1 4:00 1:00 D +Rule Nic 1992 only - Sep 24 0:00 0 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Managua -5:45:08 - LMT 1890 + -5:45:12 - MMT 1934 Jun 23 # Managua Mean Time? + -6:00 - CST 1973 May + -5:00 - EST 1975 Feb 16 + -6:00 Nic C%sT 1993 Jan 1 4:00 + -5:00 - EST 1998 Dec + -6:00 - CST + +# Panama +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Panama -5:18:08 - LMT 1890 + -5:19:36 - CMT 1908 Apr 22 # Colon Mean Time + -5:00 - EST + +# Puerto Rico +# There are too many San Juans elsewhere, so we'll use `Puerto_Rico'. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Puerto_Rico -4:24:25 - LMT 1899 Mar 28 12:00 # San Juan + -4:00 - AST 1942 May 3 + -4:00 1:00 AWT 1945 Sep 30 2:00 + -4:00 - AST + +# St Kitts-Nevis +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/St_Kitts -4:10:52 - LMT 1912 Mar 2 # Basseterre + -4:00 - AST + +# St Lucia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/St_Lucia -4:04:00 - LMT 1890 # Castries + -4:04:00 - CMT 1912 # Castries Mean Time + -4:00 - AST + +# St Pierre and Miquelon +# There are too many St Pierres elsewhere, so we'll use `Miquelon'. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Miquelon -3:44:40 - LMT 1911 May 15 # St Pierre + -4:00 - AST 1980 May + -3:00 - PMST 1987 # Pierre & Miquelon Time + -3:00 Canada PM%sT + +# St Vincent and the Grenadines +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/St_Vincent -4:04:56 - LMT 1890 # Kingstown + -4:04:56 - KMT 1912 # Kingstown Mean Time + -4:00 - AST + +# Turks and Caicos +# From Paul Eggert (1998-08-06): +# Shanks says they use US DST rules, but IATA SSIM (1991/1998) +# says they switch at midnight. Go with IATA SSIM. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule TC 1979 1986 - Apr lastSun 0:00 1:00 D +Rule TC 1979 max - Oct lastSun 0:00 0 S +Rule TC 1987 max - Apr Sun>=1 0:00 1:00 D +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Grand_Turk -4:44:32 - LMT 1890 + -5:07:12 - KMT 1912 Feb # Kingston Mean Time + -5:00 TC E%sT + +# British Virgin Is +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Tortola -4:18:28 - LMT 1911 Jul # Road Town + -4:00 - AST + +# Virgin Is +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/St_Thomas -4:19:44 - LMT 1911 Jul # Charlotte Amalie + -4:00 - AST Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/pacificnew =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/pacificnew,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/pacificnew 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,26 @@ +# @(#)pacificnew 7.10 + +# From Arthur David Olson (1989-04-05): +# On 1989-04-05, the U. S. House of Representatives passed (238-154) a bill +# establishing "Pacific Presidential Election Time"; it was not acted on +# by the Senate or signed into law by the President. +# You might want to change the "PE" (Presidential Election) below to +# "Q" (Quadrennial) to maintain three-character zone abbreviations. +# If you're really conservative, you might want to change it to "D". +# Avoid "L" (Leap Year), which won't be true in 2100. + +# If Presidential Election Time is ever established, replace "XXXX" below +# with the year the law takes effect and uncomment the "##" lines. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +## Rule Twilite XXXX max - Apr Sun>=1 2:00 1:00 D +## Rule Twilite XXXX max uspres Oct lastSun 2:00 1:00 PE +## Rule Twilite XXXX max uspres Nov Sun>=7 2:00 0 S +## Rule Twilite XXXX max nonpres Oct lastSun 2:00 0 S + +# Zone NAME GMTOFF RULES/SAVE FORMAT [UNTIL] +## Zone America/Los_Angeles-PET -8:00 US P%sT XXXX +## -8:00 Twilite P%sT + +# For now... +Link America/Los_Angeles US/Pacific-New ## Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/solar87 =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/Attic/solar87,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/solar87 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,388 @@ +# @(#)solar87 7.3 + +# So much for footnotes about Saudi Arabia. +# Apparent noon times below are for Riyadh; your mileage will vary. +# Times were computed using formulas in the U.S. Naval Observatory's +# Almanac for Computers 1987; the formulas "will give EqT to an accuracy of +# [plus or minus two] seconds during the current year." +# +# Rounding to the nearest five seconds results in fewer than +# 256 different "time types"--a limit that's faced because time types are +# stored on disk as unsigned chars. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule sol87 1987 only - Jan 1 12:03:20s -0:03:20 - +Rule sol87 1987 only - Jan 2 12:03:50s -0:03:50 - +Rule sol87 1987 only - Jan 3 12:04:15s -0:04:15 - +Rule sol87 1987 only - Jan 4 12:04:45s -0:04:45 - +Rule sol87 1987 only - Jan 5 12:05:10s -0:05:10 - +Rule sol87 1987 only - Jan 6 12:05:40s -0:05:40 - +Rule sol87 1987 only - Jan 7 12:06:05s -0:06:05 - +Rule sol87 1987 only - Jan 8 12:06:30s -0:06:30 - +Rule sol87 1987 only - Jan 9 12:06:55s -0:06:55 - +Rule sol87 1987 only - Jan 10 12:07:20s -0:07:20 - +Rule sol87 1987 only - Jan 11 12:07:45s -0:07:45 - +Rule sol87 1987 only - Jan 12 12:08:10s -0:08:10 - +Rule sol87 1987 only - Jan 13 12:08:30s -0:08:30 - +Rule sol87 1987 only - Jan 14 12:08:55s -0:08:55 - +Rule sol87 1987 only - Jan 15 12:09:15s -0:09:15 - +Rule sol87 1987 only - Jan 16 12:09:35s -0:09:35 - +Rule sol87 1987 only - Jan 17 12:09:55s -0:09:55 - +Rule sol87 1987 only - Jan 18 12:10:15s -0:10:15 - +Rule sol87 1987 only - Jan 19 12:10:35s -0:10:35 - +Rule sol87 1987 only - Jan 20 12:10:55s -0:10:55 - +Rule sol87 1987 only - Jan 21 12:11:10s -0:11:10 - +Rule sol87 1987 only - Jan 22 12:11:30s -0:11:30 - +Rule sol87 1987 only - Jan 23 12:11:45s -0:11:45 - +Rule sol87 1987 only - Jan 24 12:12:00s -0:12:00 - +Rule sol87 1987 only - Jan 25 12:12:15s -0:12:15 - +Rule sol87 1987 only - Jan 26 12:12:30s -0:12:30 - +Rule sol87 1987 only - Jan 27 12:12:40s -0:12:40 - +Rule sol87 1987 only - Jan 28 12:12:55s -0:12:55 - +Rule sol87 1987 only - Jan 29 12:13:05s -0:13:05 - +Rule sol87 1987 only - Jan 30 12:13:15s -0:13:15 - +Rule sol87 1987 only - Jan 31 12:13:25s -0:13:25 - +Rule sol87 1987 only - Feb 1 12:13:35s -0:13:35 - +Rule sol87 1987 only - Feb 2 12:13:40s -0:13:40 - +Rule sol87 1987 only - Feb 3 12:13:50s -0:13:50 - +Rule sol87 1987 only - Feb 4 12:13:55s -0:13:55 - +Rule sol87 1987 only - Feb 5 12:14:00s -0:14:00 - +Rule sol87 1987 only - Feb 6 12:14:05s -0:14:05 - +Rule sol87 1987 only - Feb 7 12:14:10s -0:14:10 - +Rule sol87 1987 only - Feb 8 12:14:10s -0:14:10 - +Rule sol87 1987 only - Feb 9 12:14:15s -0:14:15 - +Rule sol87 1987 only - Feb 10 12:14:15s -0:14:15 - +Rule sol87 1987 only - Feb 11 12:14:15s -0:14:15 - +Rule sol87 1987 only - Feb 12 12:14:15s -0:14:15 - +Rule sol87 1987 only - Feb 13 12:14:15s -0:14:15 - +Rule sol87 1987 only - Feb 14 12:14:15s -0:14:15 - +Rule sol87 1987 only - Feb 15 12:14:10s -0:14:10 - +Rule sol87 1987 only - Feb 16 12:14:10s -0:14:10 - +Rule sol87 1987 only - Feb 17 12:14:05s -0:14:05 - +Rule sol87 1987 only - Feb 18 12:14:00s -0:14:00 - +Rule sol87 1987 only - Feb 19 12:13:55s -0:13:55 - +Rule sol87 1987 only - Feb 20 12:13:50s -0:13:50 - +Rule sol87 1987 only - Feb 21 12:13:45s -0:13:45 - +Rule sol87 1987 only - Feb 22 12:13:35s -0:13:35 - +Rule sol87 1987 only - Feb 23 12:13:30s -0:13:30 - +Rule sol87 1987 only - Feb 24 12:13:20s -0:13:20 - +Rule sol87 1987 only - Feb 25 12:13:10s -0:13:10 - +Rule sol87 1987 only - Feb 26 12:13:00s -0:13:00 - +Rule sol87 1987 only - Feb 27 12:12:50s -0:12:50 - +Rule sol87 1987 only - Feb 28 12:12:40s -0:12:40 - +Rule sol87 1987 only - Mar 1 12:12:30s -0:12:30 - +Rule sol87 1987 only - Mar 2 12:12:20s -0:12:20 - +Rule sol87 1987 only - Mar 3 12:12:05s -0:12:05 - +Rule sol87 1987 only - Mar 4 12:11:55s -0:11:55 - +Rule sol87 1987 only - Mar 5 12:11:40s -0:11:40 - +Rule sol87 1987 only - Mar 6 12:11:25s -0:11:25 - +Rule sol87 1987 only - Mar 7 12:11:15s -0:11:15 - +Rule sol87 1987 only - Mar 8 12:11:00s -0:11:00 - +Rule sol87 1987 only - Mar 9 12:10:45s -0:10:45 - +Rule sol87 1987 only - Mar 10 12:10:30s -0:10:30 - +Rule sol87 1987 only - Mar 11 12:10:15s -0:10:15 - +Rule sol87 1987 only - Mar 12 12:09:55s -0:09:55 - +Rule sol87 1987 only - Mar 13 12:09:40s -0:09:40 - +Rule sol87 1987 only - Mar 14 12:09:25s -0:09:25 - +Rule sol87 1987 only - Mar 15 12:09:10s -0:09:10 - +Rule sol87 1987 only - Mar 16 12:08:50s -0:08:50 - +Rule sol87 1987 only - Mar 17 12:08:35s -0:08:35 - +Rule sol87 1987 only - Mar 18 12:08:15s -0:08:15 - +Rule sol87 1987 only - Mar 19 12:08:00s -0:08:00 - +Rule sol87 1987 only - Mar 20 12:07:40s -0:07:40 - +Rule sol87 1987 only - Mar 21 12:07:25s -0:07:25 - +Rule sol87 1987 only - Mar 22 12:07:05s -0:07:05 - +Rule sol87 1987 only - Mar 23 12:06:50s -0:06:50 - +Rule sol87 1987 only - Mar 24 12:06:30s -0:06:30 - +Rule sol87 1987 only - Mar 25 12:06:10s -0:06:10 - +Rule sol87 1987 only - Mar 26 12:05:55s -0:05:55 - +Rule sol87 1987 only - Mar 27 12:05:35s -0:05:35 - +Rule sol87 1987 only - Mar 28 12:05:15s -0:05:15 - +Rule sol87 1987 only - Mar 29 12:05:00s -0:05:00 - +Rule sol87 1987 only - Mar 30 12:04:40s -0:04:40 - +Rule sol87 1987 only - Mar 31 12:04:25s -0:04:25 - +Rule sol87 1987 only - Apr 1 12:04:05s -0:04:05 - +Rule sol87 1987 only - Apr 2 12:03:45s -0:03:45 - +Rule sol87 1987 only - Apr 3 12:03:30s -0:03:30 - +Rule sol87 1987 only - Apr 4 12:03:10s -0:03:10 - +Rule sol87 1987 only - Apr 5 12:02:55s -0:02:55 - +Rule sol87 1987 only - Apr 6 12:02:35s -0:02:35 - +Rule sol87 1987 only - Apr 7 12:02:20s -0:02:20 - +Rule sol87 1987 only - Apr 8 12:02:05s -0:02:05 - +Rule sol87 1987 only - Apr 9 12:01:45s -0:01:45 - +Rule sol87 1987 only - Apr 10 12:01:30s -0:01:30 - +Rule sol87 1987 only - Apr 11 12:01:15s -0:01:15 - +Rule sol87 1987 only - Apr 12 12:00:55s -0:00:55 - +Rule sol87 1987 only - Apr 13 12:00:40s -0:00:40 - +Rule sol87 1987 only - Apr 14 12:00:25s -0:00:25 - +Rule sol87 1987 only - Apr 15 12:00:10s -0:00:10 - +Rule sol87 1987 only - Apr 16 11:59:55s 0:00:05 - +Rule sol87 1987 only - Apr 17 11:59:45s 0:00:15 - +Rule sol87 1987 only - Apr 18 11:59:30s 0:00:30 - +Rule sol87 1987 only - Apr 19 11:59:15s 0:00:45 - +Rule sol87 1987 only - Apr 20 11:59:05s 0:00:55 - +Rule sol87 1987 only - Apr 21 11:58:50s 0:01:10 - +Rule sol87 1987 only - Apr 22 11:58:40s 0:01:20 - +Rule sol87 1987 only - Apr 23 11:58:25s 0:01:35 - +Rule sol87 1987 only - Apr 24 11:58:15s 0:01:45 - +Rule sol87 1987 only - Apr 25 11:58:05s 0:01:55 - +Rule sol87 1987 only - Apr 26 11:57:55s 0:02:05 - +Rule sol87 1987 only - Apr 27 11:57:45s 0:02:15 - +Rule sol87 1987 only - Apr 28 11:57:35s 0:02:25 - +Rule sol87 1987 only - Apr 29 11:57:25s 0:02:35 - +Rule sol87 1987 only - Apr 30 11:57:15s 0:02:45 - +Rule sol87 1987 only - May 1 11:57:10s 0:02:50 - +Rule sol87 1987 only - May 2 11:57:00s 0:03:00 - +Rule sol87 1987 only - May 3 11:56:55s 0:03:05 - +Rule sol87 1987 only - May 4 11:56:50s 0:03:10 - +Rule sol87 1987 only - May 5 11:56:45s 0:03:15 - +Rule sol87 1987 only - May 6 11:56:40s 0:03:20 - +Rule sol87 1987 only - May 7 11:56:35s 0:03:25 - +Rule sol87 1987 only - May 8 11:56:30s 0:03:30 - +Rule sol87 1987 only - May 9 11:56:25s 0:03:35 - +Rule sol87 1987 only - May 10 11:56:25s 0:03:35 - +Rule sol87 1987 only - May 11 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 12 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 13 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 14 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 15 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 16 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 17 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 18 11:56:20s 0:03:40 - +Rule sol87 1987 only - May 19 11:56:25s 0:03:35 - +Rule sol87 1987 only - May 20 11:56:25s 0:03:35 - +Rule sol87 1987 only - May 21 11:56:30s 0:03:30 - +Rule sol87 1987 only - May 22 11:56:35s 0:03:25 - +Rule sol87 1987 only - May 23 11:56:40s 0:03:20 - +Rule sol87 1987 only - May 24 11:56:45s 0:03:15 - +Rule sol87 1987 only - May 25 11:56:50s 0:03:10 - +Rule sol87 1987 only - May 26 11:56:55s 0:03:05 - +Rule sol87 1987 only - May 27 11:57:00s 0:03:00 - +Rule sol87 1987 only - May 28 11:57:10s 0:02:50 - +Rule sol87 1987 only - May 29 11:57:15s 0:02:45 - +Rule sol87 1987 only - May 30 11:57:25s 0:02:35 - +Rule sol87 1987 only - May 31 11:57:30s 0:02:30 - +Rule sol87 1987 only - Jun 1 11:57:40s 0:02:20 - +Rule sol87 1987 only - Jun 2 11:57:50s 0:02:10 - +Rule sol87 1987 only - Jun 3 11:58:00s 0:02:00 - +Rule sol87 1987 only - Jun 4 11:58:10s 0:01:50 - +Rule sol87 1987 only - Jun 5 11:58:20s 0:01:40 - +Rule sol87 1987 only - Jun 6 11:58:30s 0:01:30 - +Rule sol87 1987 only - Jun 7 11:58:40s 0:01:20 - +Rule sol87 1987 only - Jun 8 11:58:50s 0:01:10 - +Rule sol87 1987 only - Jun 9 11:59:05s 0:00:55 - +Rule sol87 1987 only - Jun 10 11:59:15s 0:00:45 - +Rule sol87 1987 only - Jun 11 11:59:30s 0:00:30 - +Rule sol87 1987 only - Jun 12 11:59:40s 0:00:20 - +Rule sol87 1987 only - Jun 13 11:59:50s 0:00:10 - +Rule sol87 1987 only - Jun 14 12:00:05s -0:00:05 - +Rule sol87 1987 only - Jun 15 12:00:15s -0:00:15 - +Rule sol87 1987 only - Jun 16 12:00:30s -0:00:30 - +Rule sol87 1987 only - Jun 17 12:00:45s -0:00:45 - +Rule sol87 1987 only - Jun 18 12:00:55s -0:00:55 - +Rule sol87 1987 only - Jun 19 12:01:10s -0:01:10 - +Rule sol87 1987 only - Jun 20 12:01:20s -0:01:20 - +Rule sol87 1987 only - Jun 21 12:01:35s -0:01:35 - +Rule sol87 1987 only - Jun 22 12:01:50s -0:01:50 - +Rule sol87 1987 only - Jun 23 12:02:00s -0:02:00 - +Rule sol87 1987 only - Jun 24 12:02:15s -0:02:15 - +Rule sol87 1987 only - Jun 25 12:02:25s -0:02:25 - +Rule sol87 1987 only - Jun 26 12:02:40s -0:02:40 - +Rule sol87 1987 only - Jun 27 12:02:50s -0:02:50 - +Rule sol87 1987 only - Jun 28 12:03:05s -0:03:05 - +Rule sol87 1987 only - Jun 29 12:03:15s -0:03:15 - +Rule sol87 1987 only - Jun 30 12:03:30s -0:03:30 - +Rule sol87 1987 only - Jul 1 12:03:40s -0:03:40 - +Rule sol87 1987 only - Jul 2 12:03:50s -0:03:50 - +Rule sol87 1987 only - Jul 3 12:04:05s -0:04:05 - +Rule sol87 1987 only - Jul 4 12:04:15s -0:04:15 - +Rule sol87 1987 only - Jul 5 12:04:25s -0:04:25 - +Rule sol87 1987 only - Jul 6 12:04:35s -0:04:35 - +Rule sol87 1987 only - Jul 7 12:04:45s -0:04:45 - +Rule sol87 1987 only - Jul 8 12:04:55s -0:04:55 - +Rule sol87 1987 only - Jul 9 12:05:05s -0:05:05 - +Rule sol87 1987 only - Jul 10 12:05:15s -0:05:15 - +Rule sol87 1987 only - Jul 11 12:05:20s -0:05:20 - +Rule sol87 1987 only - Jul 12 12:05:30s -0:05:30 - +Rule sol87 1987 only - Jul 13 12:05:40s -0:05:40 - +Rule sol87 1987 only - Jul 14 12:05:45s -0:05:45 - +Rule sol87 1987 only - Jul 15 12:05:50s -0:05:50 - +Rule sol87 1987 only - Jul 16 12:06:00s -0:06:00 - +Rule sol87 1987 only - Jul 17 12:06:05s -0:06:05 - +Rule sol87 1987 only - Jul 18 12:06:10s -0:06:10 - +Rule sol87 1987 only - Jul 19 12:06:15s -0:06:15 - +Rule sol87 1987 only - Jul 20 12:06:15s -0:06:15 - +Rule sol87 1987 only - Jul 21 12:06:20s -0:06:20 - +Rule sol87 1987 only - Jul 22 12:06:25s -0:06:25 - +Rule sol87 1987 only - Jul 23 12:06:25s -0:06:25 - +Rule sol87 1987 only - Jul 24 12:06:25s -0:06:25 - +Rule sol87 1987 only - Jul 25 12:06:30s -0:06:30 - +Rule sol87 1987 only - Jul 26 12:06:30s -0:06:30 - +Rule sol87 1987 only - Jul 27 12:06:30s -0:06:30 - +Rule sol87 1987 only - Jul 28 12:06:30s -0:06:30 - +Rule sol87 1987 only - Jul 29 12:06:25s -0:06:25 - +Rule sol87 1987 only - Jul 30 12:06:25s -0:06:25 - +Rule sol87 1987 only - Jul 31 12:06:25s -0:06:25 - +Rule sol87 1987 only - Aug 1 12:06:20s -0:06:20 - +Rule sol87 1987 only - Aug 2 12:06:15s -0:06:15 - +Rule sol87 1987 only - Aug 3 12:06:10s -0:06:10 - +Rule sol87 1987 only - Aug 4 12:06:05s -0:06:05 - +Rule sol87 1987 only - Aug 5 12:06:00s -0:06:00 - +Rule sol87 1987 only - Aug 6 12:05:55s -0:05:55 - +Rule sol87 1987 only - Aug 7 12:05:50s -0:05:50 - +Rule sol87 1987 only - Aug 8 12:05:40s -0:05:40 - +Rule sol87 1987 only - Aug 9 12:05:35s -0:05:35 - +Rule sol87 1987 only - Aug 10 12:05:25s -0:05:25 - +Rule sol87 1987 only - Aug 11 12:05:15s -0:05:15 - +Rule sol87 1987 only - Aug 12 12:05:05s -0:05:05 - +Rule sol87 1987 only - Aug 13 12:04:55s -0:04:55 - +Rule sol87 1987 only - Aug 14 12:04:45s -0:04:45 - +Rule sol87 1987 only - Aug 15 12:04:35s -0:04:35 - +Rule sol87 1987 only - Aug 16 12:04:25s -0:04:25 - +Rule sol87 1987 only - Aug 17 12:04:10s -0:04:10 - +Rule sol87 1987 only - Aug 18 12:04:00s -0:04:00 - +Rule sol87 1987 only - Aug 19 12:03:45s -0:03:45 - +Rule sol87 1987 only - Aug 20 12:03:30s -0:03:30 - +Rule sol87 1987 only - Aug 21 12:03:15s -0:03:15 - +Rule sol87 1987 only - Aug 22 12:03:00s -0:03:00 - +Rule sol87 1987 only - Aug 23 12:02:45s -0:02:45 - +Rule sol87 1987 only - Aug 24 12:02:30s -0:02:30 - +Rule sol87 1987 only - Aug 25 12:02:15s -0:02:15 - +Rule sol87 1987 only - Aug 26 12:02:00s -0:02:00 - +Rule sol87 1987 only - Aug 27 12:01:40s -0:01:40 - +Rule sol87 1987 only - Aug 28 12:01:25s -0:01:25 - +Rule sol87 1987 only - Aug 29 12:01:05s -0:01:05 - +Rule sol87 1987 only - Aug 30 12:00:50s -0:00:50 - +Rule sol87 1987 only - Aug 31 12:00:30s -0:00:30 - +Rule sol87 1987 only - Sep 1 12:00:10s -0:00:10 - +Rule sol87 1987 only - Sep 2 11:59:50s 0:00:10 - +Rule sol87 1987 only - Sep 3 11:59:35s 0:00:25 - +Rule sol87 1987 only - Sep 4 11:59:15s 0:00:45 - +Rule sol87 1987 only - Sep 5 11:58:55s 0:01:05 - +Rule sol87 1987 only - Sep 6 11:58:35s 0:01:25 - +Rule sol87 1987 only - Sep 7 11:58:15s 0:01:45 - +Rule sol87 1987 only - Sep 8 11:57:55s 0:02:05 - +Rule sol87 1987 only - Sep 9 11:57:30s 0:02:30 - +Rule sol87 1987 only - Sep 10 11:57:10s 0:02:50 - +Rule sol87 1987 only - Sep 11 11:56:50s 0:03:10 - +Rule sol87 1987 only - Sep 12 11:56:30s 0:03:30 - +Rule sol87 1987 only - Sep 13 11:56:10s 0:03:50 - +Rule sol87 1987 only - Sep 14 11:55:45s 0:04:15 - +Rule sol87 1987 only - Sep 15 11:55:25s 0:04:35 - +Rule sol87 1987 only - Sep 16 11:55:05s 0:04:55 - +Rule sol87 1987 only - Sep 17 11:54:45s 0:05:15 - +Rule sol87 1987 only - Sep 18 11:54:20s 0:05:40 - +Rule sol87 1987 only - Sep 19 11:54:00s 0:06:00 - +Rule sol87 1987 only - Sep 20 11:53:40s 0:06:20 - +Rule sol87 1987 only - Sep 21 11:53:15s 0:06:45 - +Rule sol87 1987 only - Sep 22 11:52:55s 0:07:05 - +Rule sol87 1987 only - Sep 23 11:52:35s 0:07:25 - +Rule sol87 1987 only - Sep 24 11:52:15s 0:07:45 - +Rule sol87 1987 only - Sep 25 11:51:55s 0:08:05 - +Rule sol87 1987 only - Sep 26 11:51:35s 0:08:25 - +Rule sol87 1987 only - Sep 27 11:51:10s 0:08:50 - +Rule sol87 1987 only - Sep 28 11:50:50s 0:09:10 - +Rule sol87 1987 only - Sep 29 11:50:30s 0:09:30 - +Rule sol87 1987 only - Sep 30 11:50:10s 0:09:50 - +Rule sol87 1987 only - Oct 1 11:49:50s 0:10:10 - +Rule sol87 1987 only - Oct 2 11:49:35s 0:10:25 - +Rule sol87 1987 only - Oct 3 11:49:15s 0:10:45 - +Rule sol87 1987 only - Oct 4 11:48:55s 0:11:05 - +Rule sol87 1987 only - Oct 5 11:48:35s 0:11:25 - +Rule sol87 1987 only - Oct 6 11:48:20s 0:11:40 - +Rule sol87 1987 only - Oct 7 11:48:00s 0:12:00 - +Rule sol87 1987 only - Oct 8 11:47:45s 0:12:15 - +Rule sol87 1987 only - Oct 9 11:47:25s 0:12:35 - +Rule sol87 1987 only - Oct 10 11:47:10s 0:12:50 - +Rule sol87 1987 only - Oct 11 11:46:55s 0:13:05 - +Rule sol87 1987 only - Oct 12 11:46:40s 0:13:20 - +Rule sol87 1987 only - Oct 13 11:46:25s 0:13:35 - +Rule sol87 1987 only - Oct 14 11:46:10s 0:13:50 - +Rule sol87 1987 only - Oct 15 11:45:55s 0:14:05 - +Rule sol87 1987 only - Oct 16 11:45:45s 0:14:15 - +Rule sol87 1987 only - Oct 17 11:45:30s 0:14:30 - +Rule sol87 1987 only - Oct 18 11:45:20s 0:14:40 - +Rule sol87 1987 only - Oct 19 11:45:05s 0:14:55 - +Rule sol87 1987 only - Oct 20 11:44:55s 0:15:05 - +Rule sol87 1987 only - Oct 21 11:44:45s 0:15:15 - +Rule sol87 1987 only - Oct 22 11:44:35s 0:15:25 - +Rule sol87 1987 only - Oct 23 11:44:25s 0:15:35 - +Rule sol87 1987 only - Oct 24 11:44:20s 0:15:40 - +Rule sol87 1987 only - Oct 25 11:44:10s 0:15:50 - +Rule sol87 1987 only - Oct 26 11:44:05s 0:15:55 - +Rule sol87 1987 only - Oct 27 11:43:55s 0:16:05 - +Rule sol87 1987 only - Oct 28 11:43:50s 0:16:10 - +Rule sol87 1987 only - Oct 29 11:43:45s 0:16:15 - +Rule sol87 1987 only - Oct 30 11:43:45s 0:16:15 - +Rule sol87 1987 only - Oct 31 11:43:40s 0:16:20 - +Rule sol87 1987 only - Nov 1 11:43:40s 0:16:20 - +Rule sol87 1987 only - Nov 2 11:43:35s 0:16:25 - +Rule sol87 1987 only - Nov 3 11:43:35s 0:16:25 - +Rule sol87 1987 only - Nov 4 11:43:35s 0:16:25 - +Rule sol87 1987 only - Nov 5 11:43:35s 0:16:25 - +Rule sol87 1987 only - Nov 6 11:43:40s 0:16:20 - +Rule sol87 1987 only - Nov 7 11:43:40s 0:16:20 - +Rule sol87 1987 only - Nov 8 11:43:45s 0:16:15 - +Rule sol87 1987 only - Nov 9 11:43:50s 0:16:10 - +Rule sol87 1987 only - Nov 10 11:43:55s 0:16:05 - +Rule sol87 1987 only - Nov 11 11:44:00s 0:16:00 - +Rule sol87 1987 only - Nov 12 11:44:05s 0:15:55 - +Rule sol87 1987 only - Nov 13 11:44:15s 0:15:45 - +Rule sol87 1987 only - Nov 14 11:44:20s 0:15:40 - +Rule sol87 1987 only - Nov 15 11:44:30s 0:15:30 - +Rule sol87 1987 only - Nov 16 11:44:40s 0:15:20 - +Rule sol87 1987 only - Nov 17 11:44:50s 0:15:10 - +Rule sol87 1987 only - Nov 18 11:45:05s 0:14:55 - +Rule sol87 1987 only - Nov 19 11:45:15s 0:14:45 - +Rule sol87 1987 only - Nov 20 11:45:30s 0:14:30 - +Rule sol87 1987 only - Nov 21 11:45:45s 0:14:15 - +Rule sol87 1987 only - Nov 22 11:46:00s 0:14:00 - +Rule sol87 1987 only - Nov 23 11:46:15s 0:13:45 - +Rule sol87 1987 only - Nov 24 11:46:30s 0:13:30 - +Rule sol87 1987 only - Nov 25 11:46:50s 0:13:10 - +Rule sol87 1987 only - Nov 26 11:47:10s 0:12:50 - +Rule sol87 1987 only - Nov 27 11:47:25s 0:12:35 - +Rule sol87 1987 only - Nov 28 11:47:45s 0:12:15 - +Rule sol87 1987 only - Nov 29 11:48:05s 0:11:55 - +Rule sol87 1987 only - Nov 30 11:48:30s 0:11:30 - +Rule sol87 1987 only - Dec 1 11:48:50s 0:11:10 - +Rule sol87 1987 only - Dec 2 11:49:10s 0:10:50 - +Rule sol87 1987 only - Dec 3 11:49:35s 0:10:25 - +Rule sol87 1987 only - Dec 4 11:50:00s 0:10:00 - +Rule sol87 1987 only - Dec 5 11:50:25s 0:09:35 - +Rule sol87 1987 only - Dec 6 11:50:50s 0:09:10 - +Rule sol87 1987 only - Dec 7 11:51:15s 0:08:45 - +Rule sol87 1987 only - Dec 8 11:51:40s 0:08:20 - +Rule sol87 1987 only - Dec 9 11:52:05s 0:07:55 - +Rule sol87 1987 only - Dec 10 11:52:30s 0:07:30 - +Rule sol87 1987 only - Dec 11 11:53:00s 0:07:00 - +Rule sol87 1987 only - Dec 12 11:53:25s 0:06:35 - +Rule sol87 1987 only - Dec 13 11:53:55s 0:06:05 - +Rule sol87 1987 only - Dec 14 11:54:25s 0:05:35 - +Rule sol87 1987 only - Dec 15 11:54:50s 0:05:10 - +Rule sol87 1987 only - Dec 16 11:55:20s 0:04:40 - +Rule sol87 1987 only - Dec 17 11:55:50s 0:04:10 - +Rule sol87 1987 only - Dec 18 11:56:20s 0:03:40 - +Rule sol87 1987 only - Dec 19 11:56:50s 0:03:10 - +Rule sol87 1987 only - Dec 20 11:57:20s 0:02:40 - +Rule sol87 1987 only - Dec 21 11:57:50s 0:02:10 - +Rule sol87 1987 only - Dec 22 11:58:20s 0:01:40 - +Rule sol87 1987 only - Dec 23 11:58:50s 0:01:10 - +Rule sol87 1987 only - Dec 24 11:59:20s 0:00:40 - +Rule sol87 1987 only - Dec 25 11:59:50s 0:00:10 - +Rule sol87 1987 only - Dec 26 12:00:20s -0:00:20 - +Rule sol87 1987 only - Dec 27 12:00:45s -0:00:45 - +Rule sol87 1987 only - Dec 28 12:01:15s -0:01:15 - +Rule sol87 1987 only - Dec 29 12:01:45s -0:01:45 - +Rule sol87 1987 only - Dec 30 12:02:15s -0:02:15 - +Rule sol87 1987 only - Dec 31 12:02:45s -0:02:45 - + +# Riyadh is at about 46 degrees 46 minutes East: 3 hrs, 7 mins, 4 secs +# Before and after 1987, we'll operate on local mean solar time. + +# Zone NAME GMTOFF RULES/SAVE FORMAT [UNTIL] +Zone Asia/Riyadh87 3:07:04 - ?? 1987 + 3:07:04 sol87 ?? 1988 + 3:07:04 - ?? +# For backward compatibility... +Link Asia/Riyadh87 Mideast/Riyadh87 Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/solar88 =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/Attic/solar88,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/solar88 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,388 @@ +# @(#)solar88 7.3 + +# Apparent noon times below are for Riyadh; they're a bit off for other places. +# Times were computed using formulas in the U.S. Naval Observatory's +# Almanac for Computers 1988; the formulas "will give EqT to an accuracy of +# [plus or minus two] seconds during the current year." +# +# Rounding to the nearest five seconds results in fewer than +# 256 different "time types"--a limit that's faced because time types are +# stored on disk as unsigned chars. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule sol88 1988 only - Jan 1 12:03:15s -0:03:15 - +Rule sol88 1988 only - Jan 2 12:03:40s -0:03:40 - +Rule sol88 1988 only - Jan 3 12:04:10s -0:04:10 - +Rule sol88 1988 only - Jan 4 12:04:40s -0:04:40 - +Rule sol88 1988 only - Jan 5 12:05:05s -0:05:05 - +Rule sol88 1988 only - Jan 6 12:05:30s -0:05:30 - +Rule sol88 1988 only - Jan 7 12:06:00s -0:06:00 - +Rule sol88 1988 only - Jan 8 12:06:25s -0:06:25 - +Rule sol88 1988 only - Jan 9 12:06:50s -0:06:50 - +Rule sol88 1988 only - Jan 10 12:07:15s -0:07:15 - +Rule sol88 1988 only - Jan 11 12:07:40s -0:07:40 - +Rule sol88 1988 only - Jan 12 12:08:05s -0:08:05 - +Rule sol88 1988 only - Jan 13 12:08:25s -0:08:25 - +Rule sol88 1988 only - Jan 14 12:08:50s -0:08:50 - +Rule sol88 1988 only - Jan 15 12:09:10s -0:09:10 - +Rule sol88 1988 only - Jan 16 12:09:30s -0:09:30 - +Rule sol88 1988 only - Jan 17 12:09:50s -0:09:50 - +Rule sol88 1988 only - Jan 18 12:10:10s -0:10:10 - +Rule sol88 1988 only - Jan 19 12:10:30s -0:10:30 - +Rule sol88 1988 only - Jan 20 12:10:50s -0:10:50 - +Rule sol88 1988 only - Jan 21 12:11:05s -0:11:05 - +Rule sol88 1988 only - Jan 22 12:11:25s -0:11:25 - +Rule sol88 1988 only - Jan 23 12:11:40s -0:11:40 - +Rule sol88 1988 only - Jan 24 12:11:55s -0:11:55 - +Rule sol88 1988 only - Jan 25 12:12:10s -0:12:10 - +Rule sol88 1988 only - Jan 26 12:12:25s -0:12:25 - +Rule sol88 1988 only - Jan 27 12:12:40s -0:12:40 - +Rule sol88 1988 only - Jan 28 12:12:50s -0:12:50 - +Rule sol88 1988 only - Jan 29 12:13:00s -0:13:00 - +Rule sol88 1988 only - Jan 30 12:13:10s -0:13:10 - +Rule sol88 1988 only - Jan 31 12:13:20s -0:13:20 - +Rule sol88 1988 only - Feb 1 12:13:30s -0:13:30 - +Rule sol88 1988 only - Feb 2 12:13:40s -0:13:40 - +Rule sol88 1988 only - Feb 3 12:13:45s -0:13:45 - +Rule sol88 1988 only - Feb 4 12:13:55s -0:13:55 - +Rule sol88 1988 only - Feb 5 12:14:00s -0:14:00 - +Rule sol88 1988 only - Feb 6 12:14:05s -0:14:05 - +Rule sol88 1988 only - Feb 7 12:14:10s -0:14:10 - +Rule sol88 1988 only - Feb 8 12:14:10s -0:14:10 - +Rule sol88 1988 only - Feb 9 12:14:15s -0:14:15 - +Rule sol88 1988 only - Feb 10 12:14:15s -0:14:15 - +Rule sol88 1988 only - Feb 11 12:14:15s -0:14:15 - +Rule sol88 1988 only - Feb 12 12:14:15s -0:14:15 - +Rule sol88 1988 only - Feb 13 12:14:15s -0:14:15 - +Rule sol88 1988 only - Feb 14 12:14:15s -0:14:15 - +Rule sol88 1988 only - Feb 15 12:14:10s -0:14:10 - +Rule sol88 1988 only - Feb 16 12:14:10s -0:14:10 - +Rule sol88 1988 only - Feb 17 12:14:05s -0:14:05 - +Rule sol88 1988 only - Feb 18 12:14:00s -0:14:00 - +Rule sol88 1988 only - Feb 19 12:13:55s -0:13:55 - +Rule sol88 1988 only - Feb 20 12:13:50s -0:13:50 - +Rule sol88 1988 only - Feb 21 12:13:45s -0:13:45 - +Rule sol88 1988 only - Feb 22 12:13:40s -0:13:40 - +Rule sol88 1988 only - Feb 23 12:13:30s -0:13:30 - +Rule sol88 1988 only - Feb 24 12:13:20s -0:13:20 - +Rule sol88 1988 only - Feb 25 12:13:15s -0:13:15 - +Rule sol88 1988 only - Feb 26 12:13:05s -0:13:05 - +Rule sol88 1988 only - Feb 27 12:12:55s -0:12:55 - +Rule sol88 1988 only - Feb 28 12:12:45s -0:12:45 - +Rule sol88 1988 only - Feb 29 12:12:30s -0:12:30 - +Rule sol88 1988 only - Mar 1 12:12:20s -0:12:20 - +Rule sol88 1988 only - Mar 2 12:12:10s -0:12:10 - +Rule sol88 1988 only - Mar 3 12:11:55s -0:11:55 - +Rule sol88 1988 only - Mar 4 12:11:45s -0:11:45 - +Rule sol88 1988 only - Mar 5 12:11:30s -0:11:30 - +Rule sol88 1988 only - Mar 6 12:11:15s -0:11:15 - +Rule sol88 1988 only - Mar 7 12:11:00s -0:11:00 - +Rule sol88 1988 only - Mar 8 12:10:45s -0:10:45 - +Rule sol88 1988 only - Mar 9 12:10:30s -0:10:30 - +Rule sol88 1988 only - Mar 10 12:10:15s -0:10:15 - +Rule sol88 1988 only - Mar 11 12:10:00s -0:10:00 - +Rule sol88 1988 only - Mar 12 12:09:45s -0:09:45 - +Rule sol88 1988 only - Mar 13 12:09:30s -0:09:30 - +Rule sol88 1988 only - Mar 14 12:09:10s -0:09:10 - +Rule sol88 1988 only - Mar 15 12:08:55s -0:08:55 - +Rule sol88 1988 only - Mar 16 12:08:40s -0:08:40 - +Rule sol88 1988 only - Mar 17 12:08:20s -0:08:20 - +Rule sol88 1988 only - Mar 18 12:08:05s -0:08:05 - +Rule sol88 1988 only - Mar 19 12:07:45s -0:07:45 - +Rule sol88 1988 only - Mar 20 12:07:30s -0:07:30 - +Rule sol88 1988 only - Mar 21 12:07:10s -0:07:10 - +Rule sol88 1988 only - Mar 22 12:06:50s -0:06:50 - +Rule sol88 1988 only - Mar 23 12:06:35s -0:06:35 - +Rule sol88 1988 only - Mar 24 12:06:15s -0:06:15 - +Rule sol88 1988 only - Mar 25 12:06:00s -0:06:00 - +Rule sol88 1988 only - Mar 26 12:05:40s -0:05:40 - +Rule sol88 1988 only - Mar 27 12:05:20s -0:05:20 - +Rule sol88 1988 only - Mar 28 12:05:05s -0:05:05 - +Rule sol88 1988 only - Mar 29 12:04:45s -0:04:45 - +Rule sol88 1988 only - Mar 30 12:04:25s -0:04:25 - +Rule sol88 1988 only - Mar 31 12:04:10s -0:04:10 - +Rule sol88 1988 only - Apr 1 12:03:50s -0:03:50 - +Rule sol88 1988 only - Apr 2 12:03:35s -0:03:35 - +Rule sol88 1988 only - Apr 3 12:03:15s -0:03:15 - +Rule sol88 1988 only - Apr 4 12:03:00s -0:03:00 - +Rule sol88 1988 only - Apr 5 12:02:40s -0:02:40 - +Rule sol88 1988 only - Apr 6 12:02:25s -0:02:25 - +Rule sol88 1988 only - Apr 7 12:02:05s -0:02:05 - +Rule sol88 1988 only - Apr 8 12:01:50s -0:01:50 - +Rule sol88 1988 only - Apr 9 12:01:35s -0:01:35 - +Rule sol88 1988 only - Apr 10 12:01:15s -0:01:15 - +Rule sol88 1988 only - Apr 11 12:01:00s -0:01:00 - +Rule sol88 1988 only - Apr 12 12:00:45s -0:00:45 - +Rule sol88 1988 only - Apr 13 12:00:30s -0:00:30 - +Rule sol88 1988 only - Apr 14 12:00:15s -0:00:15 - +Rule sol88 1988 only - Apr 15 12:00:00s 0:00:00 - +Rule sol88 1988 only - Apr 16 11:59:45s 0:00:15 - +Rule sol88 1988 only - Apr 17 11:59:30s 0:00:30 - +Rule sol88 1988 only - Apr 18 11:59:20s 0:00:40 - +Rule sol88 1988 only - Apr 19 11:59:05s 0:00:55 - +Rule sol88 1988 only - Apr 20 11:58:55s 0:01:05 - +Rule sol88 1988 only - Apr 21 11:58:40s 0:01:20 - +Rule sol88 1988 only - Apr 22 11:58:30s 0:01:30 - +Rule sol88 1988 only - Apr 23 11:58:15s 0:01:45 - +Rule sol88 1988 only - Apr 24 11:58:05s 0:01:55 - +Rule sol88 1988 only - Apr 25 11:57:55s 0:02:05 - +Rule sol88 1988 only - Apr 26 11:57:45s 0:02:15 - +Rule sol88 1988 only - Apr 27 11:57:35s 0:02:25 - +Rule sol88 1988 only - Apr 28 11:57:30s 0:02:30 - +Rule sol88 1988 only - Apr 29 11:57:20s 0:02:40 - +Rule sol88 1988 only - Apr 30 11:57:10s 0:02:50 - +Rule sol88 1988 only - May 1 11:57:05s 0:02:55 - +Rule sol88 1988 only - May 2 11:56:55s 0:03:05 - +Rule sol88 1988 only - May 3 11:56:50s 0:03:10 - +Rule sol88 1988 only - May 4 11:56:45s 0:03:15 - +Rule sol88 1988 only - May 5 11:56:40s 0:03:20 - +Rule sol88 1988 only - May 6 11:56:35s 0:03:25 - +Rule sol88 1988 only - May 7 11:56:30s 0:03:30 - +Rule sol88 1988 only - May 8 11:56:25s 0:03:35 - +Rule sol88 1988 only - May 9 11:56:25s 0:03:35 - +Rule sol88 1988 only - May 10 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 11 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 12 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 13 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 14 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 15 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 16 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 17 11:56:20s 0:03:40 - +Rule sol88 1988 only - May 18 11:56:25s 0:03:35 - +Rule sol88 1988 only - May 19 11:56:25s 0:03:35 - +Rule sol88 1988 only - May 20 11:56:30s 0:03:30 - +Rule sol88 1988 only - May 21 11:56:35s 0:03:25 - +Rule sol88 1988 only - May 22 11:56:40s 0:03:20 - +Rule sol88 1988 only - May 23 11:56:45s 0:03:15 - +Rule sol88 1988 only - May 24 11:56:50s 0:03:10 - +Rule sol88 1988 only - May 25 11:56:55s 0:03:05 - +Rule sol88 1988 only - May 26 11:57:00s 0:03:00 - +Rule sol88 1988 only - May 27 11:57:05s 0:02:55 - +Rule sol88 1988 only - May 28 11:57:15s 0:02:45 - +Rule sol88 1988 only - May 29 11:57:20s 0:02:40 - +Rule sol88 1988 only - May 30 11:57:30s 0:02:30 - +Rule sol88 1988 only - May 31 11:57:40s 0:02:20 - +Rule sol88 1988 only - Jun 1 11:57:50s 0:02:10 - +Rule sol88 1988 only - Jun 2 11:57:55s 0:02:05 - +Rule sol88 1988 only - Jun 3 11:58:05s 0:01:55 - +Rule sol88 1988 only - Jun 4 11:58:15s 0:01:45 - +Rule sol88 1988 only - Jun 5 11:58:30s 0:01:30 - +Rule sol88 1988 only - Jun 6 11:58:40s 0:01:20 - +Rule sol88 1988 only - Jun 7 11:58:50s 0:01:10 - +Rule sol88 1988 only - Jun 8 11:59:00s 0:01:00 - +Rule sol88 1988 only - Jun 9 11:59:15s 0:00:45 - +Rule sol88 1988 only - Jun 10 11:59:25s 0:00:35 - +Rule sol88 1988 only - Jun 11 11:59:35s 0:00:25 - +Rule sol88 1988 only - Jun 12 11:59:50s 0:00:10 - +Rule sol88 1988 only - Jun 13 12:00:00s 0:00:00 - +Rule sol88 1988 only - Jun 14 12:00:15s -0:00:15 - +Rule sol88 1988 only - Jun 15 12:00:25s -0:00:25 - +Rule sol88 1988 only - Jun 16 12:00:40s -0:00:40 - +Rule sol88 1988 only - Jun 17 12:00:55s -0:00:55 - +Rule sol88 1988 only - Jun 18 12:01:05s -0:01:05 - +Rule sol88 1988 only - Jun 19 12:01:20s -0:01:20 - +Rule sol88 1988 only - Jun 20 12:01:30s -0:01:30 - +Rule sol88 1988 only - Jun 21 12:01:45s -0:01:45 - +Rule sol88 1988 only - Jun 22 12:02:00s -0:02:00 - +Rule sol88 1988 only - Jun 23 12:02:10s -0:02:10 - +Rule sol88 1988 only - Jun 24 12:02:25s -0:02:25 - +Rule sol88 1988 only - Jun 25 12:02:35s -0:02:35 - +Rule sol88 1988 only - Jun 26 12:02:50s -0:02:50 - +Rule sol88 1988 only - Jun 27 12:03:00s -0:03:00 - +Rule sol88 1988 only - Jun 28 12:03:15s -0:03:15 - +Rule sol88 1988 only - Jun 29 12:03:25s -0:03:25 - +Rule sol88 1988 only - Jun 30 12:03:40s -0:03:40 - +Rule sol88 1988 only - Jul 1 12:03:50s -0:03:50 - +Rule sol88 1988 only - Jul 2 12:04:00s -0:04:00 - +Rule sol88 1988 only - Jul 3 12:04:10s -0:04:10 - +Rule sol88 1988 only - Jul 4 12:04:25s -0:04:25 - +Rule sol88 1988 only - Jul 5 12:04:35s -0:04:35 - +Rule sol88 1988 only - Jul 6 12:04:45s -0:04:45 - +Rule sol88 1988 only - Jul 7 12:04:55s -0:04:55 - +Rule sol88 1988 only - Jul 8 12:05:05s -0:05:05 - +Rule sol88 1988 only - Jul 9 12:05:10s -0:05:10 - +Rule sol88 1988 only - Jul 10 12:05:20s -0:05:20 - +Rule sol88 1988 only - Jul 11 12:05:30s -0:05:30 - +Rule sol88 1988 only - Jul 12 12:05:35s -0:05:35 - +Rule sol88 1988 only - Jul 13 12:05:45s -0:05:45 - +Rule sol88 1988 only - Jul 14 12:05:50s -0:05:50 - +Rule sol88 1988 only - Jul 15 12:05:55s -0:05:55 - +Rule sol88 1988 only - Jul 16 12:06:00s -0:06:00 - +Rule sol88 1988 only - Jul 17 12:06:05s -0:06:05 - +Rule sol88 1988 only - Jul 18 12:06:10s -0:06:10 - +Rule sol88 1988 only - Jul 19 12:06:15s -0:06:15 - +Rule sol88 1988 only - Jul 20 12:06:20s -0:06:20 - +Rule sol88 1988 only - Jul 21 12:06:25s -0:06:25 - +Rule sol88 1988 only - Jul 22 12:06:25s -0:06:25 - +Rule sol88 1988 only - Jul 23 12:06:25s -0:06:25 - +Rule sol88 1988 only - Jul 24 12:06:30s -0:06:30 - +Rule sol88 1988 only - Jul 25 12:06:30s -0:06:30 - +Rule sol88 1988 only - Jul 26 12:06:30s -0:06:30 - +Rule sol88 1988 only - Jul 27 12:06:30s -0:06:30 - +Rule sol88 1988 only - Jul 28 12:06:30s -0:06:30 - +Rule sol88 1988 only - Jul 29 12:06:25s -0:06:25 - +Rule sol88 1988 only - Jul 30 12:06:25s -0:06:25 - +Rule sol88 1988 only - Jul 31 12:06:20s -0:06:20 - +Rule sol88 1988 only - Aug 1 12:06:15s -0:06:15 - +Rule sol88 1988 only - Aug 2 12:06:15s -0:06:15 - +Rule sol88 1988 only - Aug 3 12:06:10s -0:06:10 - +Rule sol88 1988 only - Aug 4 12:06:05s -0:06:05 - +Rule sol88 1988 only - Aug 5 12:05:55s -0:05:55 - +Rule sol88 1988 only - Aug 6 12:05:50s -0:05:50 - +Rule sol88 1988 only - Aug 7 12:05:45s -0:05:45 - +Rule sol88 1988 only - Aug 8 12:05:35s -0:05:35 - +Rule sol88 1988 only - Aug 9 12:05:25s -0:05:25 - +Rule sol88 1988 only - Aug 10 12:05:20s -0:05:20 - +Rule sol88 1988 only - Aug 11 12:05:10s -0:05:10 - +Rule sol88 1988 only - Aug 12 12:05:00s -0:05:00 - +Rule sol88 1988 only - Aug 13 12:04:50s -0:04:50 - +Rule sol88 1988 only - Aug 14 12:04:35s -0:04:35 - +Rule sol88 1988 only - Aug 15 12:04:25s -0:04:25 - +Rule sol88 1988 only - Aug 16 12:04:15s -0:04:15 - +Rule sol88 1988 only - Aug 17 12:04:00s -0:04:00 - +Rule sol88 1988 only - Aug 18 12:03:50s -0:03:50 - +Rule sol88 1988 only - Aug 19 12:03:35s -0:03:35 - +Rule sol88 1988 only - Aug 20 12:03:20s -0:03:20 - +Rule sol88 1988 only - Aug 21 12:03:05s -0:03:05 - +Rule sol88 1988 only - Aug 22 12:02:50s -0:02:50 - +Rule sol88 1988 only - Aug 23 12:02:35s -0:02:35 - +Rule sol88 1988 only - Aug 24 12:02:20s -0:02:20 - +Rule sol88 1988 only - Aug 25 12:02:00s -0:02:00 - +Rule sol88 1988 only - Aug 26 12:01:45s -0:01:45 - +Rule sol88 1988 only - Aug 27 12:01:30s -0:01:30 - +Rule sol88 1988 only - Aug 28 12:01:10s -0:01:10 - +Rule sol88 1988 only - Aug 29 12:00:50s -0:00:50 - +Rule sol88 1988 only - Aug 30 12:00:35s -0:00:35 - +Rule sol88 1988 only - Aug 31 12:00:15s -0:00:15 - +Rule sol88 1988 only - Sep 1 11:59:55s 0:00:05 - +Rule sol88 1988 only - Sep 2 11:59:35s 0:00:25 - +Rule sol88 1988 only - Sep 3 11:59:20s 0:00:40 - +Rule sol88 1988 only - Sep 4 11:59:00s 0:01:00 - +Rule sol88 1988 only - Sep 5 11:58:40s 0:01:20 - +Rule sol88 1988 only - Sep 6 11:58:20s 0:01:40 - +Rule sol88 1988 only - Sep 7 11:58:00s 0:02:00 - +Rule sol88 1988 only - Sep 8 11:57:35s 0:02:25 - +Rule sol88 1988 only - Sep 9 11:57:15s 0:02:45 - +Rule sol88 1988 only - Sep 10 11:56:55s 0:03:05 - +Rule sol88 1988 only - Sep 11 11:56:35s 0:03:25 - +Rule sol88 1988 only - Sep 12 11:56:15s 0:03:45 - +Rule sol88 1988 only - Sep 13 11:55:50s 0:04:10 - +Rule sol88 1988 only - Sep 14 11:55:30s 0:04:30 - +Rule sol88 1988 only - Sep 15 11:55:10s 0:04:50 - +Rule sol88 1988 only - Sep 16 11:54:50s 0:05:10 - +Rule sol88 1988 only - Sep 17 11:54:25s 0:05:35 - +Rule sol88 1988 only - Sep 18 11:54:05s 0:05:55 - +Rule sol88 1988 only - Sep 19 11:53:45s 0:06:15 - +Rule sol88 1988 only - Sep 20 11:53:25s 0:06:35 - +Rule sol88 1988 only - Sep 21 11:53:00s 0:07:00 - +Rule sol88 1988 only - Sep 22 11:52:40s 0:07:20 - +Rule sol88 1988 only - Sep 23 11:52:20s 0:07:40 - +Rule sol88 1988 only - Sep 24 11:52:00s 0:08:00 - +Rule sol88 1988 only - Sep 25 11:51:40s 0:08:20 - +Rule sol88 1988 only - Sep 26 11:51:15s 0:08:45 - +Rule sol88 1988 only - Sep 27 11:50:55s 0:09:05 - +Rule sol88 1988 only - Sep 28 11:50:35s 0:09:25 - +Rule sol88 1988 only - Sep 29 11:50:15s 0:09:45 - +Rule sol88 1988 only - Sep 30 11:49:55s 0:10:05 - +Rule sol88 1988 only - Oct 1 11:49:35s 0:10:25 - +Rule sol88 1988 only - Oct 2 11:49:20s 0:10:40 - +Rule sol88 1988 only - Oct 3 11:49:00s 0:11:00 - +Rule sol88 1988 only - Oct 4 11:48:40s 0:11:20 - +Rule sol88 1988 only - Oct 5 11:48:25s 0:11:35 - +Rule sol88 1988 only - Oct 6 11:48:05s 0:11:55 - +Rule sol88 1988 only - Oct 7 11:47:50s 0:12:10 - +Rule sol88 1988 only - Oct 8 11:47:30s 0:12:30 - +Rule sol88 1988 only - Oct 9 11:47:15s 0:12:45 - +Rule sol88 1988 only - Oct 10 11:47:00s 0:13:00 - +Rule sol88 1988 only - Oct 11 11:46:45s 0:13:15 - +Rule sol88 1988 only - Oct 12 11:46:30s 0:13:30 - +Rule sol88 1988 only - Oct 13 11:46:15s 0:13:45 - +Rule sol88 1988 only - Oct 14 11:46:00s 0:14:00 - +Rule sol88 1988 only - Oct 15 11:45:45s 0:14:15 - +Rule sol88 1988 only - Oct 16 11:45:35s 0:14:25 - +Rule sol88 1988 only - Oct 17 11:45:20s 0:14:40 - +Rule sol88 1988 only - Oct 18 11:45:10s 0:14:50 - +Rule sol88 1988 only - Oct 19 11:45:00s 0:15:00 - +Rule sol88 1988 only - Oct 20 11:44:45s 0:15:15 - +Rule sol88 1988 only - Oct 21 11:44:40s 0:15:20 - +Rule sol88 1988 only - Oct 22 11:44:30s 0:15:30 - +Rule sol88 1988 only - Oct 23 11:44:20s 0:15:40 - +Rule sol88 1988 only - Oct 24 11:44:10s 0:15:50 - +Rule sol88 1988 only - Oct 25 11:44:05s 0:15:55 - +Rule sol88 1988 only - Oct 26 11:44:00s 0:16:00 - +Rule sol88 1988 only - Oct 27 11:43:55s 0:16:05 - +Rule sol88 1988 only - Oct 28 11:43:50s 0:16:10 - +Rule sol88 1988 only - Oct 29 11:43:45s 0:16:15 - +Rule sol88 1988 only - Oct 30 11:43:40s 0:16:20 - +Rule sol88 1988 only - Oct 31 11:43:40s 0:16:20 - +Rule sol88 1988 only - Nov 1 11:43:35s 0:16:25 - +Rule sol88 1988 only - Nov 2 11:43:35s 0:16:25 - +Rule sol88 1988 only - Nov 3 11:43:35s 0:16:25 - +Rule sol88 1988 only - Nov 4 11:43:35s 0:16:25 - +Rule sol88 1988 only - Nov 5 11:43:40s 0:16:20 - +Rule sol88 1988 only - Nov 6 11:43:40s 0:16:20 - +Rule sol88 1988 only - Nov 7 11:43:45s 0:16:15 - +Rule sol88 1988 only - Nov 8 11:43:45s 0:16:15 - +Rule sol88 1988 only - Nov 9 11:43:50s 0:16:10 - +Rule sol88 1988 only - Nov 10 11:44:00s 0:16:00 - +Rule sol88 1988 only - Nov 11 11:44:05s 0:15:55 - +Rule sol88 1988 only - Nov 12 11:44:10s 0:15:50 - +Rule sol88 1988 only - Nov 13 11:44:20s 0:15:40 - +Rule sol88 1988 only - Nov 14 11:44:30s 0:15:30 - +Rule sol88 1988 only - Nov 15 11:44:40s 0:15:20 - +Rule sol88 1988 only - Nov 16 11:44:50s 0:15:10 - +Rule sol88 1988 only - Nov 17 11:45:00s 0:15:00 - +Rule sol88 1988 only - Nov 18 11:45:15s 0:14:45 - +Rule sol88 1988 only - Nov 19 11:45:25s 0:14:35 - +Rule sol88 1988 only - Nov 20 11:45:40s 0:14:20 - +Rule sol88 1988 only - Nov 21 11:45:55s 0:14:05 - +Rule sol88 1988 only - Nov 22 11:46:10s 0:13:50 - +Rule sol88 1988 only - Nov 23 11:46:30s 0:13:30 - +Rule sol88 1988 only - Nov 24 11:46:45s 0:13:15 - +Rule sol88 1988 only - Nov 25 11:47:05s 0:12:55 - +Rule sol88 1988 only - Nov 26 11:47:20s 0:12:40 - +Rule sol88 1988 only - Nov 27 11:47:40s 0:12:20 - +Rule sol88 1988 only - Nov 28 11:48:00s 0:12:00 - +Rule sol88 1988 only - Nov 29 11:48:25s 0:11:35 - +Rule sol88 1988 only - Nov 30 11:48:45s 0:11:15 - +Rule sol88 1988 only - Dec 1 11:49:05s 0:10:55 - +Rule sol88 1988 only - Dec 2 11:49:30s 0:10:30 - +Rule sol88 1988 only - Dec 3 11:49:55s 0:10:05 - +Rule sol88 1988 only - Dec 4 11:50:15s 0:09:45 - +Rule sol88 1988 only - Dec 5 11:50:40s 0:09:20 - +Rule sol88 1988 only - Dec 6 11:51:05s 0:08:55 - +Rule sol88 1988 only - Dec 7 11:51:35s 0:08:25 - +Rule sol88 1988 only - Dec 8 11:52:00s 0:08:00 - +Rule sol88 1988 only - Dec 9 11:52:25s 0:07:35 - +Rule sol88 1988 only - Dec 10 11:52:55s 0:07:05 - +Rule sol88 1988 only - Dec 11 11:53:20s 0:06:40 - +Rule sol88 1988 only - Dec 12 11:53:50s 0:06:10 - +Rule sol88 1988 only - Dec 13 11:54:15s 0:05:45 - +Rule sol88 1988 only - Dec 14 11:54:45s 0:05:15 - +Rule sol88 1988 only - Dec 15 11:55:15s 0:04:45 - +Rule sol88 1988 only - Dec 16 11:55:45s 0:04:15 - +Rule sol88 1988 only - Dec 17 11:56:15s 0:03:45 - +Rule sol88 1988 only - Dec 18 11:56:40s 0:03:20 - +Rule sol88 1988 only - Dec 19 11:57:10s 0:02:50 - +Rule sol88 1988 only - Dec 20 11:57:40s 0:02:20 - +Rule sol88 1988 only - Dec 21 11:58:10s 0:01:50 - +Rule sol88 1988 only - Dec 22 11:58:40s 0:01:20 - +Rule sol88 1988 only - Dec 23 11:59:10s 0:00:50 - +Rule sol88 1988 only - Dec 24 11:59:40s 0:00:20 - +Rule sol88 1988 only - Dec 25 12:00:10s -0:00:10 - +Rule sol88 1988 only - Dec 26 12:00:40s -0:00:40 - +Rule sol88 1988 only - Dec 27 12:01:10s -0:01:10 - +Rule sol88 1988 only - Dec 28 12:01:40s -0:01:40 - +Rule sol88 1988 only - Dec 29 12:02:10s -0:02:10 - +Rule sol88 1988 only - Dec 30 12:02:35s -0:02:35 - +Rule sol88 1988 only - Dec 31 12:03:05s -0:03:05 - + +# Riyadh is at about 46 degrees 46 minutes East: 3 hrs, 7 mins, 4 secs +# Before and after 1988, we'll operate on local mean solar time. + +# Zone NAME GMTOFF RULES/SAVE FORMAT [UNTIL] +Zone Asia/Riyadh88 3:07:04 - ?? 1988 + 3:07:04 sol88 ?? 1989 + 3:07:04 - ?? +# For backward compatibility... +Link Asia/Riyadh88 Mideast/Riyadh88 Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/solar89 =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/Attic/solar89,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/solar89 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,393 @@ +# @(#)solar89 7.4 + +# Apparent noon times below are for Riyadh; they're a bit off for other places. +# Times were computed using a formula provided by the U. S. Naval Observatory: +# eqt = -105.8 * sin(l) + 596.2 * sin(2 * l) + 4.4 * sin(3 * l) +# -12.7 * sin(4 * l) - 429.0 * cos(l) - 2.1 * cos (2 * l) +# + 19.3 * cos(3 * l); +# where l is the "mean longitude of the Sun" given by +# l = 279.642 degrees + 0.985647 * d +# and d is the interval in days from January 0, 0 hours Universal Time +# (equaling the day of the year plus the fraction of a day from zero hours). +# The accuracy of the formula is plus or minus three seconds. +# +# Rounding to the nearest five seconds results in fewer than +# 256 different "time types"--a limit that's faced because time types are +# stored on disk as unsigned chars. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule sol89 1989 only - Jan 1 12:03:35s -0:03:35 - +Rule sol89 1989 only - Jan 2 12:04:05s -0:04:05 - +Rule sol89 1989 only - Jan 3 12:04:30s -0:04:30 - +Rule sol89 1989 only - Jan 4 12:05:00s -0:05:00 - +Rule sol89 1989 only - Jan 5 12:05:25s -0:05:25 - +Rule sol89 1989 only - Jan 6 12:05:50s -0:05:50 - +Rule sol89 1989 only - Jan 7 12:06:15s -0:06:15 - +Rule sol89 1989 only - Jan 8 12:06:45s -0:06:45 - +Rule sol89 1989 only - Jan 9 12:07:10s -0:07:10 - +Rule sol89 1989 only - Jan 10 12:07:35s -0:07:35 - +Rule sol89 1989 only - Jan 11 12:07:55s -0:07:55 - +Rule sol89 1989 only - Jan 12 12:08:20s -0:08:20 - +Rule sol89 1989 only - Jan 13 12:08:45s -0:08:45 - +Rule sol89 1989 only - Jan 14 12:09:05s -0:09:05 - +Rule sol89 1989 only - Jan 15 12:09:25s -0:09:25 - +Rule sol89 1989 only - Jan 16 12:09:45s -0:09:45 - +Rule sol89 1989 only - Jan 17 12:10:05s -0:10:05 - +Rule sol89 1989 only - Jan 18 12:10:25s -0:10:25 - +Rule sol89 1989 only - Jan 19 12:10:45s -0:10:45 - +Rule sol89 1989 only - Jan 20 12:11:05s -0:11:05 - +Rule sol89 1989 only - Jan 21 12:11:20s -0:11:20 - +Rule sol89 1989 only - Jan 22 12:11:35s -0:11:35 - +Rule sol89 1989 only - Jan 23 12:11:55s -0:11:55 - +Rule sol89 1989 only - Jan 24 12:12:10s -0:12:10 - +Rule sol89 1989 only - Jan 25 12:12:20s -0:12:20 - +Rule sol89 1989 only - Jan 26 12:12:35s -0:12:35 - +Rule sol89 1989 only - Jan 27 12:12:50s -0:12:50 - +Rule sol89 1989 only - Jan 28 12:13:00s -0:13:00 - +Rule sol89 1989 only - Jan 29 12:13:10s -0:13:10 - +Rule sol89 1989 only - Jan 30 12:13:20s -0:13:20 - +Rule sol89 1989 only - Jan 31 12:13:30s -0:13:30 - +Rule sol89 1989 only - Feb 1 12:13:40s -0:13:40 - +Rule sol89 1989 only - Feb 2 12:13:45s -0:13:45 - +Rule sol89 1989 only - Feb 3 12:13:55s -0:13:55 - +Rule sol89 1989 only - Feb 4 12:14:00s -0:14:00 - +Rule sol89 1989 only - Feb 5 12:14:05s -0:14:05 - +Rule sol89 1989 only - Feb 6 12:14:10s -0:14:10 - +Rule sol89 1989 only - Feb 7 12:14:10s -0:14:10 - +Rule sol89 1989 only - Feb 8 12:14:15s -0:14:15 - +Rule sol89 1989 only - Feb 9 12:14:15s -0:14:15 - +Rule sol89 1989 only - Feb 10 12:14:20s -0:14:20 - +Rule sol89 1989 only - Feb 11 12:14:20s -0:14:20 - +Rule sol89 1989 only - Feb 12 12:14:20s -0:14:20 - +Rule sol89 1989 only - Feb 13 12:14:15s -0:14:15 - +Rule sol89 1989 only - Feb 14 12:14:15s -0:14:15 - +Rule sol89 1989 only - Feb 15 12:14:10s -0:14:10 - +Rule sol89 1989 only - Feb 16 12:14:10s -0:14:10 - +Rule sol89 1989 only - Feb 17 12:14:05s -0:14:05 - +Rule sol89 1989 only - Feb 18 12:14:00s -0:14:00 - +Rule sol89 1989 only - Feb 19 12:13:55s -0:13:55 - +Rule sol89 1989 only - Feb 20 12:13:50s -0:13:50 - +Rule sol89 1989 only - Feb 21 12:13:40s -0:13:40 - +Rule sol89 1989 only - Feb 22 12:13:35s -0:13:35 - +Rule sol89 1989 only - Feb 23 12:13:25s -0:13:25 - +Rule sol89 1989 only - Feb 24 12:13:15s -0:13:15 - +Rule sol89 1989 only - Feb 25 12:13:05s -0:13:05 - +Rule sol89 1989 only - Feb 26 12:12:55s -0:12:55 - +Rule sol89 1989 only - Feb 27 12:12:45s -0:12:45 - +Rule sol89 1989 only - Feb 28 12:12:35s -0:12:35 - +Rule sol89 1989 only - Mar 1 12:12:25s -0:12:25 - +Rule sol89 1989 only - Mar 2 12:12:10s -0:12:10 - +Rule sol89 1989 only - Mar 3 12:12:00s -0:12:00 - +Rule sol89 1989 only - Mar 4 12:11:45s -0:11:45 - +Rule sol89 1989 only - Mar 5 12:11:35s -0:11:35 - +Rule sol89 1989 only - Mar 6 12:11:20s -0:11:20 - +Rule sol89 1989 only - Mar 7 12:11:05s -0:11:05 - +Rule sol89 1989 only - Mar 8 12:10:50s -0:10:50 - +Rule sol89 1989 only - Mar 9 12:10:35s -0:10:35 - +Rule sol89 1989 only - Mar 10 12:10:20s -0:10:20 - +Rule sol89 1989 only - Mar 11 12:10:05s -0:10:05 - +Rule sol89 1989 only - Mar 12 12:09:50s -0:09:50 - +Rule sol89 1989 only - Mar 13 12:09:30s -0:09:30 - +Rule sol89 1989 only - Mar 14 12:09:15s -0:09:15 - +Rule sol89 1989 only - Mar 15 12:09:00s -0:09:00 - +Rule sol89 1989 only - Mar 16 12:08:40s -0:08:40 - +Rule sol89 1989 only - Mar 17 12:08:25s -0:08:25 - +Rule sol89 1989 only - Mar 18 12:08:05s -0:08:05 - +Rule sol89 1989 only - Mar 19 12:07:50s -0:07:50 - +Rule sol89 1989 only - Mar 20 12:07:30s -0:07:30 - +Rule sol89 1989 only - Mar 21 12:07:15s -0:07:15 - +Rule sol89 1989 only - Mar 22 12:06:55s -0:06:55 - +Rule sol89 1989 only - Mar 23 12:06:35s -0:06:35 - +Rule sol89 1989 only - Mar 24 12:06:20s -0:06:20 - +Rule sol89 1989 only - Mar 25 12:06:00s -0:06:00 - +Rule sol89 1989 only - Mar 26 12:05:40s -0:05:40 - +Rule sol89 1989 only - Mar 27 12:05:25s -0:05:25 - +Rule sol89 1989 only - Mar 28 12:05:05s -0:05:05 - +Rule sol89 1989 only - Mar 29 12:04:50s -0:04:50 - +Rule sol89 1989 only - Mar 30 12:04:30s -0:04:30 - +Rule sol89 1989 only - Mar 31 12:04:10s -0:04:10 - +Rule sol89 1989 only - Apr 1 12:03:55s -0:03:55 - +Rule sol89 1989 only - Apr 2 12:03:35s -0:03:35 - +Rule sol89 1989 only - Apr 3 12:03:20s -0:03:20 - +Rule sol89 1989 only - Apr 4 12:03:00s -0:03:00 - +Rule sol89 1989 only - Apr 5 12:02:45s -0:02:45 - +Rule sol89 1989 only - Apr 6 12:02:25s -0:02:25 - +Rule sol89 1989 only - Apr 7 12:02:10s -0:02:10 - +Rule sol89 1989 only - Apr 8 12:01:50s -0:01:50 - +Rule sol89 1989 only - Apr 9 12:01:35s -0:01:35 - +Rule sol89 1989 only - Apr 10 12:01:20s -0:01:20 - +Rule sol89 1989 only - Apr 11 12:01:05s -0:01:05 - +Rule sol89 1989 only - Apr 12 12:00:50s -0:00:50 - +Rule sol89 1989 only - Apr 13 12:00:35s -0:00:35 - +Rule sol89 1989 only - Apr 14 12:00:20s -0:00:20 - +Rule sol89 1989 only - Apr 15 12:00:05s -0:00:05 - +Rule sol89 1989 only - Apr 16 11:59:50s 0:00:10 - +Rule sol89 1989 only - Apr 17 11:59:35s 0:00:25 - +Rule sol89 1989 only - Apr 18 11:59:20s 0:00:40 - +Rule sol89 1989 only - Apr 19 11:59:10s 0:00:50 - +Rule sol89 1989 only - Apr 20 11:58:55s 0:01:05 - +Rule sol89 1989 only - Apr 21 11:58:45s 0:01:15 - +Rule sol89 1989 only - Apr 22 11:58:30s 0:01:30 - +Rule sol89 1989 only - Apr 23 11:58:20s 0:01:40 - +Rule sol89 1989 only - Apr 24 11:58:10s 0:01:50 - +Rule sol89 1989 only - Apr 25 11:58:00s 0:02:00 - +Rule sol89 1989 only - Apr 26 11:57:50s 0:02:10 - +Rule sol89 1989 only - Apr 27 11:57:40s 0:02:20 - +Rule sol89 1989 only - Apr 28 11:57:30s 0:02:30 - +Rule sol89 1989 only - Apr 29 11:57:20s 0:02:40 - +Rule sol89 1989 only - Apr 30 11:57:15s 0:02:45 - +Rule sol89 1989 only - May 1 11:57:05s 0:02:55 - +Rule sol89 1989 only - May 2 11:57:00s 0:03:00 - +Rule sol89 1989 only - May 3 11:56:50s 0:03:10 - +Rule sol89 1989 only - May 4 11:56:45s 0:03:15 - +Rule sol89 1989 only - May 5 11:56:40s 0:03:20 - +Rule sol89 1989 only - May 6 11:56:35s 0:03:25 - +Rule sol89 1989 only - May 7 11:56:30s 0:03:30 - +Rule sol89 1989 only - May 8 11:56:30s 0:03:30 - +Rule sol89 1989 only - May 9 11:56:25s 0:03:35 - +Rule sol89 1989 only - May 10 11:56:25s 0:03:35 - +Rule sol89 1989 only - May 11 11:56:20s 0:03:40 - +Rule sol89 1989 only - May 12 11:56:20s 0:03:40 - +Rule sol89 1989 only - May 13 11:56:20s 0:03:40 - +Rule sol89 1989 only - May 14 11:56:20s 0:03:40 - +Rule sol89 1989 only - May 15 11:56:20s 0:03:40 - +Rule sol89 1989 only - May 16 11:56:20s 0:03:40 - +Rule sol89 1989 only - May 17 11:56:20s 0:03:40 - +Rule sol89 1989 only - May 18 11:56:25s 0:03:35 - +Rule sol89 1989 only - May 19 11:56:25s 0:03:35 - +Rule sol89 1989 only - May 20 11:56:30s 0:03:30 - +Rule sol89 1989 only - May 21 11:56:35s 0:03:25 - +Rule sol89 1989 only - May 22 11:56:35s 0:03:25 - +Rule sol89 1989 only - May 23 11:56:40s 0:03:20 - +Rule sol89 1989 only - May 24 11:56:45s 0:03:15 - +Rule sol89 1989 only - May 25 11:56:55s 0:03:05 - +Rule sol89 1989 only - May 26 11:57:00s 0:03:00 - +Rule sol89 1989 only - May 27 11:57:05s 0:02:55 - +Rule sol89 1989 only - May 28 11:57:15s 0:02:45 - +Rule sol89 1989 only - May 29 11:57:20s 0:02:40 - +Rule sol89 1989 only - May 30 11:57:30s 0:02:30 - +Rule sol89 1989 only - May 31 11:57:35s 0:02:25 - +Rule sol89 1989 only - Jun 1 11:57:45s 0:02:15 - +Rule sol89 1989 only - Jun 2 11:57:55s 0:02:05 - +Rule sol89 1989 only - Jun 3 11:58:05s 0:01:55 - +Rule sol89 1989 only - Jun 4 11:58:15s 0:01:45 - +Rule sol89 1989 only - Jun 5 11:58:25s 0:01:35 - +Rule sol89 1989 only - Jun 6 11:58:35s 0:01:25 - +Rule sol89 1989 only - Jun 7 11:58:45s 0:01:15 - +Rule sol89 1989 only - Jun 8 11:59:00s 0:01:00 - +Rule sol89 1989 only - Jun 9 11:59:10s 0:00:50 - +Rule sol89 1989 only - Jun 10 11:59:20s 0:00:40 - +Rule sol89 1989 only - Jun 11 11:59:35s 0:00:25 - +Rule sol89 1989 only - Jun 12 11:59:45s 0:00:15 - +Rule sol89 1989 only - Jun 13 12:00:00s 0:00:00 - +Rule sol89 1989 only - Jun 14 12:00:10s -0:00:10 - +Rule sol89 1989 only - Jun 15 12:00:25s -0:00:25 - +Rule sol89 1989 only - Jun 16 12:00:35s -0:00:35 - +Rule sol89 1989 only - Jun 17 12:00:50s -0:00:50 - +Rule sol89 1989 only - Jun 18 12:01:05s -0:01:05 - +Rule sol89 1989 only - Jun 19 12:01:15s -0:01:15 - +Rule sol89 1989 only - Jun 20 12:01:30s -0:01:30 - +Rule sol89 1989 only - Jun 21 12:01:40s -0:01:40 - +Rule sol89 1989 only - Jun 22 12:01:55s -0:01:55 - +Rule sol89 1989 only - Jun 23 12:02:10s -0:02:10 - +Rule sol89 1989 only - Jun 24 12:02:20s -0:02:20 - +Rule sol89 1989 only - Jun 25 12:02:35s -0:02:35 - +Rule sol89 1989 only - Jun 26 12:02:45s -0:02:45 - +Rule sol89 1989 only - Jun 27 12:03:00s -0:03:00 - +Rule sol89 1989 only - Jun 28 12:03:10s -0:03:10 - +Rule sol89 1989 only - Jun 29 12:03:25s -0:03:25 - +Rule sol89 1989 only - Jun 30 12:03:35s -0:03:35 - +Rule sol89 1989 only - Jul 1 12:03:45s -0:03:45 - +Rule sol89 1989 only - Jul 2 12:04:00s -0:04:00 - +Rule sol89 1989 only - Jul 3 12:04:10s -0:04:10 - +Rule sol89 1989 only - Jul 4 12:04:20s -0:04:20 - +Rule sol89 1989 only - Jul 5 12:04:30s -0:04:30 - +Rule sol89 1989 only - Jul 6 12:04:40s -0:04:40 - +Rule sol89 1989 only - Jul 7 12:04:50s -0:04:50 - +Rule sol89 1989 only - Jul 8 12:05:00s -0:05:00 - +Rule sol89 1989 only - Jul 9 12:05:10s -0:05:10 - +Rule sol89 1989 only - Jul 10 12:05:20s -0:05:20 - +Rule sol89 1989 only - Jul 11 12:05:25s -0:05:25 - +Rule sol89 1989 only - Jul 12 12:05:35s -0:05:35 - +Rule sol89 1989 only - Jul 13 12:05:40s -0:05:40 - +Rule sol89 1989 only - Jul 14 12:05:50s -0:05:50 - +Rule sol89 1989 only - Jul 15 12:05:55s -0:05:55 - +Rule sol89 1989 only - Jul 16 12:06:00s -0:06:00 - +Rule sol89 1989 only - Jul 17 12:06:05s -0:06:05 - +Rule sol89 1989 only - Jul 18 12:06:10s -0:06:10 - +Rule sol89 1989 only - Jul 19 12:06:15s -0:06:15 - +Rule sol89 1989 only - Jul 20 12:06:20s -0:06:20 - +Rule sol89 1989 only - Jul 21 12:06:20s -0:06:20 - +Rule sol89 1989 only - Jul 22 12:06:25s -0:06:25 - +Rule sol89 1989 only - Jul 23 12:06:25s -0:06:25 - +Rule sol89 1989 only - Jul 24 12:06:30s -0:06:30 - +Rule sol89 1989 only - Jul 25 12:06:30s -0:06:30 - +Rule sol89 1989 only - Jul 26 12:06:30s -0:06:30 - +Rule sol89 1989 only - Jul 27 12:06:30s -0:06:30 - +Rule sol89 1989 only - Jul 28 12:06:30s -0:06:30 - +Rule sol89 1989 only - Jul 29 12:06:25s -0:06:25 - +Rule sol89 1989 only - Jul 30 12:06:25s -0:06:25 - +Rule sol89 1989 only - Jul 31 12:06:20s -0:06:20 - +Rule sol89 1989 only - Aug 1 12:06:20s -0:06:20 - +Rule sol89 1989 only - Aug 2 12:06:15s -0:06:15 - +Rule sol89 1989 only - Aug 3 12:06:10s -0:06:10 - +Rule sol89 1989 only - Aug 4 12:06:05s -0:06:05 - +Rule sol89 1989 only - Aug 5 12:06:00s -0:06:00 - +Rule sol89 1989 only - Aug 6 12:05:50s -0:05:50 - +Rule sol89 1989 only - Aug 7 12:05:45s -0:05:45 - +Rule sol89 1989 only - Aug 8 12:05:35s -0:05:35 - +Rule sol89 1989 only - Aug 9 12:05:30s -0:05:30 - +Rule sol89 1989 only - Aug 10 12:05:20s -0:05:20 - +Rule sol89 1989 only - Aug 11 12:05:10s -0:05:10 - +Rule sol89 1989 only - Aug 12 12:05:00s -0:05:00 - +Rule sol89 1989 only - Aug 13 12:04:50s -0:04:50 - +Rule sol89 1989 only - Aug 14 12:04:40s -0:04:40 - +Rule sol89 1989 only - Aug 15 12:04:30s -0:04:30 - +Rule sol89 1989 only - Aug 16 12:04:15s -0:04:15 - +Rule sol89 1989 only - Aug 17 12:04:05s -0:04:05 - +Rule sol89 1989 only - Aug 18 12:03:50s -0:03:50 - +Rule sol89 1989 only - Aug 19 12:03:35s -0:03:35 - +Rule sol89 1989 only - Aug 20 12:03:25s -0:03:25 - +Rule sol89 1989 only - Aug 21 12:03:10s -0:03:10 - +Rule sol89 1989 only - Aug 22 12:02:55s -0:02:55 - +Rule sol89 1989 only - Aug 23 12:02:40s -0:02:40 - +Rule sol89 1989 only - Aug 24 12:02:20s -0:02:20 - +Rule sol89 1989 only - Aug 25 12:02:05s -0:02:05 - +Rule sol89 1989 only - Aug 26 12:01:50s -0:01:50 - +Rule sol89 1989 only - Aug 27 12:01:30s -0:01:30 - +Rule sol89 1989 only - Aug 28 12:01:15s -0:01:15 - +Rule sol89 1989 only - Aug 29 12:00:55s -0:00:55 - +Rule sol89 1989 only - Aug 30 12:00:40s -0:00:40 - +Rule sol89 1989 only - Aug 31 12:00:20s -0:00:20 - +Rule sol89 1989 only - Sep 1 12:00:00s 0:00:00 - +Rule sol89 1989 only - Sep 2 11:59:45s 0:00:15 - +Rule sol89 1989 only - Sep 3 11:59:25s 0:00:35 - +Rule sol89 1989 only - Sep 4 11:59:05s 0:00:55 - +Rule sol89 1989 only - Sep 5 11:58:45s 0:01:15 - +Rule sol89 1989 only - Sep 6 11:58:25s 0:01:35 - +Rule sol89 1989 only - Sep 7 11:58:05s 0:01:55 - +Rule sol89 1989 only - Sep 8 11:57:45s 0:02:15 - +Rule sol89 1989 only - Sep 9 11:57:20s 0:02:40 - +Rule sol89 1989 only - Sep 10 11:57:00s 0:03:00 - +Rule sol89 1989 only - Sep 11 11:56:40s 0:03:20 - +Rule sol89 1989 only - Sep 12 11:56:20s 0:03:40 - +Rule sol89 1989 only - Sep 13 11:56:00s 0:04:00 - +Rule sol89 1989 only - Sep 14 11:55:35s 0:04:25 - +Rule sol89 1989 only - Sep 15 11:55:15s 0:04:45 - +Rule sol89 1989 only - Sep 16 11:54:55s 0:05:05 - +Rule sol89 1989 only - Sep 17 11:54:35s 0:05:25 - +Rule sol89 1989 only - Sep 18 11:54:10s 0:05:50 - +Rule sol89 1989 only - Sep 19 11:53:50s 0:06:10 - +Rule sol89 1989 only - Sep 20 11:53:30s 0:06:30 - +Rule sol89 1989 only - Sep 21 11:53:10s 0:06:50 - +Rule sol89 1989 only - Sep 22 11:52:45s 0:07:15 - +Rule sol89 1989 only - Sep 23 11:52:25s 0:07:35 - +Rule sol89 1989 only - Sep 24 11:52:05s 0:07:55 - +Rule sol89 1989 only - Sep 25 11:51:45s 0:08:15 - +Rule sol89 1989 only - Sep 26 11:51:25s 0:08:35 - +Rule sol89 1989 only - Sep 27 11:51:05s 0:08:55 - +Rule sol89 1989 only - Sep 28 11:50:40s 0:09:20 - +Rule sol89 1989 only - Sep 29 11:50:20s 0:09:40 - +Rule sol89 1989 only - Sep 30 11:50:00s 0:10:00 - +Rule sol89 1989 only - Oct 1 11:49:45s 0:10:15 - +Rule sol89 1989 only - Oct 2 11:49:25s 0:10:35 - +Rule sol89 1989 only - Oct 3 11:49:05s 0:10:55 - +Rule sol89 1989 only - Oct 4 11:48:45s 0:11:15 - +Rule sol89 1989 only - Oct 5 11:48:30s 0:11:30 - +Rule sol89 1989 only - Oct 6 11:48:10s 0:11:50 - +Rule sol89 1989 only - Oct 7 11:47:50s 0:12:10 - +Rule sol89 1989 only - Oct 8 11:47:35s 0:12:25 - +Rule sol89 1989 only - Oct 9 11:47:20s 0:12:40 - +Rule sol89 1989 only - Oct 10 11:47:00s 0:13:00 - +Rule sol89 1989 only - Oct 11 11:46:45s 0:13:15 - +Rule sol89 1989 only - Oct 12 11:46:30s 0:13:30 - +Rule sol89 1989 only - Oct 13 11:46:15s 0:13:45 - +Rule sol89 1989 only - Oct 14 11:46:00s 0:14:00 - +Rule sol89 1989 only - Oct 15 11:45:50s 0:14:10 - +Rule sol89 1989 only - Oct 16 11:45:35s 0:14:25 - +Rule sol89 1989 only - Oct 17 11:45:20s 0:14:40 - +Rule sol89 1989 only - Oct 18 11:45:10s 0:14:50 - +Rule sol89 1989 only - Oct 19 11:45:00s 0:15:00 - +Rule sol89 1989 only - Oct 20 11:44:50s 0:15:10 - +Rule sol89 1989 only - Oct 21 11:44:40s 0:15:20 - +Rule sol89 1989 only - Oct 22 11:44:30s 0:15:30 - +Rule sol89 1989 only - Oct 23 11:44:20s 0:15:40 - +Rule sol89 1989 only - Oct 24 11:44:10s 0:15:50 - +Rule sol89 1989 only - Oct 25 11:44:05s 0:15:55 - +Rule sol89 1989 only - Oct 26 11:44:00s 0:16:00 - +Rule sol89 1989 only - Oct 27 11:43:50s 0:16:10 - +Rule sol89 1989 only - Oct 28 11:43:45s 0:16:15 - +Rule sol89 1989 only - Oct 29 11:43:40s 0:16:20 - +Rule sol89 1989 only - Oct 30 11:43:40s 0:16:20 - +Rule sol89 1989 only - Oct 31 11:43:35s 0:16:25 - +Rule sol89 1989 only - Nov 1 11:43:35s 0:16:25 - +Rule sol89 1989 only - Nov 2 11:43:35s 0:16:25 - +Rule sol89 1989 only - Nov 3 11:43:30s 0:16:30 - +Rule sol89 1989 only - Nov 4 11:43:35s 0:16:25 - +Rule sol89 1989 only - Nov 5 11:43:35s 0:16:25 - +Rule sol89 1989 only - Nov 6 11:43:35s 0:16:25 - +Rule sol89 1989 only - Nov 7 11:43:40s 0:16:20 - +Rule sol89 1989 only - Nov 8 11:43:45s 0:16:15 - +Rule sol89 1989 only - Nov 9 11:43:50s 0:16:10 - +Rule sol89 1989 only - Nov 10 11:43:55s 0:16:05 - +Rule sol89 1989 only - Nov 11 11:44:00s 0:16:00 - +Rule sol89 1989 only - Nov 12 11:44:05s 0:15:55 - +Rule sol89 1989 only - Nov 13 11:44:15s 0:15:45 - +Rule sol89 1989 only - Nov 14 11:44:25s 0:15:35 - +Rule sol89 1989 only - Nov 15 11:44:35s 0:15:25 - +Rule sol89 1989 only - Nov 16 11:44:45s 0:15:15 - +Rule sol89 1989 only - Nov 17 11:44:55s 0:15:05 - +Rule sol89 1989 only - Nov 18 11:45:10s 0:14:50 - +Rule sol89 1989 only - Nov 19 11:45:20s 0:14:40 - +Rule sol89 1989 only - Nov 20 11:45:35s 0:14:25 - +Rule sol89 1989 only - Nov 21 11:45:50s 0:14:10 - +Rule sol89 1989 only - Nov 22 11:46:05s 0:13:55 - +Rule sol89 1989 only - Nov 23 11:46:25s 0:13:35 - +Rule sol89 1989 only - Nov 24 11:46:40s 0:13:20 - +Rule sol89 1989 only - Nov 25 11:47:00s 0:13:00 - +Rule sol89 1989 only - Nov 26 11:47:20s 0:12:40 - +Rule sol89 1989 only - Nov 27 11:47:35s 0:12:25 - +Rule sol89 1989 only - Nov 28 11:47:55s 0:12:05 - +Rule sol89 1989 only - Nov 29 11:48:20s 0:11:40 - +Rule sol89 1989 only - Nov 30 11:48:40s 0:11:20 - +Rule sol89 1989 only - Dec 1 11:49:00s 0:11:00 - +Rule sol89 1989 only - Dec 2 11:49:25s 0:10:35 - +Rule sol89 1989 only - Dec 3 11:49:50s 0:10:10 - +Rule sol89 1989 only - Dec 4 11:50:15s 0:09:45 - +Rule sol89 1989 only - Dec 5 11:50:35s 0:09:25 - +Rule sol89 1989 only - Dec 6 11:51:00s 0:09:00 - +Rule sol89 1989 only - Dec 7 11:51:30s 0:08:30 - +Rule sol89 1989 only - Dec 8 11:51:55s 0:08:05 - +Rule sol89 1989 only - Dec 9 11:52:20s 0:07:40 - +Rule sol89 1989 only - Dec 10 11:52:50s 0:07:10 - +Rule sol89 1989 only - Dec 11 11:53:15s 0:06:45 - +Rule sol89 1989 only - Dec 12 11:53:45s 0:06:15 - +Rule sol89 1989 only - Dec 13 11:54:10s 0:05:50 - +Rule sol89 1989 only - Dec 14 11:54:40s 0:05:20 - +Rule sol89 1989 only - Dec 15 11:55:10s 0:04:50 - +Rule sol89 1989 only - Dec 16 11:55:40s 0:04:20 - +Rule sol89 1989 only - Dec 17 11:56:05s 0:03:55 - +Rule sol89 1989 only - Dec 18 11:56:35s 0:03:25 - +Rule sol89 1989 only - Dec 19 11:57:05s 0:02:55 - +Rule sol89 1989 only - Dec 20 11:57:35s 0:02:25 - +Rule sol89 1989 only - Dec 21 11:58:05s 0:01:55 - +Rule sol89 1989 only - Dec 22 11:58:35s 0:01:25 - +Rule sol89 1989 only - Dec 23 11:59:05s 0:00:55 - +Rule sol89 1989 only - Dec 24 11:59:35s 0:00:25 - +Rule sol89 1989 only - Dec 25 12:00:05s -0:00:05 - +Rule sol89 1989 only - Dec 26 12:00:35s -0:00:35 - +Rule sol89 1989 only - Dec 27 12:01:05s -0:01:05 - +Rule sol89 1989 only - Dec 28 12:01:35s -0:01:35 - +Rule sol89 1989 only - Dec 29 12:02:00s -0:02:00 - +Rule sol89 1989 only - Dec 30 12:02:30s -0:02:30 - +Rule sol89 1989 only - Dec 31 12:03:00s -0:03:00 - + +# Riyadh is at about 46 degrees 46 minutes East: 3 hrs, 7 mins, 4 secs +# Before and after 1989, we'll operate on local mean solar time. + +# Zone NAME GMTOFF RULES/SAVE FORMAT [UNTIL] +Zone Asia/Riyadh89 3:07:04 - ?? 1989 + 3:07:04 sol89 ?? 1990 + 3:07:04 - ?? +# For backward compatibility... +Link Asia/Riyadh89 Mideast/Riyadh89 Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/southamerica =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/southamerica,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/southamerica 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,1072 @@ +# @(#)southamerica 7.55 + +# This data is by no means authoritative; if you think you know better, +# go ahead and edit the file (and please send any changes to +# tz@elsie.nci.nih.gov for general use in the future). + +# From Paul Eggert (1999-07-07): +# A good source for time zone historical data outside the U.S. is +# Thomas G. Shanks, The International Atlas (5th edition), +# San Diego: ACS Publications, Inc. (1999). +# +# Gwillim Law writes that a good source +# for recent time zone data is the International Air Transport +# Association's Standard Schedules Information Manual (IATA SSIM), +# published semiannually. Law sent in several helpful summaries +# of the IATA's data after 1990. +# +# Except where otherwise noted, Shanks is the source for entries through 1990, +# and IATA SSIM is the source for entries after 1990. +# +# Earlier editions of these tables used the North American style (e.g. ARST and +# ARDT for Argentine Standard and Daylight Time), but the following quote +# suggests that it's better to use European style (e.g. ART and ARST). +# I suggest the use of _Summer time_ instead of the more cumbersome +# _daylight-saving time_. _Summer time_ seems to be in general use +# in Europe and South America. +# -- E O Cutler, _New York Times_ (1937-02-14), quoted in +# H L Mencken, _The American Language: Supplement I_ (1960), p 466 +# +# Earlier editions of these tables also used the North American style +# for time zones in Brazil, but this was incorrect, as Brazilians say +# "summer time". Reinaldo Goulart, a Sao Paulo businessman active in +# the railroad sector, writes (1999-07-06): +# The subject of time zones is currently a matter of discussion/debate in +# Brazil. Let's say that "the Brasilia time" is considered the +# "official time" because Brasilia is the capital city. +# The other three time zones are called "Brasilia time "minus one" or +# "plus one" or "plus two". As far as I know there is no such +# name/designation as "Eastern Time" or "Central Time". +# So I invented the following (English-language) abbreviations for now. +# Corrections are welcome! +# std dst +# -2:00 FNT FNST Fernando de Noronha +# -3:00 BRT BRST Brasilia +# -4:00 AMT AMST Amazon +# -5:00 ACT ACST Acre + +############################################################################### + +############################################################################### + +# Argentina + +# From Bob Devine (1988-01-28): +# Argentina: first Sunday in October to first Sunday in April since 1976. +# Double Summer time from 1969 to 1974. Switches at midnight. + +# From U. S. Naval Observatory (1988-01-199): +# ARGENTINA 3 H BEHIND UTC + +# From Hernan G. Otero (1995-06-26): +# I am sending modifications to the Argentine time zone table... +# AR was chosen because they are the ISO letters that represent Argentina. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Arg 1930 only - Dec 1 0:00 1:00 S +Rule Arg 1931 only - Apr 1 0:00 0 - +Rule Arg 1931 only - Oct 15 0:00 1:00 S +Rule Arg 1932 1940 - Mar 1 0:00 0 - +Rule Arg 1932 1939 - Nov 1 0:00 1:00 S +Rule Arg 1940 only - Jul 1 0:00 1:00 S +Rule Arg 1941 only - Jun 15 0:00 0 - +Rule Arg 1941 only - Oct 15 0:00 1:00 S +Rule Arg 1943 only - Aug 1 0:00 0 - +Rule Arg 1943 only - Oct 15 0:00 1:00 S +Rule Arg 1946 only - Mar 1 0:00 0 - +Rule Arg 1946 only - Oct 1 0:00 1:00 S +Rule Arg 1963 only - Oct 1 0:00 0 - +Rule Arg 1963 only - Dec 15 0:00 1:00 S +Rule Arg 1964 1966 - Mar 1 0:00 0 - +Rule Arg 1964 1966 - Oct 15 0:00 1:00 S +Rule Arg 1967 only - Apr 2 0:00 0 - +Rule Arg 1967 1968 - Oct Sun>=1 0:00 1:00 S +Rule Arg 1968 1969 - Apr Sun>=1 0:00 0 - +Rule Arg 1974 only - Jan 23 0:00 1:00 S +Rule Arg 1974 only - May 1 0:00 0 - +Rule Arg 1988 only - Dec 1 0:00 1:00 S +# +# From Hernan G. Otero (1995-06-26): +# These corrections were contributed by InterSoft Argentina S.A., +# obtaining the data from the: +# Talleres de Hidrografia Naval Argentina +# (Argentine Naval Hydrography Institute) +# +# Shanks stops after 1992-03-01; go with Otero. +Rule Arg 1989 1993 - Mar Sun>=1 0:00 0 - +Rule Arg 1989 1992 - Oct Sun>=15 0:00 1:00 S +# +# From Hernan G. Otero (1995-06-26): +# From this moment on, the law that mandated the daylight saving +# time corrections was derogated and no more modifications +# to the time zones (for daylight saving) are now made. +# +# From Rives McDow (2000-01-10): +# On October 3, 1999, 0:00 local, Argentina implemented daylight savings time, +# which did not result in the switch of a time zone, as they stayed 9 hours +# from the International Date Line. +Rule Arg 1999 only - Oct Sun>=1 0:00 1:00 S +Rule Arg 2000 only - Mar Sun>=1 0:00 0 - +# +# From Peter Gradelski via Steffen Thorsen (2000-03-01): +# We just checked with our Sao Paulo office and they say the government of +# Argentina decided not to become one of the countries that go on or off DST. +# So Buenos Aires should be -3 hours from GMT at all times. +# +# From Fabian L. Arce Jofre (2000-04-04): +# The law that claimed DST for Argentina was derogated by President Fernando +# de la Rua on March 2, 2000, because it would make people spend more energy +# in the winter time, rather than less. The change took effect on March 3. +# +# From Mariano Absatz (2001-06-06): +# one of the major newspapers here in Argentina said that the 1999 +# Timezone Law (which never was effectively applied) will (would?) be +# in effect.... The article is at +# http://ar.clarin.com/diario/2001-06-06/e-01701.htm +# ... The Law itself is "Ley No 25155", sanctioned on 1999-08-25, enacted +# 1999-09-17, and published 1999-09-21. The official publication is at: +# http://www.boletin.jus.gov.ar/BON/Primera/1999/09-Septiembre/21/PDF/BO21-09-99LEG.PDF +# Regretfully, you have to subscribe (and pay) for the on-line version.... +# +# (2001-06-12): +# the timezone for Argentina will not change next Sunday. +# Apparently it will do so on Sunday 24th.... +# http://ar.clarin.com/diario/2001-06-12/s-03501.htm +# +# (2001-06-25): +# Last Friday (yes, the last working day before the date of the change), the +# Senate annulled the 1999 law that introduced the changes later postponed. +# http://www.clarin.com.ar/diario/2001-06-22/s-03601.htm +# It remains the vote of the Deputies..., but it will be the same.... +# This kind of things had always been done this way in Argentina. +# We are still -03:00 all year round in all of the country. +# +# From Mariano Absatz (2004-05-21): +# Today it was officially published that the Province of Mendoza is changing +# its timezone this winter... starting tomorrow night.... +# http://www.gobernac.mendoza.gov.ar/boletin/pdf/20040521-27158-normas.pdf +# From Paul Eggert (2004-05-24): +# It's Law No. 7,210. This change is due to a public power emergency, so for +# now we'll assume it's for this year only. +# +# From Paul Eggert (2002-01-22): +# +# Hora de verano para la Republica Argentina (2000-10-01) +# says that standard time in Argentina from 1894-10-31 +# to 1920-05-01 was -4:16:48.25. Go with this more-precise value +# over Shanks. +# +# From Mariano Absatz (2004-06-05): +# These media articles from a major newspaper mostly cover the current state: +# http://www.lanacion.com.ar/04/05/27/de_604825.asp +# http://www.lanacion.com.ar/04/05/28/de_605203.asp +# +# The following eight (8) provinces pulled clocks back to UTC-04:00 at +# midnight Monday May 31st. (that is, the night between 05/31 and 06/01). +# Apparently, all nine provinces would go back to UTC-03:00 at the same +# time in October 17th. +# +# Catamarca, Chubut, La Rioja, San Juan, San Luis, Santa Cruz, +# Tierra del Fuego, Tucuman. +# +# From Mariano Absatz (2004-06-14): +# ... this weekend, the Province of Tucuman decided it'd go back to UTC-03:00 +# yesterday midnight (that is, at 24:00 Saturday 12th), since the people's +# annoyance with the change is much higher than the power savings obtained.... +# +# From Gwillim Law (2004-06-14): +# http://www.lanacion.com.ar/04/06/10/de_609078.asp ... +# "The time change in Tierra del Fuego was a conflicted decision from +# the start. The government had decreed that the measure would take +# effect on June 1, but a normative error forced the new time to begin +# three days earlier, from a Saturday to a Sunday.... +# Our understanding was that the change was originally scheduled to take place +# on June 1 at 00:00 in Chubut, Santa Cruz, Tierra del Fuego (and some other +# provinces). Sunday was May 30, only two days earlier. So the article +# contains a contradiction. I would give more credence to the Saturday/Sunday +# date than the "three days earlier" phrase, and conclude that Tierra del +# Fuego set its clocks back at 2004-05-30 00:00. +# +# From Steffen Thorsen (2004-10-05): +# The previous law 7210 which changed the province of Mendoza's time zone +# back in May have been modified slightly in a new law 7277, which set the +# new end date to 2004-09-26 (original date was 2004-10-17). +# http://www.gobernac.mendoza.gov.ar/boletin/pdf/20040924-27244-normas.pdf +# +# From Mariano Absatz (2004-10-05): +# San Juan changed from UTC-03:00 to UTC-04:00 at midnight between +# Sunday, May 30th and Monday, May 31st. It changed back to UTC-03:00 +# at midnight between Saturday, July 24th and Sunday, July 25th.... +# http://www.sanjuan.gov.ar/prensa/archivo/000329.html +# http://www.sanjuan.gov.ar/prensa/archivo/000426.html +# http://www.sanjuan.gov.ar/prensa/archivo/000441.html + +# Unless otherwise specified, data are from Shanks through 1992, from +# the IATA otherwise. As noted below, Shanks says that +# America/Cordoba split into 6 subregions during 1991/1992, but we +# haven't verified this yet so for now we'll keep it a single region. +# +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# +# Buenos Aires (BA), Capital Federal (CF), +Zone America/Argentina/Buenos_Aires -3:53:48 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May # Cordoba Mean Time + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART +# +# Santa Fe (SF), Entre Rios (ER), Corrientes (CN), Misiones (MN), Chaco (CC), +# Formosa (FM), Salta (SA), Santiago del Estero (SE), Cordoba (CB), +# San Luis (SL), La Pampa (LP), Neuquen (NQ), Rio Negro (RN) +# +# Shanks also makes the following claims, which we haven't verified: +# - Formosa switched to -3:00 on 1991-01-07. +# - Misiones switched to -3:00 on 1990-12-29. +# - Chaco switched to -3:00 on 1991-01-04. +# - San Luis switched to -4:00 on 1990-03-14, then to -3:00 on 1990-10-15, +# then to -4:00 on 1991-03-01, then to -3:00 on 1991-06-01. +# - Santiago del Estero switched to -4:00 on 1991-04-01, +# then to -3:00 on 1991-04-26. +# +Zone America/Argentina/Cordoba -4:16:48 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1991 Mar 3 + -4:00 - WART 1991 Oct 20 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART +# +# Tucuman (TM) +Zone America/Argentina/Tucuman -4:20:52 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1991 Mar 3 + -4:00 - WART 1991 Oct 20 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 Jun 1 + -4:00 - WART 2004 Jun 13 + -3:00 - ART +# +# La Rioja (LR) +Zone America/Argentina/La_Rioja -4:27:24 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1991 Mar 1 + -4:00 - WART 1991 May 7 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 Jun 1 + -4:00 - WART 2004 Jun 20 + -3:00 - ART +# +# San Juan (SJ) +Zone America/Argentina/San_Juan -4:34:04 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1991 Mar 1 + -4:00 - WART 1991 May 7 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 May 31 + -4:00 - WART 2004 Jul 25 + -3:00 - ART +# +# Jujuy (JY) +Zone America/Argentina/Jujuy -4:21:12 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1990 Mar 4 + -4:00 - WART 1990 Oct 28 + -4:00 1:00 WARST 1991 Mar 17 + -4:00 - WART 1991 Oct 6 + -3:00 1:00 ARST 1992 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART +# +# Catamarca (CT) +Zone America/Argentina/Catamarca -4:23:08 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1991 Mar 3 + -4:00 - WART 1991 Oct 20 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 Jun 1 + -4:00 - WART 2004 Jun 20 + -3:00 - ART +# +# Mendoza (MZ) +Zone America/Argentina/Mendoza -4:35:16 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1990 Mar 4 + -4:00 - WART 1990 Oct 15 + -4:00 1:00 WARST 1991 Mar 1 + -4:00 - WART 1991 Oct 15 + -4:00 1:00 WARST 1992 Mar 1 + -4:00 - WART 1992 Oct 18 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 May 23 + -4:00 - WART 2004 Sep 26 + -3:00 - ART +# +# Chubut (CH) +# The name "Comodoro Rivadavia" exceeds the 14-byte POSIX limit. +Zone America/Argentina/ComodRivadavia -4:30:00 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1991 Mar 3 + -4:00 - WART 1991 Oct 20 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 Jun 1 + -4:00 - WART 2004 Jun 20 + -3:00 - ART +# +# Santa Cruz (SC) +Zone America/Argentina/Rio_Gallegos -4:36:52 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May # Cordoba Mean Time + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 Jun 1 + -4:00 - WART 2004 Jun 20 + -3:00 - ART +# +# Tierra del Fuego, Antartida e Islas del Atlantico Sur (TF) +Zone America/Argentina/Ushuaia -4:33:12 - LMT 1894 Oct 31 + -4:16:48 - CMT 1920 May # Cordoba Mean Time + -4:00 - ART 1930 Dec + -4:00 Arg AR%sT 1969 Oct 5 + -3:00 Arg AR%sT 1999 Oct 3 + -4:00 Arg AR%sT 2000 Mar 3 + -3:00 - ART 2004 May 30 + -4:00 - WART 2004 Jun 20 + -3:00 - ART + +# Aruba +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Aruba -4:40:24 - LMT 1912 Feb 12 # Oranjestad + -4:30 - ANT 1965 # Netherlands Antilles Time + -4:00 - AST + +# Bolivia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/La_Paz -4:32:36 - LMT 1890 + -4:32:36 - CMT 1931 Oct 15 # Calamarca MT + -4:32:36 1:00 BOST 1932 Mar 21 # Bolivia ST + -4:00 - BOT # Bolivia Time + +# Brazil + +# From Paul Eggert (1993-11-18): +# The mayor of Rio recently attempted to change the time zone rules +# just in his city, in order to leave more summer time for the tourist trade. +# The rule change lasted only part of the day; +# the federal government refused to follow the city's rules, and business +# was in a chaos, so the mayor backed down that afternoon. + +# From IATA SSIM (1996-02): +# _Only_ the following states in BR1 observe DST: Rio Grande do Sul (RS), +# Santa Catarina (SC), Parana (PR), Sao Paulo (SP), Rio de Janeiro (RJ), +# Espirito Santo (ES), Minas Gerais (MG), Bahia (BA), Goias (GO), +# Distrito Federal (DF), Tocantins (TO), Sergipe [SE] and Alagoas [AL]. +# [The last three states are new to this issue of the IATA SSIM.] + +# From Gwillim Law (1996-10-07): +# Geography, history (Tocantins was part of Goias until 1989), and other +# sources of time zone information lead me to believe that AL, SE, and TO were +# always in BR1, and so the only change was whether or not they observed DST.... +# The earliest issue of the SSIM I have is 2/91. Each issue from then until +# 9/95 says that DST is observed only in the ten states I quoted from 9/95, +# along with Mato Grosso (MT) and Mato Grosso do Sul (MS), which are in BR2 +# (UTC-4).... The other two time zones given for Brazil are BR3, which is +# UTC-5, no DST, and applies only in the state of Acre (AC); and BR4, which is +# UTC-2, and applies to Fernando de Noronha (formerly FN, but I believe it's +# become part of the state of Pernambuco). The boundary between BR1 and BR2 +# has never been clearly stated. They've simply been called East and West. +# However, some conclusions can be drawn from another IATA manual: the Airline +# Coding Directory, which lists close to 400 airports in Brazil. For each +# airport it gives a time zone which is coded to the SSIM. From that +# information, I'm led to conclude that the states of Amapa (AP), Ceara (CE), +# Maranhao (MA), Paraiba (PR), Pernambuco (PE), Piaui (PI), and Rio Grande do +# Norte (RN), and the eastern part of Para (PA) are all in BR1 without DST. + +# From Marcos Tadeu (1998-09-27): +# +# Brazilian official page +# + +# From Jesper Norgaard (2000-11-03): +# [For an official list of which regions in Brazil use which time zones, see:] +# http://pcdsh01.on.br/Fusbr.htm +# http://pcdsh01.on.br/Fusbrhv.htm + +# From Celso Doria via David Madeo (2002-10-09): +# The reason for the delay this year has to do with elections in Brazil. +# +# Unlike in the United States, elections in Brazil are 100% computerized and +# the results are known almost immediately. Yesterday, it was the first +# round of the elections when 115 million Brazilians voted for President, +# Governor, Senators, Federal Deputies, and State Deputies. Nobody is +# counting (or re-counting) votes anymore and we know there will be a second +# round for the Presidency and also for some Governors. The 2nd round will +# take place on October 27th. +# +# The reason why the DST will only begin November 3rd is that the thousands +# of electoral machines used cannot have their time changed, and since the +# Constitution says the elections must begin at 8:00 AM and end at 5:00 PM, +# the Government decided to postpone DST, instead of changing the Constitution +# (maybe, for the next elections, it will be possible to change the clock)... + +# From Rodrigo Severo (2004-10-04): +# It's just the biannual change made necessary by the much hyped, supposedly +# modern Brazilian eletronic voting machines which, apparently, can't deal +# with a time change between the first and the second rounds of the elections. + +# From Paul Eggert (2002-10-10): +# The official decrees referenced below are mostly taken from +# +# Decretos sobre o Horario de Verao no Brasil +# (2001-09-20, in Portuguese). +# The official site for all decrees, including those not related to time, is +# +# Presidencia da Republica, Subchefia para Assuntos Juridicos, Decretos +# (in Portuguese). + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# Decree 20,466 (1931-10-01) +# Decree 21,896 (1932-01-10) +Rule Brazil 1931 only - Oct 3 11:00 1:00 S +Rule Brazil 1932 1933 - Apr 1 0:00 0 - +Rule Brazil 1932 only - Oct 3 0:00 1:00 S +# Decree 23,195 (1933-10-10) +# revoked DST. +# Decree 27,496 (1949-11-24) +# Decree 27,998 (1950-04-13) +Rule Brazil 1949 1952 - Dec 1 0:00 1:00 S +Rule Brazil 1950 only - Apr 16 1:00 0 - +Rule Brazil 1951 1952 - Apr 1 0:00 0 - +# Decree 32,308 (1953-02-24) +Rule Brazil 1953 only - Mar 1 0:00 0 - +# Decree 34,724 (1953-11-30) +# revoked DST. +# Decree 52,700 (1963-10-18) +# established DST from 1963-10-23 00:00 to 1964-02-29 00:00 +# in SP, RJ, GB, MG, ES, due to the prolongation of the drought. +# Decree 53,071 (1963-12-03) +# extended the above decree to all of the national territory on 12-09. +Rule Brazil 1963 only - Dec 9 0:00 1:00 S +# Decree 53,604 (1964-02-25) +# extended summer time by one day to 1964-03-01 00:00 (start of school). +Rule Brazil 1964 only - Mar 1 0:00 0 - +# Decree 55,639 (1965-01-27) +Rule Brazil 1965 only - Jan 31 0:00 1:00 S +Rule Brazil 1965 only - Mar 31 0:00 0 - +# Decree 57,303 (1965-11-22) +Rule Brazil 1965 only - Dec 1 0:00 1:00 S +# Decree 57,843 (1966-02-18) +Rule Brazil 1966 1968 - Mar 1 0:00 0 - +Rule Brazil 1966 1967 - Nov 1 0:00 1:00 S +# Decree 63,429 (1968-10-15) +# revoked DST. +# Decree 91,698 (1985-09-27) +Rule Brazil 1985 only - Nov 2 0:00 1:00 S +# Decree 92,310 (1986-01-21) +# Decree 92,463 (1986-03-13) +Rule Brazil 1986 only - Mar 15 0:00 0 - +# Decree 93,316 (1986-10-01) +Rule Brazil 1986 only - Oct 25 0:00 1:00 S +Rule Brazil 1987 only - Feb 14 0:00 0 - +# Decree 94,922 (1987-09-22) +Rule Brazil 1987 only - Oct 25 0:00 1:00 S +Rule Brazil 1988 only - Feb 7 0:00 0 - +# Decree 96,676 (1988-09-12) +# except for the states of AC, AM, PA, RR, RO, and AP (then a territory) +Rule Brazil 1988 only - Oct 16 0:00 1:00 S +Rule Brazil 1989 only - Jan 29 0:00 0 - +# Decree 98,077 (1989-08-21) +# with the same exceptions +Rule Brazil 1989 only - Oct 15 0:00 1:00 S +Rule Brazil 1990 only - Feb 11 0:00 0 - +# Decree 99,530 (1990-09-17) +# adopted by RS, SC, PR, SP, RJ, ES, MG, GO, MS, DF. +# Decree 99,629 (1990-10-19) adds BA, MT. +Rule Brazil 1990 only - Oct 21 0:00 1:00 S +Rule Brazil 1991 only - Feb 17 0:00 0 - +# Unnumbered decree (1991-09-25) +# adopted by RS, SC, PR, SP, RJ, ES, MG, BA, GO, MT, MS, DF. +Rule Brazil 1991 only - Oct 20 0:00 1:00 S +Rule Brazil 1992 only - Feb 9 0:00 0 - +# Unnumbered decree (1992-10-16) +# adopted by same states. +Rule Brazil 1992 only - Oct 25 0:00 1:00 S +Rule Brazil 1993 only - Jan 31 0:00 0 - +# Decree 942 (1993-09-28) +# adopted by same states, plus AM. +# Decree 1,252 (1994-09-22; +# web page corrected 2004-01-07) adopted by same states, minus AM. +# Decree 1,636 (1995-09-14) +# adopted by same states, plus MT and TO. +# Decree 1,674 (1995-10-13) +# adds AL, SE. +Rule Brazil 1993 1995 - Oct Sun>=11 0:00 1:00 S +Rule Brazil 1994 1995 - Feb Sun>=15 0:00 0 - +Rule Brazil 1996 only - Feb 11 0:00 0 - +# Decree 2,000 (1996-09-04) +# adopted by same states, minus AL, SE. +Rule Brazil 1996 only - Oct 6 0:00 1:00 S +Rule Brazil 1997 only - Feb 16 0:00 0 - +# From Daniel C. Sobral (1998-02-12): +# In 1997, the DS began on October 6. The stated reason was that +# because international television networks ignored Brazil's policy on DS, +# they bought the wrong times on satellite for coverage of Pope's visit. +# This year, the ending date of DS was postponed to March 1 +# to help dealing with the shortages of electric power. +# +# From Paul Eggert (1998-02-25): +# +# Brazil Prepares for Papal Visit +# , +# Church Net UK (1997-10-02). +# +# Decree 2,317 (1997-09-04), adopted by same states. +Rule Brazil 1997 only - Oct 6 0:00 1:00 S +# Decree 2,495 +# (1998-02-10) +Rule Brazil 1998 only - Mar 1 0:00 0 - +# Decree 2,780 (1998-09-11) +# adopted by the same states as before. +Rule Brazil 1998 only - Oct 11 0:00 1:00 S +Rule Brazil 1999 only - Feb 21 0:00 0 - +# Decree 3,150 +# (1999-08-23) adopted by same states. +# Decree 3,188 (1999-09-30) +# adds SE, AL, PB, PE, RN, CE, PI, MA and RR. +Rule Brazil 1999 only - Oct 3 0:00 1:00 S +Rule Brazil 2000 only - Feb 27 0:00 0 - +# Decree 3,592 (2000-09-06) +# adopted by the same states as before. +# Decree 3,630 (2000-10-13) +# repeals DST in PE and RR, effective 2000-10-15 00:00. +# Decree 3,632 (2000-10-17) +# repeals DST in SE, AL, PB, RN, CE, PI and MA, effective 2000-10-22 00:00. +# Decree 3,916 +# (2001-09-13) reestablishes DST in AL, CE, MA, PB, PE, PI, RN, SE. +Rule Brazil 2000 2001 - Oct Sun>=8 0:00 1:00 S +Rule Brazil 2001 max - Feb Sun>=15 0:00 0 - +# Decree 4,399 (2002-10-01) repeals DST in AL, CE, MA, PB, PE, PI, RN, SE. +# +Rule Brazil 2002 only - Nov 3 0:00 1:00 S +# Decree 4,844 (2003-09-24; corrected 2003-09-26) repeals DST in BA, MT, TO. +# +Rule Brazil 2003 only - Oct 19 0:00 1:00 S +# Decree 5,223 (2004-10-01) reestablishes DST in MT. +# +Rule Brazil 2004 only - Nov 2 0:00 1:00 S +# The latest ruleset listed above says that the following states observe DST: +# DF, ES, GO, MG, MS, MT, PR, RJ, RS, SC, SP. +# +Rule Brazil 2005 max - Oct Sun>=15 0:00 1:00 S +# For dates after mid-2005, the above rules with TO="max" are guesses +# and are quite possibly wrong, but are more likely than no DST at all. + + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +# +# Fernando de Noronha (administratively part of PE) +Zone America/Noronha -2:09:40 - LMT 1914 + -2:00 Brazil FN%sT 1990 Sep 17 + -2:00 - FNT 1999 Sep 30 + -2:00 Brazil FN%sT 2000 Oct 15 + -2:00 - FNT 2001 Sep 13 + -2:00 Brazil FN%sT 2002 Oct 1 + -2:00 - FNT +# Other Atlantic islands have no permanent settlement. +# These include Trindade and Martin Vaz (administratively part of ES), +# Atol das Rocas (RN), and Penedos de Sao Pedro e Sao Paulo (PE). +# Fernando de Noronha was a separate territory from 1942-09-02 to 1989-01-01; +# it also included the Penedos. +# +# Amapa (AP), east Para (PA) +# East Para includes Belem, Maraba, Serra Norte, and Sao Felix do Xingu. +# The division between east and west Para is the river Xingu. +# In the north a very small part from the river Javary (now Jari I guess, +# the border with Amapa) to the Amazon, then to the Xingu. +Zone America/Belem -3:13:56 - LMT 1914 + -3:00 Brazil BR%sT 1988 Sep 12 + -3:00 - BRT +# +# Maranhao (MA), Piaui (PI), Ceara (CE), Rio Grande do Norte (RN), +# Paraiba (PB) +Zone America/Fortaleza -2:34:00 - LMT 1914 + -3:00 Brazil BR%sT 1990 Sep 17 + -3:00 - BRT 1999 Sep 30 + -3:00 Brazil BR%sT 2000 Oct 22 + -3:00 - BRT 2001 Sep 13 + -3:00 Brazil BR%sT 2002 Oct 1 + -3:00 - BRT +# +# Pernambuco (PE) (except Atlantic islands) +Zone America/Recife -2:19:36 - LMT 1914 + -3:00 Brazil BR%sT 1990 Sep 17 + -3:00 - BRT 1999 Sep 30 + -3:00 Brazil BR%sT 2000 Oct 15 + -3:00 - BRT 2001 Sep 13 + -3:00 Brazil BR%sT 2002 Oct 1 + -3:00 - BRT +# +# Tocantins (TO) +Zone America/Araguaina -3:12:48 - LMT 1914 + -3:00 Brazil BR%sT 1990 Sep 17 + -3:00 - BRT 1995 Sep 14 + -3:00 Brazil BR%sT 2003 Sep 24 + -3:00 - BRT +# +# Alagoas (AL), Sergipe (SE) +Zone America/Maceio -2:22:52 - LMT 1914 + -3:00 Brazil BR%sT 1990 Sep 17 + -3:00 - BRT 1995 Oct 13 + -3:00 Brazil BR%sT 1996 Sep 4 + -3:00 - BRT 1999 Sep 30 + -3:00 Brazil BR%sT 2000 Oct 22 + -3:00 - BRT 2001 Sep 13 + -3:00 Brazil BR%sT 2002 Oct 1 + -3:00 - BRT +# +# Bahia (BA) +# There are too many Salvadors elsewhere, so use America/Bahia instead +# of America/Salvador. +Zone America/Bahia -2:34:04 - LMT 1914 + -3:00 Brazil BR%sT 2003 Sep 24 + -3:00 - BRT +# +# Goias (GO), Distrito Federal (DF), Minas Gerais (MG), +# Espirito Santo (ES), Rio de Janeiro (RJ), Sao Paulo (SP), Parana (PR), +# Santa Catarina (SC), Rio Grande do Sul (RS) +Zone America/Sao_Paulo -3:06:28 - LMT 1914 + -3:00 Brazil BR%sT 1963 Oct 23 00:00 + -3:00 1:00 BRST 1964 + -3:00 Brazil BR%sT +# +# Mato Grosso do Sul (MS) +Zone America/Campo_Grande -3:38:28 - LMT 1914 + -4:00 Brazil AM%sT +# +# Mato Grosso (MT) +Zone America/Cuiaba -3:44:20 - LMT 1914 + -4:00 Brazil AM%sT 2003 Sep 24 + -4:00 - AMT 2004 Oct 1 + -4:00 Brazil AM%sT +# +# west Para (PA), Rondonia (RO) +# West Para includes Altamira, Oribidos, Prainha, Oriximina, and Santarem. +Zone America/Porto_Velho -4:15:36 - LMT 1914 + -4:00 Brazil AM%sT 1988 Sep 12 + -4:00 - AMT +# +# Roraima (RR) +Zone America/Boa_Vista -4:02:40 - LMT 1914 + -4:00 Brazil AM%sT 1988 Sep 12 + -4:00 - AMT 1999 Sep 30 + -4:00 Brazil AM%sT 2000 Oct 15 + -4:00 - AMT +# +# east Amazonas (AM): Boca do Acre, Jutai, Manaus, Floriano Peixoto +# The great circle line from Tabatinga to Porto Acre divides +# east from west Amazonas. +Zone America/Manaus -4:00:04 - LMT 1914 + -4:00 Brazil AM%sT 1988 Sep 12 + -4:00 - AMT 1993 Sep 28 + -4:00 Brazil AM%sT 1994 Sep 22 + -4:00 - AMT +# +# west Amazonas (AM): Atalaia do Norte, Boca do Maoco, Benjamin Constant, +# Eirunepe, Envira, Ipixuna +Zone America/Eirunepe -4:39:28 - LMT 1914 + -5:00 Brazil AC%sT 1988 Sep 12 + -5:00 - ACT 1993 Sep 28 + -5:00 Brazil AC%sT 1994 Sep 22 + -5:00 - ACT +# +# Acre (AC) +Zone America/Rio_Branco -4:31:12 - LMT 1914 + -5:00 Brazil AC%sT 1988 Sep 12 + -5:00 - ACT + + +# Chile + +# From Eduardo Krell (1995-10-19): +# The law says to switch to DST at midnight [24:00] on the second SATURDAY +# of October.... The law is the same for March and October. +# (1998-09-29): +# Because of the drought this year, the government decided to go into +# DST earlier (saturday 9/26 at 24:00). This is a one-time change only ... +# (unless there's another dry season next year, I guess). + +# From Julio I. Pacheco Troncoso (1999-03-18): +# Because of the same drought, the government decided to end DST later, +# on April 3, (one-time change). + +# From Gwillim Law (2001-05-04): +# I came across another article in "La Tercera" about Chilean DST. +# +# It clearly confirms my earlier suggestion, that DST begins at 22:00 +# on Easter Island.... But it also seems to be saying that the +# observance of DST in Chile began in 1966, rather than 1969 as +# ... [Shanks] has it.... +# +# My translation: +# +# "The Chilean Army has announced that summer time will begin tomorrow, +# Saturday, October 14 in continental Chile, insular Chile, and +# Antarctica, as provided by Supreme Decree 25 of January 11, 1966. +# By the preceding, official time in continental Chile and Chilean +# Antarctic, and official time in Western Insular Chile, which applies +# to Easter Island and Sala y Gomez Island, will be set forward at +# midnight and at 22:00, respectively, by 20 minutes." + +# From Paul Eggert (2001-05-04): +# Go with this article in preference to Shanks's 1969 date for modern DST. +# Assume this rule has been used since DST was introduced in the islands. + +# From Paul Eggert (2002-10-24): +# gives many details that +# disagree with the following table, but we haven't had time to compare them. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Chile 1918 only - Sep 1 0:00 1:00 S +Rule Chile 1919 only - Jul 2 0:00 0 - +Rule Chile 1927 1931 - Sep 1 0:00 1:00 S +Rule Chile 1928 1932 - Apr 1 0:00 0 - +Rule Chile 1966 1997 - Oct Sun>=9 4:00u 1:00 S +Rule Chile 1967 1998 - Mar Sun>=9 3:00u 0 - +Rule Chile 1998 only - Sep 27 4:00u 1:00 S +Rule Chile 1999 only - Apr 4 3:00u 0 - +Rule Chile 1999 max - Oct Sun>=9 4:00u 1:00 S +Rule Chile 2000 max - Mar Sun>=9 3:00u 0 - +# IATA SSIM anomalies: (1990-09) says 1990-09-16; (1992-02) says 1992-03-14; +# (1996-09) says 1998-03-08. Ignore these. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Santiago -4:42:40 - LMT 1890 + -4:42:40 - SMT 1910 # Santiago Mean Time + -5:00 Chile CL%sT 1932 Sep # Chile Time + -4:00 Chile CL%sT +Zone Pacific/Easter -7:17:28 - LMT 1890 # Mataveri + -7:17:28 - MMT 1932 Sep # Mataveri Mean Time + -7:00 Chile EAS%sT 1982 Mar 14 # Easter I Time + -6:00 Chile EAS%sT +# +# Sala y Gomez Island is like Pacific/Easter. +# Other Chilean locations, including Juan Fernandez Is, San Ambrosio, +# San Felix, and Antarctic bases, are like America/Santiago. + +# Colombia +# Shanks specifies 24:00 for 1992 transition times; go with IATA, +# as it seems implausible to change clocks at midnight New Year's Eve. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule CO 1992 only - May 2 0:00 1:00 S +Rule CO 1992 only - Dec 31 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Bogota -4:56:20 - LMT 1884 Mar 13 + -4:56:20 - BMT 1914 Nov 23 # Bogota Mean Time + -5:00 CO CO%sT # Colombia Time +# Malpelo, Providencia, San Andres +# no information; probably like America/Bogota + +# Curacao +# Shanks says that Bottom and Oranjestad have been at -4:00 since +# standard time was introduced on 1912-03-02; and that Kralendijk and Rincon +# used Kralendijk Mean Time (-4:33:08) from 1912-02-02 to 1965-01-01. +# This all predates our 1970 cutoff, though. +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Curacao -4:35:44 - LMT 1912 Feb 12 # Willemstad + -4:30 - ANT 1965 # Netherlands Antilles Time + -4:00 - AST + +# Ecuador +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Guayaquil -5:19:20 - LMT 1890 + -5:14:00 - QMT 1931 # Quito Mean Time + -5:00 - ECT # Ecuador Time +Zone Pacific/Galapagos -5:58:24 - LMT 1931 # Puerto Baquerizo Moreno + -5:00 - ECT 1986 + -6:00 - GALT # Galapagos Time + +# Falklands + +# From Paul Eggert (2001-03-05): +# Between 1990 and 2000 inclusive, Shanks and the IATA agree except +# the IATA gives 1996-09-08. Go with Shanks. + +# From Falkland Islands Government Office, London (2001-01-22) +# via Jesper Norgaard: +# ... the clocks revert back to Local Mean Time at 2 am on Sunday 15 +# April 2001 and advance one hour to summer time at 2 am on Sunday 2 +# September. It is anticipated that the clocks will revert back at 2 +# am on Sunday 21 April 2002 and advance to summer time at 2 am on +# Sunday 1 September. + +# From Rives McDow (2001-02-13): +# +# I have communicated several times with people there, and the last +# time I had communications that was helpful was in 1998. Here is +# what was said then: +# +# "The general rule was that Stanley used daylight saving and the Camp +# did not. However for various reasons many people in the Camp have +# started to use daylight saving (known locally as 'Stanley Time') +# There is no rule as to who uses daylight saving - it is a matter of +# personal choice and so it is impossible to draw a map showing who +# uses it and who does not. Any list would be out of date as soon as +# it was produced. This year daylight saving ended on April 18/19th +# and started again on September 12/13th. I do not know what the rule +# is, but can find out if you like. We do not change at the same time +# as UK or Chile." +# +# I did have in my notes that the rule was "Second Saturday in Sep at +# 0:00 until third Saturday in Apr at 0:00". I think that this does +# not agree in some cases with Shanks; is this true? +# +# Also, there is no mention in the list that some areas in the +# Falklands do not use DST. I have found in my communications there +# that these areas are on the western half of East Falkland and all of +# West Falkland. Stanley is the only place that consistently observes +# DST. Again, as in other places in the world, the farmers don't like +# it. West Falkland is almost entirely sheep farmers. +# +# I know one lady there that keeps a list of which farm keeps DST and +# which doesn't each year. She runs a shop in Stanley, and says that +# the list changes each year. She uses it to communicate to her +# customers, catching them when they are home for lunch or dinner. + +# From Paul Eggert (2001-03-05): +# For now, we'll just record the time in Stanley, since we have no +# better info. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Falk 1937 1938 - Sep lastSun 0:00 1:00 S +Rule Falk 1938 1942 - Mar Sun>=19 0:00 0 - +Rule Falk 1939 only - Oct 1 0:00 1:00 S +Rule Falk 1940 1942 - Sep lastSun 0:00 1:00 S +Rule Falk 1943 only - Jan 1 0:00 0 - +Rule Falk 1983 only - Sep lastSun 0:00 1:00 S +Rule Falk 1984 1985 - Apr lastSun 0:00 0 - +Rule Falk 1984 only - Sep 16 0:00 1:00 S +Rule Falk 1985 2000 - Sep Sun>=9 0:00 1:00 S +Rule Falk 1986 2000 - Apr Sun>=16 0:00 0 - +Rule Falk 2001 max - Apr Sun>=15 2:00 0 - +Rule Falk 2001 max - Sep Sun>=1 2:00 1:00 S +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Atlantic/Stanley -3:51:24 - LMT 1890 + -3:51:24 - SMT 1912 Mar 12 # Stanley Mean Time + -4:00 Falk FK%sT 1983 May # Falkland Is Time + -3:00 Falk FK%sT 1985 Sep 15 + -4:00 Falk FK%sT + +# French Guiana +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Cayenne -3:29:20 - LMT 1911 Jul + -4:00 - GFT 1967 Oct # French Guiana Time + -3:00 - GFT + +# Guyana +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Guyana -3:52:40 - LMT 1915 Mar # Georgetown + -3:45 - GBGT 1966 May 26 # Br Guiana Time + -3:45 - GYT 1975 Jul 31 # Guyana Time + -3:00 - GYT 1991 +# IATA SSIM (1996-06) says -4:00. Assume a 1991 switch. + -4:00 - GYT + +# Paraguay +# From Paul Eggert (1999-10-29): +# Shanks (1999) says that spring transitions are from 01:00 -> 02:00, +# and autumn transitions are from 00:00 -> 23:00. Go with earlier +# editions of Shanks, and with the IATA, who say transitions occur at 00:00. +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Para 1975 1988 - Oct 1 0:00 1:00 S +Rule Para 1975 1978 - Mar 1 0:00 0 - +Rule Para 1979 1991 - Apr 1 0:00 0 - +Rule Para 1989 only - Oct 22 0:00 1:00 S +Rule Para 1990 only - Oct 1 0:00 1:00 S +Rule Para 1991 only - Oct 6 0:00 1:00 S +Rule Para 1992 only - Mar 1 0:00 0 - +Rule Para 1992 only - Oct 5 0:00 1:00 S +Rule Para 1993 only - Mar 31 0:00 0 - +Rule Para 1993 1995 - Oct 1 0:00 1:00 S +Rule Para 1994 1995 - Feb lastSun 0:00 0 - +Rule Para 1996 only - Mar 1 0:00 0 - +# IATA SSIM (2000-02) says 1999-10-10; ignore this for now. +# From Steffen Thorsen (2000-10-02): +# I have three independent reports that Paraguay changed to DST this Sunday +# (10-01). +# +# Translated by Gwillim Law (2001-02-27) from +# +# Noticias, a daily paper in Asuncion, Paraguay (2000-10-01) +# : +# Starting at 0:00 today, the clock will be set forward 60 minutes, in +# fulfillment of Decree No. 7,273 of the Executive Power.... The time change +# system has been operating for several years. Formerly there was a separate +# decree each year; the new law has the same effect, but permanently. Every +# year, the time will change on the first Sunday of October; likewise, the +# clock will be set back on the first Sunday of March. +# +# From Jesper Norgaard (2001-03-06) [an official URL saying similar things]: +# http://gateway.abc.com.py:8000/pub/pag04.mbr/artic?FHA=2001-03-03-02.24.52.900592 +# +Rule Para 1996 2001 - Oct Sun>=1 0:00 1:00 S +# IATA SSIM (1997-09) says Mar 1; go with Shanks. +Rule Para 1997 only - Feb lastSun 0:00 0 - +# Shanks says 1999-02-28; IATA SSIM (1999-02) says 1999-02-27, but +# (1999-09) reports no date; go with above sources and Gerd Knops (2001-02-27). +Rule Para 1998 2001 - Mar Sun>=1 0:00 0 - +# From Rives McDow (2002-02-28): +# A decree was issued in Paraguay (no. 16350) on 2002-02-26 that changed the +# dst method to be from the first Sunday in September to the first Sunday in +# April. +Rule Para 2002 max - Apr Sun>=1 0:00 0 - +Rule Para 2002 max - Sep Sun>=1 0:00 1:00 S + + +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Asuncion -3:50:40 - LMT 1890 + -3:50:40 - AMT 1931 Oct 10 # Asuncion Mean Time + -4:00 - PYT 1972 Oct # Paraguay Time + -3:00 - PYT 1974 Apr + -4:00 Para PY%sT + +# Peru +# +# +# From Evelyn C. Leeper via Mark Brader (2003-10-26): +# When we were in Peru in 1985-1986, they apparently switched over +# sometime between December 29 and January 3 while we were on the Amazon. +# +# From Paul Eggert (2003-11-02): +# Shanks doesn't have this transition. Assume 1986 was like 1987. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +Rule Peru 1938 only - Jan 1 0:00 1:00 S +Rule Peru 1938 only - Apr 1 0:00 0 - +Rule Peru 1938 1939 - Sep lastSun 0:00 1:00 S +Rule Peru 1939 1940 - Mar Sun>=24 0:00 0 - +Rule Peru 1986 1987 - Jan 1 0:00 1:00 S +Rule Peru 1986 1987 - Apr 1 0:00 0 - +Rule Peru 1990 only - Jan 1 0:00 1:00 S +Rule Peru 1990 only - Apr 1 0:00 0 - +# IATA is ambiguous for 1993/1995; go with Shanks. +Rule Peru 1994 only - Jan 1 0:00 1:00 S +Rule Peru 1994 only - Apr 1 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Lima -5:08:12 - LMT 1890 + -5:08:36 - LMT 1908 Jul 28 # Lima Mean Time? + -5:00 Peru PE%sT # Peru Time + +# South Georgia +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone Atlantic/South_Georgia -2:26:08 - LMT 1890 # Grytviken + -2:00 - GST # South Georgia Time + +# South Sandwich Is +# uninhabited; scientific personnel have wintered + +# Suriname +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Paramaribo -3:40:40 - LMT 1911 + -3:40:52 - PMT 1935 # Paramaribo Mean Time + -3:40:36 - PMT 1945 Oct # The capital moved? + -3:30 - NEGT 1975 Nov 20 # Dutch Guiana Time + -3:30 - SRT 1984 Oct # Suriname Time + -3:00 - SRT + +# Trinidad and Tobago +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Port_of_Spain -4:06:04 - LMT 1912 Mar 2 + -4:00 - AST + +# Uruguay +# From Paul Eggert (1993-11-18): +# Uruguay wins the prize for the strangest peacetime manipulation of the rules. +# From Shanks: +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +# Whitman gives 1923 Oct 1; go with Shanks. +Rule Uruguay 1923 only - Oct 2 0:00 0:30 HS +Rule Uruguay 1924 1926 - Apr 1 0:00 0 - +Rule Uruguay 1924 1925 - Oct 1 0:00 0:30 HS +Rule Uruguay 1933 1935 - Oct lastSun 0:00 0:30 HS +# Shanks gives 1935 Apr 1 0:00 and 1936 Mar 30 0:00; go with Whitman. +Rule Uruguay 1934 1936 - Mar Sat>=25 23:30s 0 - +Rule Uruguay 1936 only - Nov 1 0:00 0:30 HS +Rule Uruguay 1937 1941 - Mar lastSun 0:00 0 - +# Whitman gives 1937 Oct 3; go with Shanks. +Rule Uruguay 1937 1940 - Oct lastSun 0:00 0:30 HS +# Whitman gives 1941 Oct 24 - 1942 Mar 27, 1942 Dec 14 - 1943 Apr 13, +# and 1943 Apr 13 ``to present time''; go with Shanks. +Rule Uruguay 1941 only - Aug 1 0:00 0 - +Rule Uruguay 1942 only - Jan 1 0:00 0:30 HS +Rule Uruguay 1942 only - Dec 14 0:00 1:00 S +Rule Uruguay 1943 only - Mar 14 0:00 0 - +Rule Uruguay 1959 only - May 24 0:00 1:00 S +Rule Uruguay 1959 only - Nov 15 0:00 0 - +Rule Uruguay 1960 only - Jan 17 0:00 1:00 S +Rule Uruguay 1960 only - Mar 6 0:00 0 - +Rule Uruguay 1965 1967 - Apr Sun>=1 0:00 1:00 S +Rule Uruguay 1965 only - Sep 26 0:00 0 - +Rule Uruguay 1966 1967 - Oct 31 0:00 0 - +Rule Uruguay 1968 1970 - May 27 0:00 0:30 HS +Rule Uruguay 1968 1970 - Dec 2 0:00 0 - +Rule Uruguay 1972 only - Apr 24 0:00 1:00 S +Rule Uruguay 1972 only - Aug 15 0:00 0 - +Rule Uruguay 1974 only - Mar 10 0:00 0:30 HS +Rule Uruguay 1974 only - Dec 22 0:00 1:00 S +Rule Uruguay 1976 only - Oct 1 0:00 0 - +Rule Uruguay 1977 only - Dec 4 0:00 1:00 S +Rule Uruguay 1978 only - Apr 1 0:00 0 - +Rule Uruguay 1979 only - Oct 1 0:00 1:00 S +Rule Uruguay 1980 only - May 1 0:00 0 - +Rule Uruguay 1987 only - Dec 14 0:00 1:00 S +Rule Uruguay 1988 only - Mar 14 0:00 0 - +Rule Uruguay 1988 only - Dec 11 0:00 1:00 S +Rule Uruguay 1989 only - Mar 12 0:00 0 - +Rule Uruguay 1989 only - Oct 29 0:00 1:00 S +# Shanks says no DST was observed in 1990/1 and 1991/2, +# and that 1992/3's DST was from 10-25 to 03-01. Go with IATA. +Rule Uruguay 1990 1992 - Mar Sun>=1 0:00 0 - +Rule Uruguay 1990 1991 - Oct Sun>=21 0:00 1:00 S +Rule Uruguay 1992 only - Oct 18 0:00 1:00 S +Rule Uruguay 1993 only - Feb 28 0:00 0 - +# From Eduardo Cota (2004-09-20): +# The uruguayan government has decreed a change in the local time.... +# http://www.presidencia.gub.uy/decretos/2004091502.htm +Rule Uruguay 2004 only - Sep Sun>=15 0:00 1:00 S +Rule Uruguay 2005 only - Mar Sun>=8 0:00 0 - +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Montevideo -3:44:44 - LMT 1898 Jun 28 + -3:44:44 - MMT 1920 May 1 # Montevideo MT + -3:30 Uruguay UY%sT 1942 Dec 14 # Uruguay Time + -3:00 Uruguay UY%sT + +# Venezuela +# Zone NAME GMTOFF RULES FORMAT [UNTIL] +Zone America/Caracas -4:27:44 - LMT 1890 + -4:27:40 - CMT 1912 Feb 12 # Caracas Mean Time? + -4:30 - VET 1965 # Venezuela Time + -4:00 - VET Index: 3rdParty_sources/joda-time/org/joda/time/tz/src/systemv =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joda-time/org/joda/time/tz/src/systemv,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joda-time/org/joda/time/tz/src/systemv 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,50 @@ +# @(#)systemv 7.3 + +# Old rules, should the need arise. +# No attempt is made to handle Newfoundland, since it cannot be expressed +# using the System V "TZ" scheme (half-hour offset), or anything outside +# North America (no support for non-standard DST start/end dates), nor +# the change in the DST rules in the US in 1987 (which occurred before +# the old rules were written). +# +# If you need the old rules, uncomment ## lines and comment-out Link lines. +# Compile this *without* leap second correction for true conformance. + +# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S +## Rule SystemV min 1973 - Apr lastSun 2:00 1:00 D +## Rule SystemV min 1973 - Oct lastSun 2:00 0 S +## Rule SystemV 1974 only - Jan 6 2:00 1:00 D +## Rule SystemV 1974 only - Nov lastSun 2:00 0 S +## Rule SystemV 1975 only - Feb 23 2:00 1:00 D +## Rule SystemV 1975 only - Oct lastSun 2:00 0 S +## Rule SystemV 1976 max - Apr lastSun 2:00 1:00 D +## Rule SystemV 1976 max - Oct lastSun 2:00 0 S + +# Zone NAME GMTOFF RULES/SAVE FORMAT [UNTIL] +## Zone SystemV/AST4ADT -4:00 SystemV A%sT +## Zone SystemV/EST5EDT -5:00 SystemV E%sT +## Zone SystemV/CST6CDT -6:00 SystemV C%sT +## Zone SystemV/MST7MDT -7:00 SystemV M%sT +## Zone SystemV/PST8PDT -8:00 SystemV P%sT +## Zone SystemV/YST9YDT -9:00 SystemV Y%sT +## Zone SystemV/AST4 -4:00 - AST +## Zone SystemV/EST5 -5:00 - EST +## Zone SystemV/CST6 -6:00 - CST +## Zone SystemV/MST7 -7:00 - MST +## Zone SystemV/PST8 -8:00 - PST +## Zone SystemV/YST9 -9:00 - YST +## Zone SystemV/HST10 -10:00 - HST +# For now... +Link America/Halifax SystemV/AST4ADT +Link America/New_York SystemV/EST5EDT +Link America/Chicago SystemV/CST6CDT +Link America/Denver SystemV/MST7MDT +Link America/Los_Angeles SystemV/PST8PDT +Link America/Anchorage SystemV/YST9YDT +Link America/Puerto_Rico SystemV/AST4 +Link America/Indianapolis SystemV/EST5 +Link America/Regina SystemV/CST6 +Link America/Phoenix SystemV/MST7 +Link Pacific/Pitcairn SystemV/PST8 +Link Pacific/Gambier SystemV/YST9 +Link Pacific/Honolulu SystemV/HST10 Index: 3rdParty_sources/joid/org/verisign/joid/AssociationRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/AssociationRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/AssociationRequest.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,272 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.math.BigInteger; +import java.util.Iterator; +import java.util.Map; +import java.util.HashMap; +import java.util.Set; + + +/** + * Represents an OpenID association request. + */ +public class AssociationRequest extends Request +{ + private SessionType sessionType; + private AssociationType associationType; + private BigInteger dhModulus; + private BigInteger dhGenerator; + private BigInteger dhConsumerPublic; + + /** + * @TODO Delete this after re-factoring. + */ + Map toMap() + { + Map map = super.toMap(); + + map.put( OpenIdConstants.OPENID_SESSION_TYPE, sessionType.toString() ); + map.put( OpenIdConstants.OPENID_ASSOCIATION_TYPE, associationType.toString() ); + map.put( OpenIdConstants.OPENID_DH_CONSUMER_PUBLIC, getDhConsumerPublicString() ); + + return map; + } + + + /** + * @TODO this looks like it is used only by the client/consumer and should + * go somewhere else. + * + * Creates a standard association request. Default values are + * HMAC-SHA1 for association type, and DH-SHA1 + * for session type. + * + * @param crypto the Crypto implementation to use. + * @return an AssociationRequest. + * @throws OpenIdException + */ + public static AssociationRequest create( Crypto crypto ) + { + try + { + BigInteger pubKey = crypto.getPublicKey(); + Map map = new HashMap(); + map.put( OpenIdConstants.OPENID_MODE, Mode.ASSOCIATE.toString() ); + map.put( OpenIdConstants.OPENID_ASSOCIATION_TYPE, AssociationType.HMAC_SHA1.toString() ); + map.put( OpenIdConstants.OPENID_SESSION_TYPE, SessionType.DH_SHA1.toString() ); + map.put( OpenIdConstants.OPENID_NS, OpenIdConstants.OPENID_20_NAMESPACE ); + map.put( OpenIdConstants.OPENID_DH_CONSUMER_PUBLIC, Crypto.convertToString( pubKey ) ); + return new AssociationRequest( map, Mode.ASSOCIATE ); + } + catch ( OpenIdException e ) + { + throw new IllegalArgumentException( e.toString() ); + } + } + + + AssociationRequest( Map map, Mode mode ) throws OpenIdException + { + super( map, mode ); + this.sessionType = SessionType.NO_ENCRYPTION; //default value + this.associationType = AssociationType.HMAC_SHA1; //default value + + this.dhModulus = DiffieHellman.DEFAULT_MODULUS; + this.dhGenerator = DiffieHellman.DEFAULT_GENERATOR; + + Set> set = map.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + + if ( OpenIdConstants.OPENID_SESSION_TYPE.equals( key ) ) + { + this.sessionType = SessionType.parse( value ); + } + else if ( OpenIdConstants.OPENID_ASSOCIATION_TYPE.equals( key ) ) + { + this.associationType = AssociationType.parse( value ); + } + else if ( OpenIdConstants.OPENID_DH_MODULUS.equals( key ) ) + { + this.dhModulus = Crypto.convertToBigIntegerFromString( value ); + } + else if ( OpenIdConstants.OPENID_DH_GENERATOR.equals( key ) ) + { + this.dhGenerator = Crypto.convertToBigIntegerFromString( value ); + } + else if ( OpenIdConstants.OPENID_DH_CONSUMER_PUBLIC.equals( key ) ) + { + this.dhConsumerPublic = Crypto.convertToBigIntegerFromString( value ); + } + } + checkInvariants(); + } + + + /** + * Returns whether the session type in use is not encrypted. + * + * @return whether the session type is not encrypted. + */ + public boolean isNotEncrypted() + { + return SessionType.NO_ENCRYPTION == sessionType; + } + + + private void checkInvariants() throws OpenIdException + { + if ( getMode() == null ) + { + throw new OpenIdException( "Missing mode" ); + } + if ( associationType == null ) + { + throw new OpenIdException( "Missing association type" ); + } + if ( sessionType == null ) + { + throw new OpenIdException( "Missing session type" ); + } + + if ( ( sessionType == SessionType.DH_SHA1 && associationType != AssociationType.HMAC_SHA1 ) + || + ( sessionType == SessionType.DH_SHA256 && associationType != AssociationType.HMAC_SHA256 ) ) + { + throw new OpenIdException( "Mismatch " + OpenIdConstants.OPENID_SESSION_TYPE + + " and " + OpenIdConstants.OPENID_ASSOCIATION_TYPE ); + } + if ( sessionType == SessionType.DH_SHA1 || sessionType == SessionType.DH_SHA256 ) + { + if ( dhConsumerPublic == null ) + { + throw new OpenIdException( "Missing " + OpenIdConstants.OPENID_DH_CONSUMER_PUBLIC ); + } + } + } + + + /** + * @TODO delete this while refactoring. + */ + public Response processUsing( ServerInfo si ) throws OpenIdException + { + IStore store = si.getStore(); + Crypto crypto = si.getCrypto(); + IAssociation a = store.generateAssociation( this, crypto ); + store.saveAssociation( a ); + return new AssociationResponse( this, a, crypto ); + } + + + /** + * Returns the DH modulus. + * + * @return the DH modulus. + */ + public BigInteger getDhModulus() + { + return this.dhModulus; + } + + + /** + * Returns the DH generator. + * + * @return the DH generator. + */ + public BigInteger getDhGenerator() + { + return this.dhGenerator; + } + + + /** + * Returns the DH public value. + * + * @return the DH public value. + */ + public BigInteger getDhConsumerPublic() + { + return this.dhConsumerPublic; + } + + + public String getDhConsumerPublicString() + { + return Crypto.convertToString( dhConsumerPublic ); + } + + + /** + * Returns the association session type. + * + * @return the association session type. + */ + public SessionType getSessionType() + { + return this.sessionType; + } + + + /** + * Returns the association type of this request. + * + * @return the association type. + */ + public AssociationType getAssociationType() + { + return this.associationType; + } + + + public String toString() + { + StringBuilder sb = new StringBuilder( "[AssociationRequest " ); + sb.append( super.toString() ).append( ", session type=" ).append( sessionType.toString() ); + sb.append( ", association type=" ).append( associationType.toString() ).append( "]" ); + return sb.toString(); + } + + public void setAssociationType( AssociationType associationType ) + { + this.associationType = associationType; + } + + public void setDhConsumerPublic( BigInteger dhConsumerPublic ) + { + this.dhConsumerPublic = dhConsumerPublic; + } + + public void setDhModulus( BigInteger dhModulus ) + { + this.dhModulus = dhModulus; + } + + public void setSessionType( SessionType sessionType ) + { + this.sessionType = sessionType; + } + + public void setDhGenerator( BigInteger dhGenerator ) + { + this.dhGenerator = dhGenerator; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/AssociationResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/AssociationResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/AssociationResponse.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,289 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.math.BigInteger; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + + +/** + * Represents an OpenID association response. + */ +public class AssociationResponse extends Response +{ + // package scope so that ResponseFactory can trigger on this key + static String OPENID_SESSION_TYPE = "session_type"; + static String OPENID_ASSOCIATION_TYPE = "assoc_type"; + + private static String OPENID_ASSOC_NS = "ns"; + private static String OPENID_ERROR_CODE = "error_code"; + private static String OPENID_ASSOCIATION_HANDLE = "assoc_handle"; + private static String OPENID_MAC_KEY = "mac_key"; + // package scope so that ResponseFactory can trigger on this key + static String OPENID_ENC_MAC_KEY = "enc_mac_key"; + private static String OPENID_DH_SERVER_PUBLIC = "dh_server_public"; + private static String OPENID_EXPIRES_IN = "expires_in"; + + private SessionType sessionType; + private AssociationType associationType; + private String associationHandle; + private int expiresIn; + private byte[] macKey; + private BigInteger dhServerPublic; + private byte[] encryptedMacKey; + private String errorCode; + + + /** + * Returns the error code (if any) occurred while processing this response. + * @return the error code; null if none. + */ + public String getErrorCode() + { + return errorCode; + } + + + /** + * Returns the association handle in this response. + * @return the association handle in this response. + */ + public String getAssociationHandle() + { + return associationHandle; + } + + + /** + * Returns the Diffie-Hellman public server key in this response. + * @return the Diffie-Hellman public server key in this response. + */ + public BigInteger getDhServerPublic() + { + return dhServerPublic; + } + + + /** + * Returns the MAC key in this response. See also + * {@link #getEncryptedMacKey()} + * @return the MAC key in this response; null if none. + */ + public byte[] getMacKey() + { + return macKey; + } + + + /** + * Returns the encrypted MAC key in this response. See also + * {@link #getMacKey()} + * @return the encrypted MAC key in this response; null if none. + */ + public byte[] getEncryptedMacKey() + { + return encryptedMacKey; + } + + + /** + * Returns the static number of seconds this association expires in. + * @return the number of seconds until expiration. + */ + public int getExpiresIn() + { + return expiresIn; + } + + + /** + * Returns the association type in this response. + * @return the association type in this response. + */ + public AssociationType getAssociationType() + { + return associationType; + } + + + /** + * Returns the session type in this response. + * @return the session type in this response. + */ + public SessionType getSessionType() + { + return sessionType; + } + + + Map toMap() + { + Map map = super.toMap(); + + // remove "openid.ns" from map and replace with just "ns" + // openid prefix is invalid for association responses + String ns = ( String ) map.get( OpenIdConstants.OPENID_NS ); + if ( ns != null ) + { + map.put( OPENID_ASSOC_NS, ns ); + map.remove( OpenIdConstants.OPENID_NS ); + } + + if ( errorCode != null ) + { + map.put( AssociationResponse.OPENID_ERROR_CODE, errorCode ); + } + else + { + if ( !( !isVersion2() // OpenID 1.x + && SessionType.NO_ENCRYPTION == sessionType ) ) + { + // do not send session type for 1.1 responses if it is no-encryption + map.put( AssociationResponse.OPENID_SESSION_TYPE, sessionType.toString() ); + } + map.put( AssociationResponse.OPENID_ASSOCIATION_HANDLE, + associationHandle ); + map.put( AssociationResponse.OPENID_ASSOCIATION_TYPE, + associationType.toString() ); + map.put( AssociationResponse.OPENID_EXPIRES_IN, "" + expiresIn ); + if ( macKey != null ) + { + map.put( AssociationResponse.OPENID_MAC_KEY, + Crypto.convertToString( macKey ) ); + } + else if ( encryptedMacKey != null ) + { + map.put( AssociationResponse.OPENID_DH_SERVER_PUBLIC, + Crypto.convertToString( dhServerPublic ) ); + map.put( AssociationResponse.OPENID_ENC_MAC_KEY, + Crypto.convertToString( encryptedMacKey ) ); + } + } + return map; + } + + + AssociationResponse( AssociationRequest ar, IAssociation a, Crypto crypto ) + { + super( null ); + setNamespace( ar.getNamespace() ); + if ( a.isSuccessful() ) + { + this.sessionType = a.getSessionType(); + this.associationHandle = a.getHandle(); + this.associationType = a.getAssociationType(); + this.expiresIn = a.getLifetime().intValue(); + this.dhServerPublic = a.getPublicDhKey(); + if ( a.isEncrypted() ) + { + this.encryptedMacKey = a.getEncryptedMacKey(); + } + else + { + this.macKey = a.getMacKey(); + } + } + else + { + this.errorCode = a.getErrorCode(); + this.error = a.getError(); + } + } + + + AssociationResponse( Map map ) throws OpenIdException + { + super( map ); + Set> set = map.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = ( String ) mapEntry.getKey(); + String value = ( String ) mapEntry.getValue(); + + if ( AssociationResponse.OPENID_SESSION_TYPE.equals( key ) ) + { + sessionType = SessionType.parse( value ); + } + else if ( AssociationResponse.OPENID_ASSOCIATION_TYPE.equals( key ) ) + { + associationType = AssociationType.parse( value ); + } + else if ( OPENID_DH_SERVER_PUBLIC.equals( key ) ) + { + dhServerPublic = Crypto.convertToBigIntegerFromString( value ); + } + else if ( OPENID_ASSOCIATION_HANDLE.equals( key ) ) + { + associationHandle = value; + } + else if ( OPENID_EXPIRES_IN.equals( key ) ) + { + expiresIn = Integer.parseInt( value ); + } + else if ( OPENID_MAC_KEY.equals( key ) ) + { + macKey = Crypto.convertToBytes( value ); + } + else if ( OPENID_ENC_MAC_KEY.equals( key ) ) + { + encryptedMacKey = Crypto.convertToBytes( value ); + } + else if ( OPENID_ERROR_CODE.equals( key ) ) + { + errorCode = value; + } + // set namespace using association ns key + else if ( OPENID_ASSOC_NS.equals( key ) ) + { + setNamespace( value ); + } + } + } + + + public String toString() + { + StringBuilder sb = new StringBuilder( "[AssociationResponse " ); + sb.append( super.toString() ).append( ", session type=" ); + sb.append( sessionType.toString() ).append( ", association type=" ); + sb.append( associationType.toString() ).append( ", association handle=" ); + sb.append( associationHandle ).append( ", expires in=" ); + sb.append( expiresIn ); + + if ( dhServerPublic != null ) + { + sb.append( ", server public key=" ).append( Crypto.convertToString( dhServerPublic ) ); + } + if ( macKey != null ) + { + sb.append( ", MAC key=" ).append( Crypto.convertToString( macKey ) ); + } + if ( encryptedMacKey != null ) + { + sb.append( ", encrypted MAC key=" ).append( Crypto.convertToString( encryptedMacKey ) ); + } + if ( errorCode != null ) + { + sb.append( ", error code=" ).append( errorCode ); + } + + sb.append( "]" ); + return sb.toString(); + } + +} Index: 3rdParty_sources/joid/org/verisign/joid/AssociationType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/AssociationType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/AssociationType.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid; + + +/** + * An enumeration for managing AssociationTypes. + * + * @author akarasulu at apache.org + */ +public enum AssociationType +{ + HMAC_SHA1( "HMAC-SHA1" ), HMAC_SHA256( "HMAC-SHA256" ); + + + private final String name; + + + private AssociationType( String name ) + { + this.name = name; + } + + + public String toString() + { + return name; + } + + + public String getName() + { + return name; + } + + + public boolean equalsName( String name ) + { + return name.equalsIgnoreCase( name ); + } + + + public static AssociationType parse( String name ) + { + if ( name.equalsIgnoreCase( HMAC_SHA1.toString() ) ) + { + return HMAC_SHA1; + } + + + if ( name.equalsIgnoreCase( HMAC_SHA256.toString() ) ) + { + return HMAC_SHA256; + } + + throw new IllegalArgumentException( "The string '" + name + "' does not match any association type." ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/AuthenticationRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/AuthenticationRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/AuthenticationRequest.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,559 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import org.verisign.joid.extension.Extension; + +import java.math.BigInteger; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; + + +/** + * Represents an OpenID authentication request. + */ +public class AuthenticationRequest extends Request +{ + private final static Log log = LogFactory.getLog( AuthenticationRequest.class ); + + private Map extendedMap; + + private String claimed_id; + private String identity; + private String handle; + private String returnTo; + private String trustRoot; + private SimpleRegistration sreg; + + public final static String OPENID_CLAIMED_ID = "openid.claimed_id"; + public final static String OPENID_IDENTITY = "openid.identity"; + public final static String OPENID_ASSOC_HANDLE = "openid.assoc_handle"; + + public final static String ID_SELECT = "http://specs.openid.net/auth/2.0/identifier_select"; + + public final static String OPENID_RETURN_TO = "openid.return_to"; + /** + * trust_root is the 1.x equivalent to trust_realm in 2.x + */ + public final static String OPENID_TRUST_ROOT = "openid.trust_root"; + public final static String OPENID_REALM = "openid.realm"; + + public static String OPENID_DH_CONSUMER_PUBLIC = "openid.dh_consumer_public"; + + public static String OPENID_SESSION_TYPE = "openid.session_type"; + public final static String DH_SHA1 = "DH-SHA1"; + private static Map statelessMap = new HashMap(); + private static AssociationRequest statelessAr; + + static + { + statelessMap.put( AuthenticationRequest.OPENID_SESSION_TYPE, + AuthenticationRequest.DH_SHA1 ); + // this value is not used for state-less, but it's not a valid + // association request unless it's there + // + statelessMap.put( AuthenticationRequest.OPENID_DH_CONSUMER_PUBLIC, + Crypto.convertToString( BigInteger.valueOf( 1 ) ) ); + try + { + // the request mode is irrelevant + // + statelessAr = new AssociationRequest( statelessMap, Mode.ASSOCIATE ); + } + catch ( OpenIdException e ) + { + // should not happen + // + throw new RuntimeException( e ); + } + } + + + /** + * Creates a standard authentication request. + * + * @param identity the openid identity. + * @param returnTo the return_to value. + * @param trustRoot the openid trust_root. + * @param assocHandle the openid association handle. + * @return an AuthenticationRequest. + * @throws OpenIdException if the request cannot be created. + */ + public static AuthenticationRequest create( String identity, String returnTo, + String trustRoot, String assocHandle ) + throws OpenIdException + { + Map map = new HashMap(); + map.put( "openid.mode", Mode.CHECKID_SETUP.toString() ); + map.put( OPENID_IDENTITY, identity ); + map.put( OPENID_CLAIMED_ID, identity ); + map.put( OPENID_RETURN_TO, returnTo ); + map.put( OPENID_TRUST_ROOT, trustRoot ); + map.put( OPENID_REALM, trustRoot ); + map.put( OpenIdConstants.OPENID_NS, OpenIdConstants.OPENID_20_NAMESPACE ); + map.put( OPENID_ASSOC_HANDLE, assocHandle ); + return new AuthenticationRequest( map, Mode.CHECKID_SETUP ); + } + + + AuthenticationRequest( Map map, Mode mode ) throws OpenIdException + { + super( map, mode ); + Set> set = map.entrySet(); + extendedMap = new HashMap(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + + if ( OpenIdConstants.OPENID_NS.equals( key ) ) + { + setNamespace( value ); + } + else if ( OPENID_IDENTITY.equals( key ) ) + { + this.identity = value; + } + else if ( OPENID_CLAIMED_ID.equals( key ) ) + { + this.claimed_id = value; + } + else if ( OPENID_ASSOC_HANDLE.equals( key ) ) + { + this.handle = value; + } + else if ( OPENID_RETURN_TO.equals( key ) ) + { + this.returnTo = value; + } + else if ( OPENID_TRUST_ROOT.equals( key ) + || OPENID_REALM.equals( key ) ) + { + this.trustRoot = value; + } + else if ( key != null && key.startsWith( "openid." ) ) + { + String foo = key.substring( 7 ); // remove "openid." + if ( ( !( OpenIdConstants.OPENID_RESERVED_WORDS.contains( foo ) ) ) + && ( !foo.startsWith( "sreg." ) ) ) + { + extendedMap.put( foo, value ); + } + } + } + this.sreg = new SimpleRegistration( map ); + checkInvariants(); + } + + + // public for unit tests + public Map toMap() + { + Map map = super.toMap(); + + if ( claimed_id != null ) + { + map.put( AuthenticationRequest.OPENID_CLAIMED_ID, claimed_id ); + } + map.put( AuthenticationRequest.OPENID_IDENTITY, identity ); + if ( handle != null ) + { + map.put( AuthenticationRequest.OPENID_ASSOC_HANDLE, handle ); + } + map.put( AuthenticationRequest.OPENID_RETURN_TO, returnTo ); + map.put( AuthenticationRequest.OPENID_TRUST_ROOT, trustRoot ); + map.put( AuthenticationRequest.OPENID_REALM, trustRoot ); + + if ( extendedMap != null && !extendedMap.isEmpty() ) + { + for ( Iterator> iter = extendedMap.entrySet().iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + if ( value == null ) + { + continue; + } + // all keys start "openid." in the set + map.put( "openid." + key, value ); + } + } + + return map; + } + + + /** + * Returns whether this request is immediate, that is, whether the + * authentication mode is "CHECKID_IMMEDIATE". + * + * @return true if this request is immediate; false otherwise. + */ + public boolean isImmediate() + { + return Mode.CHECKID_IMMEDIATE == getMode(); + } + + + private void checkInvariants() throws OpenIdException + { + if ( getMode() == null ) + { + throw new OpenIdException( "Missing mode" ); + } + if ( identity == null ) + { + throw new OpenIdException( "Missing identity" ); + } + if ( claimed_id != null && !this.isVersion2() ) + { + throw new OpenIdException( "claimed_id not valid in version 1.x" ); + } + if ( trustRoot == null ) + { + if ( returnTo != null ) + { + trustRoot = returnTo; + } + else + { + throw new OpenIdException( "Missing trust root" ); + } + } + + checkTrustRoot(); + + Set namespaces = new HashSet(); + Set entries = new HashSet(); + Set> set = extendedMap.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + // all keys start "openid." in the set + + if ( key.startsWith( "ns." ) ) + { + key = key.substring( 3 ); + if ( OpenIdConstants.OPENID_RESERVED_WORDS.contains( key ) ) + { + throw new OpenIdException( "Cannot redefine: " + key ); + } + if ( namespaces.contains( key ) ) + { + throw new OpenIdException( "Multiple definitions: " + key ); + } + namespaces.add( key ); + } + else + { + if ( entries.contains( key ) ) + { + throw new OpenIdException( "Multiple definitions: " + key ); + } + entries.add( key ); + } + } + // don't check for invalid parameters on 1.x requests; just + // silently ignore them + if ( this.isVersion2() ) + { + for ( Iterator iter = entries.iterator(); iter.hasNext(); ) + { + String key = iter.next(); + int period = key.indexOf( '.' ); + if ( period != -1 ) + { + key = key.substring( 0, period ); + } + if ( !namespaces.contains( key ) ) + { + throw new OpenIdException( "No such namespace: " + key ); + } + } + } + } + + + private void checkTrustRoot() throws OpenIdException + { + if ( trustRoot == null ) + { + throw new OpenIdException( "No " + OPENID_TRUST_ROOT + " given" ); + } + + // URI fragments are not allowed in trustroot + // + if ( trustRoot.indexOf( '#' ) > 0 ) + { + throw new OpenIdException( "URI fragments are not allowed" ); + } + + // Matched if: + // 1. trustroot and returnto are identical + // 2. trustroot contains wild-card characters "*.", and the + // trailing part of the returnto's domain is identical to the + // part of the trustroot following the "*." wildcard + // + // Trust root Return to + // ---------- --------- + // example.com => example.com ==> ok + // *.example.com => example.com ==> ok + // *.example.com => a.example.com ==> ok + // www.example.com => a.example.com ==> not ok + // + URL r, t; + try + { + r = new URL( returnTo ); + t = new URL( trustRoot ); + } + catch ( MalformedURLException e ) + { + throw new OpenIdException( "Malformed URL" ); + } + + String tHost = new StringBuffer( t.getHost() ).reverse().toString(); + String rHost = new StringBuffer( r.getHost() ).reverse().toString(); + + String[] tNames = tHost.split( "\\." ); + String[] rNames = rHost.split( "\\." ); + int len = ( tNames.length > rNames.length ) + ? rNames.length : tNames.length; + + int i; + for ( i = 0; i < len; i += 1 ) + { + if ( !( tNames[i].equals( rNames[i] ) ) + && ( !tNames[i].equals( "*" ) ) ) + { + throw new OpenIdException( "returnTo not in trustroot set: " + + tNames[i] + ", " + rNames[i] ); + } + } + if ( ( i < tNames.length ) && ( !tNames[i].equals( "*" ) ) ) + { + throw new OpenIdException( "returnTo not in trustroot set: " + + tNames[1] ); + } + + // The return to path is equal to or a sub-directory of the + // realm's (trustroot's) path. + // + // Trust root Return to + // ---------- --------- + // /a/b/c => /a/b/c/d ==> ok + // /a/b/c => /a/b ==> not ok + // /a/b/c => /a/b/b ==> not ok + // + + String tPath = t.getPath(); + String rPath = r.getPath(); + + int n = rPath.indexOf( tPath ); + if ( n != 0 ) + { + throw new OpenIdException( "return to & trust root paths mismatch" ); + } + + // if we're here, we're good to go! + } + + + public Response processUsing( ServerInfo si ) throws OpenIdException + { + IStore store = si.getStore(); + Crypto crypto = si.getCrypto(); + IAssociation assoc = null; + String invalidate = null; + if ( handle != null ) + { + assoc = store.findAssociation( handle ); + if ( assoc != null && assoc.hasExpired() ) + { + log.info( "Association handle has expired: " + handle ); + assoc = null; + } + } + if ( handle == null || assoc == null ) + { + log.info( "Invalidating association handle: " + handle ); + invalidate = handle; + assoc = store.generateAssociation( statelessAr, crypto ); + store.saveAssociation( assoc ); + } + return new AuthenticationResponse( si, this, assoc, crypto, invalidate ); + } + + + /** + * Returns the identity used in this authentication request. + * + * @return the identity. + */ + public String getIdentity() + { + return identity; + } + + + /** + * Returns the extensions in this authentication request. + * + * @return the extensions; empty if none. + */ + public Map getExtensions() + { + return extendedMap; + } + + + /** + * Add the extension map to the internal extensions map. + * + * @param map Map of name value pairs + */ + public void addExtensions( Map map ) + { + Iterator> it = map.entrySet().iterator(); + while ( it.hasNext() ) + { + Map.Entry mapEntry = it.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + extendedMap.put( key, value ); + } + } + + + /** + * Add extension object's parameters to the extensions map. + */ + public void addExtension( Extension ext ) + { + addExtensions( ext.getParamMap() ); + } + + + /** + * Returns whether the given identity equals {@link #ID_SELECT}. + * + * @return true if the identity equals {@link #ID_SELECT}. + */ + public boolean isIdentifierSelect() + { + return AuthenticationRequest.ID_SELECT.equals( identity ); + } + + + /** + * Returns the claimed identity used in this authentication request. + * + * @return the claimed identity. + */ + public String getClaimedIdentity() + { + return claimed_id; + } + + + /** + * Sets the identity used in this authentication request. + * + * @param identity the identity. + */ + public void setIdentity( String identity ) + { + this.identity = identity; + } + + + /** + * Returns the 'return to' address in this authentication request. + * + * @return the address. + */ + public String getReturnTo() + { + return returnTo; + } + + + /** + * Returns the handle used in this authentication request. + * + * @return the handle + */ + public String getHandle() + { + return handle; + } + + + /** + * Returns the trust root address in this authentication request. + * + * @return the address. + */ + public String getTrustRoot() + { + return trustRoot; + } + + + /** + * Returns the simple registration fields in this authentication request. + * + * @return the sreg fields; or null if none present. + */ + public SimpleRegistration getSimpleRegistration() + { + return sreg; + } + + + /** + * Sets the simple registration fields in this authentication request. + * + * @param sreg the registration fields. + */ + public void setSimpleRegistration( SimpleRegistration sreg ) + { + this.sreg = sreg; + } + + + public String toString() + { + return "[AuthenticationRequest " + + super.toString() + + ", sreg=" + sreg + + ", claimed identity=" + claimed_id + + ", identity=" + identity + + ", handle=" + handle + ", return to=" + returnTo + + ", trust root=" + trustRoot + "]"; + } + +} Index: 3rdParty_sources/joid/org/verisign/joid/AuthenticationResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/AuthenticationResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/AuthenticationResponse.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,543 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import org.verisign.joid.extension.Extension; + +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.tsik.datatypes.DateTime; + + +/** + * Represents an OpenID authentication response. + */ +public class AuthenticationResponse extends Response +{ + private static Log log = LogFactory.getLog( AuthenticationResponse.class ); + + public static String OPENID_PREFIX = "openid."; + public static String OPENID_RETURN_TO = "openid.return_to"; + public static String OPENID_OP_ENDPOINT = "openid.op_endpoint"; + public static String OPENID_IDENTITY = "openid.identity"; + public static String OPENID_ERROR = "openid.error"; + public static String OPENID_NONCE = "openid.response_nonce"; + public static String OPENID_INVALIDATE_HANDLE = "openid.invalidate_handle"; + public static String OPENID_ASSOCIATION_HANDLE = "openid.assoc_handle"; + public static String OPENID_SIGNED = "openid.signed"; + // package scope so that ResponseFactory can trigger on this key + public static String OPENID_SIG = "openid.sig"; + + private Map extendedMap; + + private String claimed_id; + private String identity; + private String returnTo; + private String nonce; + private String invalidateHandle; + private String associationHandle; + private String signed; + private AssociationType algo; + private String signature; + private SimpleRegistration sreg; + private String urlEndPoint; + private byte[] key; + + + /** + * Returns the signature in this response. + * @return the signature in this response. + */ + public String getSignature() + { + return signature; + } + + + /** + * Returns the list of signed elements in this response. + * @return the comma-separated list of signed elements in this response. + */ + public String getSignedList() + { + return signed; + } + + + /** + * Returns the association handle in this response. + * @return the association handle in this response. + */ + public String getAssociationHandle() + { + return associationHandle; + } + + + /** + * Returns the internal elements mapped to a map. The keys used + * are those defined by the specification, for example + * openid.mode. + * + * TODO: Made public only for unit tests. Needs to package-scope + * limit this method. + * + * @return a map with all internal values mapped to their specification + * keys. + */ + public Map toMap() + { + Map map = super.toMap(); + + if ( isVersion2() ) + { + map.put( AuthenticationResponse.OPENID_OP_ENDPOINT, urlEndPoint ); + } + map.put( OpenIdConstants.OPENID_MODE, getMode().getValue() ); + map.put( AuthenticationResponse.OPENID_IDENTITY, identity ); + map.put( AuthenticationResponse.OPENID_RETURN_TO, returnTo ); + map.put( AuthenticationResponse.OPENID_NONCE, nonce ); + + if ( claimed_id != null ) + { + map.put( AuthenticationRequest.OPENID_CLAIMED_ID, claimed_id ); + } + + if ( invalidateHandle != null ) + { + map.put( AuthenticationResponse.OPENID_INVALIDATE_HANDLE, + invalidateHandle ); + } + map.put( AuthenticationResponse.OPENID_ASSOCIATION_HANDLE, associationHandle ); + + if ( signed != null ) + { + map.put( AuthenticationResponse.OPENID_SIGNED, signed ); + } + map.put( AuthenticationResponse.OPENID_SIG, signature ); + + Map sregMap = sreg.getSuppliedValues(); + log.debug( "sreg in authnresp = " + sreg ); + Set> set = sregMap.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + map.put( SimpleRegistration.OPENID_SREG + "." + key, value ); + } + if ( !set.isEmpty() && isVersion2() ) + { + map.put( OpenIdConstants.OPENID_NS + ".sreg", sreg.getNamespace() ); + } + + if ( extendedMap != null && !extendedMap.isEmpty() ) + { + set = extendedMap.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = ( String ) mapEntry.getKey(); + String value = ( String ) mapEntry.getValue(); + map.put( OPENID_PREFIX + key, value ); + } + } + + return map; + } + + + private String generateNonce() + { + String crumb = Crypto.generateCrumb(); + return DateTime.formatISODateTime( new Date() ) + crumb; + } + + + /** + * Unrolls this response as a string. This string will use encoding + * suitable for URLs. The string will use the same namespace as the + * incoming request. + * + * @param req the original request. + * @param e any exception that occured while processing req, + * may be null. + * + * @return the response as a string. + */ + public static String toUrlStringResponse( Request req, OpenIdException e ) + { + Map map = new HashMap(); + map.put( OpenIdConstants.OPENID_MODE, "error" ); + if ( req != null ) + { + if ( req.isVersion2() ) + { + map.put( OpenIdConstants.OPENID_NS, req.getNamespace() ); + } + map.put( AuthenticationResponse.OPENID_ERROR, e.getMessage() ); + } + else + { + map.put( AuthenticationResponse.OPENID_ERROR, "OpenID request error" ); + } + try + { + return new AuthenticationResponse( map ).toUrlString(); + } + catch ( OpenIdException ex ) + { + // this should never happen + log.error( ex ); + return "internal error"; + } + } + + + /** + * Only public for unit tests. Do not use. + */ + public String sign( byte[] key, String signed ) throws OpenIdException + { + return sign( this.algo, key, signed ); + } + + + /** + * Signs the elements designated by the signed list with the given key and + * returns the result encoded to a string. + * + * @param algorithm the algorithm to use (HMAC-SHA1, HMAC-SHA256) + * @param key the key to sign with (HMAC-SHA1, HMAC-SHA256) + * @param signed the comma-separated list of elements to sign. The elements + * must be mapped internally. + * @return the Base 64 encoded result. + * @throws OpenIdException at signature errors, or if the signed list + * points to elements that are not mapped. + */ + public String sign( AssociationType algorithm, byte[] key, String signed ) throws OpenIdException + { + Map map = toMap(); + log.debug( "in sign() map=" + map ); + log.debug( "in sign() signed=" + signed ); + StringTokenizer st = new StringTokenizer( signed, "," ); + StringBuffer sb = new StringBuffer(); + while ( st.hasMoreTokens() ) + { + String s = st.nextToken(); + String name = "openid." + s; + String value = ( String ) map.get( name ); + if ( value == null ) + { + throw new OpenIdException( "Cannot sign non-existent mapping: " + + s ); + } + sb.append( s ); + sb.append( ':' ); + sb.append( value ); + sb.append( '\n' ); + } + try + { + byte[] b; + if ( algorithm == null ) + { + algorithm = AssociationType.HMAC_SHA1; + } + if ( algorithm.equals( AssociationType.HMAC_SHA1 ) ) + { + b = Crypto.hmacSha1( key, sb.toString().getBytes( "UTF-8" ) ); + } + else if ( algorithm.equals( AssociationType.HMAC_SHA256 ) ) + { + b = Crypto.hmacSha256( key, sb.toString().getBytes( "UTF-8" ) ); + } + else + { + throw new OpenIdException( "Unknown signature algorithm" ); + } + return Crypto.convertToString( b ); + } + catch ( UnsupportedEncodingException e ) + { + throw new OpenIdException( e ); + } + catch ( InvalidKeyException e ) + { + throw new OpenIdException( e ); + } + catch ( NoSuchAlgorithmException e ) + { + throw new OpenIdException( e ); + } + } + + + /** + * throws at errors in signature creation + */ + AuthenticationResponse( ServerInfo serverInfo, + AuthenticationRequest ar, + IAssociation a, Crypto crypto, + String invalidateHandle ) + throws OpenIdException + { + super( null ); + setMode( Mode.ID_RES ); + claimed_id = ar.getClaimedIdentity(); + identity = ar.getIdentity(); + returnTo = ar.getReturnTo(); + setNamespace( ar.getNamespace() ); + nonce = generateNonce(); + this.urlEndPoint = serverInfo.getUrlEndPoint(); + this.invalidateHandle = invalidateHandle; //may be null + associationHandle = a.getHandle(); + signed = "assoc_handle,identity,response_nonce,return_to"; + if ( claimed_id != null ) + { + signed += ",claimed_id"; + } + if ( isVersion2() ) + { + signed += ",op_endpoint"; + } + sreg = ar.getSimpleRegistration(); + log.debug( "sreg=" + sreg ); + if ( sreg != null ) + { + Map map = sreg.getSuppliedValues(); + log.debug( "sreg supplied values=" + map ); + Set> set = map.entrySet(); + if ( !set.isEmpty() && isVersion2() ) + { + signed += ",ns.sreg"; + } + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + signed += ",sreg." + key; + } + } + key = a.getMacKey(); + this.algo = a.getAssociationType(); + signature = sign( key, signed ); + extendedMap = new HashMap(); + } + + + public AuthenticationResponse( Map map ) throws OpenIdException + { + super( map ); + Set> set = map.entrySet(); + extendedMap = new HashMap(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = ( String ) mapEntry.getKey(); + String value = ( String ) mapEntry.getValue(); + + if ( OpenIdConstants.OPENID_MODE.equals( key ) ) + { + setMode( Mode.parse( value ) ); + } + else if ( AuthenticationResponse.OPENID_IDENTITY.equals( key ) ) + { + identity = value; + } + else if ( AuthenticationRequest.OPENID_CLAIMED_ID.equals( key ) ) + { + claimed_id = value; + } + else if ( AuthenticationResponse.OPENID_RETURN_TO.equals( key ) ) + { + returnTo = value; + } + else if ( OPENID_NONCE.equals( key ) ) + { + nonce = value; + } + else if ( OPENID_INVALIDATE_HANDLE.equals( key ) ) + { + invalidateHandle = value; + } + else if ( OPENID_ASSOCIATION_HANDLE.equals( key ) ) + { + associationHandle = value; + } + else if ( OPENID_SIGNED.equals( key ) ) + { + signed = value; + } + else if ( OPENID_SIG.equals( key ) ) + { + signature = value; + } + else if ( OPENID_OP_ENDPOINT.equals( key ) ) + { + urlEndPoint = value; + // we get op_endpoint without a 2.0 ns for some + // check_auth requests + // since we use this class to recalculate the + // signature we need to set version 2 explicitly or we + // won't include the op_endpoint in the map + // (op_endpoint isn't allowed in 1.x responses) + if ( getNamespace() == null ) + { + setNamespace( OpenIdConstants.OPENID_20_NAMESPACE ); + } + } + else if ( key != null && key.startsWith( "openid." ) ) + { + String foo = key.substring( 7 ); // remove "openid." + if ( ( !( OpenIdConstants.OPENID_RESERVED_WORDS.contains( foo ) ) ) + && ( !foo.startsWith( "sreg." ) ) ) + { + extendedMap.put( foo, value ); + } + } + } + this.sreg = SimpleRegistration.parseFromResponse( map ); + log.debug( "authn resp constr sreg=" + sreg ); + } + + + /** + * Returns the extensions in this authentication request. + * + * @return the extensions; empty if none. + */ + public Map getExtensions() + { + return extendedMap; + } + + + /** + * Add the extension map to the internal extensions map. + * + * @param map Map of name value pairs + */ + public void addExtensions( Map map ) throws OpenIdException + { + Iterator> it = map.entrySet().iterator(); + while ( it.hasNext() ) + { + Map.Entry mapEntry = it.next(); + String key = ( String ) mapEntry.getKey(); + String value = ( String ) mapEntry.getValue(); + extendedMap.put( key, value ); + // add items to signature + // signed should already contain a list of base params to sign + signed += "," + key; + } + // recalculate signature + signature = sign( key, signed ); + } + + + /** + * Add extension object's parameters to the extensions map. + */ + public void addExtension( Extension ext ) throws OpenIdException + { + addExtensions( ext.getParamMap() ); + } + + + public String toString() + { + String s = "[AuthenticationResponse " + + super.toString(); + if ( sreg != null ) + { + s += ", sreg=" + sreg; + } + s += ", mode=" + getMode() + + ", algo=" + algo + + ", nonce=" + nonce + + ", association handle=" + associationHandle + + ", invalidation handle=" + invalidateHandle + + ", signed=" + signed + + ", signature=" + signature + + ", identity=" + identity + + ", return to=" + returnTo + + "]"; + return s; + } + + + public String getClaimedId() + { + return claimed_id; + } + + + public String getIdentity() + { + return identity; + } + + + public String getReturnTo() + { + return returnTo; + } + + + public String getNonce() + { + return nonce; + } + + + public String getInvalidateHandle() + { + return invalidateHandle; + } + + + public String getSigned() + { + return signed; + } + + + public AssociationType getAlgo() + { + return algo; + } + + + public SimpleRegistration getSreg() + { + return sreg; + } + + + public String getUrlEndPoint() + { + return urlEndPoint; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/CheckAuthenticationRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/CheckAuthenticationRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/CheckAuthenticationRequest.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,112 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.util.Map; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; + + +/** + * Represents an OpenID check authentication request. + */ +public class CheckAuthenticationRequest extends Request +{ + public final static String OPENID_ASSOC_HANDLE = "openid.assoc_handle"; + + private final static Log log = LogFactory.getLog( CheckAuthenticationRequest.class ); + + private AuthenticationResponse ar; + private String handle; + + + /** + * Creates a check_authentication request. + * + * TODO: Made public to be accessible from unit tests only. Need + * to rework that to change access level during test time. + * + * @param map the map of incoming openid parameters + * @param mode always "check_authentication" + */ + public CheckAuthenticationRequest( Map map, Mode mode ) throws OpenIdException + { + super( map, mode ); + ar = new AuthenticationResponse( map ); + handle = ar.getAssociationHandle(); + checkInvariants(); + } + + + private void checkInvariants() throws OpenIdException + { + if ( handle == null ) + { + throw new OpenIdException( "Missing " + CheckAuthenticationRequest.OPENID_ASSOC_HANDLE ); + } + } + + + public Response processUsing( ServerInfo si ) throws OpenIdException + { + String invalidate = null; + IStore store = si.getStore(); + String nonceStr = ar.getNonce(); + if ( nonceStr != null ) + { + INonce n = store.findNonce( nonceStr ); + if ( n != null ) + { + String s = "Nonce has already been checked"; + log.debug( s ); + throw new OpenIdException( s ); + } + else + { + n = store.generateNonce( nonceStr ); + store.saveNonce( n ); + } + } + IAssociation assoc = store.findAssociation( handle ); + if ( ( assoc == null ) || ( assoc.hasExpired() ) ) + { + invalidate = handle; + } + Crypto crypto = si.getCrypto(); + return new CheckAuthenticationResponse( ar, assoc, + crypto, invalidate ); + } + + + public String toString() + { + return "[CheckAuthenticationRequest " + + super.toString() + + ", handle=" + handle + + ", authentication response=" + ar + + "]"; + } + + + Map toMap() + { + // need to send all values exactly from AuthenticationResponse... + Map map = ar.toMap(); + // ... except mode + map.putAll( super.toMap() ); + + return map; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/CheckAuthenticationResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/CheckAuthenticationResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/CheckAuthenticationResponse.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,161 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.Iterator; + + +/** + * Represents an OpenID check authentication request. + */ +public class CheckAuthenticationResponse extends Response +{ + private boolean isValid; + + static String OPENID_MODE = "openid.mode"; // for 1.1 messages + static String OPENID_NS = "ns"; + static String OPENID_ERROR = "error"; + public static String OPENID_IS_VALID = "is_valid"; + public final static String OPENID_INVALIDATE_HANDLE = "invalidate_handle"; + + private AuthenticationResponse ar; + private Map map; + private String invalidateHandle; + + + /** + * This constructor is for a Consumer side response received from the server. + * @param map + */ + public CheckAuthenticationResponse( Map map ) + { + super( map ); + Set> set = map.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + + if ( OPENID_MODE.equals( key ) ) + { + setMode( Mode.parse( value ) ); + } + else if ( OPENID_IS_VALID.equals( key ) ) + { + isValid = org.verisign.joid.util.Boolean.parseBoolean( value ); + } + else if ( OPENID_INVALIDATE_HANDLE.equals( key ) ) + { + invalidateHandle = value; + } + else if ( OPENID_NS.equals( key ) ) + { + setNamespace( value ); + } + } + } + + + /** + * Returns whether this response contains notification that the request + * signature was valid. + * + * @return true if the incoming check_authentication was + * processed to be valid; false otherwise. + */ + public boolean isValid() + { + return isValid; + } + + + /** + * Returns the internal elements mapped to a map. The keys used + * are those defined by the specification, for example openid.mode. + * + * TODO: Made public only for unit tests. Needs to package-scope + * limit this method. + * + * @return a map with all internal values mapped to their specification + * keys. + */ + public Map toMap() + { + return map; + } + + + /** + * throws at errors in signature creation + */ + CheckAuthenticationResponse( AuthenticationResponse ar, + IAssociation a, Crypto crypto, + String invalidateHandle ) + throws OpenIdException + { + super( Collections.emptyMap() ); + this.ar = ar; + setNamespace( ar.getNamespace() ); + + map = new HashMap(); + if ( isVersion2() ) + { + map.put( OPENID_NS, OpenIdConstants.OPENID_20_NAMESPACE ); + } + + if ( a != null ) + { + String sig = ar.sign( a.getAssociationType(), + a.getMacKey(), ar.getSignedList() ); + isValid = sig.equals( ar.getSignature() ); + } + else + { + isValid = false; + } + if ( !isVersion2() ) + { + map.put( OPENID_MODE, "id_res" ); + } + map.put( CheckAuthenticationResponse.OPENID_IS_VALID, + isValid ? "true" : "false" ); + if ( invalidateHandle != null ) + { + map.put( CheckAuthenticationResponse.OPENID_INVALIDATE_HANDLE, + invalidateHandle ); + } + } + + + public String toString() + { + return "[CheckAuthenticationResponse " + + super.toString() + + ", is valid=" + isValid + + ", authentication response=" + ar + + "]"; + } + + + public String getInvalidateHandle() + { + return invalidateHandle; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/Crypto.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/Crypto.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/Crypto.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,335 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.apache.tsik.datatypes.Base64; +import org.apache.tsik.uuid.UUID; +import org.verisign.joid.Crypto; + + +/** + * Implements the cryptography needed for OpenID. + */ +public class Crypto +{ + private DiffieHellman dh; + private final static Log LOG = LogFactory.getLog( Crypto.class ); + + + /** + * Creates an instance of the crypto library. + */ + public Crypto() + { + LOG.debug( "Creating new instance." ); + } + + + /** + * Digests a message using SHA-1. + * @param text the bytes to digest. + * @return the digested bytes. + * @throws NoSuchAlgorithmException if SHA-1 is not available. + */ + public static byte[] sha1( byte[] text ) throws NoSuchAlgorithmException + { + MessageDigest d = MessageDigest.getInstance( "SHA-1" ); + return d.digest( text ); + } + + + /** + * Digests a message using SHA-256. + * @param text the bytes to digest. + * @return the digested bytes. + * @throws NoSuchAlgorithmException if SHA-256 is not available. + */ + public static byte[] sha256( byte[] text ) throws NoSuchAlgorithmException + { + MessageDigest d = MessageDigest.getInstance( "SHA-256" ); + return d.digest( text ); + } + + + /** + * Signs a message using HMAC SHA1. + * + * @param key the key to sign with. + * @param text the bytes to sign. + * @return the signed bytes. + * @throws InvalidKeyException if key is not a good HMAC key. + * @throws NoSuchAlgorithmException if HMACSHA1 is not available. + */ + public static byte[] hmacSha1( byte[] key, byte[] text ) + throws InvalidKeyException, NoSuchAlgorithmException + { + return hmacShaX( "HMACSHA1", key, text ); + } + + + /** + * Signs a message using HMAC SHA256. + * + * @param key the key to sign with. + * @param text the bytes to sign. + * @return the signed bytes. + * @throws InvalidKeyException if key is not a good HMAC key. + * @throws NoSuchAlgorithmException if HMACSHA1 is not available. + */ + public static byte[] hmacSha256( byte[] key, byte[] text ) + throws InvalidKeyException, NoSuchAlgorithmException + { + return hmacShaX( "HMACSHA256", key, text ); + } + + + private static byte[] hmacShaX( String keySpec, byte[] key, byte[] text ) + throws InvalidKeyException, NoSuchAlgorithmException + { + SecretKey sk = new SecretKeySpec( key, keySpec ); + Mac m = Mac.getInstance( sk.getAlgorithm() ); + m.init( sk ); + return m.doFinal( text ); + } + + private static SecureRandom random; + static + { + try + { + random = SecureRandom.getInstance( "SHA1PRNG" ); + } + catch ( NoSuchAlgorithmException e ) + { + throw new RuntimeException( "No secure random available." ); + } + } + + + /** + * Generates a random handle, in UUID format. + * + * @return a random handle. + */ + public static String generateHandle() + { + return UUID.generate().toString(); + } + + + /** + * Generates a random 'crumb' value. + * + * @return a four-byte random string. + */ + public static String generateCrumb() + { + byte[] b = new byte[4]; + random.nextBytes( b ); + return convertToString( b ); + } + + + /** + * Generates random bytes. + * + * @param s the session or association type + * @return random bytes, length fitting to the given session or + * association type (length 0 to 32 bytes). + */ + public byte[] generateRandom( String s ) + { + int len = 0; + if ( SessionType.DH_SHA1.toString().equals( s ) ) + { + len = 20; + } + else if ( SessionType.DH_SHA256.toString().equals( s ) ) + { + len = 32; + } + else if ( SessionType.NO_ENCRYPTION.toString().equals( s ) ) + { + len = 0; + } + else if ( AssociationType.HMAC_SHA1.toString().equals( s ) ) + { + len = 20; + } + else if ( AssociationType.HMAC_SHA256.toString().equals( s ) ) + { + len = 32; + } + byte[] result = new byte[len]; + random.nextBytes( result ); + return result; + } + + + /** + * Sets the Diffie-Hellman key values. + * + * @param mod the Diffie-Hellman modulus. + * @param gen the Diffie-Hellman generator. + */ + public void setDiffieHellman( BigInteger mod, BigInteger gen ) + { + this.dh = new DiffieHellman( mod, gen ); + } + + + /** + * Sets the Diffie-Hellman key values. + * + * @param dh the Diffie-Hellman value. + */ + public void setDiffieHellman( DiffieHellman dh ) + { + this.dh = dh; + } + + + /** + * Returns the Diffie-Hellman public key set + * by {@link #setDiffieHellman(BigInteger, BigInteger)}. + * + * @return the Diffie-Hellman public key. + * @throws IllegalArgumentException if this crypto instance has not + * yet been initialized. + */ + public BigInteger getPublicKey() + { + if ( dh == null ) + { + throw new IllegalArgumentException( "DH not yet initialized" ); + } + return dh.getPublicKey(); + } + + + /** + * Generates random bytes. TODO: this is a duplicate + * of {@link #generateRandom(String)} -- need to remove one. + * + * @param sessionType the session or association type + * @return random bytes, length fitting to the given session or + * association type (length 0 to 32 bytes). + */ + public byte[] generateSecret( String sessionType ) + { + return generateRandom( sessionType ); + } + + + /** + * Decrypts a secret using Diffie-Hellman. + * + * @param consumerPublic the public key used to decrypt. + * @param secret the value to decrypt. + * @return the decrypted value. + */ + public byte[] decryptSecret( BigInteger consumerPublic, byte[] secret ) + throws OpenIdException + { + return encryptSecret( consumerPublic, secret ); + } + + + /** + * Encrypts a secret using Diffie-Hellman. + * + * @param consumerPublic the public key used to encrypt. + * @param secret the value to encrypt. + * @return the encrypted secret value. + */ + public byte[] encryptSecret( BigInteger consumerPublic, byte[] secret ) + throws OpenIdException + { + if ( dh == null ) + { + throw new IllegalArgumentException( "No DH implementation set" ); + } + byte[] xoredSecret = null; + try + { + xoredSecret = dh.xorSecret( consumerPublic, secret ); + return xoredSecret; + } + catch ( NoSuchAlgorithmException e ) + { + throw new OpenIdException( e ); + } + } + + + /** + * Converts a string to bytes. + * + * @param s the string to convert. + * @return the base 64 decoded bytes. + */ + public static byte[] convertToBytes( String s ) + { + return Base64.decode( s ); + } + + + /** + * Converts bytes to string. + * + * @param b the bytes to encode. + * @return the base 64 encoded string. + */ + public static String convertToString( byte[] b ) + { + String s = Base64.encode( b ); + s = s.replaceAll( "\n", "" ); + return s; + } + + + /** + * Converts a big integer to string. + * + * @param b the big integer to convert. + * @return the base 64 encoded string. + */ + public static String convertToString( BigInteger b ) + { + return convertToString( b.toByteArray() ); + } + + + /** + * Converts a base64-encoded string to big int. + * + * @param s the string to convert, by way of base64 decoding. + * @return the converted big int. + */ + public static BigInteger convertToBigIntegerFromString( String s ) + { + return new BigInteger( Base64.decode( s ) ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/DiffieHellman.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/DiffieHellman.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/DiffieHellman.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,228 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.security.SecureRandom; +import java.math.BigInteger; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import java.security.NoSuchAlgorithmException; + + +/** + * Implements the underlying Diffie-Hellman cryptography. + */ +public class DiffieHellman +{ + private BigInteger modulus; + private BigInteger generator; + private BigInteger privateKey; + private BigInteger publicKey; + + private final static Log log = LogFactory.getLog( DiffieHellman.class ); + + + private DiffieHellman() + { + } + + /** + * The default modulus defined in the specification. + */ + public static final BigInteger DEFAULT_MODULUS = new BigInteger( + "1551728981814736974712322577637155399157248019669" + + "154044797077953140576293785419175806512274236981" + + "889937278161526466314385615958256881888899512721" + + "588426754199503412587065565498035801048705376814" + + "767265132557470407658574792912915723345106432450" + + "947150072296210941943497839259847603755949858482" + + "53359305585439638443" ); + + /** + * The default generator defined in the specification. + */ + public static final BigInteger DEFAULT_GENERATOR = BigInteger.valueOf( 2 ); + + + /** + * Returns a Diffie-Hellman instance using default modulus and + * generator. Note that each call to this method will return an instance + * with random private key. + * @return a DiffieHellman instance using modulus + * ${#DiffieHellman.DEFAULT_MODULUS}, and generator + * ${#DiffieHellman.DEFAULT_GENERATOR}. + */ + public static DiffieHellman getDefault() + { + BigInteger p = DiffieHellman.DEFAULT_MODULUS; + BigInteger g = DiffieHellman.DEFAULT_GENERATOR; + return new DiffieHellman( p, g ); + } + + private static SecureRandom random; + static + { + try + { + random = SecureRandom.getInstance( "SHA1PRNG" ); + } + catch ( NoSuchAlgorithmException e ) + { + throw new RuntimeException( "No secure random available!" ); + } + } + + + /** + * Returns the private key. + * @return the private key. + */ + public BigInteger getPrivateKey() + { + return privateKey; + } + + + /** + * Returns the public key. + * @return the public key. + */ + public BigInteger getPublicKey() + { + return publicKey; + } + + + /** + * Creates a DiffieHellman instance. + * + * @param mod the modulus to use. If null, use {@link #DEFAULT_MODULUS}. + * @param gen the generator to use. If null, use + * {@link #DEFAULT_GENERATOR}. + */ + public DiffieHellman( BigInteger mod, BigInteger gen ) + { + modulus = ( mod != null ? mod : DiffieHellman.DEFAULT_MODULUS ); + generator = ( gen != null ? gen : DiffieHellman.DEFAULT_GENERATOR ); + + int bits = modulus.bitLength(); + BigInteger max = modulus.subtract( BigInteger.ONE ); + while ( true ) + { + BigInteger pkey = new BigInteger( bits, random ); + if ( pkey.compareTo( max ) >= 0 ) + { //too large + continue; + } + else if ( pkey.compareTo( BigInteger.ONE ) <= 0 ) + {//too small + continue; + } + privateKey = pkey; + publicKey = generator.modPow( privateKey, modulus ); + break; + } + } + + + /** + * Recreates a DiffieHellman instance. + * + * @param privateKey the private key. Cannot be null. + * @param modulus the modulus to use. Cannot be be null. + */ + public static DiffieHellman recreate( BigInteger privateKey, + BigInteger modulus ) + { + if ( privateKey == null || modulus == null ) + { + throw new IllegalArgumentException( "Null parameter" ); + } + DiffieHellman dh = new DiffieHellman(); + dh.setPrivateKey( privateKey ); + dh.setModulus( modulus ); + return dh; + } + + + private void setPrivateKey( BigInteger privateKey ) + { + this.privateKey = privateKey; + } + + + private void setModulus( BigInteger modulus ) + { + this.modulus = modulus; + } + + + /** + * Returns the shared secret. + * + * @param composite the composite number (public key) with which this + * instance shares a secret. + * @return the shared secret. + */ + public BigInteger getSharedSecret( BigInteger composite ) + { + return composite.modPow( privateKey, modulus ); + } + + + /** + * Returns the shared secret SHA-1 hashed and XOR 'encrypted'. + * + * @param otherPublic the other party's public modulus; cannot be null. + * @param secret the key to XOR encrypt with. + * @return the encrypted secret. + * @throws IllegalArgumentException if otherPublic is null. + * @throws RuntimeException if length of secret is + * incorrect. Big TODO here to make this error reporting better. + */ + public byte[] xorSecret( BigInteger otherPublic, byte[] secret ) + throws NoSuchAlgorithmException + { + if ( otherPublic == null ) + { + throw new IllegalArgumentException( "otherPublic cannot be null" ); + } + + BigInteger shared = getSharedSecret( otherPublic ); + byte[] hashed; + if ( secret.length == 32 ) + { + hashed = Crypto.sha256( shared.toByteArray() ); + } + else + { + hashed = Crypto.sha1( shared.toByteArray() ); + } + + if ( secret.length != hashed.length ) + { + log.warn( "invalid secret byte[] length: secret=" + secret.length + + ", hashed=" + hashed.length ); + throw new RuntimeException( "nyi" ); + } + + byte[] result = new byte[secret.length]; + for ( int i = 0; i < result.length; i++ ) + { + result[i] = ( byte ) ( hashed[i] ^ secret[i] ); + } + return result; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/IAssociation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/IAssociation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/IAssociation.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,134 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.math.BigInteger; +import java.util.Date; + + +/** + * An association between a relying party and an OpenID provider. + * + * Implement this interface to represent an OpenID association. + */ +public interface IAssociation +{ + /** Returns whether this association is valid (was successful). + * + * @return true is successful; false otherwise. + */ + boolean isSuccessful(); + + + /** + * Returns error as a string. + * + * @return error as a string, null if no error. + */ + String getError(); + + + /** + * Returns error code as a string. + * + * @return error code as a string, null if no error string. + */ + String getErrorCode(); + + + /** + * Get's the secret for this IAssociation. + * + * @return the secret + */ + String getSecret(); + + + /** + * Returns the association's handle. This handle should be suitable + * to put on the wire as part of the OpenID protocol. + * + * @return handle as a string, null if no handle yet available. + */ + String getHandle(); + + + /** + * Gets the lifetime of this association. This is static, that is, + * current time is not taken into consideration. + * + * @return lifetime the lifetime in seconds. + */ + Long getLifetime(); + + + /** + * Gets the OpenID protocol association type, for example "HMAC-SHA1". + * + * @return the association type. + */ + AssociationType getAssociationType(); + + + /** + * Gets the OpenID protocol session type, for example "DH-SHA1". + * + * @return the session type. + */ + SessionType getSessionType(); + + + /** + * Returns the MAC key for this association. + * + * @return the MAC key; null if key doesn't exist. + */ + byte[] getMacKey(); + + + /** + * Returns the public Diffie-Hellman key in use. + * + * @return the DH key. + */ + BigInteger getPublicDhKey(); + + + /** + * Returns whether the association negotiates an encrypted secret. + * + * @return true if the secret is encrypted; false otherwise. + */ + boolean isEncrypted(); + + + /** + * Returns the encrypted MAC key for this association. + * + * @return the encrypted MAC key; null if key doesn't exist. + */ + byte[] getEncryptedMacKey(); + + + /** + * Returns whether this association has expired. + * + * @return whether this association has expired. + */ + boolean hasExpired(); + + + Date getIssuedDate(); +} Index: 3rdParty_sources/joid/org/verisign/joid/INonce.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/INonce.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/INonce.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,45 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.util.Date; + + +/** + * A nonce. + * + * Implement this interface to represent an OpenID association's nonce. + */ +public interface INonce +{ + + /** + * Returns the nonce. + * + * @return nonce as a string. + */ + public String getNonce(); + + + /** + * Sets the date this nonce was checked. + * + * @param checkedDate the timestamp of check. + */ + public void setCheckedDate( Date checkedDate ); + + + public Date getCheckedDate(); +} Index: 3rdParty_sources/joid/org/verisign/joid/IStore.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/IStore.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/IStore.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,91 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +/** + * Represents a store that is used by JOID for persisting associations. + */ +public interface IStore +{ + /** + * Generates and returns association. To store the association + * use {@link IStore#saveAssociation(IAssociation) saveAssociation()} + * + * @param req the association request. + * @param crypto the crypto implementation to use. + * @return the generated assocation. + * + * @throws OpenIdException at unrecoverable errors. + */ + IAssociation generateAssociation( AssociationRequest req, Crypto crypto ) throws OpenIdException; + + + /** + * Deletes an association from the store. + * + * @param a the association to delete. + */ + void deleteAssociation( IAssociation a ) throws OpenIdException; + + + /** + * Saves an association in the store. + * + * @param a the association to store. + */ + void saveAssociation( IAssociation a ) throws OpenIdException; + + + /** + * Finds an association in the store. + * + * @param handle the handle of the association to find. + * @return the assocation if found; null otherwise. + * + * @throws OpenIdException at unrecoverable errors. + */ + IAssociation findAssociation( String handle ) throws OpenIdException; + + + /** + * Finds a nonce in the store. + * + * @param nonce the nonce to find. + * @return the nonce if found; null otherwise. + * + * @throws OpenIdException at unrecoverable errors. + */ + INonce findNonce( String nonce ) throws OpenIdException; + + + /** + * Saves an nonce in the store. + * + * @param n the nonce to store. + */ + void saveNonce( INonce n ) throws OpenIdException; + + + /** + * Generates and returns a nonce. To store the nonce + * use {@link IStore#saveNonce(INonce) saveNonce()} + * + * @param nonce the nonce to use. + * @return the generated nonce. + * + * @throws OpenIdException at unrecoverable errors. + */ + INonce generateNonce( String nonce ) throws OpenIdException; +} Index: 3rdParty_sources/joid/org/verisign/joid/InvalidOpenIdQueryException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/InvalidOpenIdQueryException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/InvalidOpenIdQueryException.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.verisign.joid; + + +/** + * TODO InvalidOpenIdQueryException. + * + * @author Birkan Duman + */ +public class InvalidOpenIdQueryException extends OpenIdException +{ + public InvalidOpenIdQueryException( String s ) + { + super( s ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/Message.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/Message.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/Message.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,148 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// +package org.verisign.joid; + + +import java.util.HashMap; +import java.util.Map; + + +/** + * Represents an OpenID message. + */ +public abstract class Message +{ + private Mode mode; + private String ns; + private Boolean version2 = null; + + + /** + * Returns whether this request is an OpenID 2.0 request. + * + * @return true if this request is an OpenID 2.0 request. + */ + public boolean isVersion2() + { + if ( version2 == null ) + { + version2 = OpenIdConstants.OPENID_20_NAMESPACE.equals( this.ns ); + } + + return version2; + } + + + public Mode getMode() + { + return mode; + } + + + public void setMode( Mode mode ) + { + this.mode = mode; + } + + + /** + * Returns the namespace of this message. For OpenID 2.0 messages, + * this namespace will be http://specs.openid.net/auth/2.0. + * + * @return the namespace, or null if none (OpenID 1.x). + */ + public String getNamespace() + { + return ns; + } + + + public void setNamespace( String ns ) + { + this.ns = ns; + } + + + /** + * Returns a string representation of this message. + * + * @return a string representation of this message. + */ + public String toString() + { + StringBuilder sb = new StringBuilder( "version=" ); + + if ( isVersion2() ) + { + sb.append( "2.0" ); + } + else + { + sb.append( "1.x" ); + } + + if ( ns != null ) + { + sb.append( ", namespace=" ).append( ns ); + } + + return sb.toString(); + } + + + /** + * TODO delete me after re-factoring. + * Unrolls this message as a string. This string will use the + * name:value format of the specification. See also + * {@link #toUrlString()}. + * + * @return the message as a string. + */ + public String toPostString() throws OpenIdException + { + return MessageParser.toPostString( this ); + } + + + /** + * TODO delete me after re-factoring. + * Unrolls this message as a string. This string will use encoding + * suitable for URLs. See also {@link #toPostString()}. + * + * @return the message as a string. + */ + public String toUrlString() throws OpenIdException + { + return MessageParser.toUrlString( this ); + } + + + /** + * TODO delete me after re-factoring. + * + * @return + */ + Map toMap() + { + Map map = new HashMap(); + if ( ns != null ) + { + map.put( OpenIdConstants.OPENID_NS, ns ); + } + if ( mode != null ) + { + map.put( OpenIdConstants.OPENID_MODE, mode.toString() ); + } + return map; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/MessageParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/MessageParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/MessageParser.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,184 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; + + +/** + * Parses an OpenID message. + */ +public class MessageParser +{ + private final static Log LOG = LogFactory.getLog( MessageParser.class ); + static char newline = '\n'; + + + /** + * Unrolls a message as a string. This string will use the + * name:value format of the specification. See also + * {@link #toUrlString()}. + * + * @return the message as a string. + */ + static String toPostString( Message message ) throws OpenIdException + { + return toStringDelimitedBy( message, ":", newline ); + } + + + /** + * Unrolls a message as a string. This string will use encoding + * suitable for URLs. See also {@link #toPostString()}. + * + * @return the message as a string. + */ + static String toUrlString( Message message ) throws OpenIdException + { + return toStringDelimitedBy( message, "=", '&' ); + } + + + private static String toStringDelimitedBy( Message message, + String kvDelim, char lineDelim ) throws OpenIdException + { + Map map = message.toMap(); + Set> set = map.entrySet(); + StringBuffer sb = new StringBuffer(); + try + { + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + + if ( lineDelim == newline ) + { + sb.append( key + kvDelim + value ); + sb.append( lineDelim ); + } + else + { + if ( value != null ) + { + sb.append( URLEncoder.encode( key, "UTF-8" ) + kvDelim + + URLEncoder.encode( value, "UTF-8" ) ); + if ( iter.hasNext() ) + { + sb.append( lineDelim ); + } + } + else + { + StringBuilder msg = new StringBuilder( "Value for key '" ); + msg.append( key ).append( "' is null in message map" ); + LOG.error( msg ); + throw new OpenIdException( msg.toString() ); + } + } + + } + return sb.toString(); + } + catch ( UnsupportedEncodingException e ) + { + // should not happen + throw new RuntimeException( "Internal error" ); + } + } + + + static int numberOfNewlines( String query ) throws IOException + { + BufferedReader br = new BufferedReader( new StringReader( query ) ); + int n = 0; + while ( br.readLine() != null ) + { + n += 1; + } + //log.warn ("number of lines="+n+" for "+query); + return n; + } + + + /** + * Translate a query string to a Map. Duplicate values are + * overwritten, so don't use this routine for general query string + * parsing. + * + * TODO: Made public only for unit tests. Do not use. + */ + public static Map urlEncodedToMap( String query ) + throws UnsupportedEncodingException + { + Map map = new HashMap(); + if ( query == null ) + { + return map; + } + String[] parts = query.split( "[&;]" ); + for ( int i = 0; i < parts.length; i++ ) + { + String[] nameval = parts[i].split( "=" ); + String name = URLDecoder.decode( nameval[0], "UTF-8" ); + String value = null; + if ( nameval.length > 1 ) + { + value = URLDecoder.decode( nameval[1], "UTF-8" ); + } + map.put( name, value ); + } + return map; + } + + + public static Map postedToMap( String query ) throws IOException + { + Map map = new HashMap(); + if ( query == null ) + { + return map; + } + BufferedReader br = new BufferedReader( new StringReader( query ) ); + String s = br.readLine(); + while ( s != null ) + { + int index = s.indexOf( ":" ); + if ( index != -1 ) + { + String name = s.substring( 0, index ); + String value = s.substring( index + 1, s.length() ); + if ( name != null && value != null ) + { + map.put( name, value ); + } + } + s = br.readLine(); + } + return map; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/Mode.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/Mode.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/Mode.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid; + + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + + +/** + * TODO Mode. + * + * @author Alex Karasulu + */ +public enum Mode +{ + ERROR( "error" ), + ID_RES( "id_res" ), + CANCEL( "cancel" ), + ASSOCIATE( "associate"), + SETUP_NEEDED( "setup_needed" ), + CHECKID_IMMEDIATE( "checkid_immediate" ), + CHECK_AUTHENTICATION( "check_authentication" ), + CHECKID_SETUP( "checkid_setup" ); + + + private final static Map MAP; + + + static + { + Map m = new HashMap(); + m.put( ERROR.getValue(), ERROR ); + m.put( ID_RES.getValue(), ID_RES ); + m.put( CANCEL.getValue(), CANCEL ); + m.put( ASSOCIATE.getValue(), ASSOCIATE ); + m.put( SETUP_NEEDED.getValue(), SETUP_NEEDED ); + m.put( CHECKID_IMMEDIATE.getValue(), CHECKID_IMMEDIATE ); + m.put( CHECK_AUTHENTICATION.getValue(), CHECK_AUTHENTICATION ); + m.put( CHECKID_SETUP.getValue(), CHECKID_SETUP ); + + MAP = Collections.unmodifiableMap( m ); + } + + + public static Mode parse( String value ) + { + if ( MAP.containsKey( value ) ) + { + return MAP.get( value ); + } + + String lowercase = value.toLowerCase(); + if ( MAP.containsKey( lowercase ) ) + { + return MAP.get( lowercase ); + } + + throw new IllegalArgumentException( "'" + value + "' does not correspond to a value Mode value" ); + } + + + private final String value; + + + private Mode( String value ) + { + this.value = value; + } + + + public String toString() + { + return value; + } + + + public String getValue() + { + return value; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/OpenId.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/OpenId.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/OpenId.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,291 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.io.UnsupportedEncodingException; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + +/** + * The main OpenID implementation. + * + * The simplest way to implement OpenID is to let this class handle the + * request and produce the response. + * + *
+ * // Get a store implementation. You need this to store/retrieve associations,
+ * // which is the way an OpenID provider and an OpenID relying party recognize
+ * // each other.
+ * Store store = ...
+ *
+ * // Get an OpenID implementation
+ * OpenId openId = new OpenId(store);
+ *
+ * // Process the request into a response
+ * String response = openId.handleRequest(query);
+ *
+ * // then send the response back to the sender.
+ * 
+ */ +public class OpenId +{ + private final static Log log = LogFactory.getLog( OpenId.class ); + private ServerInfo serverInfo; + + + /** + * Creates an OpenId instance. This instance will use the default crypto + * implementation {@link Crypto}. + * + * @param serverInfo information about this service. + */ + public OpenId( ServerInfo serverInfo ) + { + this.serverInfo = serverInfo; + } + + + /** + * Returns whether the query is a valid OpenId message + * that this implementation can handle. + * + * @param query the query top check. + * @return true if this is a message that can be handled; false otherwise. + */ + public boolean canHandle( String query ) + { + try + { + RequestFactory.parse( query ); + return true; + } + catch ( Exception e ) + { + log.info( e, e ); + return false; + } + } + + + /** + * Return the server info + */ + public ServerInfo getServerInfo() + { + return serverInfo; + } + + + /** + * Call this method if the data is posted by way of HTTP POST + */ + public String handleRequest( Map map ) throws OpenIdException + { + throw new RuntimeException( "nyi" ); + } + + + /** + * Returns whether the incoming request is an Association Request. + * + * @param query the request to check. + * @return true if the incoming request is an Association Request; false + * otherwise. + * @throws InvalidOpenIdQueryException + */ + public boolean isAssociationRequest( String query ) throws InvalidOpenIdQueryException + { + + if ( query == null || query.equals( "" ) ) + { + throw new InvalidOpenIdQueryException( "empty query" ); + } + + try + { + return ( query.indexOf( new StringBuilder(RequestFactory.OPENID_MODE).append("=" ).append( Mode.ASSOCIATE ).toString() ) >= 0 ); + } + catch ( Exception e ) + { + log.error( e, e ); + throw new InvalidOpenIdQueryException( "cannot parse query: " + query ); + + } + + /* try + { + Request req = RequestFactory.parse( query ); + return ( req instanceof AssociationRequest ); + } + catch ( OpenIdException e ) + { + log.info( e, e ); + return false; + } + catch ( UnsupportedEncodingException e ) + { + log.info( e, e ); + return false; + }*/ + } + + + /** + * Returns whether the incoming request is an Authentication Request. + * + * @param query the request to check. + * @return true if the incoming request is an Authentication Request; false + * otherwise. + * @throws InvalidOpenIdQueryException + */ + public boolean isAuthenticationRequest( String query ) throws InvalidOpenIdQueryException + { + + if ( query == null || query.equals( "" ) ) + { + throw new InvalidOpenIdQueryException( "empty query" ); + } + + try + { + return ( query.indexOf( new StringBuilder(RequestFactory.OPENID_MODE).append("=" ).append( Mode.CHECKID_SETUP ).toString() ) >= 0 + || query.indexOf( new StringBuilder(RequestFactory.OPENID_MODE).append("=" ).append( Mode.CHECKID_IMMEDIATE ).toString() ) >= 0 ); + } + catch ( Exception e ) + { + log.error( e, e ); + throw new InvalidOpenIdQueryException( "cannot parse query: " + query ); + + } + + /* + try + { + Request req = RequestFactory.parse( query ); + return ( req instanceof AuthenticationRequest ); + } + catch ( OpenIdException e ) + { + log.info( e, e ); + return false; + } + catch ( UnsupportedEncodingException e ) + { + log.info( e, e ); + return false; + } + */ + } + + + /** + * Returns whether the incoming request is a Check Authentication Request. + * + * @param query the request to check. + * @return true if the incoming request is a Check Authentication + * Request; false otherwise. + * @throws InvalidOpenIdQueryException + */ + public boolean isCheckAuthenticationRequest( String query ) throws InvalidOpenIdQueryException + { + + if ( query == null || query.equals( "" ) ) + { + throw new InvalidOpenIdQueryException( "empty query" ); + } + + try + { + Pattern openIdModePattern = Pattern.compile( ".*" + RequestFactory.OPENID_MODE + "=(.+?)&.*" ); + + Matcher matcher = openIdModePattern.matcher( query ); + + if ( matcher.find() ) + { + return Mode.parse( matcher.group( 1 ) ).equals( Mode.CHECK_AUTHENTICATION ); + } + else + { + return false; + } + } + catch ( Exception e ) + { + log.error( e, e ); + throw new InvalidOpenIdQueryException( "cannot parse query: " + query ); + } + } + + + /** + * Processes an OpenID request into an OpenID response. + * @param query the query + * @return the response. The format of the response is depending + * on the request: if the request is an authentication request, the + * response will be suitable for redirecting via URL; otherwise the + * response will be name/value pair encoded as per specification. + * @throws InvalidOpenIdQueryException + */ + public String handleRequest( String query ) throws OpenIdException, InvalidOpenIdQueryException + { + Request req = null; + try + { + req = RequestFactory.parse( query ); + } + catch ( UnsupportedEncodingException e ) + { + log.warn( "exception=" + e ); + throw new OpenIdException( e ); + } + + Response resp = req.processUsing( serverInfo ); + if ( req instanceof AuthenticationRequest ) + { + return resp.toUrlString(); + } + else + { + return resp.toPostString(); + } + } + + + /** + * Returns whether the response is an error response. + * + * @param s the response. + * @return true if the response is an error response, that is, whether + * processing the request yielded this response to contain an error; false + * otherwise. + */ + public boolean isAnErrorResponse( String s ) + { + try + { + Response resp = ResponseFactory.parse( s ); + return ( resp.getError() != null ); + } + catch ( OpenIdException e ) + { + return false; + } + } +} Index: 3rdParty_sources/joid/org/verisign/joid/OpenIdConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/OpenIdConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/OpenIdConstants.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + + +/** + * Various query string key constants used by OpenID. + * + * @author Alex Karasulu + */ +public interface OpenIdConstants +{ + //------------------- + // keys + //------------------- + + String OPENID_SESSION_TYPE = "openid.session_type"; + String OPENID_DH_CONSUMER_PUBLIC = "openid.dh_consumer_public"; + String OPENID_DH_GENERATOR = "openid.dh_gen"; + String OPENID_DH_MODULUS = "openid.dh_modulus"; + String OPENID_ASSOCIATION_TYPE = "openid.assoc_type"; + String OPENID_MODE = "openid.mode"; + String OPENID_NS = "openid.ns"; + + //------------------- + // other constants + //------------------- + + String ENCODED_NS_VERSION2 = "http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0"; + String OPENID_20_NAMESPACE = "http://specs.openid.net/auth/2.0"; + + Set OPENID_RESERVED_WORDS = Collections.unmodifiableSet ( + new HashSet( Arrays.asList( new String[] + { "assoc_handle", "assoc_type", "claimed_id", "contact", "delegate", + "dh_consumer_public", "dh_gen", "dh_modulus", "error", "identity", + "invalidate_handle", "mode", "ns", "op_endpoint", "openid", "realm", + "reference", "response_nonce", "return_to", "server", "session_type", + "sig", "signed", "trust_root" + } ) ) ); +} Index: 3rdParty_sources/joid/org/verisign/joid/OpenIdException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/OpenIdException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/OpenIdException.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,68 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +/** + * The main exception class of the OpenId librbary. + */ +public class OpenIdException extends Exception +{ + private static final long serialVersionUID = 28732439387623L; + + + /** + * Creates an exception. + * @param s a string value to encapsulate. + */ + public OpenIdException( String s ) + { + super( s ); + } + + + /** + * Creates an exception. + * @param e a exception to encapsulate. + */ + public OpenIdException( Exception e ) + { + super( e ); + } + + + public OpenIdException( String s, Exception e ) + { + super( s, e ); + } + + + /** + * Returns this exception's message. + * @return a string message of this exception (either the encapsulated string, + * or the encapsulated exception). + */ + public String getMessage() + { + Throwable t = getCause(); + if ( t != null ) + { + return t.getMessage(); + } + else + { + return super.getMessage(); + } + } +} Index: 3rdParty_sources/joid/org/verisign/joid/OpenIdRuntimeException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/OpenIdRuntimeException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/OpenIdRuntimeException.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,26 @@ +package org.verisign.joid; + + +/** + * For throwing RuntimeExceptions from joid. + * + * User: treeder + * Date: Dec 20, 2007 + * Time: 12:41:14 PM + */ +public class OpenIdRuntimeException extends RuntimeException +{ + private static final long serialVersionUID = 9171669934119626199L; + + + public OpenIdRuntimeException( String s ) + { + super( s ); + } + + + public OpenIdRuntimeException( String s, Throwable t ) + { + super( s, t ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/Request.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/Request.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/Request.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,65 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.util.Map; + + +/** + * Represents an OpenID request. Valid for OpenID 1.1 and 2.0 namespace. + */ +public abstract class Request extends Message +{ + /** + * @TODO delete this after re-factoring + */ + Request( Map map, Mode mode ) + { + setMode( mode ); + + if ( map != null ) + { + setNamespace( ( String ) map.get( OpenIdConstants.OPENID_NS ) ); + } + } + + + /** + * @TODO delete this after re-factoring + */ + Map toMap() + { + return super.toMap(); + } + + + /** + * @TODO delete this after re-factoring + * + * Processes this request using the given store and crypto implementations. + * This processing step should produce a valid response that can be + * sent back to the requestor. Associations may be read from, written to, + * or deleted from the store by way of this processing step. + * + * @param serverInfo information about this server's implementation. + * + * @return the response + * + * @throws OpenIdException unrecoverable errors happen. + */ + public abstract Response processUsing( ServerInfo serverInfo ) + throws OpenIdException; + +} Index: 3rdParty_sources/joid/org/verisign/joid/RequestFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/RequestFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/RequestFactory.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,84 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// +package org.verisign.joid; + + +import java.io.UnsupportedEncodingException; +import java.util.Map; + + +/** + * Produces requests from incoming queries. + */ +public class RequestFactory +{ + public static String OPENID_MODE = "openid.mode"; + + + /** + * Parses a query into a request. + * + * @param query the query to parse. + * @return the parsed request. + * @throws OpenIdException if the query cannot be parsed into a known + * request. + * @throws InvalidOpenIdQueryException + */ + public static Request parse( String query ) + throws UnsupportedEncodingException, OpenIdException, InvalidOpenIdQueryException + { + Map map; + + try + { + map = parseQuery( query ); + } + catch ( UnsupportedEncodingException e ) + { + throw new OpenIdException( "Error parsing " + query + ": " + e.toString() ); + } + + Mode mode = Mode.parse( map.get( OPENID_MODE ) ); + + if ( Mode.ASSOCIATE == mode ) + { + return new AssociationRequest( map, Mode.ASSOCIATE ); + } + else if ( Mode.CHECKID_IMMEDIATE == mode || Mode.CHECKID_SETUP == mode ) + { + return new AuthenticationRequest( map, mode ); + } + else if ( Mode.CHECK_AUTHENTICATION == mode ) + { + return new CheckAuthenticationRequest( map, Mode.CHECK_AUTHENTICATION ); + } + else + { + throw new InvalidOpenIdQueryException( new StringBuilder( "Cannot parse request from " ).append( query ).toString() ); + } + } + + + /** + * Parses a query into a map. + * + * @param query the query to parse. + * @return the parsed request. + * @throws UnsupportedEncodingException if the string is not properly + * UTF-8 encoded. + */ + public static Map parseQuery( String query ) throws UnsupportedEncodingException + { + return MessageParser.urlEncodedToMap( query ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/Response.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/Response.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/Response.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,77 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// +package org.verisign.joid; + + +import java.util.Map; + + +/** + * Represents an OpenID response. Valid for OpenID 1.1 and 2.0 namespace. Adds + * a simple error property in addition to standard {@link Message} properties + * and this is to handle openid.mode=error type messages. + */ +public abstract class Response extends Message +{ + static String OPENID_ERROR = "error"; + + String error; + + + String getError() + { + return error; + } + + + /** + * @TODO delete this after re-factoring + */ + Map toMap() + { + return super.toMap(); + } + + + /** + * @TODO delete this after re-factoring + */ + Response( Map map ) + { + if ( map != null ) + { + if ( map != null ) + { + setNamespace( ( String ) map.get( OpenIdConstants.OPENID_NS ) ); + } + + this.error = ( String ) map.get( Response.OPENID_ERROR ); + } + } + + + /** + * Returns a string representation of this response. + * + * @return a string representation of this response. + */ + public String toString() + { + String s = super.toString(); + if ( error != null ) + { + s += ", error=" + error; + } + return s; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/ResponseFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/ResponseFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/ResponseFactory.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,81 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.io.IOException; +import java.util.Map; +import java.util.Set; + + +/** + * Produces requests from incoming queries. + */ +public class ResponseFactory +{ + private ResponseFactory() + { + } + + + /** + * Parses a query into a response. + * + * @param query the query to parse. + * @return the parsed response. + * @throws OpenIdException if the query cannot be parsed into a known + * response. + */ + public static Response parse( String query ) throws OpenIdException + { + Map map; + try + { + if ( MessageParser.numberOfNewlines( query ) == 1 ) + { + map = MessageParser.urlEncodedToMap( query ); + } + else + { + map = MessageParser.postedToMap( query ); + } + } + catch ( IOException e ) + { + throw new OpenIdException( "Error parsing " + query + ": " + + e.toString() ); + } + + Set set = map.keySet(); + if ( ( set.contains( AssociationResponse.OPENID_SESSION_TYPE ) && + set.contains( AssociationResponse.OPENID_ENC_MAC_KEY ) ) || + set.contains( AssociationResponse.OPENID_ASSOCIATION_TYPE ) ) + { + return new AssociationResponse( map ); + } + else if ( set.contains( AuthenticationResponse.OPENID_SIG ) ) + { + return new AuthenticationResponse( map ); + } + else if ( set.contains( CheckAuthenticationResponse.OPENID_IS_VALID ) ) + { + return new CheckAuthenticationResponse( map ); + } + else + { + throw new OpenIdException( "Cannot parse response from " + query ); + } + } + +} Index: 3rdParty_sources/joid/org/verisign/joid/ServerInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/ServerInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/ServerInfo.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,58 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +/** + * Information about this server. + */ +public class ServerInfo +{ + private String urlEndPoint; + private IStore store; + private Crypto crypto; + + + /** + * Creates an instance of the server information. + * + * @param urlEndPoint the URL endpoint for the service. + * @param store the store implementation to use. + * @param crypto the crypto implementation to use. + */ + public ServerInfo( String urlEndPoint, IStore store, Crypto crypto ) + { + this.urlEndPoint = urlEndPoint; + this.store = store; + this.crypto = crypto; + } + + + public String getUrlEndPoint() + { + return urlEndPoint; + } + + + public IStore getStore() + { + return store; + } + + + public Crypto getCrypto() + { + return crypto; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/SessionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/SessionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/SessionType.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid; + + +/** + * An enumeration for managing SessionTypes. + * + * @author akarasulu at apache.org + */ +public enum SessionType +{ + NO_ENCRYPTION( "no-encryption" ), DH_SHA1( "DH-SHA1" ), DH_SHA256( "DH-SHA256" ); + + + private final String name; + + + private SessionType( String name ) + { + this.name = name; + } + + + public String toString() + { + return name; + } + + + public String getName() + { + return name; + } + + + public boolean equalsName( String name ) + { + return name.equalsIgnoreCase( name ); + } + + + public static SessionType parse( String name ) + { + if ( name.equalsIgnoreCase( NO_ENCRYPTION.toString() ) ) + { + return NO_ENCRYPTION; + } + + + if ( name.equalsIgnoreCase( DH_SHA1.toString() ) ) + { + return DH_SHA1; + } + + + if ( name.equalsIgnoreCase( DH_SHA256.toString() ) ) + { + return DH_SHA256; + } + + throw new IllegalArgumentException( "The string '" + name + "' does not match any session type." ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/SimpleRegistration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/SimpleRegistration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/SimpleRegistration.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,466 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.StringTokenizer; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; + + +/** + * Simple registration extensions, as defined by + * http://openid.net/specs/openid-simple-registration-extension-1_0.html + * + * This class should only be used by internal request/response + * processing. + * + * TODO to make this clearer. + */ +public class SimpleRegistration +{ + private final static Log LOG = LogFactory.getLog( SimpleRegistration.class ); + + private Set required; + private Set optional; + private Map supplied; + private String policyUrl; + + /** The openid.sreg value */ + public final static String OPENID_SREG = "openid.sreg"; + + /** The openid.ns.sreg value */ + public final static String OPENID_SREG_NSDEF = "openid.ns.sreg"; + + /** The openid.sreg.required value */ + public final static String OPENID_SREG_REQUIRED = OPENID_SREG + ".required"; + + /** The openid.sreg.optional value */ + public final static String OPENID_SREG_OPTIONAL = OPENID_SREG + ".optional"; + + /** The openid.sreg.policy_url value */ + public final static String OPENID_SREG_POLICY_URL = OPENID_SREG + ".policy_url"; + + /** Invalid namespace for sreg (from XRDS) seen in the wild */ + public final static String OPENID_SREG_NAMESPACE_10 = "http://openid.net/sreg/1.0"; + + /** Standard namespace value for sreg */ + public final static String OPENID_SREG_NAMESPACE_11 = "http://openid.net/extensions/sreg/1.1"; + + private final static String SREG_NICKNAME = "nickname"; + private final static String SREG_EMAIL = "email"; + private final static String SREG_FULLNAME = "fullname"; + private final static String SREG_DOB = "dob"; + private final static String SREG_GENDER = "gender"; + private final static String SREG_POSTCODE = "postcode"; + private final static String SREG_COUNTRY = "country"; + private final static String SREG_LANGUAGE = "language"; + private final static String SREG_TIMEZONE = "timezone"; + + private String namespace; + private String nickName; + private String email; + private String fullName; + private String dob; + private String gender; + private String postCode; + private String country; + private String language; + private String timeZone; + + /** + * The set of the nine allowed SREG values. + */ + public final static Set ALLOWED; + static + { + Set set = new HashSet(); + set.add( SREG_NICKNAME ); + set.add( SREG_EMAIL ); + set.add( SREG_FULLNAME ); + set.add( SREG_DOB ); + set.add( SREG_GENDER ); + set.add( SREG_POSTCODE ); + set.add( SREG_COUNTRY ); + set.add( SREG_LANGUAGE ); + set.add( SREG_TIMEZONE ); + + ALLOWED = Collections.unmodifiableSet( set ); + } + + + /** + * Creates a simple registration. + */ + SimpleRegistration( Set required, Set optional, Map supplied, + String policyUrl ) + { + this.required = required; + this.optional = optional; + this.supplied = supplied; + this.policyUrl = policyUrl; + this.namespace = OPENID_SREG_NAMESPACE_11; + } + + + /** + * Creates a simple registration. + */ + SimpleRegistration( Set required, Set optional, Map supplied, + String policyUrl, String namespace ) + { + this.required = required; + this.optional = optional; + this.supplied = supplied; + this.policyUrl = policyUrl; + this.namespace = namespace; + } + + + SimpleRegistration( Map map ) throws OpenIdException + { + required = new HashSet(); + optional = new HashSet(); + supplied = new HashMap(); + namespace = OPENID_SREG_NAMESPACE_11; + + Set> set = map.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + + if ( OPENID_SREG_REQUIRED.equals( key ) ) + { + addToSetFromList( required, value ); + } + else if ( OPENID_SREG_OPTIONAL.equals( key ) ) + { + addToSetFromList( optional, value ); + } + else if ( OPENID_SREG_POLICY_URL.equals( key ) ) + { + policyUrl = value; + } + else if ( OPENID_SREG_NSDEF.equals( key ) ) + { + if ( OPENID_SREG_NAMESPACE_10.equals( value ) || OPENID_SREG_NAMESPACE_11.equals( value ) ) + { + namespace = value; + } + } + } + } + + + public boolean isRequested() + { + return ( !( required.isEmpty() && optional.isEmpty() ) ); + } + + + /** + * Expects a map with values like "openid.sreg.nickname=blahblah" in it + */ + public static SimpleRegistration parseFromResponse( Map map ) + { + Set req = new HashSet(); + Set opt = new HashSet(); + Map sup = new HashMap(); + String ns = OPENID_SREG_NAMESPACE_11; + + String trigger = OPENID_SREG + "."; + int triggerLength = trigger.length(); + Set> set = map.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + + if ( key.startsWith( trigger ) ) + { + sup.put( key.substring( triggerLength ), value ); + } + else if ( OPENID_SREG_NSDEF.equals( key ) ) + { + if ( OPENID_SREG_NAMESPACE_10.equals( value ) || OPENID_SREG_NAMESPACE_11.equals( value ) ) + { + ns = value; + } + } + } + return new SimpleRegistration( req, opt, sup, "", ns ); + } + + + private void addToSetFromList( Set set, String value ) + { + if ( value == null ) + { + return; + } + StringTokenizer st = new StringTokenizer( value, "," ); + while ( st.hasMoreTokens() ) + { + String token = st.nextToken().trim(); + if ( ALLOWED.contains( token ) ) + { + set.add( token ); + } + else + { + LOG.info( "Illegal sreg value: " + token ); + } + } + } + + + public String getPolicyUrl() + { + return policyUrl; + } + + + public Set getRequired() + { + return Collections.unmodifiableSet( required ); + } + + + public Set getOptional() + { + return Collections.unmodifiableSet( optional ); + } + + + public void setRequired( Set set ) + { + required = set; + } + + + public void setOptional( Set set ) + { + optional = set; + } + + + public String getNamespace() + { + return namespace; + } + + + public Map getSuppliedValues() + { + Map map = new HashMap(); + addAllNonEmpty( supplied, map ); + return map; + } + + + private void addAllNonEmpty( Map from, Map to ) + { + Set> set = from.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + if ( value != null ) + { + to.put( key, value ); + } + } + } + + + public String toString() + { + return "[SimpleRegistration required=" + required + + ", optional=" + optional + ", supplied=" + supplied + + ", policy url=" + policyUrl + + ", namespace=" + namespace + "]"; + } + + + /** + * @param nickName the nickName to set + */ + public void setNickName( String nickName ) + { + this.nickName = nickName; + } + + + /** + * @return the nickName + */ + public String getNickName() + { + return nickName; + } + + + /** + * @param email the email to set + */ + public void setEmail( String email ) + { + this.email = email; + } + + + /** + * @return the email + */ + public String getEmail() + { + return email; + } + + + /** + * @param fullName the fullName to set + */ + public void setFullName( String fullName ) + { + this.fullName = fullName; + } + + + /** + * @return the fullName + */ + public String getFullName() + { + return fullName; + } + + + /** + * @param postCode the postCode to set + */ + public void setPostCode( String postCode ) + { + this.postCode = postCode; + } + + + /** + * @return the postCode + */ + public String getPostCode() + { + return postCode; + } + + + /** + * @param dob the dob to set + */ + public void setDob( String dob ) + { + this.dob = dob; + } + + + /** + * @return the dob + */ + public String getDob() + { + return dob; + } + + + /** + * @param country the country to set + */ + public void setCountry( String country ) + { + this.country = country; + } + + + /** + * @return the country + */ + public String getCountry() + { + return country; + } + + + /** + * @param language the language to set + */ + public void setLanguage( String language ) + { + this.language = language; + } + + + /** + * @return the language + */ + public String getLanguage() + { + return language; + } + + + /** + * @param timeZone the timeZone to set + */ + public void setTimeZone( String timeZone ) + { + this.timeZone = timeZone; + } + + + /** + * @return the timeZone + */ + public String getTimeZone() + { + return timeZone; + } + + + /** + * @param gender the gender to set + */ + public void setGender( String gender ) + { + this.gender = gender; + } + + + /** + * @return the gender + */ + public String getGender() + { + return gender; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/StoreFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/StoreFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/StoreFactory.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,65 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid; + + +import org.verisign.joid.util.DependencyUtils; + + +/** + * Creates stores. JOID comes with the DbStore. + */ +public class StoreFactory +{ + private StoreFactory() + { + } + + + /** + * Returns whether the store type is implemented. + * + * @param storeType the type to check. + * @return true if the store type is implemented; false otherwise. + */ + public static boolean hasType( String storeType ) + { + return "db".equals( storeType ); + } + + + /** + * Gets a store implementation. + * + * @param className the class name of the store to instantiate. + * @return the store. + * @throws IllegalArgumentException if the class doesn't exist or is + * not a store type. + */ + public static IStore getInstance( String className ) + { + return ( IStore ) DependencyUtils.newInstance( className ); + } + + /** + * Gets a database store implementation of type + * {@link org.verisign.joid.db.DbStore}. + * + * @return the database store. + */ + /*public static Store getDbInstance() + { + return DbStore.getInstance(); + }*/ +} Index: 3rdParty_sources/joid/org/verisign/joid/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/Attic/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/package.html 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,46 @@ + + + +The JOID Java OpenID package. + +JOID processes messages by using a factory to parse the request, and then +use this request to generate a response. + +There are two ways of using this package, depending on your needs. + +

High level

+
+// Get a store implementation (used to handle associations).
+Store store = ...
+
+// Get an OpenID implementation
+OpenId openId = new OpenId(store);
+
+// Process the request into a response
+String response = openid.handleRequest(query);
+
+// then send the response back to the sender
+
+ +

Slightly lower lever

+If you need to specify which type of crypto implementation to use, +or if you need to inspect incoming requests or outgoing responses, +you can operate on a slightly lower level + +
+// Parse the incoming message
+Request req = RequestFactory.parse(string);
+
+// Get a store implementation (used to handle associations) and a 
+// crypto implementation (to handle the OpenID protocol crypto)
+Store store = ...
+Crypto crypto = ...
+
+// Use the request and process with the store and crypto to
+// produce a response
+Response resp = req.processUsing(store, crypto);
+
+ + + + Index: 3rdParty_sources/joid/org/verisign/joid/consumer/AuthenticationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/AuthenticationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/AuthenticationException.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,17 @@ +package org.verisign.joid.consumer; + + +/** + * User: treeder + * Date: Jun 20, 2007 + * Time: 11:23:55 PM + */ +public class AuthenticationException extends RuntimeException +{ + private static final long serialVersionUID = 2537052042761934028L; + + public AuthenticationException( String s ) + { + super( s ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/AuthenticationResult.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/AuthenticationResult.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/AuthenticationResult.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,67 @@ +package org.verisign.joid.consumer; + + +import org.verisign.joid.AuthenticationResponse; + + +/** + * This class is returned by JoidConsumer.authenticate() and is just a holder for + * the results. + * + * User: treeder + * Date: Aug 13, 2007 + * Time: 11:09:36 PM + */ +public class AuthenticationResult +{ + private boolean successful; + private String identity; + private AuthenticationResponse response; + + + public AuthenticationResult( String identity, AuthenticationResponse response ) + { + this.identity = identity; + this.response = response; + if ( identity != null ) + { + successful = true; + } + } + + + public AuthenticationResponse getResponse() + { + return response; + } + + + public void setResponse( AuthenticationResponse response ) + { + this.response = response; + } + + + public String getIdentity() + { + return identity; + } + + + public void setIdentity( String identity ) + { + this.identity = identity; + } + + + public boolean isSuccessful() + { + return successful; + } + + + public void setSuccessful( boolean successful ) + { + this.successful = successful; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/Discoverer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/Discoverer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/Discoverer.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,239 @@ +package org.verisign.joid.consumer; + + +import org.verisign.joid.OpenIdException; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.methods.GetMethod; +import org.xml.sax.SAXException; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.w3c.dom.Node; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Iterator; +import java.util.List; + + +/** + * User: treeder + * Date: Jul 17, 2007 + * Time: 5:05:52 PM + */ +public class Discoverer +{ + + public ServerAndDelegate findIdServer( String identityUrl ) + throws Exception + { + + ServerAndDelegate serverAndDelegate = new ServerAndDelegate(); + + // OpenID 2.0, we first try to check with YADIS protocol + findWithYadis( identityUrl, serverAndDelegate ); + + if ( serverAndDelegate.getServer() == null ) + { + throw new OpenIdException( "No openid.server found on identity page." ); + } + return serverAndDelegate; + } + + + public void findWithYadis( String identityUrl, ServerAndDelegate serverAndDelegate ) throws Exception + { + BufferedReader in = null; + HttpClient httpClient = new HttpClient(); + httpClient.getParams().setSoTimeout( 15000 ); + httpClient.getParams().setConnectionManagerTimeout( 15000 ); + + GetMethod get = null; + try + { + + System.out.println( "identityUrl=" + identityUrl ); + get = new GetMethod( identityUrl ); + // test + int status = httpClient.executeMethod( get ); + System.out.println( "status=" + status ); + dumpHeaders( get.getResponseHeaders() ); + + Header contentType = get.getResponseHeader( "Content-Type" ); + if ( contentType != null && contentType.getValue().contains( "application/xrds+xml" ) ) + { + // then we're looking at the xrds service doc already + XRDSDocument xrdsDocument = buildXrdsDocument( get ); + handleXrdsDocument( serverAndDelegate, xrdsDocument ); + return; + } + + Header locationHeader = get.getResponseHeader( "X-XRDS-Location" ); + if ( locationHeader != null ) + { + // then we go to this URL + get.releaseConnection(); + System.out.println( "found yadis header: " + locationHeader.getValue() ); + XRDSDocument xrdsDocument = fetchYadisDocument( httpClient, locationHeader.getValue() ); + handleXrdsDocument( serverAndDelegate, xrdsDocument ); + return; + } + else + { + // try to find it in the HTML, OpenID 1.0 style + // @TODO: should also look for X-XRDS-Location in a meta tag here + in = new BufferedReader( new InputStreamReader( get.getResponseBodyAsStream() ) ); + findServerAndDelegate( serverAndDelegate, in ); + return; + } + + /* + This is the last try for YADIS: + get = new GetMethod(identityUrl); + get.setRequestHeader("Accept", " application/xrds+xml"); + httpClient.executeMethod(get); + + Header contentType = get.getResponseHeader("content-type"); + System.out.println("content-type=" + contentType); + get.releaseConnection(); + + */ + } + finally + { + if ( in != null ) + in.close(); + if ( get != null ) + get.releaseConnection(); + } + } + + + private void handleXrdsDocument( ServerAndDelegate serverAndDelegate, XRDSDocument xrdsDocument ) + { + List services = xrdsDocument.getServiceList(); + Iterator it = services.iterator(); + while ( it.hasNext() ) + { + XRDSService service = it.next(); + System.out.println( "service=" + service.getUri() ); + serverAndDelegate.setServer( service.getUri() ); + // @TODO: also set delegate after we get it + } + } + + + private void dumpHeaders( Header[] responseHeaders ) + { + for ( int i = 0; i < responseHeaders.length; i++ ) + { + Header responseHeader = responseHeaders[i]; + System.out.println( responseHeader.getName() + "=" + responseHeader.getValue() ); + } + } + + + private void findServerAndDelegate( ServerAndDelegate serverAndDelegate, BufferedReader in ) + throws IOException + { + String str; + while ( ( str = in.readLine() ) != null ) + { + if ( serverAndDelegate.getServer() == null ) + { + serverAndDelegate.setServer( findLinkTag( str, "openid.server", in ) ); + } + if ( serverAndDelegate.getDelegate() == null ) + { + serverAndDelegate.setDelegate( findLinkTag( str, "openid.delegate", in ) ); + } + if ( str.indexOf( "" ) >= 0 ) + { + break; + } + } + } + + + private XRDSDocument fetchYadisDocument( HttpClient httpClient, String location ) throws IOException, + ParserConfigurationException, SAXException + { + GetMethod get = new GetMethod( location ); + httpClient.executeMethod( get ); + // System.out.println("got: " + get.getResponseBodyAsString()); + XRDSDocument doc = buildXrdsDocument( get ); + return doc; + } + + + private XRDSDocument buildXrdsDocument( GetMethod get ) + throws ParserConfigurationException, SAXException, IOException + { + XRDSDocument doc = new XRDSDocument(); + DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + javax.xml.parsers.DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); + Document document = docBuilder.parse( get.getResponseBodyAsStream() ); + get.releaseConnection(); + NodeList list = document.getElementsByTagName( "Service" ); + for ( int i = 0; i < list.getLength(); i++ ) + { + Node node = list.item( i ); + System.out.println( "servicenode=" + node ); + NodeList childNodes = node.getChildNodes(); + XRDSService service = new XRDSService(); + for ( int j = 0; j < childNodes.getLength(); j++ ) + { + // todo: ensure is http://openid.net/signon/1.0 - http://yadis.org/wiki/Yadis_1.0_(HTML)#7._The_Yadis_document + // todo: get delegate + Node node2 = childNodes.item( j ); + System.out.println( node2.getNodeName() ); + if ( node2.getNodeName().equalsIgnoreCase( "URI" ) ) + { + service.setUri( node2.getTextContent() ); + } + } + doc.addService( service ); + } + return doc; + } + + + private String findLinkTag( String str, String rel, BufferedReader in ) + throws IOException + { + int index = str.indexOf( rel ); + if ( index != -1 ) + { + // todo: ensure it's a proper link tag + // todo: allow multiple line tag + // todo: allow reverse ordering + String href = findHref( str, index ); + if ( href == null ) + { + // no href found, check next line + str = in.readLine(); + if ( str != null ) + { + href = findHref( str, 0 ); + } + } + return href; + } + return null; + } + + + private String findHref( String str, int index ) + { + String href = null; + int indexOfHref = str.indexOf( "href=", index ); + if ( indexOfHref != -1 ) + { + href = str.substring( indexOfHref + 6, str.indexOf( "\"", indexOfHref + 8 ) ); + } + return href; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/JoidConsumer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/JoidConsumer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/JoidConsumer.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,287 @@ +package org.verisign.joid.consumer; + + +import org.verisign.joid.*; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + + +/** + * This is the main class for consumers to use. + *

+ * It performs the following operations given an OpenID user identifier. + * - Finds the OpenId Server + * - Associates with the server if it hasn't done so already or if the + * association has expired + * - Provides url to the server an application to redirect to. + *

+ * ... some time later ... + *

+ * - Takes a request from an OpenId server after user has authenticated + * - Verifies server signature and our signatures match to authenticate + * - Returns the user's identifier if ok + *

+ *

+ * User: treeder + * Date: Jun 27, 2007 + * Time: 11:52:40 AM + */ +public class JoidConsumer +{ + + private static Log log = LogFactory.getLog( JoidConsumer.class ); + + private Map propSingleton; + private Map handleToIdServer; + private Discoverer discoverer = new Discoverer(); + + + public JoidConsumer() + { + log.info( "Constructor: JoidConsumer" ); + } + + + private synchronized Properties getProps( String idserver ) + { + // @TODO: just store the AssociationResponse instead of converting to props + if ( propSingleton == null ) + { + propSingleton = new HashMap(); + handleToIdServer = new HashMap(); + } + Properties props = ( Properties ) propSingleton.get( idserver ); + if ( props == null ) + { // @TODO: also check expires_in time to make sure it's still valid + try + { + props = associate( idserver ); + propSingleton.put( idserver, props ); + handleToIdServer.put( props.getProperty( "handle" ), idserver ); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + return props; + } + + + private Properties getPropsByHandle( String associationHandle ) + throws OpenIdException + { + String idServer = ( String ) handleToIdServer.get( associationHandle ); + log.info( "got idserver for handle: " + associationHandle + + " - " + idServer ); + if ( idServer == null ) + { + throw new OpenIdException( "handle for server not found!" ); + } + return getProps( idServer ); + } + + + /** + * To associate with an openid server + * + * @param idserver server url + * @return + * @throws java.io.IOException + * @throws org.verisign.joid.OpenIdException + * + */ + public Properties associate( String idserver ) + throws IOException, OpenIdException + { + DiffieHellman dh = DiffieHellman.getDefault(); + Crypto crypto = new Crypto(); + crypto.setDiffieHellman( dh ); + + AssociationRequest ar = AssociationRequest.create( crypto ); + + log.info( "[JoidConsumer] Attempting to associate with: " + idserver ); + log.info( "Request=" + ar ); + + Response response = Util.send( ar, idserver ); + log.info( "Response=" + response + "\n" ); + + AssociationResponse asr = ( AssociationResponse ) response; + + Properties props = new Properties(); + props.setProperty( "idServer", idserver ); + props.setProperty( "handle", asr.getAssociationHandle() ); + props.setProperty( "publicKey", + Crypto.convertToString( asr.getDhServerPublic() ) ); + props.setProperty( "encryptedKey", + Crypto.convertToString( asr.getEncryptedMacKey() ) ); + + BigInteger privateKey = dh.getPrivateKey(); + props.setProperty( "privateKey", Crypto.convertToString( privateKey ) ); + props.setProperty( "modulus", + Crypto.convertToString( DiffieHellman.DEFAULT_MODULUS ) ); + + props.setProperty( "_dest", idserver ); + props.setProperty( "expiresIn", "" + asr.getExpiresIn() ); + + /* + Crypto crypto = new Crypto(); + dh = DiffieHellman.recreate(privateKey, p); + crypto.setDiffieHellman(dh); + byte[] clearKey = crypto.decryptSecret(asr.getDhServerPublic(), + asr.getEncryptedMacKey()); + System.out.println("Clear key: "+Crypto.convertToString(clearKey)); + */ + return props; + } + + + /** + *

+ * This method is used by a relying party to create the url to redirect a + * user to after entering their OpenId URL in a form. + *

+ *

+ * It will find the id server found at the OpenID url, associate with the + * server if necessary and return an authentication request url. + *

+ * + * @param identity users OpenID url + * @param returnTo the url to return to after user is finished with OpenId provider + * @param trustRoot base url that the authentication should apply to + * @return + * @throws OpenIdException + */ + public String getAuthUrl( String identity, String returnTo, String trustRoot ) + throws OpenIdException + { + + // find id server + ServerAndDelegate idserver = null; + try + { + //FIX ME is it required to do each authentication? maybe we can cache the idServer with association ! see the spec!!! + idserver = discoverer.findIdServer( identity ); + } + catch ( Exception e ) + { + e.printStackTrace(); + throw new OpenIdException( "Could not get OpenId server from " + + "identifier.", e ); + } + + Properties p = getProps( idserver.getServer() ); + String handle = p.getProperty( "handle" ); + + // todo: use delegate here, replace identity? + + AuthenticationRequest ar = AuthenticationRequest.create( identity, + returnTo, trustRoot, handle ); + + log.info( "urlString=" + ar.toUrlString() ); + + return idserver.getServer() + "?" + ar.toUrlString(); + } + + + /** + * This method will attempt to authenticate against the OpenID server. + * + * @param map + * @return openid.identity if authentication was successful, null if unsuccessful + * @throws IOException + * @throws OpenIdException + * @throws NoSuchAlgorithmException + */ + public AuthenticationResult authenticate( Map map ) + throws IOException, OpenIdException, NoSuchAlgorithmException + { + + log.debug( "request map in authenticate: " + map ); + AuthenticationResponse response = + new AuthenticationResponse( map ); + // @TODO: store nonce's to ensure we never accept the same value again - see sec 11.3 of spec 2.0 + Properties props; + if ( response.getInvalidateHandle() != null ) + { + // then we have to send a authentication_request (dumb mode) to verify the signature + CheckAuthenticationRequest checkReq = + new CheckAuthenticationRequest( response.toMap(), Mode.CHECK_AUTHENTICATION ); + props = getPropsByHandle( response.getInvalidateHandle() ); + CheckAuthenticationResponse response2 = ( CheckAuthenticationResponse ) + Util.send( checkReq, props.getProperty( "idServer" ) ); + // @TODO: verify the invalidate_handle in response2 is the same as in response + removeInvalidHandle( response.getInvalidateHandle() ); + if ( response2.isValid() ) + { + // then this is a valid request, lets send it back + return new AuthenticationResult( response.getIdentity(), response ); + } + else + { + throw new AuthenticationException( "Signature invalid, identity denied." ); + } + } + else + { + // normal properties + props = getPropsByHandle( response.getAssociationHandle() ); + + // todo: before returning a valid response, ensure return_to is a suburl of trust_root + + BigInteger privKey = Crypto.convertToBigIntegerFromString( props.getProperty( "privateKey" ) ); + BigInteger modulus = Crypto.convertToBigIntegerFromString( props.getProperty( "modulus" ) ); + BigInteger serverPublic = Crypto.convertToBigIntegerFromString( props.getProperty( "publicKey" ) ); + byte[] encryptedKey = Crypto.convertToBytes( props.getProperty( "encryptedKey" ) ); + + /* String sig = response.sign(response.getAssociationType(), + a.getMacKey(), response.getSignedList()); + isValid = sig.equals(response.getSignature()); + */ + DiffieHellman dh = DiffieHellman.recreate( privKey, modulus ); + Crypto crypto = new Crypto(); + crypto.setDiffieHellman( dh ); + byte[] clearKey = crypto.decryptSecret( serverPublic, encryptedKey ); + + String signature = response.getSignature(); + log.info( "Server's signature: " + signature ); + + String sigList = response.getSignedList(); + String reSigned = response.sign( clearKey, sigList ); + log.info( "Our signature: " + reSigned ); + String identity = response.getIdentity(); + if ( !signature.equals( reSigned ) ) + { + throw new AuthenticationException( "OpenID signatures do not match! " + + "claimed identity: " + identity ); + } + log.info( "Signatures match, identity is ok: " + identity ); + return new AuthenticationResult( identity, response ); + } + + } + + + /** + * If openid.invalidate_handle was received, this will remove it from our + * cache so it won't be used again. + * + * @param invalidateHandle + */ + private void removeInvalidHandle( String invalidateHandle ) + { + String idServer = ( String ) handleToIdServer.remove( invalidateHandle ); + if ( idServer != null ) + { + propSingleton.remove( idServer ); + } + } + +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/OpenIdFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/OpenIdFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/OpenIdFilter.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,202 @@ +package org.verisign.joid.consumer; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.verisign.joid.OpenIdRuntimeException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + + +/** + * This filter will log a user in automatically if it sees the required openid + * parameters in the request. + * + * User: treeder + * Date: Jun 8, 2007 + * Time: 6:50:15 PM + */ +public class OpenIdFilter implements Filter +{ + private static Log log = LogFactory.getLog( OpenIdFilter.class ); + private static JoidConsumer joid = new JoidConsumer(); + public static final String OPENID_ATTRIBUTE = "openid.identity"; // @TODO: remove one of these + public static final String OPENID_IDENTITY = OPENID_ATTRIBUTE; + boolean saveIdentityUrlAsCookie = false; + private String cookieDomain; + private List ignorePaths = new ArrayList(); + private static boolean configuredProperly = false; + private Integer cookieMaxAge; + + + public void init( FilterConfig filterConfig ) throws ServletException + { + log.info( "init OpenIdFilter" ); + String saveInCookie = filterConfig.getInitParameter( "saveInCookie" ); + if ( saveInCookie != null ) + { + saveIdentityUrlAsCookie = org.verisign.joid.util.Boolean.parseBoolean( saveInCookie ); + //saveIdentityUrlAsCookie = Boolean.parseBoolean(saveInCookie); + log.debug( "saving identities in cookie: " + saveIdentityUrlAsCookie ); + } + cookieDomain = filterConfig.getInitParameter( "cookieDomain" ); + String cookieMaxAgeString = filterConfig.getInitParameter( "cookieMaxAge" ); + if ( cookieMaxAgeString != null ) + { + cookieMaxAge = Integer.valueOf( cookieMaxAgeString ); + } + String ignorePaths = filterConfig.getInitParameter( "ignorePaths" ); + if ( ignorePaths != null ) + { + String paths[] = ignorePaths.split( "," ); + for ( int i = 0; i < paths.length; i++ ) + { + String path = paths[i].trim(); + this.ignorePaths.add( path ); + } + } + configuredProperly = true; + log.debug( "end init OpenIdFilter" ); + } + + + /** + * This is to check to make sure the OpenIdFilter is setup propertly in the + * web.xml. + */ + private static void ensureFilterConfiguredProperly() + { + if ( !configuredProperly ) + { + // log.warn("OpenIdFilter Not Configured Properly!"); + throw new OpenIdRuntimeException( + "OpenIdFilter Not Configured Properly! Check your web.xml for OpenIdFilter." ); + } + } + + + public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, + FilterChain filterChain ) throws IOException, ServletException + { + // basically just check for openId parameters + HttpServletRequest request = ( HttpServletRequest ) servletRequest; + if ( servletRequest.getParameter( OPENID_IDENTITY ) != null && !ignored( request ) ) + { + try + { + @SuppressWarnings("unchecked") + AuthenticationResult result = joid.authenticate( convertToStringValueMap( servletRequest + .getParameterMap() ) ); + String identity = result.getIdentity(); + if ( identity != null ) + { + HttpServletRequest req = ( HttpServletRequest ) servletRequest; + req.getSession( true ).setAttribute( OpenIdFilter.OPENID_ATTRIBUTE, identity ); + HttpServletResponse resp = ( HttpServletResponse ) servletResponse; // could check this before setting + Cookie cookie = new Cookie( OPENID_IDENTITY, identity ); + if ( cookieDomain != null ) + { + cookie.setDomain( cookieDomain ); + } + if ( cookieMaxAge != null ) + { + cookie.setMaxAge( cookieMaxAge.intValue() ); + } + resp.addCookie( cookie ); + // redirect to get rid of the long url + resp.sendRedirect( result.getResponse().getReturnTo() ); + return; + } + } + catch ( AuthenticationException e ) + { + e.printStackTrace(); + log.info( "auth failed: " + e.getMessage() ); + // should this be handled differently? + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + filterChain.doFilter( servletRequest, servletResponse ); + } + + + private boolean ignored( HttpServletRequest request ) + { + String servletPath = request.getServletPath(); + for ( int i = 0; i < ignorePaths.size(); i++ ) + { + String s = ignorePaths.get( i ); + if ( servletPath.startsWith( s ) ) + { + // System.out.println("IGNORING: " + servletPath); + return true; + } + } + return false; + } + + + public static void logout( HttpSession session ) + { + session.removeAttribute( OPENID_ATTRIBUTE ); + } + + + private Map convertToStringValueMap( Map parameterMap ) + { + Map ret = new HashMap(); + Set> set = parameterMap.entrySet(); + for ( Iterator> iter = set.iterator(); iter.hasNext(); ) + { + Map.Entry mapEntry = iter.next(); + String key = mapEntry.getKey(); + String[] value = mapEntry.getValue(); + ret.put( key, value[0] ); + } + return ret; + } + + + public void destroy() + { + + } + + + public static JoidConsumer joid() + { + return joid; + } + + + public static String getCurrentUser( HttpSession session ) + { + ensureFilterConfiguredProperly(); + String openid = ( String ) session.getAttribute( OpenIdFilter.OPENID_ATTRIBUTE ); + if ( openid != null ) + { + return openid; + } + // @TODO: THIS COOKIE THING CAN'T WORK BECAUSE SOMEONE COULD FAKE IT, NEEDS AN AUTH TOKEN ALONG WITH IT + return openid; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/ServerAndDelegate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/ServerAndDelegate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/ServerAndDelegate.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,43 @@ +package org.verisign.joid.consumer; + + +/** + * User: treeder + * Date: Jul 17, 2007 + * Time: 4:35:43 PM + */ +public class ServerAndDelegate +{ + private String server; + private String delegate; + + + public String getServer() + { + return server; + } + + + public void setServer( String server ) + { + this.server = server; + } + + + public String getDelegate() + { + return delegate; + } + + + public void setDelegate( String delegate ) + { + this.delegate = delegate; + } + + + public String toString() + { + return "ServerAndDelegate[server=" + server + ", delegate=" + delegate + "]"; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/Util.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/Util.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/Util.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,56 @@ +package org.verisign.joid.consumer; + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import org.verisign.joid.OpenIdException; +import org.verisign.joid.Request; +import org.verisign.joid.Response; +import org.verisign.joid.ResponseFactory; + + +public class Util +{ + public static Response send( Request req, String dest ) + throws IOException, OpenIdException + { + String toSend = req.toUrlString(); + StringBuffer b = new StringBuffer(); + + BufferedReader in = null; + try + { + // TODO: See reply/patch of Sergey: http://groups.google.com/group/joid-dev/browse_thread/thread/962cf46501ea660d + + URL url = new URL( dest + "?" + toSend ); + HttpURLConnection.setFollowRedirects( true ); + HttpURLConnection connection = ( HttpURLConnection ) url.openConnection(); + + in = new BufferedReader( new InputStreamReader( connection + .getInputStream() ) ); + String str; + int lines = 0; + while ( ( str = in.readLine() ) != null ) + { + b.append( str ); + b.append( '\n' ); + lines += 1; + } + if ( lines == 1 ) + { + // query string + b.deleteCharAt( b.length() - 1 ); + } + } + finally + { + if ( in != null ) + in.close(); + } + return ResponseFactory.parse( b.toString() ); + } + +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/XRDSDocument.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/XRDSDocument.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/XRDSDocument.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,35 @@ +package org.verisign.joid.consumer; + + +import java.util.List; +import java.util.ArrayList; + + +/** + * User: treeder + * Date: Oct 2, 2008 + * Time: 11:56:56 PM + */ +public class XRDSDocument +{ + // List + private List serviceList = new ArrayList(); + + + public List getServiceList() + { + return serviceList; + } + + + public void setServiceList( List serviceList ) + { + this.serviceList = serviceList; + } + + + public void addService( XRDSService service ) + { + serviceList.add( service ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/XRDSService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/XRDSService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/XRDSService.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,24 @@ +package org.verisign.joid.consumer; + + +/** + * User: treeder + * Date: Oct 3, 2008 + * Time: 12:08:11 AM + */ +public class XRDSService +{ + private String uri; + + + public void setUri( String uri ) + { + this.uri = uri; + } + + + public String getUri() + { + return uri; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/consumer/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/consumer/Attic/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/consumer/package.html 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,24 @@ + +Add Filter to web.xml + + + OpenIdFilter + org.verisign.joid.consumer.OpenIdFilter + + saveInCookie + true + Will store the identity url in a cookie under "openid.identity" if set to true. + + + cookieDomain + .mydomain.com + Domain to store cookie based on RFC 2109. + + + + + + OpenIdFilter + /* + + Index: 3rdParty_sources/joid/org/verisign/joid/extension/Extension.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/extension/Attic/Extension.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/extension/Extension.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,434 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid.extension; + + +import org.verisign.joid.OpenIdException; + +import java.io.Serializable; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; + + +/** + * Base class for OpenID extension information classes, with utility + * functions for getting and setting different parameter types. + */ +public class Extension implements Serializable +{ + private static final long serialVersionUID = 2222867117628997071L; + + /** + * RFC3339 date format + */ + private static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + /** + * Namespace for this extension (OpenID 2.0) + */ + protected String ns; + /** + * Preferred alias prefix for the extension parameters. + */ + protected String prefix; + /** + * The list of parameters, in a Map object. + */ + protected Map params; + + + /** + * Create an extension object with the namespace and prefix. This + * constructor is intended to be used to construct extension + * objects "from scratch" without parsing an existing message + * object. + * + * @param ns the extension namespace as a String value + * @param prefix the extension's prefix alias as a String value + */ + public Extension( String ns, String prefix ) + { + this.ns = ns; + this.prefix = prefix; + params = null; + } + + + /** + * Create an extension object with the namespace and prefix. This + * constructor is intended to be used to construct extension + * objects from parsing an existing message object. + * + * @param ns the extension namespace as a String value + * @param extensionMap extension parameters in Map form + */ + public Extension( String ns, Map extensionMap ) + { + this.ns = ns; + getParams( extensionMap ); + } + + + /** + * Extract parameters for the extension from the given OpenID + * parameter map based on the extension's namespace. + * + * @param extensionMap extension parameters in Map form + */ + public void getParams( Map extensionMap ) + { + params = null; + String prefix = getPrefix( extensionMap ); + if ( prefix == null ) + { + return; + } + this.prefix = prefix; + params = new HashMap(); + Iterator> it = extensionMap.entrySet().iterator(); + while ( it.hasNext() ) + { + Map.Entry mapEntry = it.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + if ( key.startsWith( prefix ) ) + { + params.put( key.substring( prefix.length() + 1 ), value ); + } + } + if ( params.isEmpty() ) + { + params = null; + } + } + + + /** + * Return whether the extension object has any parameters assigned + * to it. + * + * @return true if a parameter map exists + */ + public boolean isValid() + { + return params != null; + } + + + /** + * Returns whether there are any valid extension parameters in the + * given parameter map. + * + * @param extensionMap extension parameters in Map form + * @return true if there are parameters for this extension in the map + */ + public boolean isValid( Map extensionMap ) + { + return getPrefix( extensionMap ) != null; + } + + + /** + * Extract the extension's alias from the map. + * + * @param extensionMap a Map value + * @return alias String + */ + public String getPrefix( Map extensionMap ) + { + Iterator> it = extensionMap.entrySet().iterator(); + while ( it.hasNext() ) + { + Map.Entry mapEntry = it.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + if ( key.startsWith( "ns." ) && value.equals( ns ) ) + { + return key.substring( 3 ); + } + } + return null; + } + + + /** + * Remove extension parameter. + * + * @param name Parameter name + */ + public void clearParam( String name ) + { + if ( params != null ) + { + params.remove( name ); + } + } + + + /** + * Get String extension parameter value. + * + * @param name Parameter name + * @return value String + */ + public String getParam( String name ) + { + return ( String ) params.get( name ); + } + + + /** + * Set extension parameter's String value. + * + * @param name Parameter name + * @param value value String + */ + public void setParam( String name, String value ) + { + if ( params == null ) + { + params = new HashMap(); + } + params.put( name, value ); + } + + + /** + * Get Integer extension parameter value. + * + * @param name Parameter name + * @return value Integer + * @exception OpenIdException if the parameter was not a valid Integer + */ + public Integer getIntParam( String name ) throws OpenIdException + { + try + { + String paramStr = getParam( name ); + if ( paramStr != null ) + { + return new Integer( paramStr ); + } + return null; + } + catch ( NumberFormatException e ) + { + // invalid parameter value, throw a protocol error + throw new OpenIdException( "Invalid " + name + " parameter", e ); + } + } + + + /** + * Set extension parameter's Integer value. + * + * @param name Parameter name + * @param value value Integer + */ + public void setIntParam( String name, Integer value ) + { + setParam( name, value == null ? null : value.toString() ); + } + + + /** + * Get Date extension parameter value. + * + * @param name Parameter name + * @return value Date + * @exception OpenIdException if the parameter was not a valid Date + */ + public Date getDateParam( String name ) throws OpenIdException + { + SimpleDateFormat dateFormat = new SimpleDateFormat( DATE_FORMAT ); + dateFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); + try + { + String paramStr = getParam( name ); + if ( paramStr != null ) + { + return dateFormat.parse( paramStr.toUpperCase() ); + } + return null; + } + catch ( ParseException e ) + { + // invalid parameter value, throw a protocol error + throw new OpenIdException( "Invalid " + name + " parameter", e ); + } + } + + + /** + * Set extension parameter's Date value. + * + * @param name Parameter name + * @param value value Date + */ + public void setDateParam( String name, Date value ) + { + SimpleDateFormat dateFormat = new SimpleDateFormat( DATE_FORMAT ); + dateFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); + setParam( name, dateFormat.format( value ) ); + } + + + /** + * Get extension parameter's List value. + * + * @param name Parameter name + * @param separator Separation String between list values + * @return value List of Strings + */ + public List getListParam( String name, String separator ) + { + List paramList = new ArrayList(); + String paramStr = getParam( name ); + if ( paramStr != null ) + { + String[] paramArray = paramStr.split( separator ); + for ( int i = 0; i < paramArray.length; i++ ) + { + paramList.add( paramArray[i] ); + } + } + return paramList; + } + + + /** + * Get extension parameter's Set value. + * + * @param name Parameter name + * @param separator Separation String between set values + * @return value Set of Strings + */ + public Set getSetParam( String name, String separator ) + { + return new LinkedHashSet( getListParam( name, separator ) ); + } + + + /** + * Set an extension parameter with multiple values. + * + * @param name Parameter name + * @param paramList a Collection of String values + * @param separator Separation String between list values + */ + public void setListParam( String name, Collection paramList, String separator ) + { + StringBuffer paramStr = new StringBuffer( "" ); + Iterator it = paramList.iterator(); + while ( it.hasNext() ) + { + String param = it.next(); + paramStr.append( param ); + if ( it.hasNext() ) + { + paramStr.append( separator ); + } + } + setParam( name, paramStr.toString() ); + } + + + /** + * Returns a map containing all the extension parameter name value + * pairs. All parameter names are prefixed by the specified + * namespace alias. In addition, the namespace alias is defined in a + * name value pair of the form: + * ns.= + * + * @param nsSuffix the namespace alias for this extension + * @return a Map containing all extension parameters + */ + public Map getParamMap( String nsSuffix ) + { + if ( ( nsSuffix == null ) || ( nsSuffix.length() == 0 ) ) + { + throw new IllegalArgumentException( "Missing namespace alias for " + ns ); + } + + Map map = new HashMap(); + // add all non empty params with the openid.ns prefix + Iterator> it = params.entrySet().iterator(); + while ( it.hasNext() ) + { + Map.Entry mapEntry = it.next(); + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + if ( value != null ) + { + map.put( nsSuffix + "." + key, value ); + } + } + map.put( "ns." + nsSuffix, ns ); + return map; + } + + + /** + * Returns a map containing all the extension parameters with the + * namespace alias set to the current value. + * + * @return a Map containing all extension parameters + * @see #getParamMap(String) + */ + public Map getParamMap() + { + return getParamMap( prefix ); + } + + + /** + * Returns a simple string representation of the object. + * + * @return a String containing the extension properties + */ + public String toString() + { + StringBuffer sb = new StringBuffer( "" ); + sb.append( "[Extension " ).append( ns ).append( ", " ); + sb.append( "prefix=" ).append( prefix ).append( ", " ); + if ( params == null ) + { + sb.append( "No extension params" ); + } + else + { + Iterator it = params.keySet().iterator(); + while ( it.hasNext() ) + { + String key = it.next(); + sb.append( key ).append( "='" ).append( ( String ) params.get( key ) ).append( "'" ); + if ( it.hasNext() ) + { + sb.append( ", " ); + } + } + } + sb.append( "]" ); + return sb.toString(); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/extension/PapeConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/extension/Attic/PapeConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/extension/PapeConstants.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,44 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid.extension; + + +/** + * Provider Authentication Policy Extension constants from the + * specification. + */ +public interface PapeConstants +{ + /** + * PAPE namespace + */ + String PAPE_NAMESPACE = "http://specs.openid.net/extensions/pape/1.0"; + /** + * Preferred PAPE namespace identifier + */ + String PAPE_IDENTIFIER = "pape"; + + /** + * Phishing-Resistant authentication policy + */ + String AUTH_PHISHING_RESISTANT = "http://schemas.openid.net/pape/policies/2007/06/phishing-resistant"; + /** + * Multi-Factor authentication policy + */ + String AUTH_MULTI_FACTOR = "http://schemas.openid.net/pape/policies/2007/06/multi-factor"; + /** + * Physical Multi-Factor authentication policy + */ + String AUTH_PHYSICAL_MULTI_FACTOR = "http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical"; +} Index: 3rdParty_sources/joid/org/verisign/joid/extension/PapeRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/extension/Attic/PapeRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/extension/PapeRequest.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,383 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid.extension; + + +import org.verisign.joid.OpenIdException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Iterator; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + + +/** + * Provider Authentication Policy Extension request message. See the + * specification. + *

+ * Example of parsing incoming requests: + *

+ *     AuthenticationRequest ar = (AuthenticationRequest) req;
+ *     PapeRequest pr = new PapeRequest(ar.getExtensions());
+ *     if (pr.isValid()) {
+ *         ...
+ *     }
+ * }
+ * 
+ *

+ * + *

+ * Example of inserting PAPE request to an outgoing request: + *

+ * AuthenticationRequest ar = AuthenticationRequest.create(identity,
+ *                                                         returnTo,
+ *                                                         trustRoot,
+ *                                                         assocHandle);
+ * PapeRequest pr = new PapeRequest();
+ * pr.setMaxAuthAge(3600);
+ * ar.addExtension(pr);
+ * 
+ *

+ */ +public class PapeRequest extends Extension implements PapeConstants +{ + private static final long serialVersionUID = 5360473914710207818L; + + /** + * PAPE request parameter: If the End User has not actively + * authenticated to the OP within the number of seconds specified + * in a manner fitting the requested policies, the OP SHOULD + * authenticate the End User for this request. Value: Integer + * value greater than or equal to zero in seconds, and is + * optional. + */ + static String MAX_AUTH_AGE = "max_auth_age"; + /** + * PAPE request parameter: Zero or more authentication policy URIs + * that the OP SHOULD conform to when authenticating the user. If + * multiple policies are requested, the OP SHOULD satisfy as many + * as it can. + */ + static String PREFERRED_AUTH_POLICIES = "preferred_auth_policies"; + /** + * The name space for the custom Assurance Level. Assurance levels + * and their name spaces are defined by various parties, such as + * country or industry specific standards bodies, or other groups + * or individuals. + */ + static String AUTH_LEVEL_NS = "auth_level.ns."; + /** + * A list of the name space aliases for the custom Assurance Level + * name spaces that the RP requests be present in the response, in + * the order of its preference. + */ + static String PREFERRED_AUTH_LEVELS = "preferred_auth_level_types"; + + + /** + * Construct PapeRequest object with the correct + * namespace and an empty set of attributes. + * preferred_auth_policies is initialized to an empty + * string. + */ + public PapeRequest() + { + super( PAPE_NAMESPACE, PAPE_IDENTIFIER ); + // PREFERRED_AUTH_POLICIES is a mandatory parameter, default + // to none + setParam( PREFERRED_AUTH_POLICIES, "" ); + } + + + /** + * Construct PapeRequest object using the given + * parameter mappings. Get the extensionMap + * parameter from + * AuthenticationRequest.getExtensions. + * + * @param extensionMap a Map containing the parameter mappings + */ + public PapeRequest( Map extensionMap ) + { + super( PAPE_NAMESPACE, extensionMap ); + } + + + /** + * Retrieve the max_auth_age parameter. + * + * @return the maximum authentication age as an Integer value + * @exception OpenIdException if the parameter didn't parse to an integer + * @see #MAX_AUTH_AGE + */ + public Integer getMaxAuthAge() throws OpenIdException + { + return getIntParam( MAX_AUTH_AGE ); + } + + + /** + * Set the max_auth_age parameter with the given + * value. + * + * @param age maximum authentication age as an int value + * @see #MAX_AUTH_AGE + */ + public void setMaxAuthAge( int age ) + { + setMaxAuthAge( new Integer( age ) ); + } + + + /** + * Set the max_auth_age parameter with the given + * value. If null is specified as the value, the + * parameter will be removed. + * + * @param age maximum authentication age as an Integer value + * @see #MAX_AUTH_AGE + */ + public void setMaxAuthAge( Integer age ) + { + if ( age == null ) + { + // max_auth_age is optional, remove it if set to null + clearParam( MAX_AUTH_AGE ); + } + else + { + Integer minVal = new Integer( 0 ); + if ( age.compareTo( minVal ) < 0 ) + { + setIntParam( MAX_AUTH_AGE, minVal ); + } + else + { + setIntParam( MAX_AUTH_AGE, age ); + } + } + } + + + /** + * Retrieve the preferred_auth_policies parameter + * values. + * + * @return preferred authentication policies as a Set value + * @see #PREFERRED_AUTH_POLICIES + */ + public Set getPreferredAuthPolicies() + { + return getSetParam( PREFERRED_AUTH_POLICIES, " " ); + } + + + /** + * Set the preferred_auth_policies parameter with the + * given array of policy URI strings. Duplicate URIs will be + * discarded. + * + * @param policies a set of policy URIs as a String[] value + * @see #PREFERRED_AUTH_POLICIES + */ + public void setPreferredAuthPolicies( String[] policies ) + { + setPreferredAuthPolicies( new LinkedHashSet( Arrays.asList( policies ) ) ); + } + + + /** + * Set the preferred_auth_policies parameter with the + * given set of policy URI strings. + * + * @param policies a set of policy URIs as a Set value + * @see #PREFERRED_AUTH_POLICIES + */ + public void setPreferredAuthPolicies( Set policies ) + { + setListParam( PREFERRED_AUTH_POLICIES, policies, " " ); + } + + + /** + * Retrieve the auth_level_ns namespaces and values. + * + * @return namespaces as a Map + * @see #AUTH_LEVEL_NS + */ + Map getAuthLevelNS() + { + Map map = new HashMap(); + Iterator iter = getParamMap().keySet().iterator(); + while ( iter.hasNext() ) + { + String key = iter.next(); + int i = key.indexOf( AUTH_LEVEL_NS ); + if ( i >= 0 ) + { + key = key.substring( i ); + map.put( key.substring( AUTH_LEVEL_NS.length() ), getParam( key ) ); + } + } + return map; + } + + + /** + * Retrieve the auth_level_ns namespaces and values. + * + * @param namespace name of namespace + * @return namespace value + * @see #AUTH_LEVEL_NS + */ + String getAuthLevelNS( String namespace ) + { + return getParam( AUTH_LEVEL_NS + namespace ); + } + + + /** + * Set the auth_level_ns namespaces and values. + * + * @param authLevels a set of auth level namespaces as a Map + * @see #AUTH_LEVEL_NS + */ + void setAuthLevelNS( Map authLevels ) + { + Iterator iter = authLevels.keySet().iterator(); + while ( iter.hasNext() ) + { + String key = iter.next(); + addAuthLevelNS( key, ( String ) authLevels.get( key ) ); + } + } + + + /** + * Add an auth_level_ns namespace. + * + * @param namespace the name of the namespace + * @param value the value of the namespace's URL identifier + * @see #AUTH_LEVEL_NS + */ + void addAuthLevelNS( String namespace, String value ) + { + setParam( AUTH_LEVEL_NS + namespace, value ); + } + + + /** + * Retrieve the preferred_auth_levels parameter + * values. + * + * @return preferred authentication levels as a List value + * @see #PREFERRED_AUTH_LEVELS + */ + List getPreferredAuthLevelNSs() + { + return getListParam( PREFERRED_AUTH_LEVELS, " " ); + } + + + /** + * Set the preferred_auth_levels parameter with the + * given array of policy URI strings. Duplicate URIs will be + * discarded. + * + * @param levels a set of policy URIs as a String[] value + * @see #PREFERRED_AUTH_LEVELS + */ + void setPreferredAuthLevelNSs( String[] levels ) + { + setPreferredAuthLevels( new ArrayList( Arrays.asList( levels ) ) ); + } + + + /** + * Set the preferred_auth_levels parameter with the + * given set of policy URI strings. + * + * @param levels a list of policy namespaces ordered by preference as a List value + * @see #PREFERRED_AUTH_LEVELS + */ + void setPreferredAuthLevelNSs( List levels ) + { + setListParam( PREFERRED_AUTH_LEVELS, levels, " " ); + } + + + /** + * Retrieve the preferred_auth_levels parameter + * values, translated to the values in + * auth_level.ns.*. + * + * @return preferred authentication levels as a List value + * @see #PREFERRED_AUTH_LEVELS + * @see #AUTH_LEVEL_NS + */ + public List getPreferredAuthLevels() + { + Iterator it = getPreferredAuthLevelNSs().iterator(); + List levels = new ArrayList(); + while ( it.hasNext() ) + { + levels.add( getAuthLevelNS( ( String ) it.next() ) ); + } + return levels; + } + + + /** + * Set the preferred_auth_levels and + * auth_level.ns.* parameter with the given array of + * policy URI strings. Duplicate URIs will be discarded. + * + * @param levels a set of policy URIs as a String[] value + * @see #PREFERRED_AUTH_LEVELS + * @see #AUTH_LEVEL_NS + */ + public void setPreferredAuthLevels( String[] levels ) + { + setPreferredAuthLevels( new ArrayList( Arrays.asList( levels ) ) ); + } + + + /** + * Set the preferred_auth_levels and + * auth_level.ns.* parameter with the given ordered + * list of policy URI strings. + * + * @param levels a list of policy namespaces ordered by preference as a List value + * @see #PREFERRED_AUTH_LEVELS + * @see #AUTH_LEVEL_NS + */ + public void setPreferredAuthLevels( List levels ) + { + int i = 0; + List prefNS = new ArrayList(); + Iterator it = levels.iterator(); + while ( it.hasNext() ) + { + String level = it.next(); + String ns = "ns" + Integer.toString( i++, 16 ); + addAuthLevelNS( ns, level ); + prefNS.add( ns ); + } + setPreferredAuthLevelNSs( prefNS ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/extension/PapeResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/extension/Attic/PapeResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/extension/PapeResponse.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,494 @@ +// +// (C) Copyright 2007 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid.extension; + + +import org.verisign.joid.OpenIdException; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.LinkedHashSet; +import java.util.Iterator; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + + +/** + * Provider Authentication Policy Extension response message. See the + * specification. + *

+ * Example of parsing incoming responses: + *

+ * Response resp = ResponseFactory.parse(s);
+ * if (resp instanceof AuthenticationResponse) {
+ *     AuthenticationResponse ar = (AuthenticationResponse) resp;
+ *     PapeResponse pr = new PapeResponse(ar.getExtensions());
+ *     if (pr.isValid()) {
+ *         ...
+ *     }
+ * }
+ * 
+ *

+ * + *

+ * Example of inserting PAPE response to an outgoing reponse: + *

+ * Response resp = request.processUsing(serverInfo);
+ * if (resp instanceof AuthenticationResponse) {
+ *     AuthenticationResponse ar = (AuthenticationResponse)resp;
+ *     PapeResponse pr = new PapeResponse();
+ *     pr.setAuthAge(3600);
+ *     pr.setAuthPolicies(new String[] 
+ *         { "http://schemas.openid.net/pape/policies/2007/06/phishing-resistant",
+ *           "http://schemas.openid.net/pape/policies/2007/06/multi-factor",
+ *           "http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical" });
+ *     pr.setNistAuthLevel(4);
+ *     ar.addExtension(pr);
+ * }
+ * 
+ *

+ */ +public class PapeResponse extends Extension implements PapeConstants +{ + private static final long serialVersionUID = -4854806350672731345L; + + /** + * PAPE response parameter: One or more authentication policy URIs + * that the OP conformed to when authenticating the End User. If + * no policies were met though the OP wishes to convey other + * information in the response, this parameter MUST be included + * with the value of "none". + */ + static String AUTH_POLICIES = "auth_policies"; + static String EMPTY_AUTH_POLICIES = "http://schemas.openid.net/pape/policies/2007/06/none"; + /** + * PAPE response parameter: The most recent timestamp when the End + * User has actively authenticated to the OP in a manner fitting + * the asserted policies. If the RP's request included the + * "openid.max_auth_age" parameter then the OP MUST include + * "openid.auth_time" in its response. If "openid.max_auth_age" + * was not requested, the OP MAY choose to include + * "openid.auth_time" in its response. + */ + static String AUTH_TIME = "auth_time"; + /** + * The name space for the custom Assurance Level defined by + * various parties, such as a country or industry specific + * standards body, or other groups or individuals. + */ + static String AUTH_LEVEL_NS = "auth_level.ns."; + /** + * The Assurance Level as defined by the above standards body, + * group, or individual that corresponds to the authentication + * method and policies employed by the OP when authenticating the + * End User. + */ + static String AUTH_LEVEL_ASSURANCE = "auth_level."; + + + /** + * Creates a new PapeResponse instance with the + * correct namespace and an empty set of + * attributes. auth_policies is initialized to the + * empty value. + */ + public PapeResponse() + { + super( PAPE_NAMESPACE, PAPE_IDENTIFIER ); + // AUTH_POLICIES is a mandatory parameter + setParam( AUTH_POLICIES, EMPTY_AUTH_POLICIES ); + } + + + /** + * Creates a new PapeResponse instance using the + * given parameter mappings. Get the extensionMap + * parameter from + * AuthenticationResponse.getExtensions() + * + * @param extensionMap a Map containing the parameter mappings + */ + public PapeResponse( Map extensionMap ) + { + super( PAPE_NAMESPACE, extensionMap ); + } + + + /** + * Retrieve the auth_time parameter. + * + * @return the authentication age as a Date value + * @exception OpenIdException if the parameter didn't parse to a Date + * @see #AUTH_TIME + */ + public Date getAuthTime() throws OpenIdException + { + return getDateParam( AUTH_TIME ); + } + + + /** + * Set the auth_time parameter with the given value. + * + * @param age authentication age in seconds as an int value + * @see #AUTH_TIME + */ + public void setAuthTime( int age ) + { + Date now = new Date(); + long time = now.getTime(); + time -= age * 1000; // decrement time by age seconds + setAuthTime( new Date( time ) ); + } + + + /** + * Set the auth_time parameter with the given value. + * If null is specified as the value, the parameter + * will be removed. Remember to include auth_time in the response + * if it was in the request. + * + * @param age authentication age as a Date value + * @see #AUTH_TIME + */ + public void setAuthTime( Date authTime ) + { + if ( authTime == null ) + { + // auth_time is optional, remove it if set to null + clearParam( AUTH_TIME ); + } + else + { + setDateParam( AUTH_TIME, authTime ); + } + } + + + /** + * Retrieve the auth_policies parameter values. + * + * @return authentication policies as a Set value + * @see #AUTH_POLICIES + */ + public Set getAuthPolicies() + { + if ( getParam( AUTH_POLICIES ).equals( EMPTY_AUTH_POLICIES ) ) + { + return Collections.emptySet(); + } + return getSetParam( AUTH_POLICIES, " " ); + } + + + /** + * Set the auth_policies parameter with the given + * array of policy URI strings. Duplicate URIs will be discarded. + * + * @param policies a set of policy URIs as a String[] value + * @see #AUTH_POLICIES + */ + public void setAuthPolicies( String[] policies ) + { + setAuthPolicies( new LinkedHashSet( Arrays.asList( policies ) ) ); + } + + + /** + * Set the auth_policies parameter with the given set + * of policy URI strings. + * + * @param policies a set of policy URIs as a Set value + * @see #AUTH_POLICIES + */ + public void setAuthPolicies( Set policies ) + { + if ( policies.isEmpty() ) + { + setParam( AUTH_POLICIES, EMPTY_AUTH_POLICIES ); + } + else + { + setListParam( AUTH_POLICIES, policies, " " ); + } + } + + + /** + * Retrieve the auth_level_ns namespaces and values. + * + * @return namespaces as a Map + * @see #AUTH_LEVEL_NS + */ + Map getAuthLevelNS() + { + Map map = new HashMap(); + Iterator iter = getParamMap().keySet().iterator(); + while ( iter.hasNext() ) + { + String key = iter.next(); + int i = key.indexOf( AUTH_LEVEL_NS ); + if ( i >= 0 ) + { + key = key.substring( i ); + map.put( key.substring( AUTH_LEVEL_NS.length() ), getParam( key ) ); + } + } + return map; + } + + + /** + * Retrieve the auth_level_ns namespaces and values. + * + * @param namespace name of namespace + * @return namespace value + * @see #AUTH_LEVEL_NS + */ + String getAuthLevelNS( String namespace ) + { + return getParam( AUTH_LEVEL_NS + namespace ); + } + + + /** + * Set the auth_level_ns namespaces and values. + * + * @param authLevels a set of auth level namespaces as a Map + * @see #AUTH_LEVEL_NS + */ + void setAuthLevelNS( Map authLevels ) throws OpenIdException + { + Iterator iter = authLevels.keySet().iterator(); + while ( iter.hasNext() ) + { + String key = iter.next(); + addAuthLevelNS( key, authLevels.get( key ) ); + } + } + + + /** + * Add an auth_level_ns namespace. + * + * @param namespace the name of the namespace + * @param value the value of the namespace's URL identifier + * @see #AUTH_LEVEL_NS + */ + void addAuthLevelNS( String namespace, String value ) throws OpenIdException + { + if ( "ns".equals( namespace ) ) + { + throw new OpenIdException( "Invalid " + AUTH_LEVEL_NS + " parameter; \"ns\" not allowed" ); + } + setParam( AUTH_LEVEL_NS + namespace, value ); + } + + + /** + * Gets the base assurance level value for the given assurance + * level namespace alias. The base assurance level parameter is + * defined in section 5.2 as + * openid.pape.auth_level.. + * + * @param namespace assurance level URL namespace alias + * @return string value of the parameter + * @see #AUTH_LEVEL_ASSURANCE + */ + String getAuthNSAssuranceLevel( String namespace ) + { + return getAuthNSAssuranceLevel( namespace, null ); + } + + + /** + * Gets an additional assurance level parameter value for the + * given assurance level namespace alias. Additional assurance + * level parameters are defined in section 5.2 as + * openid.pape.auth_level... + * + * @param namespace assurance level URL namespace alias + * @param param the parameter name (if null, default to base parameter) + * @return string value of the parameter + * @see #AUTH_LEVEL_ASSURANCE + */ + String getAuthNSAssuranceLevel( String namespace, String param ) + { + String paramName = new String( AUTH_LEVEL_ASSURANCE + namespace ); + if ( param != null ) + { + paramName += "." + param; + } + return getParam( paramName ); + } + + + /** + * Set the base assurance level value for the given assurance + * level namespace alias. The base assurance level parameter is + * defined in section 5.2 as + * openid.pape.auth_level.. + * + * @param namespace assurance level URL + * @param value string defined according to this assurance level + * @see #AUTH_LEVEL_ASSURANCE + */ + void setAuthNSAssuranceLevel( String namespace, String value ) throws OpenIdException + { + setAuthNSAssuranceLevel( namespace, null, value ); + } + + + /** + * Sets an additional assurance level parameter value for the + * given assurance level namespace alias. Additional assurance + * level parameters are defined in section 5.2 as + * openid.pape.auth_level... + * + * @param namespace assurance level URL + * @param param the parameter name (if null, default to base parameter) + * @param value string defined according to this assurance level + * @see #AUTH_LEVEL_ASSURANCE + */ + void setAuthNSAssuranceLevel( String namespace, String param, String value ) throws OpenIdException + { + if ( "ns".equals( namespace ) ) + { + throw new OpenIdException( "Invalid " + AUTH_LEVEL_NS + " parameter; \"ns\" not allowed" ); + } + String paramName = new String( AUTH_LEVEL_ASSURANCE + namespace ); + if ( param != null ) + { + paramName += "." + param; + } + setParam( paramName, value ); + } + + + /** + * Gets the base assurance level value for the given assurance + * level namespace URL. The base assurance level parameter is + * defined in section 5.2 as + * openid.pape.auth_level.. + * + * @param namespace assurance level URL + * @return string value of the parameter + * @see #AUTH_LEVEL_ASSURANCE + */ + public String getAuthAssuranceLevel( String namespace ) + { + return getAuthAssuranceLevel( namespace, null ); + } + + + /** + * Gets an additional assurance level parameter value for the + * given assurance level namespace URL. Additional assurance + * level parameters are defined in section 5.2 as + * openid.pape.auth_level... + * + * @param namespace assurance level URL + * @param param the parameter name (if null, default to base parameter) + * @return string value of the parameter + * @see #AUTH_LEVEL_ASSURANCE + */ + public String getAuthAssuranceLevel( String namespace, String param ) + { + Map nsmap = getAuthLevelNS(); + Iterator> it = nsmap.entrySet().iterator(); + while ( it.hasNext() ) + { + Map.Entry entry = it.next(); + if ( namespace.equals( entry.getValue() ) ) + { + return getAuthNSAssuranceLevel( entry.getKey(), param ); + } + } + return null; + } + + + /** + * Set the base assurance level value for the given assurance + * level namespace URL. The base assurance level parameter is + * defined in section 5.2 as + * openid.pape.auth_level.. This method will + * define a namespace alias for the URL if one is not already + * defined. + * + * @param namespace assurance level URL + * @param value string defined according to this assurance level + * @see #AUTH_LEVEL_ASSURANCE + */ + public void setAuthAssuranceLevel( String namespace, String value ) throws OpenIdException + { + setAuthAssuranceLevel( namespace, null, value ); + } + + + /** + * Sets an additional assurance level parameter value for the + * given assurance level namespace URL. Additional assurance + * level parameters are defined in section 5.2 as + * openid.pape.auth_level... + * This method will define a namespace alias for the URL if one is + * not already defined. + * + * @param namespace assurance level URL + * @param param the parameter name (if null, default to base parameter) + * @param value string defined according to this assurance level + * @see #AUTH_LEVEL_ASSURANCE + */ + public void setAuthAssuranceLevel( String namespace, String param, String value ) throws OpenIdException + { + Map nsmap = getAuthLevelNS(); + Iterator> it = nsmap.entrySet().iterator(); + while ( it.hasNext() ) + { + Map.Entry entry = it.next(); + if ( namespace.equals( entry.getValue() ) ) + { + setAuthNSAssuranceLevel( entry.getKey(), param, value ); + return; + } + } + int i = 0; + String ns; + do + { + ns = "ns" + Integer.toString( i++, 16 ); + } + while ( nsmap.keySet().contains( ns ) && ( i < Integer.MAX_VALUE ) ); + if ( i == Integer.MAX_VALUE ) + { + throw new OpenIdException( "Couldn't find a free namespace" ); + } + addAuthLevelNS( ns, namespace ); + setAuthNSAssuranceLevel( ns, param, value ); + } + + + /** + * Retrieve a set containing all of the defined assurance level + * namespace URLs. + * + * @return assurance level URLs as a Set value + */ + public Set getAuthAssuranceLevelSet() + { + return new LinkedHashSet( getAuthLevelNS().values() ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/extension/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/extension/Attic/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/extension/package.html 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,72 @@ + + + +The JOID OpenID extensions package. + +This package contains code for OpenID extensions, and provides a +convenient base class to derive extensions from. + +

+To make use of the extensions classes, use the +getExtensions and addExtension methods in +the AuthenticationRequest and +AuthenticationResponse classes. Validate that the +extension exists using the Extension.isValid method. +

+ +

+Example of parsing incoming requests or responses: +

+Request req = RequestFactory.parse(s);
+if (req instanceof AuthenticationRequest) {
+    AuthenticationRequest ar = (AuthenticationRequest) req;
+    PapeRequest pr = new PapeRequest(ar.getExtensions());
+    if (pr.isValid()) {
+        ...
+    }
+}
+
+and +
+Response resp = ResponseFactory.parse(s);
+if (resp instanceof AuthenticationResponse) {
+    AuthenticationResponse ar = (AuthenticationResponse) resp;
+    PapeResponse pr = new PapeResponse(ar.getExtensions());
+    if (pr.isValid()) {
+        ...
+    }
+}
+
+

+ +

+Example of submitting extensions to outgoing requests or responses: +

+AuthenticationRequest ar = AuthenticationRequest.create(identity,
+                                                        returnTo,
+                                                        trustRoot,
+                                                        assocHandle);
+PapeRequest pr = new PapeRequest();
+pr.setMaxAuthAge(3600);
+ar.addExtension(pr);
+
+and +
+Response resp = request.processUsing(serverInfo);
+if (resp instanceof AuthenticationResponse) {
+    AuthenticationResponse ar = (AuthenticationResponse)resp;
+    PapeResponse pr = new PapeResponse();
+    pr.setAuthAge(3600);
+    pr.setAuthPolicies(new String[] 
+        { "http://schemas.openid.net/pape/policies/2007/06/phishing-resistant",
+          "http://schemas.openid.net/pape/policies/2007/06/multi-factor",
+          "http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical" });
+    pr.setNistAuthLevel(4);
+    ar.addExtension(pr);
+}
+
+

+ + + + Index: 3rdParty_sources/joid/org/verisign/joid/handlers/AssociationRequestDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/AssociationRequestDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/AssociationRequestDecoder.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.verisign.joid.handlers; + +import org.verisign.joid.AssociationRequest; +import org.verisign.joid.AssociationType; +import org.verisign.joid.Crypto; +import org.verisign.joid.OpenIdConstants; +import org.verisign.joid.SessionType; + +/** + * TODO AssociationRequestDecoder. + * + * @author Birkan Duman + */ +public class AssociationRequestDecoder extends MessageDecoder +{ + @Override + public void decode( DecoderContext context ) + { + super.decode( context ); + + AssociationRequest message = context.getMessage(); + + message.setSessionType( SessionType.parse( context.getMap().get( OpenIdConstants.OPENID_SESSION_TYPE ) ) ); + message.setAssociationType( AssociationType.parse( context.getMap().get( OpenIdConstants.OPENID_ASSOCIATION_TYPE ) ) ); + message.setDhModulus( Crypto.convertToBigIntegerFromString( context.getMap().get( OpenIdConstants.OPENID_DH_MODULUS ) ) ); + message.setDhGenerator( Crypto.convertToBigIntegerFromString( context.getMap().get( OpenIdConstants.OPENID_DH_GENERATOR ) ) ); + message.setDhConsumerPublic( Crypto.convertToBigIntegerFromString( context.getMap().get( OpenIdConstants.OPENID_DH_CONSUMER_PUBLIC ) ) ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/AssociationRequestEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/AssociationRequestEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/AssociationRequestEncoder.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.verisign.joid.AssociationRequest; +import org.verisign.joid.OpenIdConstants; +import org.verisign.joid.OpenIdException; + + +/** + * An encoder for AssociationRequests. + * + * @author Alex Karasulu + */ +public final class AssociationRequestEncoder extends MessageEncoder +{ + private final static Logger LOG = LoggerFactory.getLogger( AssociationRequestEncoder.class ); + + + public final StringBuilder encode( AssociationRequest message, EncodingMode mode, StringBuilder sb ) throws OpenIdException + { + if ( sb == null ) + { + sb = new StringBuilder(); + } + else + { + if ( sb.charAt( sb.length() - 1 ) != mode.getNewLine() ) + { + sb.append( mode.getNewLine() ); + } + } + + super.encode( message, mode, sb ); + + // append the session type + sb.append( OpenIdConstants.OPENID_SESSION_TYPE ); + sb.append( mode.getKvDelim() ); + sb.append( message.getSessionType().toString() ); + sb.append( mode.getNewLine() ); + + // append the association type + sb.append( OpenIdConstants.OPENID_ASSOCIATION_TYPE ); + sb.append( mode.getKvDelim() ); + sb.append( message.getAssociationType().toString() ); + sb.append( mode.getNewLine() ); + + // append the consumer's DH public key as a string + sb.append( OpenIdConstants.OPENID_DH_CONSUMER_PUBLIC ); + sb.append( mode.getKvDelim() ); + if ( mode == EncodingMode.URL_STRING ) + { + sb.append( message.getDhConsumerPublicString() ); + } + else + { + try + { + sb.append( URLEncoder.encode( message.getDhConsumerPublicString(), "UTF-8" ) ); + } + catch ( UnsupportedEncodingException e ) + { + String msg = "Failed to URL encode the " + OpenIdConstants.OPENID_DH_CONSUMER_PUBLIC + + " key's value of '" + message.getDhConsumerPublicString() + "'"; + LOG.error( msg, e ); + throw new OpenIdException( msg, e ); + } + } + + return sb; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/Decoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/Decoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/Decoder.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + + +import org.verisign.joid.Message; + + +/** + * A {@link Message} decoder. + * + * @author Alex Karasulu + */ +public interface Decoder +{ + void decode( DecoderContext context ); +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/DecoderContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/DecoderContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/DecoderContext.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.verisign.joid.Message; +import org.verisign.joid.MessageParser; +import org.verisign.joid.OpenIdException; + + +/** + * A context used to store information while decoding. + * + * @author Alex Karasulu + */ +public class DecoderContext +{ + private static final Logger LOG = LoggerFactory.getLogger( DecoderContext.class ); + + private final EncodingMode mode; + private final String query; + + private E message; + private Map map; + + + public DecoderContext( String query, EncodingMode mode ) throws OpenIdException + { + this.query = query; + this.mode = mode; + + if ( mode == EncodingMode.URL_STRING ) + { + try + { + this.map = MessageParser.urlEncodedToMap( query ); + } + catch ( UnsupportedEncodingException e ) + { + String msg = "Could not parse query string: '" + query + "'"; + LOG.error( msg, e ); + throw new OpenIdException( msg, e ); + } + } + else + { + try + { + this.map = MessageParser.postedToMap( query ); + } + catch ( IOException e ) + { + String msg = "Could not parse query string: '" + query + "'"; + LOG.error( msg, e ); + throw new OpenIdException( msg, e ); + } + } + } + + + public EncodingMode getEncodingMode() + { + return mode; + } + + + public E getMessage() + { + return message; + } + + + public void setMessage( E message ) + { + this.message = message; + } + + + public String getQuery() + { + return query; + } + + + public Map getMap() + { + return map; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/Encoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/Encoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/Encoder.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + +import org.verisign.joid.Message; +import org.verisign.joid.OpenIdException; + + +/** + * Encodes a specific OpenID {@link Message} type directly into a query string. + * + * @author Alex Karasulu + */ +public interface Encoder +{ + StringBuilder encode( E message, EncodingMode mode, StringBuilder sb ) throws OpenIdException; +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/EncodingMode.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/EncodingMode.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/EncodingMode.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + + +/** + * The mode of query string encoding used. + * + * @author Birkan Duman + * @author Alex Karasulu + */ +public enum EncodingMode +{ + URL_STRING( '=', '&' ), POST_STRING( ':', '\n' ); + + + private final char kvDelim; + private final char newLine; + + + private EncodingMode( char kvDelim, char newLine ) + { + this.kvDelim = kvDelim; + this.newLine = newLine; + } + + + public char getKvDelim() + { + return kvDelim; + } + + + public char getNewLine() + { + return newLine; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/MessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/MessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/MessageDecoder.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + + +import org.verisign.joid.Message; +import org.verisign.joid.Mode; +import org.verisign.joid.OpenIdConstants; + + +/** + * TODO MessageDecoder. + * + * @author Alex Karasulu + */ +public class MessageDecoder implements Decoder +{ + public void decode( DecoderContext context ) + { + E message = context.getMessage(); + + message.setMode( Mode.parse( context.getMap().get( OpenIdConstants.OPENID_MODE ) ) ); + message.setNamespace( context.getMap().get( OpenIdConstants.OPENID_NS ) ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/MessageEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/MessageEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/MessageEncoder.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.verisign.joid.Message; +import org.verisign.joid.OpenIdConstants; +import org.verisign.joid.OpenIdException; + + +/** + * An encoder for general messages adding their common attributes to the query + * string. + * + * @author Birkan Duman + * @author Alex Karasulu + */ +public class MessageEncoder implements Encoder +{ + private static final Logger LOG = LoggerFactory.getLogger( MessageEncoder.class ); + + + /** + * {@inheritDoc} + * @throws OpenIdException + */ + public StringBuilder encode( E message, EncodingMode mode, StringBuilder sb ) throws OpenIdException + { + if ( sb == null ) + { + sb = new StringBuilder(); + } + else + { + if ( sb.charAt( sb.length() - 1 ) != mode.getNewLine() ) + { + sb.append( mode.getNewLine() ); + } + } + + // append the openid.mode key value pair + sb.append( OpenIdConstants.OPENID_MODE ).append( mode.getKvDelim() ).append( message.getMode().toString() ); + sb.append( mode.getNewLine() ); + + // append the openid.ns key value pair + sb.append( OpenIdConstants.OPENID_NS ).append( mode.getKvDelim() ); + if ( mode == EncodingMode.POST_STRING ) + { + sb.append( message.getNamespace() ); + } + else + { + if ( message.isVersion2() ) + { + sb.append( OpenIdConstants.ENCODED_NS_VERSION2 ); + } + else + { + try + { + sb.append( URLEncoder.encode( message.getNamespace(), "UTF-8" ) ); + } + catch ( UnsupportedEncodingException e ) + { + LOG.error( "This error to decode pre-set URL should never fail.", e ); + } + } + } + + return sb; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/RequestHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/RequestHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/RequestHandler.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + + +import org.verisign.joid.Request; +import org.verisign.joid.Response; + + +/** + * JOID message handlers are involved with the implementation logic of various + * OpenID messages (openid.mode). They are not involved with [de]marshalling + * which is the responsibility of the codec. Handlers are registered with the + * codec, to deal with handling specific messages when they are decode. + * + * @author Alex Karasulu + */ +public interface RequestHandler +{ + P handle( Q request ); +} Index: 3rdParty_sources/joid/org/verisign/joid/handlers/ResponseHandler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/handlers/Attic/ResponseHandler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/handlers/ResponseHandler.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.verisign.joid.handlers; + + +import org.verisign.joid.Response; + + +/** + * Handler to deal with responses. + * + * @author Alex Karasulu + */ +public interface ResponseHandler

+{ + void handle( P request ); +} Index: 3rdParty_sources/joid/org/verisign/joid/server/Association.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/server/Attic/Association.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/server/Association.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,233 @@ +package org.verisign.joid.server; + + +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.verisign.joid.AssociationType; +import org.verisign.joid.Crypto; +import org.verisign.joid.SessionType; + +import java.util.Date; +import java.util.Calendar; +import java.math.BigInteger; +import java.text.SimpleDateFormat; + + +/** + * An OpenID Association implementation. + */ +public class Association implements org.verisign.joid.IAssociation +{ + + private final static Log log = LogFactory.getLog( Association.class ); + private Long id; + private String handle; + private String secret; + private Date issuedDate; + private Long lifetime; + private AssociationType at = AssociationType.HMAC_SHA1; + + // Not in db + private String error; + private SessionType sessionType; + private byte[] encryptedMacKey; + private BigInteger publicKey; + + + public boolean isSuccessful() + { + return ( error == null ); + } + + + public boolean isEncrypted() + { + return SessionType.DH_SHA1 == sessionType || SessionType.DH_SHA256 == sessionType; + } + + + /** + * Hibernate mapping. + */ + public Long getId() + { + return id; + } + + + /** Hibernate mapping. */ + public String getSecret() + { + return secret; + } + + + /** Hibernate mapping. */ + public void setSecret( String secret ) + { + this.secret = secret; + } + + + /** Hibernate mapping. */ + public void setId( Long id ) + { + this.id = id; + } + + + /** Hibernate mapping. */ + public String getHandle() + { + return handle; + } + + + /** Hibernate mapping. */ + public void setHandle( String s ) + { + this.handle = s; + } + + + /** Hibernate mapping. */ + public Date getIssuedDate() + { + return issuedDate; + } + + + /** Hibernate mapping. */ + public void setIssuedDate( Date issuedDate ) + { + SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); + Date tmp = issuedDate; + sdf.format( tmp ); + this.issuedDate = tmp; + } + + + public Long getLifetime() + { + return lifetime; + } + + + /** + * + * @param lifetime in seconds for this association. Expires after. + */ + public void setLifetime( Long lifetime ) + { + this.lifetime = lifetime; + } + + + public AssociationType getAssociationType() + { + return at; + } + + + public void setAssociationType( AssociationType s ) + { + this.at = s; + } + + + /** + * Returns a string representation of this Association. + * + * @return a string representation of this Association. + */ + public String toString() + { + String s = "[Association secret=" + secret; + if ( encryptedMacKey != null ) + { + s += ", encrypted secret=" + Crypto.convertToString( encryptedMacKey ); + } + if ( publicKey != null ) + { + s += ", public key=" + Crypto.convertToString( publicKey ); + } + s += ", type=" + at + ", issuedDate=" + issuedDate + "]"; + return s; + } + + + public String getError() + { + return error; + } + + + public String getErrorCode() + { + throw new RuntimeException( "nyi" ); + } + + + public void setSessionType( SessionType sessionType ) + { + this.sessionType = sessionType; + } + + + public SessionType getSessionType() + { + return sessionType; + } + + + /** Hibernate mapping. */ + public void setMacKey( byte[] macKey ) + { + this.secret = Crypto.convertToString( macKey ); + } + + + /** Hibernate mapping. */ + public byte[] getMacKey() + { + return Crypto.convertToBytes( secret ); + } + + + public void setEncryptedMacKey( byte[] b ) + { + encryptedMacKey = b; + } + + + public byte[] getEncryptedMacKey() + { + return encryptedMacKey; + } + + + public void setPublicDhKey( BigInteger pk ) + { + publicKey = pk; + } + + + public BigInteger getPublicDhKey() + { + return publicKey; + } + + + public boolean hasExpired() + { + Calendar now = Calendar.getInstance(); + log.debug( "now: " + now.toString() ); + Calendar expired = Calendar.getInstance(); + log.debug( "issuedDate: " + issuedDate.toString() ); + expired.setTime( issuedDate ); + expired.add( Calendar.SECOND, lifetime.intValue() ); + log.debug( "expired: " + expired.toString() ); + log.debug( "now.after(expired): " + now.after( expired ) ); + return now.after( expired ); + } +} Index: 3rdParty_sources/joid/org/verisign/joid/server/MemoryStore.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/server/Attic/MemoryStore.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/server/MemoryStore.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,121 @@ +package org.verisign.joid.server; + + +import org.verisign.joid.IAssociation; +import org.verisign.joid.AssociationRequest; +import org.verisign.joid.Crypto; +import org.verisign.joid.INonce; +import org.verisign.joid.OpenIdException; +import org.verisign.joid.IStore; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.ListIterator; + + +public class MemoryStore implements IStore +{ + public static long DEFAULT_LIFESPAN = 300; // @TODO: should probably increase this + private static List associationList = new ArrayList(); + private static List nonceList = new ArrayList(); + private long associationLifetime = DEFAULT_LIFESPAN; + + + public IAssociation generateAssociation( AssociationRequest req, Crypto crypto ) + throws OpenIdException + { + // boldly reusing the db implementation of Association + Association a = new Association(); + a.setHandle( Crypto.generateHandle() ); + a.setSessionType( req.getSessionType() ); + + byte[] secret = null; + if ( req.isNotEncrypted() ) + { + secret = crypto.generateSecret( req.getAssociationType().toString() ); + } + else + { + secret = crypto.generateSecret( req.getSessionType().toString() ); + crypto.setDiffieHellman( req.getDhModulus(), req.getDhGenerator() ); + byte[] encryptedSecret = crypto.encryptSecret( req.getDhConsumerPublic(), secret ); + a.setEncryptedMacKey( encryptedSecret ); + a.setPublicDhKey( crypto.getPublicKey() ); + } + a.setMacKey( secret ); + a.setIssuedDate( new Date() ); + a.setLifetime( new Long( associationLifetime ) ); + + a.setAssociationType( req.getAssociationType() ); + return a; + } + + + public void saveAssociation( IAssociation a ) + { + associationList.add( a ); + } + + + public void saveNonce( INonce n ) + { + nonceList.add( n ); + } + + + public void deleteAssociation( IAssociation a ) + { + throw new RuntimeException( "not yet implemented" ); + // "associationList.delete(a)" + } + + + public IAssociation findAssociation( String handle ) throws OpenIdException + { + if ( handle == null ) + return null; + ListIterator li = associationList.listIterator(); + while ( li.hasNext() ) + { + IAssociation a = li.next(); + if ( handle.equals( a.getHandle() ) ) + { + return a; + } + } + return null; + } + + + public INonce findNonce( String nonce ) throws OpenIdException + { + if ( nonce == null ) + return null; + ListIterator li = nonceList.listIterator(); + while ( li.hasNext() ) + { + INonce n = li.next(); + if ( nonce.equals( n.getNonce() ) ) + { + return n; + } + } + return null; + } + + + public INonce generateNonce( String nonce ) throws OpenIdException + { + Nonce n = new Nonce(); + n.setNonce( nonce ); + n.setCheckedDate( new Date() ); + return n; + } + + + public void setAssociationLifetime( long associationLifetime ) + { + this.associationLifetime = associationLifetime; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/server/MemoryUserManager.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/server/Attic/MemoryUserManager.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/server/MemoryUserManager.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,70 @@ +package org.verisign.joid.server; + + +import java.util.HashMap; +import java.util.Map; + + +/** + * User: treeder + * Date: Jul 17, 2007 + * Time: 5:33:31 PM + */ +public class MemoryUserManager implements UserManager +{ + private Map userMap = new HashMap(); + private Map rememberMeMap = new HashMap(); + + + public User getUser( String username ) + { + return ( User ) userMap.get( username ); + } + + + public void save( User user ) + { + userMap.put( user.getUsername(), user ); + } + + + public void remember( String username, String authKey ) + { + rememberMeMap.put( username, authKey ); + } + + + public String getRememberedUser( String username, String authKey ) + { + if ( username == null || authKey == null ) + return null; + String auth = ( String ) rememberMeMap.get( username ); + if ( auth != null ) + { + if ( authKey.equals( auth ) ) + { + // then we have a match + return username; + } + } + return null; + } + + + /** + * + * + * @param username + * @param claimedId + * @return + */ + public boolean canClaim( String username, String claimedId ) + { + String usernameFromClaimedId = claimedId.substring( claimedId.lastIndexOf( "/" ) + 1 ); + if ( username.equals( usernameFromClaimedId ) ) + { + return true; + } + return false; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/server/Nonce.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/server/Attic/Nonce.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/server/Nonce.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,97 @@ +package org.verisign.joid.server; + + +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.verisign.joid.INonce; + + +/** + * A simple Nonce implementation. + * + * @TODO Remove hibernate residue and fix the damn javadocs. + */ +public class Nonce implements INonce +{ + private Long id; + private String nonce; + private Date checkedDate; + + + /** + * Hibernate mapping. + * + * @TODO Why in the world would the hibernate mapping key be + * exposed in the primary object? This is something that should + * be removed. + */ + public Long getId() + { + return id; + } + + + /** Hibernate mapping. */ + public void setId( Long id ) + { + this.id = id; + } + + + /** Hibernate mapping. */ + public String getNonce() + { + return nonce; + } + + + /** Hibernate mapping. */ + public void setNonce( String s ) + { + nonce = s; + } + + + /** Hibernate mapping. */ + public Date getCheckedDate() + { + return checkedDate; + } + + + /** + * Set's the checkedDate property by cloning the date. + */ + public void setCheckedDate( Date date ) + { + this.checkedDate = ( Date ) date.clone(); + } + + + /** + * Original flawed setter which used simple date format parsing and looses + * the milliseconds argument which is used in LDAP timestamps. + * + * @deprecated + * @TODO - confirm no issues with replacing this then delete this method + */ + public void _setCheckedDate( Date date ) + { + SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); + Date tmp = date; + sdf.format( tmp ); + this.checkedDate = tmp; + } + + + /** + * Returns a string representation of this Nonce. + * + * @return a string representation of this Nonce. + */ + public String toString() + { + return "[Nonce nonce=" + nonce + ", checked=" + checkedDate + "]"; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/server/OpenIdServlet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/server/Attic/OpenIdServlet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/server/OpenIdServlet.java 17 Aug 2012 14:55:11 -0000 1.1 @@ -0,0 +1,362 @@ +package org.verisign.joid.server; + + +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.verisign.joid.AuthenticationRequest; +import org.verisign.joid.Crypto; +import org.verisign.joid.InvalidOpenIdQueryException; +import org.verisign.joid.OpenId; +import org.verisign.joid.OpenIdException; +import org.verisign.joid.RequestFactory; +import org.verisign.joid.ServerInfo; +import org.verisign.joid.IStore; +import org.verisign.joid.StoreFactory; +import org.verisign.joid.util.CookieUtils; +import org.verisign.joid.util.DependencyUtils; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.util.Enumeration; +import java.util.Map; + + +/** + * User: treeder + * Date: Jul 18, 2007 + * Time: 4:50:33 PM + */ +public class OpenIdServlet extends HttpServlet +{ + private static Log log = LogFactory.getLog( OpenIdServlet.class ); + private static final long serialVersionUID = 297366254782L; + private static OpenId openId; + private IStore store; + private Crypto crypto; + private String loginPage; + public static final String USERNAME_ATTRIBUTE = "username"; + public static final String ID_CLAIMED = "idClaimed"; + public static final String QUERY = "query"; + public static final String COOKIE_AUTH_NAME = "authKey"; + public static final String COOKIE_USERNAME = "username"; + private static UserManager userManager; + + public void init( ServletConfig config ) throws ServletException + { + super.init( config ); + String storeClassName = config.getInitParameter( "storeClassName" ); + String userManagerClassName = config.getInitParameter( "userManagerClassName" ); + store = StoreFactory.getInstance( storeClassName ); + MemoryStore mStore = ( MemoryStore ) store; + mStore.setAssociationLifetime( 600 ); + userManager = ( UserManager ) DependencyUtils.newInstance( userManagerClassName ); + crypto = new Crypto(); + loginPage = config.getInitParameter( "loginPage" ); + String endPointUrl = config.getInitParameter( "endPointUrl" ); + openId = new OpenId( new ServerInfo( endPointUrl, store, crypto ) ); + } + + public void doGet( HttpServletRequest request, + HttpServletResponse response ) + throws ServletException, IOException + { + doQuery( request.getQueryString(), request, response ); + } + + public void doPost( HttpServletRequest request, + HttpServletResponse response ) + throws ServletException, IOException + { + + doQuery( populateQueryStringFromPost( request ), request, response ); + } + + public void doQuery( String queryString, + HttpServletRequest request, HttpServletResponse response ) + throws ServletException, IOException + { + + log.info( queryString ); + +// if ( !( openId.canHandle( queryString ) ) ) +// { +// returnError( queryString, response ); +// return; +// } + + try + { + boolean isAuth = openId.isAuthenticationRequest( queryString ); + + HttpSession session = request.getSession( true ); + + String user = getLoggedIn( request ); + + if ( request.getParameter( AuthenticationRequest.OPENID_TRUST_ROOT ) != null ) + { + session.setAttribute( + AuthenticationRequest.OPENID_TRUST_ROOT, + request.getParameter( AuthenticationRequest.OPENID_TRUST_ROOT ) ); + } + if ( request.getParameter( AuthenticationRequest.OPENID_RETURN_TO ) != null ) + { + session.setAttribute( + AuthenticationRequest.OPENID_RETURN_TO, + request.getParameter( AuthenticationRequest.OPENID_RETURN_TO ) ); + } + + if ( isAuth ) + { + if ( user == null ) + { + //if we fall here, then a relying party redirected to this provider with a get request, so we are setting required session attributes and redirecting the user to our login page + + // @TODO: should ask user to accept realm even if logged in, but only once + // ask user to accept this realm + request.setAttribute( QUERY, queryString ); + request.setAttribute( AuthenticationRequest.OPENID_REALM, + request.getParameter( AuthenticationRequest.OPENID_REALM ) ); + session.setAttribute( QUERY, queryString ); + //if claimed_id is null then use identity instead (because of diffs between v2 & v1 of spec) + if ( request.getParameter( AuthenticationRequest.OPENID_CLAIMED_ID ) == null ) + { + session.setAttribute( + AuthenticationRequest.OPENID_CLAIMED_ID, + request.getParameter( AuthenticationRequest.OPENID_IDENTITY ) ); + } + else + { + session.setAttribute( + AuthenticationRequest.OPENID_CLAIMED_ID, + request.getParameter( AuthenticationRequest.OPENID_CLAIMED_ID ) ); + } + + session.setAttribute( + AuthenticationRequest.OPENID_REALM, + request.getParameter( AuthenticationRequest.OPENID_REALM ) ); + + //redirecting to OpenID Provider login page + response.sendRedirect( loginPage ); + return; + } + else + { + processAuthenticationRequest( request, response, queryString ); + } + } + else + { + processAssocationRequest( response, queryString ); + } + } + catch (InvalidOpenIdQueryException e) { + returnError( queryString, response ); + } + + catch ( OpenIdException e ) + { + e.printStackTrace(); + response.sendError( HttpServletResponse + .SC_INTERNAL_SERVER_ERROR, e.getMessage() ); + } + } + + private void processAuthenticationRequest( HttpServletRequest request, HttpServletResponse response, + String queryString ) throws UnsupportedEncodingException, + OpenIdException, IOException, InvalidOpenIdQueryException + { + String openIdResponse = openId.handleRequest( queryString ); + + + + AuthenticationRequest authReq = ( AuthenticationRequest ) + RequestFactory.parse( queryString ); + + String claimedId = (String) request.getSession().getAttribute(ID_CLAIMED); + + /* Ensure that the previously claimed id is the same as the just + passed in claimed id. */ + String identity; + if ( request.getParameter( AuthenticationRequest.OPENID_CLAIMED_ID ) == null ) + { + identity = request.getParameter( AuthenticationRequest.OPENID_IDENTITY ); + } + else + { + identity = authReq.getClaimedIdentity(); + } + + if ( getUserManager().canClaim( getLoggedIn( request ) , identity ) ) + { + String returnTo = ( String ) request.getSession().getAttribute( AuthenticationRequest.OPENID_RETURN_TO ); + + String delim = ( returnTo.indexOf( '?' ) >= 0 ) ? "&" : "?"; + + String returnToUrlWithOpenIdResponse = response.encodeRedirectURL( returnTo + delim + openIdResponse ); + + //redirecting to relying party with OpenID response query + response.sendRedirect( returnToUrlWithOpenIdResponse ); + return; + } + else + { + throw new OpenIdException( "User cannot claim this id." ); + } + } + + private void processAssocationRequest( HttpServletResponse response, String queryString ) throws IOException, OpenIdException, InvalidOpenIdQueryException + { + // Association request + String openIdResponse = openId.handleRequest( queryString ); + + + int len = openIdResponse.length(); + PrintWriter out = response.getWriter(); + response.setHeader( "Content-Length", Integer.toString( len ) ); + if ( openId.isAnErrorResponse( openIdResponse ) ) + { + response.setStatus( HttpServletResponse.SC_BAD_REQUEST ); + } + out.print( openIdResponse ); + out.flush(); + return; + } + + /** + * + * @param request + * @return Username the user is logged in as + */ + public static String getLoggedIn( HttpServletRequest request ) + { + String o = ( String ) request.getSession( true ).getAttribute( USERNAME_ATTRIBUTE ); + if ( o != null ) + return o; + // check Remember Me cookies + String authKey = CookieUtils.getCookieValue( request, COOKIE_AUTH_NAME, null ); + if ( authKey != null ) + { + String username = CookieUtils.getCookieValue( request, COOKIE_USERNAME, null ); + if ( username != null ) + { + // lets check the UserManager to make sure this is a valid match + o = getUserManager().getRememberedUser( username, authKey ); + if ( o != null ) + { + request.getSession( true ).setAttribute( USERNAME_ATTRIBUTE, o ); + } + } + } + return o; + } + + private String populateQueryStringFromPost( HttpServletRequest request ) throws IOException + { + StringBuffer sb = new StringBuffer(); + Enumeration e = request.getParameterNames(); + while ( e.hasMoreElements() ) + { + String name = ( String ) e.nextElement(); + String[] values = request.getParameterValues( name ); + if ( values.length == 0 ) + { + throw new IOException( "Empty value not allowed: " + + name + " has no value" ); + } + try + { + sb.append( URLEncoder.encode( name, "UTF-8" ) + "=" + + URLEncoder.encode( values[0], "UTF-8" ) ); + } + catch ( UnsupportedEncodingException ex ) + { + throw new IOException( ex.toString() ); + } + if ( e.hasMoreElements() ) + { + sb.append( "&" ); + } + } + return sb.toString(); + } + + public static void setLoggedIn( HttpServletRequest request, String username ) + { + request.getSession( true ).setAttribute( USERNAME_ATTRIBUTE, username ); + } + + private void returnError( String query, HttpServletResponse response ) + throws ServletException, IOException + { + Map map = RequestFactory.parseQuery( query ); + String returnTo = ( String ) map.get( "openid.return_to" ); + boolean goodReturnTo = false; + try + { + @SuppressWarnings("unused") + URL url = new URL( returnTo ); + goodReturnTo = true; + } + catch ( MalformedURLException e ) + { + e.printStackTrace(); + } + + if ( goodReturnTo ) + { + String s = "?openid.ns:http://specs.openid.net/auth/2.0" + + "&openid.mode=error&openid.error=BAD_REQUEST"; + s = response.encodeRedirectURL( returnTo + s ); + response.sendRedirect( s ); + } + else + { + PrintWriter out = response.getWriter(); + // response.setContentLength() seems to be broken, + // so set the header manually + String s = "ns:http://specs.openid.net/auth/2.0\n" + + "&mode:error" + + "&error:BAD_REQUEST\n"; + int len = s.length(); + response.setHeader( "Content-Length", Integer.toString( len ) ); + response.setStatus( HttpServletResponse.SC_BAD_REQUEST ); + out.print( s ); + out.flush(); + } + } + + public void log( String s ) + { + // @TODO: resolve issue with non-prime servlet container + log4j/commons and replace + System.out.println( s ); + } + + + /** + * This sets a session variable stating that the claimed_id for this request + * has been verified so we can now return back to the relying party. + * + * @param session + * @param claimedId + */ + public static void idClaimed( HttpSession session, String claimedId ) + { + session.setAttribute( ID_CLAIMED, claimedId ); + } + + + public static UserManager getUserManager() + { + return userManager; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/server/User.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/server/Attic/User.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/server/User.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,56 @@ +package org.verisign.joid.server; + + +/** + * User: treeder + * Date: Jul 17, 2007 + * Time: 5:34:30 PM + */ +public class User +{ + private String password; + private String username; + + + public User() + { + } + + + public User( String username, String password ) + { + + this.username = username; + this.password = password; + } + + + public String getPassword() + { + return password; + } + + + public void setPassword( String password ) + { + this.password = password; + } + + + public String getUsername() + { + return username; + } + + + public void setUsername( String username ) + { + this.username = username; + } + + + public String toString() + { + return username; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/server/UserManager.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/server/Attic/UserManager.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/server/UserManager.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,41 @@ +package org.verisign.joid.server; + + +/** + * User: treeder + * Date: Jul 17, 2007 + * Time: 5:33:09 PM + */ +public interface UserManager +{ + // removing this to get rid of the User dependency + // User getUser(String username); + // void save(User user); + + /** + * The implementation should store this relationship so it can retrieve it later + * for auto login. + * @param username + * @param authKey + */ + void remember( String username, String authKey ); + + + /** + * Returns a User based on a generated authKey from a user selecting "Remember Me". + * @param username + * @param authKey + * @return + */ + String getRememberedUser( String username, String authKey ); + + + /** + * todo: This might be better off as an abstract method on OpenIdServlet + * + * @param username + * @param claimedIdentity + * @return + */ + boolean canClaim( String username, String claimedIdentity ); +} Index: 3rdParty_sources/joid/org/verisign/joid/util/Boolean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/util/Attic/Boolean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/util/Boolean.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,55 @@ +// +// (C) Copyright 2008 VeriSign, Inc. All Rights Reserved. +// +// VeriSign, Inc. shall have no responsibility, financial or +// otherwise, for any consequences arising out of the use of +// this material. The program material is provided on an "AS IS" +// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +// express or implied. +// +// Distributed under an Apache License +// http://www.apache.org/licenses/LICENSE-2.0 +// + +package org.verisign.joid.util; + + +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; + + +/** + * Boolean in order to comply with Java 1.4. + */ +public class Boolean +{ + private final static Log log = LogFactory.getLog( Boolean.class ); + + + /** + * + */ + public static boolean parseBoolean( String s ) + { + if ( s != null ) + { + if ( s.equals( "true" ) ) + { + return true; + } + else if ( s.equals( "false" ) ) + { + return false; + } + else + { + // TBD: Throw an exception! + log.error( "No such value: " + s ); + return false; + } + } + // TBD: Throw an exception! + log.error( "No such value: " + s ); + return false; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/util/CookieUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/util/Attic/CookieUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/util/CookieUtils.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,69 @@ +package org.verisign.joid.util; + + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +/** + * User: treeder + * Date: Aug 8, 2007 + * Time: 5:18:08 PM + */ +public class CookieUtils +{ + /** Default age is 30 days */ + private static final int DEFAULT_AGE = 60 * 60 * 24 * 30; + + + /** + * Sets the cookie + * @param response + * @param cookieName + * @param value + */ + public static void setCookie( HttpServletResponse response, + String cookieName, String value ) + { + Cookie cookie = new Cookie( cookieName, value ); + cookie.setMaxAge( DEFAULT_AGE ); + response.addCookie( cookie ); + } + + + /** + * Returns the value of the cookie specified by cookieName or defaultValue if + * Cookie does not exist. + * + * @param request + * @param cookieName + * @param defaultValue + * @return + */ + public static String getCookieValue( HttpServletRequest request, + String cookieName, + String defaultValue ) + { + Cookie cookie = getCookie( request, cookieName ); + if ( cookie == null ) + return defaultValue; + else + return cookie.getValue(); + } + + + public static Cookie getCookie( HttpServletRequest request, String cookieName ) + { + Cookie[] cookies = request.getCookies(); + if ( cookies == null ) + return null; + for ( int i = 0; i < cookies.length; i++ ) + { + Cookie cookie = cookies[i]; + if ( cookieName.equals( cookie.getName() ) ) + return cookie; + } + return null; + } +} Index: 3rdParty_sources/joid/org/verisign/joid/util/DependencyUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/util/Attic/DependencyUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/util/DependencyUtils.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,37 @@ +package org.verisign.joid.util; + + +/** + * User: treeder + * Date: Aug 9, 2007 + * Time: 2:31:00 PM + */ +public class DependencyUtils +{ + /** + * This method will create a new instance of the class specified by className. + * + * @param className + * @return + */ + public static Object newInstance( String className ) + { + try + { + return Class.forName( className ).newInstance(); + } + catch ( ClassNotFoundException e ) + { + throw new IllegalArgumentException( "Not found " + className ); + } + catch ( IllegalAccessException e ) + { + throw new IllegalArgumentException( "No access to " + className ); + } + catch ( InstantiationException e ) + { + throw new IllegalArgumentException( "Cannot instantiate " + + className ); + } + } +} Index: 3rdParty_sources/joid/org/verisign/joid/util/UrlUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/joid/org/verisign/joid/util/Attic/UrlUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/joid/org/verisign/joid/util/UrlUtils.java 17 Aug 2012 14:55:13 -0000 1.1 @@ -0,0 +1,73 @@ +package org.verisign.joid.util; + + +import javax.servlet.http.HttpServletRequest; + + +/** + * User: treeder + * Date: Jul 19, 2007 + * Time: 4:05:35 PM + */ +public class UrlUtils +{ + + public static String getFullUrl( HttpServletRequest request ) + { + StringBuffer b = getServletUrl( request ); + String queryString = request.getQueryString(); + if ( queryString != null ) + { + b.append( "?" ).append( queryString ); + } + return b.toString(); + } + + + public static StringBuffer getServletUrl( HttpServletRequest request ) + { + StringBuffer b = new StringBuffer( getBaseUrl( request ) ); + String servletPath = request.getServletPath(); + if ( servletPath != null ) + { + b.append( servletPath ); + } + return b; + } + + + /** + * + * @param request + * @return the url of the local host including the context, not including a trailing "/" + * // todo: make these return StringBuffer instead + */ + public static String getBaseUrl( HttpServletRequest request ) + { + StringBuffer b = new StringBuffer(); + b.append( getHostUrl( request ) ); + String context = request.getContextPath(); + if ( context != null ) + { + b.append( context ); + } + return b.toString(); + } + + + /** + * + * @param request + * @return the host url without the context + * // todo: make these return StringBuffer instead + */ + public static String getHostUrl( HttpServletRequest request ) + { + String scheme = request.getScheme(); + String serverName = request.getServerName(); + String port = request.getServerPort() == 80 || request.getServerPort() == 443 ? "" : ":" + + request.getServerPort(); + String start = scheme + "://" + serverName + port; + return start; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/LucenePackage.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/LucenePackage.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/LucenePackage.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,29 @@ +package org.apache.lucene; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Lucene's package information, including version. **/ +public final class LucenePackage { + + private LucenePackage() {} // can't construct + + /** Return Lucene's package, including version information. */ + public static Package get() { + return LucenePackage.class.getPackage(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/package.html 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,17 @@ + +Top-level package. Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/Analyzer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/Analyzer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/Analyzer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,81 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; +import java.io.IOException; + +/** An Analyzer builds TokenStreams, which analyze text. It thus represents a + * policy for extracting index terms from text. + *

+ * Typical implementations first build a Tokenizer, which breaks the stream of + * characters from the Reader into raw Tokens. One or more TokenFilters may + * then be applied to the output of the Tokenizer. + */ +public abstract class Analyzer { + /** Creates a TokenStream which tokenizes all the text in the provided + * Reader. Must be able to handle null field name for backward compatibility. + */ + public abstract TokenStream tokenStream(String fieldName, Reader reader); + + /** Creates a TokenStream that is allowed to be re-used + * from the previous time that the same thread called + * this method. Callers that do not need to use more + * than one TokenStream at the same time from this + * analyzer should use this method for better + * performance. + */ + public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { + return tokenStream(fieldName, reader); + } + + private ThreadLocal tokenStreams = new ThreadLocal(); + + /** Used by Analyzers that implement reusableTokenStream + * to retrieve previously saved TokenStreams for re-use + * by the same thread. */ + protected Object getPreviousTokenStream() { + return tokenStreams.get(); + } + + /** Used by Analyzers that implement reusableTokenStream + * to save a TokenStream for later re-use by the same + * thread. */ + protected void setPreviousTokenStream(Object obj) { + tokenStreams.set(obj); + } + + + /** + * Invoked before indexing a Fieldable instance if + * terms have already been added to that field. This allows custom + * analyzers to place an automatic position increment gap between + * Fieldable instances using the same field name. The default value + * position increment gap is 0. With a 0 position increment gap and + * the typical default token position increment of 1, all terms in a field, + * including across Fieldable instances, are in successive positions, allowing + * exact PhraseQuery matches, for instance, across Fieldable instance boundaries. + * + * @param fieldName Fieldable name being indexed. + * @return position increment gap, added to the next token emitted from {@link #tokenStream(String,Reader)} + */ + public int getPositionIncrementGap(String fieldName) + { + return 0; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/CachingTokenFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/CachingTokenFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/CachingTokenFilter.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,73 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * This class can be used if the Tokens of a TokenStream + * are intended to be consumed more than once. It caches + * all Tokens locally in a List. + * + * CachingTokenFilter implements the optional method + * {@link TokenStream#reset()}, which repositions the + * stream to the first Token. + * + */ +public class CachingTokenFilter extends TokenFilter { + private List cache; + private Iterator iterator; + + public CachingTokenFilter(TokenStream input) { + super(input); + } + + public Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + if (cache == null) { + // fill cache lazily + cache = new LinkedList(); + fillCache(reusableToken); + iterator = cache.iterator(); + } + + if (!iterator.hasNext()) { + // the cache is exhausted, return null + return null; + } + // Since the TokenFilter can be reset, the tokens need to be preserved as immutable. + Token nextToken = (Token) iterator.next(); + return (Token) nextToken.clone(); + } + + public void reset() throws IOException { + if(cache != null) { + iterator = cache.iterator(); + } + } + + private void fillCache(final Token reusableToken) throws IOException { + for (Token nextToken = input.next(reusableToken); nextToken != null; nextToken = input.next(reusableToken)) { + cache.add(nextToken.clone()); + } + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/CharArraySet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/CharArraySet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/CharArraySet.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,288 @@ +package org.apache.lucene.analysis; + +import java.util.AbstractSet; +import java.util.Collection; +import java.util.Iterator; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * A simple class that stores Strings as char[]'s in a + * hash table. Note that this is not a general purpose + * class. For example, it cannot remove items from the + * set, nor does it resize its hash table to be smaller, + * etc. It is designed to be quick to test if a char[] + * is in the set without the necessity of converting it + * to a String first. + */ + +public class CharArraySet extends AbstractSet { + private final static int INIT_SIZE = 8; + private char[][] entries; + private int count; + private final boolean ignoreCase; + + /** Create set with enough capacity to hold startSize + * terms */ + public CharArraySet(int startSize, boolean ignoreCase) { + this.ignoreCase = ignoreCase; + int size = INIT_SIZE; + while(startSize + (startSize>>2) > size) + size <<= 1; + entries = new char[size][]; + } + + /** Create set from a Collection of char[] or String */ + public CharArraySet(Collection c, boolean ignoreCase) { + this(c.size(), ignoreCase); + addAll(c); + } + + /** true if the len chars of text starting at off + * are in the set */ + public boolean contains(char[] text, int off, int len) { + return entries[getSlot(text, off, len)] != null; + } + + /** true if the CharSequence is in the set */ + public boolean contains(CharSequence cs) { + return entries[getSlot(cs)] != null; + } + + private int getSlot(char[] text, int off, int len) { + int code = getHashCode(text, off, len); + int pos = code & (entries.length-1); + char[] text2 = entries[pos]; + if (text2 != null && !equals(text, off, len, text2)) { + final int inc = ((code>>8)+code)|1; + do { + code += inc; + pos = code & (entries.length-1); + text2 = entries[pos]; + } while (text2 != null && !equals(text, off, len, text2)); + } + return pos; + } + + /** Returns true if the String is in the set */ + private int getSlot(CharSequence text) { + int code = getHashCode(text); + int pos = code & (entries.length-1); + char[] text2 = entries[pos]; + if (text2 != null && !equals(text, text2)) { + final int inc = ((code>>8)+code)|1; + do { + code += inc; + pos = code & (entries.length-1); + text2 = entries[pos]; + } while (text2 != null && !equals(text, text2)); + } + return pos; + } + + /** Add this CharSequence into the set */ + public boolean add(CharSequence text) { + return add(text.toString()); // could be more efficient + } + + /** Add this String into the set */ + public boolean add(String text) { + return add(text.toCharArray()); + } + + /** Add this char[] directly to the set. + * If ignoreCase is true for this Set, the text array will be directly modified. + * The user should never modify this text array after calling this method. + */ + public boolean add(char[] text) { + if (ignoreCase) + for(int i=0;i>2) > entries.length) { + rehash(); + } + + return true; + } + + private boolean equals(char[] text1, int off, int len, char[] text2) { + if (len != text2.length) + return false; + if (ignoreCase) { + for(int i=0;i for this set. Strings are constructed on the fly, so + * use nextCharArray for more efficient access. */ + public class CharArraySetIterator implements Iterator { + int pos=-1; + char[] next; + CharArraySetIterator() { + goNext(); + } + + private void goNext() { + next = null; + pos++; + while (pos < entries.length && (next=entries[pos]) == null) pos++; + } + + public boolean hasNext() { + return next != null; + } + + /** do not modify the returned char[] */ + public char[] nextCharArray() { + char[] ret = next; + goNext(); + return ret; + } + + /** Returns the next String, as a Set would... + * use nextCharArray() for better efficiency. */ + public Object next() { + return new String(nextCharArray()); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + } + + + public Iterator iterator() { + return new CharArraySetIterator(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/CharTokenizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/CharTokenizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/CharTokenizer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,97 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.Reader; + +/** An abstract base class for simple, character-oriented tokenizers.*/ +public abstract class CharTokenizer extends Tokenizer { + public CharTokenizer(Reader input) { + super(input); + } + + private int offset = 0, bufferIndex = 0, dataLen = 0; + private static final int MAX_WORD_LEN = 255; + private static final int IO_BUFFER_SIZE = 4096; + private final char[] ioBuffer = new char[IO_BUFFER_SIZE]; + + /** Returns true iff a character should be included in a token. This + * tokenizer generates as tokens adjacent sequences of characters which + * satisfy this predicate. Characters for which this is false are used to + * define token boundaries and are not included in tokens. */ + protected abstract boolean isTokenChar(char c); + + /** Called on each token character to normalize it before it is added to the + * token. The default implementation does nothing. Subclasses may use this + * to, e.g., lowercase tokens. */ + protected char normalize(char c) { + return c; + } + + public final Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + reusableToken.clear(); + int length = 0; + int start = bufferIndex; + char[] buffer = reusableToken.termBuffer(); + while (true) { + + if (bufferIndex >= dataLen) { + offset += dataLen; + dataLen = input.read(ioBuffer); + if (dataLen == -1) { + if (length > 0) + break; + else + return null; + } + bufferIndex = 0; + } + + final char c = ioBuffer[bufferIndex++]; + + if (isTokenChar(c)) { // if it's a token char + + if (length == 0) // start of token + start = offset + bufferIndex - 1; + else if (length == buffer.length) + buffer = reusableToken.resizeTermBuffer(1+length); + + buffer[length++] = normalize(c); // buffer it, normalized + + if (length == MAX_WORD_LEN) // buffer overflow! + break; + + } else if (length > 0) // at non-Letter w/ chars + break; // return 'em + } + + reusableToken.setTermLength(length); + reusableToken.setStartOffset(start); + reusableToken.setEndOffset(start+length); + return reusableToken; + } + + public void reset(Reader input) throws IOException { + super.reset(input); + bufferIndex = 0; + offset = 0; + dataLen = 0; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/ISOLatin1AccentFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/ISOLatin1AccentFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/ISOLatin1AccentFilter.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,252 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A filter that replaces accented characters in the ISO Latin 1 character set + * (ISO-8859-1) by their unaccented equivalent. The case will not be altered. + *

+ * For instance, 'à' will be replaced by 'a'. + *

+ */ +public class ISOLatin1AccentFilter extends TokenFilter { + public ISOLatin1AccentFilter(TokenStream input) { + super(input); + } + + private char[] output = new char[256]; + private int outputPos; + + public final Token next(final Token reusableToken) throws java.io.IOException { + assert reusableToken != null; + Token nextToken = input.next(reusableToken); + if (nextToken != null) { + final char[] buffer = nextToken.termBuffer(); + final int length = nextToken.termLength(); + // If no characters actually require rewriting then we + // just return token as-is: + for(int i=0;i= '\u00c0' && c <= '\uFB06') { + removeAccents(buffer, length); + nextToken.setTermBuffer(output, 0, outputPos); + break; + } + } + return nextToken; + } else + return null; + } + + /** + * To replace accented characters in a String by unaccented equivalents. + */ + public final void removeAccents(char[] input, int length) { + + // Worst-case length required: + final int maxSizeNeeded = 2*length; + + int size = output.length; + while (size < maxSizeNeeded) + size *= 2; + + if (size != output.length) + output = new char[size]; + + outputPos = 0; + + int pos = 0; + + for (int i=0; i '\uFB06') + output[outputPos++] = c; + else { + switch (c) { + case '\u00C0' : // À + case '\u00C1' : // Á + case '\u00C2' : //  + case '\u00C3' : // à + case '\u00C4' : // Ä + case '\u00C5' : // Å + output[outputPos++] = 'A'; + break; + case '\u00C6' : // Æ + output[outputPos++] = 'A'; + output[outputPos++] = 'E'; + break; + case '\u00C7' : // Ç + output[outputPos++] = 'C'; + break; + case '\u00C8' : // È + case '\u00C9' : // É + case '\u00CA' : // Ê + case '\u00CB' : // Ë + output[outputPos++] = 'E'; + break; + case '\u00CC' : // Ì + case '\u00CD' : // Í + case '\u00CE' : // Î + case '\u00CF' : // Ï + output[outputPos++] = 'I'; + break; + case '\u0132' : // IJ + output[outputPos++] = 'I'; + output[outputPos++] = 'J'; + break; + case '\u00D0' : // Ð + output[outputPos++] = 'D'; + break; + case '\u00D1' : // Ñ + output[outputPos++] = 'N'; + break; + case '\u00D2' : // Ò + case '\u00D3' : // Ó + case '\u00D4' : // Ô + case '\u00D5' : // Õ + case '\u00D6' : // Ö + case '\u00D8' : // Ø + output[outputPos++] = 'O'; + break; + case '\u0152' : // Œ + output[outputPos++] = 'O'; + output[outputPos++] = 'E'; + break; + case '\u00DE' : // Þ + output[outputPos++] = 'T'; + output[outputPos++] = 'H'; + break; + case '\u00D9' : // Ù + case '\u00DA' : // Ú + case '\u00DB' : // Û + case '\u00DC' : // Ü + output[outputPos++] = 'U'; + break; + case '\u00DD' : // Ý + case '\u0178' : // Ÿ + output[outputPos++] = 'Y'; + break; + case '\u00E0' : // à + case '\u00E1' : // á + case '\u00E2' : // â + case '\u00E3' : // ã + case '\u00E4' : // ä + case '\u00E5' : // å + output[outputPos++] = 'a'; + break; + case '\u00E6' : // æ + output[outputPos++] = 'a'; + output[outputPos++] = 'e'; + break; + case '\u00E7' : // ç + output[outputPos++] = 'c'; + break; + case '\u00E8' : // è + case '\u00E9' : // é + case '\u00EA' : // ê + case '\u00EB' : // ë + output[outputPos++] = 'e'; + break; + case '\u00EC' : // ì + case '\u00ED' : // í + case '\u00EE' : // î + case '\u00EF' : // ï + output[outputPos++] = 'i'; + break; + case '\u0133' : // ij + output[outputPos++] = 'i'; + output[outputPos++] = 'j'; + break; + case '\u00F0' : // ð + output[outputPos++] = 'd'; + break; + case '\u00F1' : // ñ + output[outputPos++] = 'n'; + break; + case '\u00F2' : // ò + case '\u00F3' : // ó + case '\u00F4' : // ô + case '\u00F5' : // õ + case '\u00F6' : // ö + case '\u00F8' : // ø + output[outputPos++] = 'o'; + break; + case '\u0153' : // œ + output[outputPos++] = 'o'; + output[outputPos++] = 'e'; + break; + case '\u00DF' : // ß + output[outputPos++] = 's'; + output[outputPos++] = 's'; + break; + case '\u00FE' : // þ + output[outputPos++] = 't'; + output[outputPos++] = 'h'; + break; + case '\u00F9' : // ù + case '\u00FA' : // ú + case '\u00FB' : // û + case '\u00FC' : // ü + output[outputPos++] = 'u'; + break; + case '\u00FD' : // ý + case '\u00FF' : // ÿ + output[outputPos++] = 'y'; + break; + case '\uFB00': // ff + output[outputPos++] = 'f'; + output[outputPos++] = 'f'; + break; + case '\uFB01': // fi + output[outputPos++] = 'f'; + output[outputPos++] = 'i'; + break; + case '\uFB02': // fl + output[outputPos++] = 'f'; + output[outputPos++] = 'l'; + break; + // following 2 are commented as they can break the maxSizeNeeded (and doing *3 could be expensive) +// case '\uFB03': // ffi +// output[outputPos++] = 'f'; +// output[outputPos++] = 'f'; +// output[outputPos++] = 'i'; +// break; +// case '\uFB04': // ffl +// output[outputPos++] = 'f'; +// output[outputPos++] = 'f'; +// output[outputPos++] = 'l'; +// break; + case '\uFB05': // ſt + output[outputPos++] = 'f'; + output[outputPos++] = 't'; + break; + case '\uFB06': // st + output[outputPos++] = 's'; + output[outputPos++] = 't'; + break; + default : + output[outputPos++] = c; + break; + } + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/KeywordAnalyzer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/KeywordAnalyzer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/KeywordAnalyzer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,42 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.Reader; + +/** + * "Tokenizes" the entire stream as a single token. This is useful + * for data like zip codes, ids, and some product names. + */ +public class KeywordAnalyzer extends Analyzer { + public TokenStream tokenStream(String fieldName, + final Reader reader) { + return new KeywordTokenizer(reader); + } + public TokenStream reusableTokenStream(String fieldName, + final Reader reader) throws IOException { + Tokenizer tokenizer = (Tokenizer) getPreviousTokenStream(); + if (tokenizer == null) { + tokenizer = new KeywordTokenizer(reader); + setPreviousTokenStream(tokenizer); + } else + tokenizer.reset(reader); + return tokenizer; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/KeywordTokenizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/KeywordTokenizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/KeywordTokenizer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,65 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.Reader; + +/** + * Emits the entire input as a single token. + */ +public class KeywordTokenizer extends Tokenizer { + + private static final int DEFAULT_BUFFER_SIZE = 256; + + private boolean done; + + public KeywordTokenizer(Reader input) { + this(input, DEFAULT_BUFFER_SIZE); + } + + public KeywordTokenizer(Reader input, int bufferSize) { + super(input); + this.done = false; + } + + public Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + if (!done) { + done = true; + int upto = 0; + reusableToken.clear(); + char[] buffer = reusableToken.termBuffer(); + while (true) { + final int length = input.read(buffer, upto, buffer.length-upto); + if (length == -1) break; + upto += length; + if (upto == buffer.length) + buffer = reusableToken.resizeTermBuffer(1+buffer.length); + } + reusableToken.setTermLength(upto); + return reusableToken; + } + return null; + } + + public void reset(Reader input) throws IOException { + super.reset(input); + this.done = false; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/LengthFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/LengthFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/LengthFilter.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,62 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + * Removes words that are too long and too short from the stream. + * + * + * @version $Id: LengthFilter.java,v 1.1 2012/08/17 14:55:08 marcin Exp $ + */ +public final class LengthFilter extends TokenFilter { + + final int min; + final int max; + + /** + * Build a filter that removes words that are too long or too + * short from the text. + */ + public LengthFilter(TokenStream in, int min, int max) + { + super(in); + this.min = min; + this.max = max; + } + + /** + * Returns the next input Token whose term() is the right len + */ + public final Token next(final Token reusableToken) throws IOException + { + assert reusableToken != null; + // return the first non-stop word found + for (Token nextToken = input.next(reusableToken); nextToken != null; nextToken = input.next(reusableToken)) + { + int len = nextToken.termLength(); + if (len >= min && len <= max) { + return nextToken; + } + // note: else we ignore it but should we index each part of it? + } + // reached EOS -- return null + return null; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/LetterTokenizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/LetterTokenizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/LetterTokenizer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,40 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; + +/** A LetterTokenizer is a tokenizer that divides text at non-letters. That's + to say, it defines tokens as maximal strings of adjacent letters, as defined + by java.lang.Character.isLetter() predicate. + + Note: this does a decent job for most European languages, but does a terrible + job for some Asian languages, where words are not separated by spaces. */ + +public class LetterTokenizer extends CharTokenizer { + /** Construct a new LetterTokenizer. */ + public LetterTokenizer(Reader in) { + super(in); + } + + /** Collects only characters which satisfy + * {@link Character#isLetter(char)}.*/ + protected boolean isTokenChar(char c) { + return Character.isLetter(c); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/LowerCaseFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/LowerCaseFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/LowerCaseFilter.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,46 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + * Normalizes token text to lower case. + * + * @version $Id: LowerCaseFilter.java,v 1.1 2012/08/17 14:55:08 marcin Exp $ + */ +public final class LowerCaseFilter extends TokenFilter { + public LowerCaseFilter(TokenStream in) { + super(in); + } + + public final Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + Token nextToken = input.next(reusableToken); + if (nextToken != null) { + + final char[] buffer = nextToken.termBuffer(); + final int length = nextToken.termLength(); + for(int i=0;i + * Note: this does a decent job for most European languages, but does a terrible + * job for some Asian languages, where words are not separated by spaces. + */ +public final class LowerCaseTokenizer extends LetterTokenizer { + /** Construct a new LowerCaseTokenizer. */ + public LowerCaseTokenizer(Reader in) { + super(in); + } + + /** Collects only characters which satisfy + * {@link Character#isLetter(char)}.*/ + protected char normalize(char c) { + return Character.toLowerCase(c); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/PerFieldAnalyzerWrapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/PerFieldAnalyzerWrapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/PerFieldAnalyzerWrapper.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,98 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; +import java.io.IOException; +import java.util.Map; +import java.util.HashMap; + +/** + * This analyzer is used to facilitate scenarios where different + * fields require different analysis techniques. Use {@link #addAnalyzer} + * to add a non-default analyzer on a field name basis. + * + *

Example usage: + * + *

+ *   PerFieldAnalyzerWrapper aWrapper =
+ *      new PerFieldAnalyzerWrapper(new StandardAnalyzer());
+ *   aWrapper.addAnalyzer("firstname", new KeywordAnalyzer());
+ *   aWrapper.addAnalyzer("lastname", new KeywordAnalyzer());
+ * 
+ * + *

In this example, StandardAnalyzer will be used for all fields except "firstname" + * and "lastname", for which KeywordAnalyzer will be used. + * + *

A PerFieldAnalyzerWrapper can be used like any other analyzer, for both indexing + * and query parsing. + */ +public class PerFieldAnalyzerWrapper extends Analyzer { + private Analyzer defaultAnalyzer; + private Map analyzerMap = new HashMap(); + + + /** + * Constructs with default analyzer. + * + * @param defaultAnalyzer Any fields not specifically + * defined to use a different analyzer will use the one provided here. + */ + public PerFieldAnalyzerWrapper(Analyzer defaultAnalyzer) { + this.defaultAnalyzer = defaultAnalyzer; + } + + /** + * Defines an analyzer to use for the specified field. + * + * @param fieldName field name requiring a non-default analyzer + * @param analyzer non-default analyzer to use for field + */ + public void addAnalyzer(String fieldName, Analyzer analyzer) { + analyzerMap.put(fieldName, analyzer); + } + + public TokenStream tokenStream(String fieldName, Reader reader) { + Analyzer analyzer = (Analyzer) analyzerMap.get(fieldName); + if (analyzer == null) { + analyzer = defaultAnalyzer; + } + + return analyzer.tokenStream(fieldName, reader); + } + + public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { + Analyzer analyzer = (Analyzer) analyzerMap.get(fieldName); + if (analyzer == null) + analyzer = defaultAnalyzer; + + return analyzer.reusableTokenStream(fieldName, reader); + } + + /** Return the positionIncrementGap from the analyzer assigned to fieldName */ + public int getPositionIncrementGap(String fieldName) { + Analyzer analyzer = (Analyzer) analyzerMap.get(fieldName); + if (analyzer == null) + analyzer = defaultAnalyzer; + return analyzer.getPositionIncrementGap(fieldName); + } + + public String toString() { + return "PerFieldAnalyzerWrapper(" + analyzerMap + ", default=" + defaultAnalyzer + ")"; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/PorterStemFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/PorterStemFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/PorterStemFilter.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,58 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** Transforms the token stream as per the Porter stemming algorithm. + Note: the input to the stemming filter must already be in lower case, + so you will need to use LowerCaseFilter or LowerCaseTokenizer farther + down the Tokenizer chain in order for this to work properly! +

+ To use this filter with other analyzers, you'll want to write an + Analyzer class that sets up the TokenStream chain as you want it. + To use this with LowerCaseTokenizer, for example, you'd write an + analyzer like this: +

+

+    class MyAnalyzer extends Analyzer {
+      public final TokenStream tokenStream(String fieldName, Reader reader) {
+        return new PorterStemFilter(new LowerCaseTokenizer(reader));
+      }
+    }
+    
+*/ +public final class PorterStemFilter extends TokenFilter { + private PorterStemmer stemmer; + + public PorterStemFilter(TokenStream in) { + super(in); + stemmer = new PorterStemmer(); + } + + public final Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + Token nextToken = input.next(reusableToken); + if (nextToken == null) + return null; + + if (stemmer.stem(nextToken.termBuffer(), 0, nextToken.termLength())) + nextToken.setTermBuffer(stemmer.getResultBuffer(), 0, stemmer.getResultLength()); + return nextToken; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/PorterStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/PorterStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/PorterStemmer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,545 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + + Porter stemmer in Java. The original paper is in + + Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, + no. 3, pp 130-137, + + See also http://www.tartarus.org/~martin/PorterStemmer/index.html + + Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below. + Tthe words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1] + is then out outside the bounds of b. + + Similarly, + + Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below. + 'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and + b[j] is then outside the bounds of b. + + Release 3. + + [ This version is derived from Release 3, modified by Brian Goetz to + optimize for fewer object creations. ] + +*/ + + +import java.io.*; + +/** + * + * Stemmer, implementing the Porter Stemming Algorithm + * + * The Stemmer class transforms a word into its root form. The input + * word can be provided a character at time (by calling add()), or at once + * by calling one of the various stem(something) methods. + */ + +class PorterStemmer +{ + private char[] b; + private int i, /* offset into b */ + j, k, k0; + private boolean dirty = false; + private static final int INC = 50; /* unit of size whereby b is increased */ + private static final int EXTRA = 1; + + public PorterStemmer() { + b = new char[INC]; + i = 0; + } + + /** + * reset() resets the stemmer so it can stem another word. If you invoke + * the stemmer by calling add(char) and then stem(), you must call reset() + * before starting another word. + */ + public void reset() { i = 0; dirty = false; } + + /** + * Add a character to the word being stemmed. When you are finished + * adding characters, you can call stem(void) to process the word. + */ + public void add(char ch) { + if (b.length <= i + EXTRA) { + char[] new_b = new char[b.length+INC]; + System.arraycopy(b, 0, new_b, 0, b.length); + b = new_b; + } + b[i++] = ch; + } + + /** + * After a word has been stemmed, it can be retrieved by toString(), + * or a reference to the internal buffer can be retrieved by getResultBuffer + * and getResultLength (which is generally more efficient.) + */ + public String toString() { return new String(b,0,i); } + + /** + * Returns the length of the word resulting from the stemming process. + */ + public int getResultLength() { return i; } + + /** + * Returns a reference to a character buffer containing the results of + * the stemming process. You also need to consult getResultLength() + * to determine the length of the result. + */ + public char[] getResultBuffer() { return b; } + + /* cons(i) is true <=> b[i] is a consonant. */ + + private final boolean cons(int i) { + switch (b[i]) { + case 'a': case 'e': case 'i': case 'o': case 'u': + return false; + case 'y': + return (i==k0) ? true : !cons(i-1); + default: + return true; + } + } + + /* m() measures the number of consonant sequences between k0 and j. if c is + a consonant sequence and v a vowel sequence, and <..> indicates arbitrary + presence, + + gives 0 + vc gives 1 + vcvc gives 2 + vcvcvc gives 3 + .... + */ + + private final int m() { + int n = 0; + int i = k0; + while(true) { + if (i > j) + return n; + if (! cons(i)) + break; + i++; + } + i++; + while(true) { + while(true) { + if (i > j) + return n; + if (cons(i)) + break; + i++; + } + i++; + n++; + while(true) { + if (i > j) + return n; + if (! cons(i)) + break; + i++; + } + i++; + } + } + + /* vowelinstem() is true <=> k0,...j contains a vowel */ + + private final boolean vowelinstem() { + int i; + for (i = k0; i <= j; i++) + if (! cons(i)) + return true; + return false; + } + + /* doublec(j) is true <=> j,(j-1) contain a double consonant. */ + + private final boolean doublec(int j) { + if (j < k0+1) + return false; + if (b[j] != b[j-1]) + return false; + return cons(j); + } + + /* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant + and also if the second c is not w,x or y. this is used when trying to + restore an e at the end of a short word. e.g. + + cav(e), lov(e), hop(e), crim(e), but + snow, box, tray. + + */ + + private final boolean cvc(int i) { + if (i < k0+2 || !cons(i) || cons(i-1) || !cons(i-2)) + return false; + else { + int ch = b[i]; + if (ch == 'w' || ch == 'x' || ch == 'y') return false; + } + return true; + } + + private final boolean ends(String s) { + int l = s.length(); + int o = k-l+1; + if (o < k0) + return false; + for (int i = 0; i < l; i++) + if (b[o+i] != s.charAt(i)) + return false; + j = k-l; + return true; + } + + /* setto(s) sets (j+1),...k to the characters in the string s, readjusting + k. */ + + void setto(String s) { + int l = s.length(); + int o = j+1; + for (int i = 0; i < l; i++) + b[o+i] = s.charAt(i); + k = j+l; + dirty = true; + } + + /* r(s) is used further down. */ + + void r(String s) { if (m() > 0) setto(s); } + + /* step1() gets rid of plurals and -ed or -ing. e.g. + + caresses -> caress + ponies -> poni + ties -> ti + caress -> caress + cats -> cat + + feed -> feed + agreed -> agree + disabled -> disable + + matting -> mat + mating -> mate + meeting -> meet + milling -> mill + messing -> mess + + meetings -> meet + + */ + + private final void step1() { + if (b[k] == 's') { + if (ends("sses")) k -= 2; + else if (ends("ies")) setto("i"); + else if (b[k-1] != 's') k--; + } + if (ends("eed")) { + if (m() > 0) + k--; + } + else if ((ends("ed") || ends("ing")) && vowelinstem()) { + k = j; + if (ends("at")) setto("ate"); + else if (ends("bl")) setto("ble"); + else if (ends("iz")) setto("ize"); + else if (doublec(k)) { + int ch = b[k--]; + if (ch == 'l' || ch == 's' || ch == 'z') + k++; + } + else if (m() == 1 && cvc(k)) + setto("e"); + } + } + + /* step2() turns terminal y to i when there is another vowel in the stem. */ + + private final void step2() { + if (ends("y") && vowelinstem()) { + b[k] = 'i'; + dirty = true; + } + } + + /* step3() maps double suffices to single ones. so -ization ( = -ize plus + -ation) maps to -ize etc. note that the string before the suffix must give + m() > 0. */ + + private final void step3() { + if (k == k0) return; /* For Bug 1 */ + switch (b[k-1]) { + case 'a': + if (ends("ational")) { r("ate"); break; } + if (ends("tional")) { r("tion"); break; } + break; + case 'c': + if (ends("enci")) { r("ence"); break; } + if (ends("anci")) { r("ance"); break; } + break; + case 'e': + if (ends("izer")) { r("ize"); break; } + break; + case 'l': + if (ends("bli")) { r("ble"); break; } + if (ends("alli")) { r("al"); break; } + if (ends("entli")) { r("ent"); break; } + if (ends("eli")) { r("e"); break; } + if (ends("ousli")) { r("ous"); break; } + break; + case 'o': + if (ends("ization")) { r("ize"); break; } + if (ends("ation")) { r("ate"); break; } + if (ends("ator")) { r("ate"); break; } + break; + case 's': + if (ends("alism")) { r("al"); break; } + if (ends("iveness")) { r("ive"); break; } + if (ends("fulness")) { r("ful"); break; } + if (ends("ousness")) { r("ous"); break; } + break; + case 't': + if (ends("aliti")) { r("al"); break; } + if (ends("iviti")) { r("ive"); break; } + if (ends("biliti")) { r("ble"); break; } + break; + case 'g': + if (ends("logi")) { r("log"); break; } + } + } + + /* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */ + + private final void step4() { + switch (b[k]) { + case 'e': + if (ends("icate")) { r("ic"); break; } + if (ends("ative")) { r(""); break; } + if (ends("alize")) { r("al"); break; } + break; + case 'i': + if (ends("iciti")) { r("ic"); break; } + break; + case 'l': + if (ends("ical")) { r("ic"); break; } + if (ends("ful")) { r(""); break; } + break; + case 's': + if (ends("ness")) { r(""); break; } + break; + } + } + + /* step5() takes off -ant, -ence etc., in context vcvc. */ + + private final void step5() { + if (k == k0) return; /* for Bug 1 */ + switch (b[k-1]) { + case 'a': + if (ends("al")) break; + return; + case 'c': + if (ends("ance")) break; + if (ends("ence")) break; + return; + case 'e': + if (ends("er")) break; return; + case 'i': + if (ends("ic")) break; return; + case 'l': + if (ends("able")) break; + if (ends("ible")) break; return; + case 'n': + if (ends("ant")) break; + if (ends("ement")) break; + if (ends("ment")) break; + /* element etc. not stripped before the m */ + if (ends("ent")) break; + return; + case 'o': + if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break; + /* j >= 0 fixes Bug 2 */ + if (ends("ou")) break; + return; + /* takes care of -ous */ + case 's': + if (ends("ism")) break; + return; + case 't': + if (ends("ate")) break; + if (ends("iti")) break; + return; + case 'u': + if (ends("ous")) break; + return; + case 'v': + if (ends("ive")) break; + return; + case 'z': + if (ends("ize")) break; + return; + default: + return; + } + if (m() > 1) + k = j; + } + + /* step6() removes a final -e if m() > 1. */ + + private final void step6() { + j = k; + if (b[k] == 'e') { + int a = m(); + if (a > 1 || a == 1 && !cvc(k-1)) + k--; + } + if (b[k] == 'l' && doublec(k) && m() > 1) + k--; + } + + + /** + * Stem a word provided as a String. Returns the result as a String. + */ + public String stem(String s) { + if (stem(s.toCharArray(), s.length())) + return toString(); + else + return s; + } + + /** Stem a word contained in a char[]. Returns true if the stemming process + * resulted in a word different from the input. You can retrieve the + * result with getResultLength()/getResultBuffer() or toString(). + */ + public boolean stem(char[] word) { + return stem(word, word.length); + } + + /** Stem a word contained in a portion of a char[] array. Returns + * true if the stemming process resulted in a word different from + * the input. You can retrieve the result with + * getResultLength()/getResultBuffer() or toString(). + */ + public boolean stem(char[] wordBuffer, int offset, int wordLen) { + reset(); + if (b.length < wordLen) { + char[] new_b = new char[wordLen + EXTRA]; + b = new_b; + } + System.arraycopy(wordBuffer, offset, b, 0, wordLen); + i = wordLen; + return stem(0); + } + + /** Stem a word contained in a leading portion of a char[] array. + * Returns true if the stemming process resulted in a word different + * from the input. You can retrieve the result with + * getResultLength()/getResultBuffer() or toString(). + */ + public boolean stem(char[] word, int wordLen) { + return stem(word, 0, wordLen); + } + + /** Stem the word placed into the Stemmer buffer through calls to add(). + * Returns true if the stemming process resulted in a word different + * from the input. You can retrieve the result with + * getResultLength()/getResultBuffer() or toString(). + */ + public boolean stem() { + return stem(0); + } + + public boolean stem(int i0) { + k = i - 1; + k0 = i0; + if (k > k0+1) { + step1(); step2(); step3(); step4(); step5(); step6(); + } + // Also, a word is considered dirty if we lopped off letters + // Thanks to Ifigenia Vairelles for pointing this out. + if (i != k+1) + dirty = true; + i = k+1; + return dirty; + } + + /** Test program for demonstrating the Stemmer. It reads a file and + * stems each word, writing the result to standard out. + * Usage: Stemmer file-name + */ + public static void main(String[] args) { + PorterStemmer s = new PorterStemmer(); + + for (int i = 0; i < args.length; i++) { + try { + InputStream in = new FileInputStream(args[i]); + byte[] buffer = new byte[1024]; + int bufferLen, offset, ch; + + bufferLen = in.read(buffer); + offset = 0; + s.reset(); + + while(true) { + if (offset < bufferLen) + ch = buffer[offset++]; + else { + bufferLen = in.read(buffer); + offset = 0; + if (bufferLen < 0) + ch = -1; + else + ch = buffer[offset++]; + } + + if (Character.isLetter((char) ch)) { + s.add(Character.toLowerCase((char) ch)); + } + else { + s.stem(); + System.out.print(s.toString()); + s.reset(); + if (ch < 0) + break; + else { + System.out.print((char) ch); + } + } + } + + in.close(); + } + catch (IOException e) { + System.out.println("error reading " + args[i]); + } + } + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/SimpleAnalyzer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/SimpleAnalyzer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/SimpleAnalyzer.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,39 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; +import java.io.IOException; + +/** An Analyzer that filters LetterTokenizer with LowerCaseFilter. */ + +public final class SimpleAnalyzer extends Analyzer { + public TokenStream tokenStream(String fieldName, Reader reader) { + return new LowerCaseTokenizer(reader); + } + + public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { + Tokenizer tokenizer = (Tokenizer) getPreviousTokenStream(); + if (tokenizer == null) { + tokenizer = new LowerCaseTokenizer(reader); + setPreviousTokenStream(tokenizer); + } else + tokenizer.reset(reader); + return tokenizer; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/SinkTokenizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/SinkTokenizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/SinkTokenizer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,108 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.analysis; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +/** + * A SinkTokenizer can be used to cache Tokens for use in an Analyzer + * + * @see TeeTokenFilter + * + **/ +public class SinkTokenizer extends Tokenizer { + protected List/**/ lst = new ArrayList/**/(); + protected Iterator/**/ iter; + + public SinkTokenizer(List/**/ input) { + this.lst = input; + if (this.lst == null) this.lst = new ArrayList/**/(); + } + + public SinkTokenizer() { + this.lst = new ArrayList/**/(); + } + + public SinkTokenizer(int initCap){ + this.lst = new ArrayList/**/(initCap); + } + + /** + * Get the tokens in the internal List. + *

+ * WARNING: Adding tokens to this list requires the {@link #reset()} method to be called in order for them + * to be made available. Also, this Tokenizer does nothing to protect against {@link java.util.ConcurrentModificationException}s + * in the case of adds happening while {@link #next(org.apache.lucene.analysis.Token)} is being called. + *

+ * WARNING: Since this SinkTokenizer can be reset and the cached tokens made available again, do not modify them. Modify clones instead. + * + * @return A List of {@link org.apache.lucene.analysis.Token}s + */ + public List/**/ getTokens() { + return lst; + } + + /** + * Returns the next token out of the list of cached tokens + * @return The next {@link org.apache.lucene.analysis.Token} in the Sink. + * @throws IOException + */ + public Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + if (iter == null) iter = lst.iterator(); + // Since this TokenStream can be reset we have to maintain the tokens as immutable + if (iter.hasNext()) { + Token nextToken = (Token) iter.next(); + return (Token) nextToken.clone(); + } + return null; + } + + + + /** + * Override this method to cache only certain tokens, or new tokens based + * on the old tokens. + * + * @param t The {@link org.apache.lucene.analysis.Token} to add to the sink + */ + public void add(Token t) { + if (t == null) return; + lst.add((Token) t.clone()); + } + + public void close() throws IOException { + //nothing to close + input = null; + lst = null; + } + + /** + * Reset the internal data structures to the start at the front of the list of tokens. Should be called + * if tokens were added to the list after an invocation of {@link #next(Token)} + * @throws IOException + */ + public void reset() throws IOException { + iter = lst.iterator(); + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/StopAnalyzer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/StopAnalyzer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/StopAnalyzer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,92 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.Set; + +/** Filters LetterTokenizer with LowerCaseFilter and StopFilter. */ + +public final class StopAnalyzer extends Analyzer { + private Set stopWords; + + /** An array containing some common English words that are not usually useful + for searching. */ + public static final String[] ENGLISH_STOP_WORDS = { + "a", "an", "and", "are", "as", "at", "be", "but", "by", + "for", "if", "in", "into", "is", "it", + "no", "not", "of", "on", "or", "such", + "that", "the", "their", "then", "there", "these", + "they", "this", "to", "was", "will", "with" + }; + + /** Builds an analyzer which removes words in ENGLISH_STOP_WORDS. */ + public StopAnalyzer() { + stopWords = StopFilter.makeStopSet(ENGLISH_STOP_WORDS); + } + + /** Builds an analyzer with the stop words from the given set. + */ + public StopAnalyzer(Set stopWords) { + this.stopWords = stopWords; + } + + /** Builds an analyzer which removes words in the provided array. */ + public StopAnalyzer(String[] stopWords) { + this.stopWords = StopFilter.makeStopSet(stopWords); + } + + /** Builds an analyzer with the stop words from the given file. + * @see WordlistLoader#getWordSet(File) + */ + public StopAnalyzer(File stopwordsFile) throws IOException { + stopWords = WordlistLoader.getWordSet(stopwordsFile); + } + + /** Builds an analyzer with the stop words from the given reader. + * @see WordlistLoader#getWordSet(Reader) + */ + public StopAnalyzer(Reader stopwords) throws IOException { + stopWords = WordlistLoader.getWordSet(stopwords); + } + + /** Filters LowerCaseTokenizer with StopFilter. */ + public TokenStream tokenStream(String fieldName, Reader reader) { + return new StopFilter(new LowerCaseTokenizer(reader), stopWords); + } + + /** Filters LowerCaseTokenizer with StopFilter. */ + private class SavedStreams { + Tokenizer source; + TokenStream result; + }; + public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { + SavedStreams streams = (SavedStreams) getPreviousTokenStream(); + if (streams == null) { + streams = new SavedStreams(); + streams.source = new LowerCaseTokenizer(reader); + streams.result = new StopFilter(streams.source, stopWords); + setPreviousTokenStream(streams); + } else + streams.source.reset(reader); + return streams.result; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/StopFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/StopFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/StopFilter.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,173 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Arrays; +import java.util.Set; + +/** + * Removes stop words from a token stream. + */ + +public final class StopFilter extends TokenFilter { + + private static boolean ENABLE_POSITION_INCREMENTS_DEFAULT = false; + + private final CharArraySet stopWords; + private boolean enablePositionIncrements = ENABLE_POSITION_INCREMENTS_DEFAULT; + + /** + * Construct a token stream filtering the given input. + */ + public StopFilter(TokenStream input, String [] stopWords) + { + this(input, stopWords, false); + } + + /** + * Constructs a filter which removes words from the input + * TokenStream that are named in the array of words. + */ + public StopFilter(TokenStream in, String[] stopWords, boolean ignoreCase) { + super(in); + this.stopWords = (CharArraySet)makeStopSet(stopWords, ignoreCase); + } + + + /** + * Construct a token stream filtering the given input. + * If stopWords is an instance of {@link CharArraySet} (true if + * makeStopSet() was used to construct the set) it will be directly used + * and ignoreCase will be ignored since CharArraySet + * directly controls case sensitivity. + *

+ * If stopWords is not an instance of {@link CharArraySet}, + * a new CharArraySet will be constructed and ignoreCase will be + * used to specify the case sensitivity of that set. + * + * @param input + * @param stopWords The set of Stop Words. + * @param ignoreCase -Ignore case when stopping. + */ + public StopFilter(TokenStream input, Set stopWords, boolean ignoreCase) + { + super(input); + if (stopWords instanceof CharArraySet) { + this.stopWords = (CharArraySet)stopWords; + } else { + this.stopWords = new CharArraySet(stopWords.size(), ignoreCase); + this.stopWords.addAll(stopWords); + } + } + + /** + * Constructs a filter which removes words from the input + * TokenStream that are named in the Set. + * + * @see #makeStopSet(java.lang.String[]) + */ + public StopFilter(TokenStream in, Set stopWords) { + this(in, stopWords, false); + } + + /** + * Builds a Set from an array of stop words, + * appropriate for passing into the StopFilter constructor. + * This permits this stopWords construction to be cached once when + * an Analyzer is constructed. + * + * @see #makeStopSet(java.lang.String[], boolean) passing false to ignoreCase + */ + public static final Set makeStopSet(String[] stopWords) { + return makeStopSet(stopWords, false); + } + + /** + * + * @param stopWords + * @param ignoreCase If true, all words are lower cased first. + * @return a Set containing the words + */ + public static final Set makeStopSet(String[] stopWords, boolean ignoreCase) { + CharArraySet stopSet = new CharArraySet(stopWords.length, ignoreCase); + stopSet.addAll(Arrays.asList(stopWords)); + return stopSet; + } + + /** + * Returns the next input Token whose term() is not a stop word. + */ + public final Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + // return the first non-stop word found + int skippedPositions = 0; + for (Token nextToken = input.next(reusableToken); nextToken != null; nextToken = input.next(reusableToken)) { + if (!stopWords.contains(nextToken.termBuffer(), 0, nextToken.termLength())) { + if (enablePositionIncrements) { + nextToken.setPositionIncrement(nextToken.getPositionIncrement() + skippedPositions); + } + return nextToken; + } + skippedPositions += nextToken.getPositionIncrement(); + } + // reached EOS -- return null + return null; + } + + /** + * @see #setEnablePositionIncrementsDefault(boolean). + */ + public static boolean getEnablePositionIncrementsDefault() { + return ENABLE_POSITION_INCREMENTS_DEFAULT; + } + + /** + * Set the default position increments behavior of every StopFilter created from now on. + *

+ * Note: behavior of a single StopFilter instance can be modified + * with {@link #setEnablePositionIncrements(boolean)}. + * This static method allows control over behavior of classes using StopFilters internally, + * for example {@link org.apache.lucene.analysis.standard.StandardAnalyzer StandardAnalyzer}. + *

+ * Default : false. + * @see #setEnablePositionIncrements(boolean). + */ + public static void setEnablePositionIncrementsDefault(boolean defaultValue) { + ENABLE_POSITION_INCREMENTS_DEFAULT = defaultValue; + } + + /** + * @see #setEnablePositionIncrements(boolean). + */ + public boolean getEnablePositionIncrements() { + return enablePositionIncrements; + } + + /** + * Set to true to make this StopFilter enable position increments to result tokens. + *

+ * When set, when a token is stopped (omitted), the position increment of + * the following token is incremented. + *

+ * Default: see {@link #setEnablePositionIncrementsDefault(boolean)}. + */ + public void setEnablePositionIncrements(boolean enable) { + this.enablePositionIncrements = enable; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/TeeTokenFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/TeeTokenFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/TeeTokenFilter.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,72 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.analysis; + +import java.io.IOException; + + +/** + * Works in conjunction with the SinkTokenizer to provide the ability to set aside tokens + * that have already been analyzed. This is useful in situations where multiple fields share + * many common analysis steps and then go their separate ways. + *

+ * It is also useful for doing things like entity extraction or proper noun analysis as + * part of the analysis workflow and saving off those tokens for use in another field. + * + *

+SinkTokenizer sink1 = new SinkTokenizer(null);
+SinkTokenizer sink2 = new SinkTokenizer(null);
+
+TokenStream source1 = new TeeTokenFilter(new TeeTokenFilter(new WhitespaceTokenizer(reader1), sink1), sink2);
+TokenStream source2 = new TeeTokenFilter(new TeeTokenFilter(new WhitespaceTokenizer(reader2), sink1), sink2);
+
+TokenStream final1 = new LowerCaseFilter(source1);
+TokenStream final2 = source2;
+TokenStream final3 = new EntityDetect(sink1);
+TokenStream final4 = new URLDetect(sink2);
+
+d.add(new Field("f1", final1));
+d.add(new Field("f2", final2));
+d.add(new Field("f3", final3));
+d.add(new Field("f4", final4));
+ * 
+ * In this example, sink1 and sink2 will both get tokens from both reader1 and reader2 after whitespace tokenizer + and now we can further wrap any of these in extra analysis, and more "sources" can be inserted if desired. + Note, the EntityDetect and URLDetect TokenStreams are for the example and do not currently exist in Lucene +

+ * + * See http://issues.apache.org/jira/browse/LUCENE-1058 + * @see SinkTokenizer + * + **/ +public class TeeTokenFilter extends TokenFilter { + SinkTokenizer sink; + + public TeeTokenFilter(TokenStream input, SinkTokenizer sink) { + super(input); + this.sink = sink; + } + + public Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + Token nextToken = input.next(reusableToken); + sink.add(nextToken); + return nextToken; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/Token.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/Token.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/Token.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,859 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.Payload; +import org.apache.lucene.index.TermPositions; // for javadoc +import org.apache.lucene.util.ArrayUtil; + +/** A Token is an occurrence of a term from the text of a field. It consists of + a term's text, the start and end offset of the term in the text of the field, + and a type string. +

+ The start and end offsets permit applications to re-associate a token with + its source text, e.g., to display highlighted query terms in a document + browser, or to show matching text fragments in a KWIC (KeyWord In Context) + display, etc. +

+ The type is a string, assigned by a lexical analyzer + (a.k.a. tokenizer), naming the lexical or syntactic class that the token + belongs to. For example an end of sentence marker token might be implemented + with type "eos". The default token type is "word". +

+ A Token can optionally have metadata (a.k.a. Payload) in the form of a variable + length byte array. Use {@link TermPositions#getPayloadLength()} and + {@link TermPositions#getPayload(byte[], int)} to retrieve the payloads from the index. + +

+

+ WARNING: The status of the Payloads feature is experimental. + The APIs introduced here might change in the future and will not be + supported anymore in such a case. + +

+ +

NOTE: As of 2.3, Token stores the term text + internally as a malleable char[] termBuffer instead of + String termText. The indexing code and core tokenizers + have been changed to re-use a single Token instance, changing + its buffer and other fields in-place as the Token is + processed. This provides substantially better indexing + performance as it saves the GC cost of new'ing a Token and + String for every term. The APIs that accept String + termText are still available but a warning about the + associated performance cost has been added (below). The + {@link #termText()} method has been deprecated.

+ +

Tokenizers and filters should try to re-use a Token + instance when possible for best performance, by + implementing the {@link TokenStream#next(Token)} API. + Failing that, to create a new Token you should first use + one of the constructors that starts with null text. To load + the token from a char[] use {@link #setTermBuffer(char[], int, int)}. + To load from a String use {@link #setTermBuffer(String)} or {@link #setTermBuffer(String, int, int)}. + Alternatively you can get the Token's termBuffer by calling either {@link #termBuffer()}, + if you know that your text is shorter than the capacity of the termBuffer + or {@link #resizeTermBuffer(int)}, if there is any possibility + that you may need to grow the buffer. Fill in the characters of your term into this + buffer, with {@link String#getChars(int, int, char[], int)} if loading from a string, + or with {@link System#arraycopy(Object, int, Object, int, int)}, and finally call {@link #setTermLength(int)} to + set the length of the term text. See LUCENE-969 + for details.

+

Typical reuse patterns: +

    +
  • Copying text from a string (type is reset to #DEFAULT_TYPE if not specified):
    +
    +    return reusableToken.reinit(string, startOffset, endOffset[, type]);
    +  
    +
  • +
  • Copying some text from a string (type is reset to #DEFAULT_TYPE if not specified):
    +
    +    return reusableToken.reinit(string, 0, string.length(), startOffset, endOffset[, type]);
    +  
    +
  • + +
  • Copying text from char[] buffer (type is reset to #DEFAULT_TYPE if not specified):
    +
    +    return reusableToken.reinit(buffer, 0, buffer.length, startOffset, endOffset[, type]);
    +  
    +
  • +
  • Copying some text from a char[] buffer (type is reset to #DEFAULT_TYPE if not specified):
    +
    +    return reusableToken.reinit(buffer, start, end - start, startOffset, endOffset[, type]);
    +  
    +
  • +
  • Copying from one one Token to another (type is reset to #DEFAULT_TYPE if not specified):
    +
    +    return reusableToken.reinit(source.termBuffer(), 0, source.termLength(), source.startOffset(), source.endOffset()[, source.type()]);
    +  
    +
  • +
+ A few things to note: +
    +
  • clear() initializes most of the fields to default values, but not startOffset, endOffset and type.
  • +
  • Because TokenStreams can be chained, one cannot assume that the Token's current type is correct.
  • +
  • The startOffset and endOffset represent the start and offset in the source text. So be careful in adjusting them.
  • +
  • When caching a reusable token, clone it. When injecting a cached token into a stream that can be reset, clone it again.
  • +
+

+ + @see org.apache.lucene.index.Payload +*/ +public class Token implements Cloneable { + + public static final String DEFAULT_TYPE = "word"; + + private static int MIN_BUFFER_SIZE = 10; + + /** @deprecated We will remove this when we remove the + * deprecated APIs */ + private String termText; + + /** + * Characters for the term text. + * @deprecated This will be made private. Instead, use: + * {@link termBuffer()}, + * {@link #setTermBuffer(char[], int, int)}, + * {@link #setTermBuffer(String)}, or + * {@link #setTermBuffer(String, int, int)} + */ + char[] termBuffer; + + /** + * Length of term text in the buffer. + * @deprecated This will be made private. Instead, use: + * {@link termLength()}, or @{link setTermLength(int)}. + */ + int termLength; + + /** + * Start in source text. + * @deprecated This will be made private. Instead, use: + * {@link startOffset()}, or @{link setStartOffset(int)}. + */ + int startOffset; + + /** + * End in source text. + * @deprecated This will be made private. Instead, use: + * {@link endOffset()}, or @{link setEndOffset(int)}. + */ + int endOffset; + + /** + * The lexical type of the token. + * @deprecated This will be made private. Instead, use: + * {@link type()}, or @{link setType(String)}. + */ + String type = DEFAULT_TYPE; + + private int flags; + + /** + * @deprecated This will be made private. Instead, use: + * {@link getPayload()}, or @{link setPayload(Payload)}. + */ + Payload payload; + + /** + * @deprecated This will be made private. Instead, use: + * {@link getPositionIncrement()}, or @{link setPositionIncrement(String)}. + */ + int positionIncrement = 1; + + /** Constructs a Token will null text. */ + public Token() { + } + + /** Constructs a Token with null text and start & end + * offsets. + * @param start start offset in the source text + * @param end end offset in the source text */ + public Token(int start, int end) { + startOffset = start; + endOffset = end; + } + + /** Constructs a Token with null text and start & end + * offsets plus the Token type. + * @param start start offset in the source text + * @param end end offset in the source text + * @param typ the lexical type of this Token */ + public Token(int start, int end, String typ) { + startOffset = start; + endOffset = end; + type = typ; + } + + /** + * Constructs a Token with null text and start & end + * offsets plus flags. NOTE: flags is EXPERIMENTAL. + * @param start start offset in the source text + * @param end end offset in the source text + * @param flags The bits to set for this token + */ + public Token(int start, int end, int flags) { + startOffset = start; + endOffset = end; + this.flags = flags; + } + + /** Constructs a Token with the given term text, and start + * & end offsets. The type defaults to "word." + * NOTE: for better indexing speed you should + * instead use the char[] termBuffer methods to set the + * term text. + * @param text term text + * @param start start offset + * @param end end offset + * @deprecated + */ + public Token(String text, int start, int end) { + termText = text; + startOffset = start; + endOffset = end; + } + + /** Constructs a Token with the given text, start and end + * offsets, & type. NOTE: for better indexing + * speed you should instead use the char[] termBuffer + * methods to set the term text. + * @param text term text + * @param start start offset + * @param end end offset + * @param typ token type + * @deprecated + */ + public Token(String text, int start, int end, String typ) { + termText = text; + startOffset = start; + endOffset = end; + type = typ; + } + + /** + * Constructs a Token with the given text, start and end + * offsets, & type. NOTE: for better indexing + * speed you should instead use the char[] termBuffer + * methods to set the term text. + * @param text + * @param start + * @param end + * @param flags token type bits + * @deprecated + */ + public Token(String text, int start, int end, int flags) { + termText = text; + startOffset = start; + endOffset = end; + this.flags = flags; + } + + /** + * Constructs a Token with the given term buffer (offset + * & length), start and end + * offsets + * @param startTermBuffer + * @param termBufferOffset + * @param termBufferLength + * @param start + * @param end + */ + public Token(char[] startTermBuffer, int termBufferOffset, int termBufferLength, int start, int end) { + setTermBuffer(startTermBuffer, termBufferOffset, termBufferLength); + startOffset = start; + endOffset = end; + } + + /** Set the position increment. This determines the position of this token + * relative to the previous Token in a {@link TokenStream}, used in phrase + * searching. + * + *

The default value is one. + * + *

Some common uses for this are:

    + * + *
  • Set it to zero to put multiple terms in the same position. This is + * useful if, e.g., a word has multiple stems. Searches for phrases + * including either stem will match. In this case, all but the first stem's + * increment should be set to zero: the increment of the first instance + * should be one. Repeating a token with an increment of zero can also be + * used to boost the scores of matches on that token. + * + *
  • Set it to values greater than one to inhibit exact phrase matches. + * If, for example, one does not want phrases to match across removed stop + * words, then one could build a stop word filter that removes stop words and + * also sets the increment to the number of stop words removed before each + * non-stop word. Then exact phrase queries will only match when the terms + * occur with no intervening stop words. + * + *
+ * @param positionIncrement the distance from the prior term + * @see org.apache.lucene.index.TermPositions + */ + public void setPositionIncrement(int positionIncrement) { + if (positionIncrement < 0) + throw new IllegalArgumentException + ("Increment must be zero or greater: " + positionIncrement); + this.positionIncrement = positionIncrement; + } + + /** Returns the position increment of this Token. + * @see #setPositionIncrement + */ + public int getPositionIncrement() { + return positionIncrement; + } + + /** Sets the Token's term text. NOTE: for better + * indexing speed you should instead use the char[] + * termBuffer methods to set the term text. + * @deprecated use {@link #setTermBuffer(char[], int, int)} or + * {@link #setTermBuffer(String)} or + * {@link #setTermBuffer(String, int, int)}. + */ + public void setTermText(String text) { + termText = text; + termBuffer = null; + } + + /** Returns the Token's term text. + * + * @deprecated This method now has a performance penalty + * because the text is stored internally in a char[]. If + * possible, use {@link #termBuffer()} and {@link + * #termLength()} directly instead. If you really need a + * String, use {@link #term()} + */ + public final String termText() { + if (termText == null && termBuffer != null) + termText = new String(termBuffer, 0, termLength); + return termText; + } + + /** Returns the Token's term text. + * + * This method has a performance penalty + * because the text is stored internally in a char[]. If + * possible, use {@link #termBuffer()} and {@link + * #termLength()} directly instead. If you really need a + * String, use this method, which is nothing more than + * a convenience call to new String(token.termBuffer(), 0, token.termLength()) + */ + public final String term() { + if (termText != null) + return termText; + initTermBuffer(); + return new String(termBuffer, 0, termLength); + } + + /** Copies the contents of buffer, starting at offset for + * length characters, into the termBuffer array. + * @param buffer the buffer to copy + * @param offset the index in the buffer of the first character to copy + * @param length the number of characters to copy + */ + public final void setTermBuffer(char[] buffer, int offset, int length) { + termText = null; + char[] newCharBuffer = growTermBuffer(length); + if (newCharBuffer != null) { + termBuffer = newCharBuffer; + } + System.arraycopy(buffer, offset, termBuffer, 0, length); + termLength = length; + } + + /** Copies the contents of buffer into the termBuffer array. + * @param buffer the buffer to copy + */ + public final void setTermBuffer(String buffer) { + termText = null; + int length = buffer.length(); + char[] newCharBuffer = growTermBuffer(length); + if (newCharBuffer != null) { + termBuffer = newCharBuffer; + } + buffer.getChars(0, length, termBuffer, 0); + termLength = length; + } + + /** Copies the contents of buffer, starting at offset and continuing + * for length characters, into the termBuffer array. + * @param buffer the buffer to copy + * @param offset the index in the buffer of the first character to copy + * @param length the number of characters to copy + */ + public final void setTermBuffer(String buffer, int offset, int length) { + assert offset <= buffer.length(); + assert offset + length <= buffer.length(); + termText = null; + char[] newCharBuffer = growTermBuffer(length); + if (newCharBuffer != null) { + termBuffer = newCharBuffer; + } + buffer.getChars(offset, offset + length, termBuffer, 0); + termLength = length; + } + + /** Returns the internal termBuffer character array which + * you can then directly alter. If the array is too + * small for your token, use {@link + * #resizeTermBuffer(int)} to increase it. After + * altering the buffer be sure to call {@link + * #setTermLength} to record the number of valid + * characters that were placed into the termBuffer. */ + public final char[] termBuffer() { + initTermBuffer(); + return termBuffer; + } + + /** Grows the termBuffer to at least size newSize, preserving the + * existing content. Note: If the next operation is to change + * the contents of the term buffer use + * {@link #setTermBuffer(char[], int, int)}, + * {@link #setTermBuffer(String)}, or + * {@link #setTermBuffer(String, int, int)} + * to optimally combine the resize with the setting of the termBuffer. + * @param newSize minimum size of the new termBuffer + * @return newly created termBuffer with length >= newSize + */ + public char[] resizeTermBuffer(int newSize) { + char[] newCharBuffer = growTermBuffer(newSize); + if (termBuffer == null) { + // If there were termText, then preserve it. + // note that if termBuffer is null then newCharBuffer cannot be null + assert newCharBuffer != null; + if (termText != null) { + termText.getChars(0, termText.length(), newCharBuffer, 0); + } + termBuffer = newCharBuffer; + } else if (newCharBuffer != null) { + // Note: if newCharBuffer != null then termBuffer needs to grow. + // If there were a termBuffer, then preserve it + System.arraycopy(termBuffer, 0, newCharBuffer, 0, termBuffer.length); + termBuffer = newCharBuffer; + } + termText = null; + return termBuffer; + } + + /** Allocates a buffer char[] of at least newSize + * @param newSize minimum size of the buffer + * @return newly created buffer with length >= newSize or null if the current termBuffer is big enough + */ + private char[] growTermBuffer(int newSize) { + if (termBuffer != null) { + if (termBuffer.length >= newSize) + // Already big enough + return null; + else + // Not big enough; create a new array with slight + // over allocation: + return new char[ArrayUtil.getNextSize(newSize)]; + } else { + + // determine the best size + // The buffer is always at least MIN_BUFFER_SIZE + if (newSize < MIN_BUFFER_SIZE) { + newSize = MIN_BUFFER_SIZE; + } + + // If there is already a termText, then the size has to be at least that big + if (termText != null) { + int ttLength = termText.length(); + if (newSize < ttLength) { + newSize = ttLength; + } + } + + return new char[newSize]; + } + } + + // TODO: once we remove the deprecated termText() method + // and switch entirely to char[] termBuffer we don't need + // to use this method anymore + private void initTermBuffer() { + if (termBuffer == null) { + if (termText == null) { + termBuffer = new char[MIN_BUFFER_SIZE]; + termLength = 0; + } else { + int length = termText.length(); + if (length < MIN_BUFFER_SIZE) length = MIN_BUFFER_SIZE; + termBuffer = new char[length]; + termLength = termText.length(); + termText.getChars(0, termText.length(), termBuffer, 0); + termText = null; + } + } else if (termText != null) + termText = null; + } + + /** Return number of valid characters (length of the term) + * in the termBuffer array. */ + public final int termLength() { + initTermBuffer(); + return termLength; + } + + /** Set number of valid characters (length of the term) in + * the termBuffer array. Use this to truncate the termBuffer + * or to synchronize with external manipulation of the termBuffer. + * Note: to grow the size of the array, + * use {@link #resizeTermBuffer(int)} first. + * @param length the truncated length + */ + public final void setTermLength(int length) { + initTermBuffer(); + if (length > termBuffer.length) + throw new IllegalArgumentException("length " + length + " exceeds the size of the termBuffer (" + termBuffer.length + ")"); + termLength = length; + } + + /** Returns this Token's starting offset, the position of the first character + corresponding to this token in the source text. + + Note that the difference between endOffset() and startOffset() may not be + equal to termText.length(), as the term text may have been altered by a + stemmer or some other filter. */ + public final int startOffset() { + return startOffset; + } + + /** Set the starting offset. + @see #startOffset() */ + public void setStartOffset(int offset) { + this.startOffset = offset; + } + + /** Returns this Token's ending offset, one greater than the position of the + last character corresponding to this token in the source text. The length + of the token in the source text is (endOffset - startOffset). */ + public final int endOffset() { + return endOffset; + } + + /** Set the ending offset. + @see #endOffset() */ + public void setEndOffset(int offset) { + this.endOffset = offset; + } + + /** Returns this Token's lexical type. Defaults to "word". */ + public final String type() { + return type; + } + + /** Set the lexical type. + @see #type() */ + public final void setType(String type) { + this.type = type; + } + + /** + * EXPERIMENTAL: While we think this is here to stay, we may want to change it to be a long. + *

+ * + * Get the bitset for any bits that have been set. This is completely distinct from {@link #type()}, although they do share similar purposes. + * The flags can be used to encode information about the token for use by other {@link org.apache.lucene.analysis.TokenFilter}s. + * + * + * @return The bits + */ + public int getFlags() { + return flags; + } + + /** + * @see #getFlags() + */ + public void setFlags(int flags) { + this.flags = flags; + } + + /** + * Returns this Token's payload. + */ + public Payload getPayload() { + return this.payload; + } + + /** + * Sets this Token's payload. + */ + public void setPayload(Payload payload) { + this.payload = payload; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append('('); + initTermBuffer(); + if (termBuffer == null) + sb.append("null"); + else + sb.append(termBuffer, 0, termLength); + sb.append(',').append(startOffset).append(',').append(endOffset); + if (!type.equals("word")) + sb.append(",type=").append(type); + if (positionIncrement != 1) + sb.append(",posIncr=").append(positionIncrement); + sb.append(')'); + return sb.toString(); + } + + /** Resets the term text, payload, flags, and positionIncrement to default. + * Other fields such as startOffset, endOffset and the token type are + * not reset since they are normally overwritten by the tokenizer. */ + public void clear() { + payload = null; + // Leave termBuffer to allow re-use + termLength = 0; + termText = null; + positionIncrement = 1; + flags = 0; + // startOffset = endOffset = 0; + // type = DEFAULT_TYPE; + } + + public Object clone() { + try { + Token t = (Token)super.clone(); + // Do a deep clone + if (termBuffer != null) { + t.termBuffer = (char[]) termBuffer.clone(); + } + if (payload != null) { + t.setPayload((Payload) payload.clone()); + } + return t; + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); // shouldn't happen + } + } + + /** Makes a clone, but replaces the term buffer & + * start/end offset in the process. This is more + * efficient than doing a full clone (and then calling + * setTermBuffer) because it saves a wasted copy of the old + * termBuffer. */ + public Token clone(char[] newTermBuffer, int newTermOffset, int newTermLength, int newStartOffset, int newEndOffset) { + final Token t = new Token(newTermBuffer, newTermOffset, newTermLength, newStartOffset, newEndOffset); + t.positionIncrement = positionIncrement; + t.flags = flags; + t.type = type; + if (payload != null) + t.payload = (Payload) payload.clone(); + return t; + } + + public boolean equals(Object obj) { + if (obj == this) + return true; + + if (obj instanceof Token) { + Token other = (Token) obj; + + initTermBuffer(); + other.initTermBuffer(); + + if (termLength == other.termLength && + startOffset == other.startOffset && + endOffset == other.endOffset && + flags == other.flags && + positionIncrement == other.positionIncrement && + subEqual(type, other.type) && + subEqual(payload, other.payload)) { + for(int i=0;i + This is an abstract class. + NOTE: subclasses must override {@link #next(Token)}. It's + also OK to instead override {@link #next()} but that + method is now deprecated in favor of {@link #next(Token)}. + */ +public abstract class TokenFilter extends TokenStream { + /** The source of tokens for this filter. */ + protected TokenStream input; + + /** Construct a token stream filtering the given input. */ + protected TokenFilter(TokenStream input) { + this.input = input; + } + + /** Close the input TokenStream. */ + public void close() throws IOException { + input.close(); + } + + /** Reset the filter as well as the input TokenStream. */ + public void reset() throws IOException { + super.reset(); + input.reset(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/TokenStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/TokenStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/TokenStream.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,110 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.Payload; + +import java.io.IOException; + +/** A TokenStream enumerates the sequence of tokens, either from + fields of a document or from query text. +

+ This is an abstract class. Concrete subclasses are: +

    +
  • {@link Tokenizer}, a TokenStream + whose input is a Reader; and +
  • {@link TokenFilter}, a TokenStream + whose input is another TokenStream. +
+ NOTE: subclasses must override {@link #next(Token)}. It's + also OK to instead override {@link #next()} but that + method is now deprecated in favor of {@link #next(Token)}. + */ + +public abstract class TokenStream { + + /** Returns the next token in the stream, or null at EOS. + * @deprecated The returned Token is a "full private copy" (not + * re-used across calls to next()) but will be slower + * than calling {@link #next(Token)} instead.. */ + public Token next() throws IOException { + final Token reusableToken = new Token(); + Token nextToken = next(reusableToken); + + if (nextToken != null) { + Payload p = nextToken.getPayload(); + if (p != null) { + nextToken.setPayload((Payload) p.clone()); + } + } + + return nextToken; + } + + /** Returns the next token in the stream, or null at EOS. + * When possible, the input Token should be used as the + * returned Token (this gives fastest tokenization + * performance), but this is not required and a new Token + * may be returned. Callers may re-use a single Token + * instance for successive calls to this method. + *

+ * This implicitly defines a "contract" between + * consumers (callers of this method) and + * producers (implementations of this method + * that are the source for tokens): + *

    + *
  • A consumer must fully consume the previously + * returned Token before calling this method again.
  • + *
  • A producer must call {@link Token#clear()} + * before setting the fields in it & returning it
  • + *
+ * Also, the producer must make no assumptions about a + * Token after it has been returned: the caller may + * arbitrarily change it. If the producer needs to hold + * onto the token for subsequent calls, it must clone() + * it before storing it. + * Note that a {@link TokenFilter} is considered a consumer. + * @param reusableToken a Token that may or may not be used to + * return; this parameter should never be null (the callee + * is not required to check for null before using it, but it is a + * good idea to assert that it is not null.) + * @return next token in the stream or null if end-of-stream was hit + */ + public Token next(final Token reusableToken) throws IOException { + // We don't actually use inputToken, but still add this assert + assert reusableToken != null; + return next(); + } + + /** Resets this stream to the beginning. This is an + * optional operation, so subclasses may or may not + * implement this method. Reset() is not needed for + * the standard indexing process. However, if the Tokens + * of a TokenStream are intended to be consumed more than + * once, it is necessary to implement reset(). Note that + * if your TokenStream caches tokens and feeds them back + * again after a reset, it is imperative that you + * clone the tokens when you store them away (on the + * first pass) as well as when you return them (on future + * passes after reset()). + */ + public void reset() throws IOException {} + + /** Releases resources associated with this stream. */ + public void close() throws IOException {} +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/Tokenizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/Tokenizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/Tokenizer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,59 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; +import java.io.IOException; + +/** A Tokenizer is a TokenStream whose input is a Reader. +

+ This is an abstract class. +

+ NOTE: subclasses must override {@link #next(Token)}. It's + also OK to instead override {@link #next()} but that + method is now deprecated in favor of {@link #next(Token)}. +

+ NOTE: subclasses overriding {@link #next(Token)} must + call {@link Token#clear()}. + */ + +public abstract class Tokenizer extends TokenStream { + /** The text source for this Tokenizer. */ + protected Reader input; + + /** Construct a tokenizer with null input. */ + protected Tokenizer() {} + + /** Construct a token stream processing the given input. */ + protected Tokenizer(Reader input) { + this.input = input; + } + + /** By default, closes the input Reader. */ + public void close() throws IOException { + input.close(); + } + + /** Expert: Reset the tokenizer to a new reader. Typically, an + * analyzer (in its reusableTokenStream method) will use + * this to re-use a previously created tokenizer. */ + public void reset(Reader input) throws IOException { + this.input = input; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/WhitespaceAnalyzer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/WhitespaceAnalyzer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/WhitespaceAnalyzer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,39 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; +import java.io.IOException; + +/** An Analyzer that uses WhitespaceTokenizer. */ + +public final class WhitespaceAnalyzer extends Analyzer { + public TokenStream tokenStream(String fieldName, Reader reader) { + return new WhitespaceTokenizer(reader); + } + + public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { + Tokenizer tokenizer = (Tokenizer) getPreviousTokenStream(); + if (tokenizer == null) { + tokenizer = new WhitespaceTokenizer(reader); + setPreviousTokenStream(tokenizer); + } else + tokenizer.reset(reader); + return tokenizer; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/WhitespaceTokenizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/WhitespaceTokenizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/WhitespaceTokenizer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,36 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; + +/** A WhitespaceTokenizer is a tokenizer that divides text at whitespace. + * Adjacent sequences of non-Whitespace characters form tokens. */ + +public class WhitespaceTokenizer extends CharTokenizer { + /** Construct a new WhitespaceTokenizer. */ + public WhitespaceTokenizer(Reader in) { + super(in); + } + + /** Collects only characters which do not satisfy + * {@link Character#isWhitespace(char)}.*/ + protected boolean isTokenChar(char c) { + return !Character.isWhitespace(c); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/WordlistLoader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/WordlistLoader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/WordlistLoader.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,120 @@ +package org.apache.lucene.analysis; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.HashMap; +import java.util.HashSet; + +/** + * Loader for text files that represent a list of stopwords. + * + * + * @version $Id: WordlistLoader.java,v 1.1 2012/08/17 14:55:08 marcin Exp $ + */ +public class WordlistLoader { + + /** + * Loads a text file and adds every line as an entry to a HashSet (omitting + * leading and trailing whitespace). Every line of the file should contain only + * one word. The words need to be in lowercase if you make use of an + * Analyzer which uses LowerCaseFilter (like StandardAnalyzer). + * + * @param wordfile File containing the wordlist + * @return A HashSet with the file's words + */ + public static HashSet getWordSet(File wordfile) throws IOException { + HashSet result = new HashSet(); + FileReader reader = null; + try { + reader = new FileReader(wordfile); + result = getWordSet(reader); + } + finally { + if (reader != null) + reader.close(); + } + return result; + } + + /** + * Reads lines from a Reader and adds every line as an entry to a HashSet (omitting + * leading and trailing whitespace). Every line of the Reader should contain only + * one word. The words need to be in lowercase if you make use of an + * Analyzer which uses LowerCaseFilter (like StandardAnalyzer). + * + * @param reader Reader containing the wordlist + * @return A HashSet with the reader's words + */ + public static HashSet getWordSet(Reader reader) throws IOException { + HashSet result = new HashSet(); + BufferedReader br = null; + try { + if (reader instanceof BufferedReader) { + br = (BufferedReader) reader; + } else { + br = new BufferedReader(reader); + } + String word = null; + while ((word = br.readLine()) != null) { + result.add(word.trim()); + } + } + finally { + if (br != null) + br.close(); + } + return result; + } + + /** + * Reads a stem dictionary. Each line contains: + *

word\tstem
+ * (i.e. two tab seperated words) + * + * @return stem dictionary that overrules the stemming algorithm + * @throws IOException + */ + public static HashMap getStemDict(File wordstemfile) throws IOException { + if (wordstemfile == null) + throw new NullPointerException("wordstemfile may not be null"); + HashMap result = new HashMap(); + BufferedReader br = null; + FileReader fr = null; + try { + fr = new FileReader(wordstemfile); + br = new BufferedReader(fr); + String line; + while ((line = br.readLine()) != null) { + String[] wordstem = line.split("\t", 2); + result.put(wordstem[0], wordstem[1]); + } + } finally { + if (fr != null) + fr.close(); + if (br != null) + br.close(); + } + return result; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/package.html 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,272 @@ + + + + + + + + +

API and code to convert text into indexable/searchable tokens. Covers {@link org.apache.lucene.analysis.Analyzer} and related classes.

+

Parsing? Tokenization? Analysis!

+

+Lucene, indexing and search library, accepts only plain text input. +

+

Parsing

+

+Applications that build their search capabilities upon Lucene may support documents in various formats – HTML, XML, PDF, Word – just to name a few. +Lucene does not care about the Parsing of these and other document formats, and it is the responsibility of the +application using Lucene to use an appropriate Parser to convert the original format into plain text before passing that plain text to Lucene. +

+

Tokenization

+

+Plain text passed to Lucene for indexing goes through a process generally called tokenization – namely breaking of the +input text into small indexing elements – +{@link org.apache.lucene.analysis.Token Tokens}. +The way input text is broken into tokens very +much dictates further capabilities of search upon that text. +For instance, sentences beginnings and endings can be identified to provide for more accurate phrase +and proximity searches (though sentence identification is not provided by Lucene). +

+In some cases simply breaking the input text into tokens is not enough – a deeper Analysis is needed, +providing for several functions, including (but not limited to): +

    +
  • Stemming – + Replacing of words by their stems. + For instance with English stemming "bikes" is replaced by "bike"; + now query "bike" can find both documents containing "bike" and those containing "bikes". +
  • +
  • Stop Words Filtering – + Common words like "the", "and" and "a" rarely add any value to a search. + Removing them shrinks the index size and increases performance. + It may also reduce some "noise" and actually improve search quality. +
  • +
  • Text Normalization – + Stripping accents and other character markings can make for better searching. +
  • +
  • Synonym Expansion – + Adding in synonyms at the same token position as the current word can mean better + matching when users search with words in the synonym set. +
  • +
+

+

Core Analysis

+

+ The analysis package provides the mechanism to convert Strings and Readers into tokens that can be indexed by Lucene. There + are three main classes in the package from which all analysis processes are derived. These are: +

    +
  • {@link org.apache.lucene.analysis.Analyzer} – An Analyzer is responsible for building a {@link org.apache.lucene.analysis.TokenStream} which can be consumed + by the indexing and searching processes. See below for more information on implementing your own Analyzer.
  • +
  • {@link org.apache.lucene.analysis.Tokenizer} – A Tokenizer is a {@link org.apache.lucene.analysis.TokenStream} and is responsible for breaking + up incoming text into {@link org.apache.lucene.analysis.Token}s. In most cases, an Analyzer will use a Tokenizer as the first step in + the analysis process.
  • +
  • {@link org.apache.lucene.analysis.TokenFilter} – A TokenFilter is also a {@link org.apache.lucene.analysis.TokenStream} and is responsible + for modifying {@link org.apache.lucene.analysis.Token}s that have been created by the Tokenizer. Common modifications performed by a + TokenFilter are: deletion, stemming, synonym injection, and down casing. Not all Analyzers require TokenFilters
  • +
+

+

Hints, Tips and Traps

+

+ The synergy between {@link org.apache.lucene.analysis.Analyzer} and {@link org.apache.lucene.analysis.Tokenizer} + is sometimes confusing. To ease on this confusion, some clarifications: +

    +
  • The {@link org.apache.lucene.analysis.Analyzer} is responsible for the entire task of + creating tokens out of the input text, while the {@link org.apache.lucene.analysis.Tokenizer} + is only responsible for breaking the input text into tokens. Very likely, tokens created + by the {@link org.apache.lucene.analysis.Tokenizer} would be modified or even omitted + by the {@link org.apache.lucene.analysis.Analyzer} (via one or more + {@link org.apache.lucene.analysis.TokenFilter}s) before being returned. +
  • +
  • {@link org.apache.lucene.analysis.Tokenizer} is a {@link org.apache.lucene.analysis.TokenStream}, + but {@link org.apache.lucene.analysis.Analyzer} is not. +
  • +
  • {@link org.apache.lucene.analysis.Analyzer} is "field aware", but + {@link org.apache.lucene.analysis.Tokenizer} is not. +
  • +
+

+

+ Lucene Java provides a number of analysis capabilities, the most commonly used one being the {@link + org.apache.lucene.analysis.standard.StandardAnalyzer}. Many applications will have a long and industrious life with nothing more + than the StandardAnalyzer. However, there are a few other classes/packages that are worth mentioning: +

    +
  1. {@link org.apache.lucene.analysis.PerFieldAnalyzerWrapper} – Most Analyzers perform the same operation on all + {@link org.apache.lucene.document.Field}s. The PerFieldAnalyzerWrapper can be used to associate a different Analyzer with different + {@link org.apache.lucene.document.Field}s.
  2. +
  3. The contrib/analyzers library located at the root of the Lucene distribution has a number of different Analyzer implementations to solve a variety + of different problems related to searching. Many of the Analyzers are designed to analyze non-English languages.
  4. +
  5. The contrib/snowball library + located at the root of the Lucene distribution has Analyzer and TokenFilter + implementations for a variety of Snowball stemmers. + See http://snowball.tartarus.org + for more information on Snowball stemmers.
  6. +
  7. There are a variety of Tokenizer and TokenFilter implementations in this package. Take a look around, chances are someone has implemented what you need.
  8. +
+

+

+ Analysis is one of the main causes of performance degradation during indexing. Simply put, the more you analyze the slower the indexing (in most cases). + Perhaps your application would be just fine using the simple {@link org.apache.lucene.analysis.WhitespaceTokenizer} combined with a + {@link org.apache.lucene.analysis.StopFilter}. The contrib/benchmark library can be useful for testing out the speed of the analysis process. +

+

Invoking the Analyzer

+

+ Applications usually do not invoke analysis – Lucene does it for them: +

    +
  • At indexing, as a consequence of + {@link org.apache.lucene.index.IndexWriter#addDocument(org.apache.lucene.document.Document) addDocument(doc)}, + the Analyzer in effect for indexing is invoked for each indexed field of the added document. +
  • +
  • At search, as a consequence of + {@link org.apache.lucene.queryParser.QueryParser#parse(java.lang.String) QueryParser.parse(queryText)}, + the QueryParser may invoke the Analyzer in effect. + Note that for some queries analysis does not take place, e.g. wildcard queries. +
  • +
+ However an application might invoke Analysis of any text for testing or for any other purpose, something like: +
+      Analyzer analyzer = new StandardAnalyzer(); // or any other analyzer
+      TokenStream ts = analyzer.tokenStream("myfield",new StringReader("some text goes here"));
+      Token t = ts.next();
+      while (t!=null) {
+        System.out.println("token: "+t));
+        t = ts.next();
+      }
+  
+

+

Indexing Analysis vs. Search Analysis

+

+ Selecting the "correct" analyzer is crucial + for search quality, and can also affect indexing and search performance. + The "correct" analyzer differs between applications. + Lucene java's wiki page + AnalysisParalysis + provides some data on "analyzing your analyzer". + Here are some rules of thumb: +

    +
  1. Test test test... (did we say test?)
  2. +
  3. Beware of over analysis – might hurt indexing performance.
  4. +
  5. Start with same analyzer for indexing and search, otherwise searches would not find what they are supposed to...
  6. +
  7. In some cases a different analyzer is required for indexing and search, for instance: +
      +
    • Certain searches require more stop words to be filtered. (I.e. more than those that were filtered at indexing.)
    • +
    • Query expansion by synonyms, acronyms, auto spell correction, etc.
    • +
    + This might sometimes require a modified analyzer – see the next section on how to do that. +
  8. +
+

+

Implementing your own Analyzer

+

Creating your own Analyzer is straightforward. It usually involves either wrapping an existing Tokenizer and set of TokenFilters to create a new Analyzer +or creating both the Analyzer and a Tokenizer or TokenFilter. Before pursuing this approach, you may find it worthwhile +to explore the contrib/analyzers library and/or ask on the java-user@lucene.apache.org mailing list first to see if what you need already exists. +If you are still committed to creating your own Analyzer or TokenStream derivation (Tokenizer or TokenFilter) have a look at +the source code of any one of the many samples located in this package. +

+

+ The following sections discuss some aspects of implementing your own analyzer. +

+

Field Section Boundaries

+

+ When {@link org.apache.lucene.document.Document#add(org.apache.lucene.document.Fieldable) document.add(field)} + is called multiple times for the same field name, we could say that each such call creates a new + section for that field in that document. + In fact, a separate call to + {@link org.apache.lucene.analysis.Analyzer#tokenStream(java.lang.String, java.io.Reader) tokenStream(field,reader)} + would take place for each of these so called "sections". + However, the default Analyzer behavior is to treat all these sections as one large section. + This allows phrase search and proximity search to seamlessly cross + boundaries between these "sections". + In other words, if a certain field "f" is added like this: +

+      document.add(new Field("f","first ends",...);
+      document.add(new Field("f","starts two",...);
+      indexWriter.addDocument(document);
+  
+ Then, a phrase search for "ends starts" would find that document. + Where desired, this behavior can be modified by introducing a "position gap" between consecutive field "sections", + simply by overriding + {@link org.apache.lucene.analysis.Analyzer#getPositionIncrementGap(java.lang.String) Analyzer.getPositionIncrementGap(fieldName)}: +
+      Analyzer myAnalyzer = new StandardAnalyzer() {
+         public int getPositionIncrementGap(String fieldName) {
+           return 10;
+         }
+      };
+  
+

+

Token Position Increments

+

+ By default, all tokens created by Analyzers and Tokenizers have a + {@link org.apache.lucene.analysis.Token#getPositionIncrement() position increment} of one. + This means that the position stored for that token in the index would be one more than + that of the previous token. + Recall that phrase and proximity searches rely on position info. +

+

+ If the selected analyzer filters the stop words "is" and "the", then for a document + containing the string "blue is the sky", only the tokens "blue", "sky" are indexed, + with position("sky") = 1 + position("blue"). Now, a phrase query "blue is the sky" + would find that document, because the same analyzer filters the same stop words from + that query. But also the phrase query "blue sky" would find that document. +

+

+ If this behavior does not fit the application needs, + a modified analyzer can be used, that would increment further the positions of + tokens following a removed stop word, using + {@link org.apache.lucene.analysis.Token#setPositionIncrement(int)}. + This can be done with something like: +

+      public TokenStream tokenStream(final String fieldName, Reader reader) {
+        final TokenStream ts = someAnalyzer.tokenStream(fieldName, reader);
+        TokenStream res = new TokenStream() {
+          public Token next() throws IOException {
+            int extraIncrement = 0;
+            while (true) {
+              Token t = ts.next();
+              if (t!=null) {
+                if (stopWords.contains(t.termText())) {
+                  extraIncrement++; // filter this word
+                  continue;
+                } 
+                if (extraIncrement>0) {
+                  t.setPositionIncrement(t.getPositionIncrement()+extraIncrement);
+                }
+              }
+              return t;
+            }
+          }
+        };
+        return res;
+      }
+   
+ Now, with this modified analyzer, the phrase query "blue sky" would find that document. + But note that this is yet not a perfect solution, because any phrase query "blue w1 w2 sky" + where both w1 and w2 are stop words would match that document. +

+

+ Few more use cases for modifying position increments are: +

    +
  1. Inhibiting phrase and proximity matches in sentence boundaries – for this, a tokenizer that + identifies a new sentence can add 1 to the position increment of the first token of the new sentence.
  2. +
  3. Injecting synonyms – here, synonyms of a token should be added after that token, + and their position increment should be set to 0. + As result, all synonyms of a token would be considered to appear in exactly the + same position as that token, and so would they be seen by phrase and proximity searches.
  4. +
+

+ + Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/SnowballAnalyzer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/SnowballAnalyzer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/SnowballAnalyzer.java 17 Aug 2012 14:55:15 -0000 1.1 @@ -0,0 +1,59 @@ +package org.apache.lucene.analysis.snowball; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.*; +import org.apache.lucene.analysis.standard.*; + +import java.io.Reader; +import java.util.Set; + +/** Filters {@link StandardTokenizer} with {@link StandardFilter}, {@link + * LowerCaseFilter}, {@link StopFilter} and {@link SnowballFilter}. + * + * Available stemmers are listed in {@link net.sf.snowball.ext}. The name of a + * stemmer is the part of the class name before "Stemmer", e.g., the stemmer in + * {@link org.tartarus.snowball.ext.EnglishStemmer} is named "English". + */ +public class SnowballAnalyzer extends Analyzer { + private String name; + private Set stopSet; + + /** Builds the named analyzer with no stop words. */ + public SnowballAnalyzer(String name) { + this.name = name; + } + + /** Builds the named analyzer with the given stop words. */ + public SnowballAnalyzer(String name, String[] stopWords) { + this(name); + stopSet = StopFilter.makeStopSet(stopWords); + } + + /** Constructs a {@link StandardTokenizer} filtered by a {@link + StandardFilter}, a {@link LowerCaseFilter} and a {@link StopFilter}. */ + public TokenStream tokenStream(String fieldName, Reader reader) { + TokenStream result = new StandardTokenizer(reader); + result = new StandardFilter(result); + result = new LowerCaseFilter(result); + if (stopSet != null) + result = new StopFilter(result, stopSet); + result = new SnowballFilter(result, name); + return result; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/SnowballFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/SnowballFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/SnowballFilter.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,76 @@ +package org.apache.lucene.analysis.snowball; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.analysis.Token; +import org.apache.lucene.analysis.TokenFilter; +import org.apache.lucene.analysis.TokenStream; +import org.tartarus.snowball.SnowballProgram; + +/** + * A filter that stems words using a Snowball-generated stemmer. + * + * Available stemmers are listed in {@link org.tartarus.snowball.ext}. + */ +public class SnowballFilter extends TokenFilter { + + private SnowballProgram stemmer; + + public SnowballFilter(TokenStream input, SnowballProgram stemmer) { + super(input); + this.stemmer = stemmer; + } + + /** + * Construct the named stemming filter. + * + * Available stemmers are listed in {@link org.tartarus.snowball.ext}. + * The name of a stemmer is the part of the class name before "Stemmer", + * e.g., the stemmer in {@link org.tartarus.snowball.ext.EnglishStemmer} is named "English". + * + * @param in the input tokens to stem + * @param name the name of a stemmer + */ + public SnowballFilter(TokenStream in, String name) { + super(in); + try { + Class stemClass = Class.forName("org.tartarus.snowball.ext." + name + "Stemmer"); + stemmer = (SnowballProgram) stemClass.newInstance(); + } catch (Exception e) { + throw new RuntimeException(e.toString()); + } + } + + /** Returns the next input Token, after being stemmed */ + public final Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + Token nextToken = input.next(reusableToken); + if (nextToken == null) + return null; + String originalTerm = nextToken.term(); + stemmer.setCurrent(originalTerm); + stemmer.stem(); + String finalTerm = stemmer.getCurrent(); + // Don't bother updating, if it is unchanged. + if (!originalTerm.equals(finalTerm)) + nextToken.setTermBuffer(finalTerm); + return nextToken; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/snowball/package.html 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,7 @@ + + +{@link org.apache.lucene.analysis.TokenFilter} and {@link +org.apache.lucene.analysis.Analyzer} implementations that use Snowball +stemmers. + + Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardAnalyzer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardAnalyzer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardAnalyzer.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,264 @@ +package org.apache.lucene.analysis.standard; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.*; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.Set; + +/** + * Filters {@link StandardTokenizer} with {@link StandardFilter}, {@link + * LowerCaseFilter} and {@link StopFilter}, using a list of English stop words. + * + * @version $Id: StandardAnalyzer.java,v 1.1 2012/08/17 14:55:14 marcin Exp $ + */ +public class StandardAnalyzer extends Analyzer { + private Set stopSet; + + /** + * Specifies whether deprecated acronyms should be replaced with HOST type. + * This is false by default to support backward compatibility. + * + * @deprecated this should be removed in the next release (3.0). + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + */ + private boolean replaceInvalidAcronym = defaultReplaceInvalidAcronym; + + private static boolean defaultReplaceInvalidAcronym; + + // Default to true (fixed the bug), unless the system prop is set + static { + final String v = System.getProperty("org.apache.lucene.analysis.standard.StandardAnalyzer.replaceInvalidAcronym"); + if (v == null || v.equals("true")) + defaultReplaceInvalidAcronym = true; + else + defaultReplaceInvalidAcronym = false; + } + + /** + * + * @return true if new instances of StandardTokenizer will + * replace mischaracterized acronyms + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * @deprecated This will be removed (hardwired to true) in 3.0 + */ + public static boolean getDefaultReplaceInvalidAcronym() { + return defaultReplaceInvalidAcronym; + } + + /** + * + * @param replaceInvalidAcronym Set to true to have new + * instances of StandardTokenizer replace mischaracterized + * acronyms by default. Set to false to preseve the + * previous (before 2.4) buggy behavior. Alternatively, + * set the system property + * org.apache.lucene.analysis.standard.StandardAnalyzer.replaceInvalidAcronym + * to false. + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * @deprecated This will be removed (hardwired to true) in 3.0 + */ + public static void setDefaultReplaceInvalidAcronym(boolean replaceInvalidAcronym) { + defaultReplaceInvalidAcronym = replaceInvalidAcronym; + } + + + /** An array containing some common English words that are usually not + useful for searching. */ + public static final String[] STOP_WORDS = StopAnalyzer.ENGLISH_STOP_WORDS; + + /** Builds an analyzer with the default stop words ({@link #STOP_WORDS}). */ + public StandardAnalyzer() { + this(STOP_WORDS); + } + + /** Builds an analyzer with the given stop words. */ + public StandardAnalyzer(Set stopWords) { + stopSet = stopWords; + } + + /** Builds an analyzer with the given stop words. */ + public StandardAnalyzer(String[] stopWords) { + stopSet = StopFilter.makeStopSet(stopWords); + } + + /** Builds an analyzer with the stop words from the given file. + * @see WordlistLoader#getWordSet(File) + */ + public StandardAnalyzer(File stopwords) throws IOException { + stopSet = WordlistLoader.getWordSet(stopwords); + } + + /** Builds an analyzer with the stop words from the given reader. + * @see WordlistLoader#getWordSet(Reader) + */ + public StandardAnalyzer(Reader stopwords) throws IOException { + stopSet = WordlistLoader.getWordSet(stopwords); + } + + /** + * + * @param replaceInvalidAcronym Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * + * @deprecated Remove in 3.X and make true the only valid value + */ + public StandardAnalyzer(boolean replaceInvalidAcronym) { + this(STOP_WORDS); + this.replaceInvalidAcronym = replaceInvalidAcronym; + } + + /** + * @param stopwords The stopwords to use + * @param replaceInvalidAcronym Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * + * @deprecated Remove in 3.X and make true the only valid value + */ + public StandardAnalyzer(Reader stopwords, boolean replaceInvalidAcronym) throws IOException{ + this(stopwords); + this.replaceInvalidAcronym = replaceInvalidAcronym; + } + + /** + * @param stopwords The stopwords to use + * @param replaceInvalidAcronym Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * + * @deprecated Remove in 3.X and make true the only valid value + */ + public StandardAnalyzer(File stopwords, boolean replaceInvalidAcronym) throws IOException{ + this(stopwords); + this.replaceInvalidAcronym = replaceInvalidAcronym; + } + + /** + * + * @param stopwords The stopwords to use + * @param replaceInvalidAcronym Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * + * @deprecated Remove in 3.X and make true the only valid value + */ + public StandardAnalyzer(String [] stopwords, boolean replaceInvalidAcronym) throws IOException{ + this(stopwords); + this.replaceInvalidAcronym = replaceInvalidAcronym; + } + + /** + * @param stopwords The stopwords to use + * @param replaceInvalidAcronym Set to true if this analyzer should replace mischaracterized acronyms in the StandardTokenizer + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * + * @deprecated Remove in 3.X and make true the only valid value + */ + public StandardAnalyzer(Set stopwords, boolean replaceInvalidAcronym) throws IOException{ + this(stopwords); + this.replaceInvalidAcronym = replaceInvalidAcronym; + } + + /** Constructs a {@link StandardTokenizer} filtered by a {@link + StandardFilter}, a {@link LowerCaseFilter} and a {@link StopFilter}. */ + public TokenStream tokenStream(String fieldName, Reader reader) { + StandardTokenizer tokenStream = new StandardTokenizer(reader, replaceInvalidAcronym); + tokenStream.setMaxTokenLength(maxTokenLength); + TokenStream result = new StandardFilter(tokenStream); + result = new LowerCaseFilter(result); + result = new StopFilter(result, stopSet); + return result; + } + + private static final class SavedStreams { + StandardTokenizer tokenStream; + TokenStream filteredTokenStream; + } + + /** Default maximum allowed token length */ + public static final int DEFAULT_MAX_TOKEN_LENGTH = 255; + + private int maxTokenLength = DEFAULT_MAX_TOKEN_LENGTH; + + /** + * Set maximum allowed token length. If a token is seen + * that exceeds this length then it is discarded. This + * setting only takes effect the next time tokenStream or + * reusableTokenStream is called. + */ + public void setMaxTokenLength(int length) { + maxTokenLength = length; + } + + /** + * @see #setMaxTokenLength + */ + public int getMaxTokenLength() { + return maxTokenLength; + } + + public TokenStream reusableTokenStream(String fieldName, Reader reader) throws IOException { + SavedStreams streams = (SavedStreams) getPreviousTokenStream(); + if (streams == null) { + streams = new SavedStreams(); + setPreviousTokenStream(streams); + streams.tokenStream = new StandardTokenizer(reader); + streams.filteredTokenStream = new StandardFilter(streams.tokenStream); + streams.filteredTokenStream = new LowerCaseFilter(streams.filteredTokenStream); + streams.filteredTokenStream = new StopFilter(streams.filteredTokenStream, stopSet); + } else { + streams.tokenStream.reset(reader); + } + streams.tokenStream.setMaxTokenLength(maxTokenLength); + + streams.tokenStream.setReplaceInvalidAcronym(replaceInvalidAcronym); + + return streams.filteredTokenStream; + } + + /** + * + * @return true if this Analyzer is replacing mischaracterized acronyms in the StandardTokenizer + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * @deprecated This will be removed (hardwired to true) in 3.0 + */ + public boolean isReplaceInvalidAcronym() { + return replaceInvalidAcronym; + } + + /** + * + * @param replaceInvalidAcronym Set to true if this Analyzer is replacing mischaracterized acronyms in the StandardTokenizer + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + * @deprecated This will be removed (hardwired to true) in 3.0 + */ + public void setReplaceInvalidAcronym(boolean replaceInvalidAcronym) { + this.replaceInvalidAcronym = replaceInvalidAcronym; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardFilter.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,70 @@ +package org.apache.lucene.analysis.standard; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.TokenFilter; +import org.apache.lucene.analysis.Token; +import org.apache.lucene.analysis.TokenStream; + +/** Normalizes tokens extracted with {@link StandardTokenizer}. */ + +public final class StandardFilter extends TokenFilter { + + + /** Construct filtering in. */ + public StandardFilter(TokenStream in) { + super(in); + } + + private static final String APOSTROPHE_TYPE = StandardTokenizerImpl.TOKEN_TYPES[StandardTokenizerImpl.APOSTROPHE]; + private static final String ACRONYM_TYPE = StandardTokenizerImpl.TOKEN_TYPES[StandardTokenizerImpl.ACRONYM]; + + /** Returns the next token in the stream, or null at EOS. + *

Removes 's from the end of words. + *

Removes dots from acronyms. + */ + public final Token next(final Token reusableToken) throws java.io.IOException { + assert reusableToken != null; + Token nextToken = input.next(reusableToken); + + if (nextToken == null) + return null; + + char[] buffer = nextToken.termBuffer(); + final int bufferLength = nextToken.termLength(); + final String type = nextToken.type(); + + if (type == APOSTROPHE_TYPE && // remove 's + bufferLength >= 2 && + buffer[bufferLength-2] == '\'' && + (buffer[bufferLength-1] == 's' || buffer[bufferLength-1] == 'S')) { + // Strip last 2 characters off + nextToken.setTermLength(bufferLength - 2); + } else if (type == ACRONYM_TYPE) { // remove dots + int upto = 0; + for(int i=0;i This should be a good tokenizer for most European-language documents: + * + *

    + *
  • Splits words at punctuation characters, removing punctuation. However, a + * dot that's not followed by whitespace is considered part of a token. + *
  • Splits words at hyphens, unless there's a number in the token, in which case + * the whole token is interpreted as a product number and is not split. + *
  • Recognizes email addresses and internet hostnames as one token. + *
+ * + *

Many applications have specific tokenizer needs. If this tokenizer does + * not suit your application, please consider copying this source code + * directory to your project and maintaining your own grammar-based tokenizer. + */ + +public class StandardTokenizer extends Tokenizer { + /** A private instance of the JFlex-constructed scanner */ + private final StandardTokenizerImpl scanner; + + public static final int ALPHANUM = 0; + public static final int APOSTROPHE = 1; + public static final int ACRONYM = 2; + public static final int COMPANY = 3; + public static final int EMAIL = 4; + public static final int HOST = 5; + public static final int NUM = 6; + public static final int CJ = 7; + + /** + * @deprecated this solves a bug where HOSTs that end with '.' are identified + * as ACRONYMs. It is deprecated and will be removed in the next + * release. + */ + public static final int ACRONYM_DEP = 8; + + /** String token types that correspond to token type int constants */ + public static final String [] TOKEN_TYPES = new String [] { + "", + "", + "", + "", + "", + "", + "", + "", + "" + }; + + /** @deprecated Please use {@link #TOKEN_TYPES} instead */ + public static final String [] tokenImage = TOKEN_TYPES; + + /** + * Specifies whether deprecated acronyms should be replaced with HOST type. + * This is false by default to support backward compatibility. + *

+ * See http://issues.apache.org/jira/browse/LUCENE-1068 + * + * @deprecated this should be removed in the next release (3.0). + */ + private boolean replaceInvalidAcronym = false; + + void setInput(Reader reader) { + this.input = reader; + } + + private int maxTokenLength = StandardAnalyzer.DEFAULT_MAX_TOKEN_LENGTH; + + /** Set the max allowed token length. Any token longer + * than this is skipped. */ + public void setMaxTokenLength(int length) { + this.maxTokenLength = length; + } + + /** @see #setMaxTokenLength */ + public int getMaxTokenLength() { + return maxTokenLength; + } + + /** + * Creates a new instance of the {@link StandardTokenizer}. Attaches the + * input to a newly created JFlex scanner. + */ + public StandardTokenizer(Reader input) { + this.input = input; + this.scanner = new StandardTokenizerImpl(input); + } + + /** + * Creates a new instance of the {@link org.apache.lucene.analysis.standard.StandardTokenizer}. Attaches + * the input to the newly created JFlex scanner. + * + * @param input The input reader + * @param replaceInvalidAcronym Set to true to replace mischaracterized acronyms with HOST. + * + * See http://issues.apache.org/jira/browse/LUCENE-1068 + */ + public StandardTokenizer(Reader input, boolean replaceInvalidAcronym) { + this.replaceInvalidAcronym = replaceInvalidAcronym; + this.input = input; + this.scanner = new StandardTokenizerImpl(input); + } + + /* + * (non-Javadoc) + * + * @see org.apache.lucene.analysis.TokenStream#next() + */ + public Token next(final Token reusableToken) throws IOException { + assert reusableToken != null; + int posIncr = 1; + + while(true) { + int tokenType = scanner.getNextToken(); + + if (tokenType == StandardTokenizerImpl.YYEOF) { + return null; + } + + if (scanner.yylength() <= maxTokenLength) { + reusableToken.clear(); + reusableToken.setPositionIncrement(posIncr); + scanner.getText(reusableToken); + final int start = scanner.yychar(); + reusableToken.setStartOffset(start); + reusableToken.setEndOffset(start+reusableToken.termLength()); + // This 'if' should be removed in the next release. For now, it converts + // invalid acronyms to HOST. When removed, only the 'else' part should + // remain. + if (tokenType == StandardTokenizerImpl.ACRONYM_DEP) { + if (replaceInvalidAcronym) { + reusableToken.setType(StandardTokenizerImpl.TOKEN_TYPES[StandardTokenizerImpl.HOST]); + reusableToken.setTermLength(reusableToken.termLength() - 1); // remove extra '.' + } else { + reusableToken.setType(StandardTokenizerImpl.TOKEN_TYPES[StandardTokenizerImpl.ACRONYM]); + } + } else { + reusableToken.setType(StandardTokenizerImpl.TOKEN_TYPES[tokenType]); + } + return reusableToken; + } else + // When we skip a too-long term, we still increment the + // position increment + posIncr++; + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.lucene.analysis.TokenStream#reset() + */ + public void reset() throws IOException { + super.reset(); + scanner.yyreset(input); + } + + public void reset(Reader reader) throws IOException { + input = reader; + reset(); + } + + /** + * Prior to https://issues.apache.org/jira/browse/LUCENE-1068, StandardTokenizer mischaracterized as acronyms tokens like www.abc.com + * when they should have been labeled as hosts instead. + * @return true if StandardTokenizer now returns these tokens as Hosts, otherwise false + * + * @deprecated Remove in 3.X and make true the only valid value + */ + public boolean isReplaceInvalidAcronym() { + return replaceInvalidAcronym; + } + + /** + * + * @param replaceInvalidAcronym Set to true to replace mischaracterized acronyms as HOST. + * @deprecated Remove in 3.X and make true the only valid value + * + * See https://issues.apache.org/jira/browse/LUCENE-1068 + */ + public void setReplaceInvalidAcronym(boolean replaceInvalidAcronym) { + this.replaceInvalidAcronym = replaceInvalidAcronym; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardTokenizerImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardTokenizerImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardTokenizerImpl.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,714 @@ +/* The following code was generated by JFlex 1.4.1 on 9/4/08 6:49 PM */ + +package org.apache.lucene.analysis.standard; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + +NOTE: if you change this file and need to regenerate the tokenizer, + remember to use JRE 1.4 when running jflex (before Lucene 3.0). + This grammar now uses constructs (eg :digit:) whose meaning can + vary according to the JRE used to run jflex. See + https://issues.apache.org/jira/browse/LUCENE-1126 for details + +*/ + +import org.apache.lucene.analysis.Token; + + +/** + * This class is a scanner generated by + * JFlex 1.4.1 + * on 9/4/08 6:49 PM from the specification file + * /tango/mike/src/lucene.standarddigit/src/java/org/apache/lucene/analysis/standard/StandardTokenizerImpl.jflex + */ +class StandardTokenizerImpl { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\0\1\15\1\0\1\0\1\14\22\0\1\0\5\0\1\5"+ + "\1\3\4\0\1\11\1\7\1\4\1\11\12\2\6\0\1\6\32\12"+ + "\4\0\1\10\1\0\32\12\57\0\1\12\12\0\1\12\4\0\1\12"+ + "\5\0\27\12\1\0\37\12\1\0\u0128\12\2\0\22\12\34\0\136\12"+ + "\2\0\11\12\2\0\7\12\16\0\2\12\16\0\5\12\11\0\1\12"+ + "\213\0\1\12\13\0\1\12\1\0\3\12\1\0\1\12\1\0\24\12"+ + "\1\0\54\12\1\0\10\12\2\0\32\12\14\0\202\12\12\0\71\12"+ + "\2\0\2\12\2\0\2\12\3\0\46\12\2\0\2\12\67\0\46\12"+ + "\2\0\1\12\7\0\47\12\110\0\33\12\5\0\3\12\56\0\32\12"+ + "\5\0\13\12\25\0\12\2\7\0\143\12\1\0\1\12\17\0\2\12"+ + "\11\0\12\2\3\12\23\0\1\12\1\0\33\12\123\0\46\12\u015f\0"+ + "\65\12\3\0\1\12\22\0\1\12\7\0\12\12\4\0\12\2\25\0"+ + "\10\12\2\0\2\12\2\0\26\12\1\0\7\12\1\0\1\12\3\0"+ + "\4\12\42\0\2\12\1\0\3\12\4\0\12\2\2\12\23\0\6\12"+ + "\4\0\2\12\2\0\26\12\1\0\7\12\1\0\2\12\1\0\2\12"+ + "\1\0\2\12\37\0\4\12\1\0\1\12\7\0\12\2\2\0\3\12"+ + "\20\0\7\12\1\0\1\12\1\0\3\12\1\0\26\12\1\0\7\12"+ + "\1\0\2\12\1\0\5\12\3\0\1\12\22\0\1\12\17\0\1\12"+ + "\5\0\12\2\25\0\10\12\2\0\2\12\2\0\26\12\1\0\7\12"+ + "\1\0\2\12\2\0\4\12\3\0\1\12\36\0\2\12\1\0\3\12"+ + "\4\0\12\2\25\0\6\12\3\0\3\12\1\0\4\12\3\0\2\12"+ + "\1\0\1\12\1\0\2\12\3\0\2\12\3\0\3\12\3\0\10\12"+ + "\1\0\3\12\55\0\11\2\25\0\10\12\1\0\3\12\1\0\27\12"+ + "\1\0\12\12\1\0\5\12\46\0\2\12\4\0\12\2\25\0\10\12"+ + "\1\0\3\12\1\0\27\12\1\0\12\12\1\0\5\12\44\0\1\12"+ + "\1\0\2\12\4\0\12\2\25\0\10\12\1\0\3\12\1\0\27\12"+ + "\1\0\20\12\46\0\2\12\4\0\12\2\25\0\22\12\3\0\30\12"+ + "\1\0\11\12\1\0\1\12\2\0\7\12\71\0\1\1\60\12\1\1"+ + "\2\12\14\1\7\12\11\1\12\2\47\0\2\12\1\0\1\12\2\0"+ + "\2\12\1\0\1\12\2\0\1\12\6\0\4\12\1\0\7\12\1\0"+ + "\3\12\1\0\1\12\1\0\1\12\2\0\2\12\1\0\4\12\1\0"+ + "\2\12\11\0\1\12\2\0\5\12\1\0\1\12\11\0\12\2\2\0"+ + "\2\12\42\0\1\12\37\0\12\2\26\0\10\12\1\0\42\12\35\0"+ + "\4\12\164\0\42\12\1\0\5\12\1\0\2\12\25\0\12\2\6\0"+ + "\6\12\112\0\46\12\12\0\47\12\11\0\132\12\5\0\104\12\5\0"+ + "\122\12\6\0\7\12\1\0\77\12\1\0\1\12\1\0\4\12\2\0"+ + "\7\12\1\0\1\12\1\0\4\12\2\0\47\12\1\0\1\12\1\0"+ + "\4\12\2\0\37\12\1\0\1\12\1\0\4\12\2\0\7\12\1\0"+ + "\1\12\1\0\4\12\2\0\7\12\1\0\7\12\1\0\27\12\1\0"+ + "\37\12\1\0\1\12\1\0\4\12\2\0\7\12\1\0\47\12\1\0"+ + "\23\12\16\0\11\2\56\0\125\12\14\0\u026c\12\2\0\10\12\12\0"+ + "\32\12\5\0\113\12\225\0\64\12\54\0\12\2\46\0\12\2\6\0"+ + "\130\12\10\0\51\12\u0557\0\234\12\4\0\132\12\6\0\26\12\2\0"+ + "\6\12\2\0\46\12\2\0\6\12\2\0\10\12\1\0\1\12\1\0"+ + "\1\12\1\0\1\12\1\0\37\12\2\0\65\12\1\0\7\12\1\0"+ + "\1\12\3\0\3\12\1\0\7\12\3\0\4\12\2\0\6\12\4\0"+ + "\15\12\5\0\3\12\1\0\7\12\202\0\1\12\202\0\1\12\4\0"+ + "\1\12\2\0\12\12\1\0\1\12\3\0\5\12\6\0\1\12\1\0"+ + "\1\12\1\0\1\12\1\0\4\12\1\0\3\12\1\0\7\12\u0ecb\0"+ + "\2\12\52\0\5\12\12\0\1\13\124\13\10\13\2\13\2\13\132\13"+ + "\1\13\3\13\6\13\50\13\3\13\1\0\136\12\21\0\30\12\70\0"+ + "\20\13\u0100\0\200\13\200\0\u19b6\13\12\13\100\0\u51a6\13\132\13\u048d\12"+ + "\u0773\0\u2ba4\12\u215c\0\u012e\13\322\13\7\12\14\0\5\12\5\0\1\12"+ + "\1\0\12\12\1\0\15\12\1\0\5\12\1\0\1\12\1\0\2\12"+ + "\1\0\2\12\1\0\154\12\41\0\u016b\12\22\0\100\12\2\0\66\12"+ + "\50\0\14\12\164\0\3\12\1\0\1\12\1\0\207\12\23\0\12\2"+ + "\7\0\32\12\6\0\32\12\12\0\1\13\72\13\37\12\3\0\6\12"+ + "\2\0\6\12\2\0\6\12\2\0\3\12\43\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\3\2\1\3\1\1\13\0\1\2\3\4"+ + "\2\0\1\5\1\0\1\5\3\4\6\5\1\6\1\4"+ + "\2\7\1\10\1\0\1\10\3\0\2\10\1\11\1\12"+ + "\1\4"; + + private static int [] zzUnpackAction() { + int [] result = new int[51]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\16\0\34\0\52\0\70\0\16\0\106\0\124"+ + "\0\142\0\160\0\176\0\214\0\232\0\250\0\266\0\304"+ + "\0\322\0\340\0\356\0\374\0\u010a\0\u0118\0\u0126\0\u0134"+ + "\0\u0142\0\u0150\0\u015e\0\u016c\0\u017a\0\u0188\0\u0196\0\u01a4"+ + "\0\u01b2\0\u01c0\0\u01ce\0\u01dc\0\u01ea\0\u01f8\0\322\0\u0206"+ + "\0\u0214\0\u0222\0\u0230\0\u023e\0\u024c\0\u025a\0\124\0\214"+ + "\0\u0268\0\u0276\0\u0284"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[51]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\7\2\1\5\1\6\1\7\1\2"+ + "\17\0\2\3\1\0\1\10\1\0\1\11\2\12\1\13"+ + "\1\3\4\0\1\3\1\4\1\0\1\14\1\0\1\11"+ + "\2\15\1\16\1\4\4\0\1\3\1\4\1\17\1\20"+ + "\1\21\1\22\2\12\1\13\1\23\20\0\1\2\1\0"+ + "\1\24\1\25\7\0\1\26\4\0\2\27\7\0\1\27"+ + "\4\0\1\30\1\31\7\0\1\32\5\0\1\33\7\0"+ + "\1\13\4\0\1\34\1\35\7\0\1\36\4\0\1\37"+ + "\1\40\7\0\1\41\4\0\1\42\1\43\7\0\1\44"+ + "\15\0\1\45\4\0\1\24\1\25\7\0\1\46\15\0"+ + "\1\47\4\0\2\27\7\0\1\50\4\0\1\3\1\4"+ + "\1\17\1\10\1\21\1\22\2\12\1\13\1\23\4\0"+ + "\2\24\1\0\1\51\1\0\1\11\2\52\1\0\1\24"+ + "\4\0\1\24\1\25\1\0\1\53\1\0\1\11\2\54"+ + "\1\55\1\25\4\0\1\24\1\25\1\0\1\51\1\0"+ + "\1\11\2\52\1\0\1\26\4\0\2\27\1\0\1\56"+ + "\2\0\1\56\2\0\1\27\4\0\2\30\1\0\1\52"+ + "\1\0\1\11\2\52\1\0\1\30\4\0\1\30\1\31"+ + "\1\0\1\54\1\0\1\11\2\54\1\55\1\31\4\0"+ + "\1\30\1\31\1\0\1\52\1\0\1\11\2\52\1\0"+ + "\1\32\5\0\1\33\1\0\1\55\2\0\3\55\1\33"+ + "\4\0\2\34\1\0\1\57\1\0\1\11\2\12\1\13"+ + "\1\34\4\0\1\34\1\35\1\0\1\60\1\0\1\11"+ + "\2\15\1\16\1\35\4\0\1\34\1\35\1\0\1\57"+ + "\1\0\1\11\2\12\1\13\1\36\4\0\2\37\1\0"+ + "\1\12\1\0\1\11\2\12\1\13\1\37\4\0\1\37"+ + "\1\40\1\0\1\15\1\0\1\11\2\15\1\16\1\40"+ + "\4\0\1\37\1\40\1\0\1\12\1\0\1\11\2\12"+ + "\1\13\1\41\4\0\2\42\1\0\1\13\2\0\3\13"+ + "\1\42\4\0\1\42\1\43\1\0\1\16\2\0\3\16"+ + "\1\43\4\0\1\42\1\43\1\0\1\13\2\0\3\13"+ + "\1\44\6\0\1\17\6\0\1\45\4\0\1\24\1\25"+ + "\1\0\1\61\1\0\1\11\2\52\1\0\1\26\4\0"+ + "\2\27\1\0\1\56\2\0\1\56\2\0\1\50\4\0"+ + "\2\24\7\0\1\24\4\0\2\30\7\0\1\30\4\0"+ + "\2\34\7\0\1\34\4\0\2\37\7\0\1\37\4\0"+ + "\2\42\7\0\1\42\4\0\2\62\7\0\1\62\4\0"+ + "\2\24\7\0\1\63\4\0\2\62\1\0\1\56\2\0"+ + "\1\56\2\0\1\62\4\0\2\24\1\0\1\61\1\0"+ + "\1\11\2\52\1\0\1\24\3\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[658]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\3\1\1\11\1\1\13\0\4\1\2\0"+ + "\1\1\1\0\17\1\1\0\1\1\3\0\5\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[51]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the textposition at the last state to be included in yytext */ + private int zzPushbackPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /* user code: */ + +public static final int ALPHANUM = StandardTokenizer.ALPHANUM; +public static final int APOSTROPHE = StandardTokenizer.APOSTROPHE; +public static final int ACRONYM = StandardTokenizer.ACRONYM; +public static final int COMPANY = StandardTokenizer.COMPANY; +public static final int EMAIL = StandardTokenizer.EMAIL; +public static final int HOST = StandardTokenizer.HOST; +public static final int NUM = StandardTokenizer.NUM; +public static final int CJ = StandardTokenizer.CJ; +/** + * @deprecated this solves a bug where HOSTs that end with '.' are identified + * as ACRONYMs. It is deprecated and will be removed in the next + * release. + */ +public static final int ACRONYM_DEP = StandardTokenizer.ACRONYM_DEP; + +public static final String [] TOKEN_TYPES = StandardTokenizer.TOKEN_TYPES; + +public final int yychar() +{ + return yychar; +} + +/** + * Fills Lucene token with the current token text. + */ +final void getText(Token t) { + t.setTermBuffer(zzBuffer, zzStartRead, zzMarkedPos-zzStartRead); +} + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + StandardTokenizerImpl(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + StandardTokenizerImpl(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 1154) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzPushbackPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead < 0) { + return true; + } + else { + zzEndRead+= numRead; + return false; + } + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = zzPushbackPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public int getNextToken() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = zzLexicalState; + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 4: + { return HOST; + } + case 11: break; + case 9: + { return ACRONYM; + } + case 12: break; + case 8: + { return ACRONYM_DEP; + } + case 13: break; + case 1: + { /* ignore */ + } + case 14: break; + case 5: + { return NUM; + } + case 15: break; + case 3: + { return CJ; + } + case 16: break; + case 2: + { return ALPHANUM; + } + case 17: break; + case 7: + { return COMPANY; + } + case 18: break; + case 6: + { return APOSTROPHE; + } + case 19: break; + case 10: + { return EMAIL; + } + case 20: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + return YYEOF; + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardTokenizerImpl.jflex =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardTokenizerImpl.jflex,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/StandardTokenizerImpl.jflex 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,136 @@ +package org.apache.lucene.analysis.standard; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + +NOTE: if you change StandardTokenizerImpl.jflex and need to regenerate + the tokenizer, remember to use JRE 1.4 to run jflex (before + Lucene 3.0). This grammar now uses constructs (eg :digit:, + :letter:) whose meaning can vary according to the JRE used to + run jflex. See + https://issues.apache.org/jira/browse/LUCENE-1126 for details. + +*/ + +import org.apache.lucene.analysis.Token; + +%% + +%class StandardTokenizerImpl +%unicode +%integer +%function getNextToken +%pack +%char + +%{ + +public static final int ALPHANUM = StandardTokenizer.ALPHANUM; +public static final int APOSTROPHE = StandardTokenizer.APOSTROPHE; +public static final int ACRONYM = StandardTokenizer.ACRONYM; +public static final int COMPANY = StandardTokenizer.COMPANY; +public static final int EMAIL = StandardTokenizer.EMAIL; +public static final int HOST = StandardTokenizer.HOST; +public static final int NUM = StandardTokenizer.NUM; +public static final int CJ = StandardTokenizer.CJ; +/** + * @deprecated this solves a bug where HOSTs that end with '.' are identified + * as ACRONYMs. It is deprecated and will be removed in the next + * release. + */ +public static final int ACRONYM_DEP = StandardTokenizer.ACRONYM_DEP; + +public static final String [] TOKEN_TYPES = StandardTokenizer.TOKEN_TYPES; + +public final int yychar() +{ + return yychar; +} + +/** + * Fills Lucene token with the current token text. + */ +final void getText(Token t) { + t.setTermBuffer(zzBuffer, zzStartRead, zzMarkedPos-zzStartRead); +} +%} + +THAI = [\u0E00-\u0E59] + +// basic word: a sequence of digits & letters (includes Thai to enable ThaiAnalyzer to function) +ALPHANUM = ({LETTER}|{THAI}|[:digit:])+ + +// internal apostrophes: O'Reilly, you're, O'Reilly's +// use a post-filter to remove possesives +APOSTROPHE = {ALPHA} ("'" {ALPHA})+ + +// acronyms: U.S.A., I.B.M., etc. +// use a post-filter to remove dots +ACRONYM = {LETTER} "." ({LETTER} ".")+ + +ACRONYM_DEP = {ALPHANUM} "." ({ALPHANUM} ".")+ + +// company names like AT&T and Excite@Home. +COMPANY = {ALPHA} ("&"|"@") {ALPHA} + +// email addresses +EMAIL = {ALPHANUM} (("."|"-"|"_") {ALPHANUM})* "@" {ALPHANUM} (("."|"-") {ALPHANUM})+ + +// hostname +HOST = {ALPHANUM} ((".") {ALPHANUM})+ + +// floating point, serial, model numbers, ip addresses, etc. +// every other segment must have at least one digit +NUM = ({ALPHANUM} {P} {HAS_DIGIT} + | {HAS_DIGIT} {P} {ALPHANUM} + | {ALPHANUM} ({P} {HAS_DIGIT} {P} {ALPHANUM})+ + | {HAS_DIGIT} ({P} {ALPHANUM} {P} {HAS_DIGIT})+ + | {ALPHANUM} {P} {HAS_DIGIT} ({P} {ALPHANUM} {P} {HAS_DIGIT})+ + | {HAS_DIGIT} {P} {ALPHANUM} ({P} {HAS_DIGIT} {P} {ALPHANUM})+) + +// punctuation +P = ("_"|"-"|"/"|"."|",") + +// at least one digit +HAS_DIGIT = ({LETTER}|[:digit:])* [:digit:] ({LETTER}|[:digit:])* + +ALPHA = ({LETTER})+ + +// From the JFlex manual: "the expression that matches everything of not matched by is !(!|)" +LETTER = !(![:letter:]|{CJ}) + +// Chinese and Japanese (but NOT Korean, which is included in [:letter:]) +CJ = [\u3100-\u312f\u3040-\u309F\u30A0-\u30FF\u31F0-\u31FF\u3300-\u337f\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff65-\uff9f] + +WHITESPACE = \r\n | [ \r\n\t\f] + +%% + +{ALPHANUM} { return ALPHANUM; } +{APOSTROPHE} { return APOSTROPHE; } +{ACRONYM} { return ACRONYM; } +{COMPANY} { return COMPANY; } +{EMAIL} { return EMAIL; } +{HOST} { return HOST; } +{NUM} { return NUM; } +{CJ} { return CJ; } +{ACRONYM_DEP} { return ACRONYM_DEP; } + +/** Ignore the rest */ +. | {WHITESPACE} { /* ignore */ } Index: 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/analysis/standard/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/analysis/standard/package.html 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,26 @@ + + + + + + + + +A fast grammar-based tokenizer constructed with JFlex. + + Index: 3rdParty_sources/lucene/org/apache/lucene/document/AbstractField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/AbstractField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/AbstractField.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,340 @@ +package org.apache.lucene.document; +/** + * Copyright 2006 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * + * + **/ +public abstract class AbstractField implements Fieldable { + + protected String name = "body"; + protected boolean storeTermVector = false; + protected boolean storeOffsetWithTermVector = false; + protected boolean storePositionWithTermVector = false; + protected boolean omitNorms = false; + protected boolean isStored = false; + protected boolean isIndexed = true; + protected boolean isTokenized = true; + protected boolean isBinary = false; + protected boolean isCompressed = false; + protected boolean lazy = false; + protected boolean omitTf = false; + protected float boost = 1.0f; + // the one and only data object for all different kind of field values + protected Object fieldsData = null; + //length/offset for all primitive types + protected int binaryLength; + protected int binaryOffset; + + protected AbstractField() + { + } + + protected AbstractField(String name, Field.Store store, Field.Index index, Field.TermVector termVector) { + if (name == null) + throw new NullPointerException("name cannot be null"); + this.name = name.intern(); // field names are interned + + if (store == Field.Store.YES){ + this.isStored = true; + this.isCompressed = false; + } + else if (store == Field.Store.COMPRESS) { + this.isStored = true; + this.isCompressed = true; + } + else if (store == Field.Store.NO){ + this.isStored = false; + this.isCompressed = false; + } + else + throw new IllegalArgumentException("unknown store parameter " + store); + + if (index == Field.Index.NO) { + this.isIndexed = false; + this.isTokenized = false; + } else if (index == Field.Index.ANALYZED) { + this.isIndexed = true; + this.isTokenized = true; + } else if (index == Field.Index.NOT_ANALYZED) { + this.isIndexed = true; + this.isTokenized = false; + } else if (index == Field.Index.NOT_ANALYZED_NO_NORMS) { + this.isIndexed = true; + this.isTokenized = false; + this.omitNorms = true; + } else if (index == Field.Index.ANALYZED_NO_NORMS) { + this.isIndexed = true; + this.isTokenized = true; + this.omitNorms = true; + } else { + throw new IllegalArgumentException("unknown index parameter " + index); + } + + this.isBinary = false; + + setStoreTermVector(termVector); + } + + /** Sets the boost factor hits on this field. This value will be + * multiplied into the score of all hits on this this field of this + * document. + * + *

The boost is multiplied by {@link org.apache.lucene.document.Document#getBoost()} of the document + * containing this field. If a document has multiple fields with the same + * name, all such values are multiplied together. This product is then + * multipled by the value {@link org.apache.lucene.search.Similarity#lengthNorm(String,int)}, and + * rounded by {@link org.apache.lucene.search.Similarity#encodeNorm(float)} before it is stored in the + * index. One should attempt to ensure that this product does not overflow + * the range of that encoding. + * + * @see org.apache.lucene.document.Document#setBoost(float) + * @see org.apache.lucene.search.Similarity#lengthNorm(String, int) + * @see org.apache.lucene.search.Similarity#encodeNorm(float) + */ + public void setBoost(float boost) { + this.boost = boost; + } + + /** Returns the boost factor for hits for this field. + * + *

The default value is 1.0. + * + *

Note: this value is not stored directly with the document in the index. + * Documents returned from {@link org.apache.lucene.index.IndexReader#document(int)} and + * {@link org.apache.lucene.search.Hits#doc(int)} may thus not have the same value present as when + * this field was indexed. + * + * @see #setBoost(float) + */ + public float getBoost() { + return boost; + } + + /** Returns the name of the field as an interned string. + * For example "date", "title", "body", ... + */ + public String name() { return name; } + + protected void setStoreTermVector(Field.TermVector termVector) { + if (termVector == Field.TermVector.NO) { + this.storeTermVector = false; + this.storePositionWithTermVector = false; + this.storeOffsetWithTermVector = false; + } + else if (termVector == Field.TermVector.YES) { + this.storeTermVector = true; + this.storePositionWithTermVector = false; + this.storeOffsetWithTermVector = false; + } + else if (termVector == Field.TermVector.WITH_POSITIONS) { + this.storeTermVector = true; + this.storePositionWithTermVector = true; + this.storeOffsetWithTermVector = false; + } + else if (termVector == Field.TermVector.WITH_OFFSETS) { + this.storeTermVector = true; + this.storePositionWithTermVector = false; + this.storeOffsetWithTermVector = true; + } + else if (termVector == Field.TermVector.WITH_POSITIONS_OFFSETS) { + this.storeTermVector = true; + this.storePositionWithTermVector = true; + this.storeOffsetWithTermVector = true; + } + else { + throw new IllegalArgumentException("unknown termVector parameter " + termVector); + } + } + + /** True iff the value of the field is to be stored in the index for return + with search hits. It is an error for this to be true if a field is + Reader-valued. */ + public final boolean isStored() { return isStored; } + + /** True iff the value of the field is to be indexed, so that it may be + searched on. */ + public final boolean isIndexed() { return isIndexed; } + + /** True iff the value of the field should be tokenized as text prior to + indexing. Un-tokenized fields are indexed as a single word and may not be + Reader-valued. */ + public final boolean isTokenized() { return isTokenized; } + + /** True if the value of the field is stored and compressed within the index */ + public final boolean isCompressed() { return isCompressed; } + + /** True iff the term or terms used to index this field are stored as a term + * vector, available from {@link org.apache.lucene.index.IndexReader#getTermFreqVector(int,String)}. + * These methods do not provide access to the original content of the field, + * only to terms used to index it. If the original content must be + * preserved, use the stored attribute instead. + * + * @see org.apache.lucene.index.IndexReader#getTermFreqVector(int, String) + */ + public final boolean isTermVectorStored() { return storeTermVector; } + + /** + * True iff terms are stored as term vector together with their offsets + * (start and end positon in source text). + */ + public boolean isStoreOffsetWithTermVector(){ + return storeOffsetWithTermVector; + } + + /** + * True iff terms are stored as term vector together with their token positions. + */ + public boolean isStorePositionWithTermVector(){ + return storePositionWithTermVector; + } + + /** True iff the value of the filed is stored as binary */ + public final boolean isBinary() { + return isBinary; + } + + + /** + * Return the raw byte[] for the binary field. Note that + * you must also call {@link #getBinaryLength} and {@link + * #getBinaryOffset} to know which range of bytes in this + * returned array belong to the field. + * @return reference to the Field value as byte[]. + */ + public byte[] getBinaryValue() { + return getBinaryValue(null); + } + + public byte[] getBinaryValue(byte[] result){ + if (isBinary || fieldsData instanceof byte[]) + return (byte[]) fieldsData; + else + return null; + } + + /** + * Returns length of byte[] segment that is used as value, if Field is not binary + * returned value is undefined + * @return length of byte[] segment that represents this Field value + */ + public int getBinaryLength() { + if (isBinary) { + if (!isCompressed) + return binaryLength; + else + return ((byte[]) fieldsData).length; + } else if (fieldsData instanceof byte[]) + return ((byte[]) fieldsData).length; + else + return 0; + } + + /** + * Returns offset into byte[] segment that is used as value, if Field is not binary + * returned value is undefined + * @return index of the first character in byte[] segment that represents this Field value + */ + public int getBinaryOffset() { + return binaryOffset; + } + + /** True if norms are omitted for this indexed field */ + public boolean getOmitNorms() { return omitNorms; } + + /** True if tf is omitted for this indexed field */ + public boolean getOmitTf() { return omitTf; } + + /** Expert: + * + * If set, omit normalization factors associated with this indexed field. + * This effectively disables indexing boosts and length normalization for this field. + */ + public void setOmitNorms(boolean omitNorms) { this.omitNorms=omitNorms; } + + /** Expert: + * + * If set, omit tf from postings of this indexed field. + */ + public void setOmitTf(boolean omitTf) { this.omitTf=omitTf; } + + public boolean isLazy() { + return lazy; + } + + /** Prints a Field for human consumption. */ + public final String toString() { + StringBuffer result = new StringBuffer(); + if (isStored) { + result.append("stored"); + if (isCompressed) + result.append("/compressed"); + else + result.append("/uncompressed"); + } + if (isIndexed) { + if (result.length() > 0) + result.append(","); + result.append("indexed"); + } + if (isTokenized) { + if (result.length() > 0) + result.append(","); + result.append("tokenized"); + } + if (storeTermVector) { + if (result.length() > 0) + result.append(","); + result.append("termVector"); + } + if (storeOffsetWithTermVector) { + if (result.length() > 0) + result.append(","); + result.append("termVectorOffsets"); + } + if (storePositionWithTermVector) { + if (result.length() > 0) + result.append(","); + result.append("termVectorPosition"); + } + if (isBinary) { + if (result.length() > 0) + result.append(","); + result.append("binary"); + } + if (omitNorms) { + result.append(",omitNorms"); + } + if (omitTf) { + result.append(",omitTf"); + } + if (lazy){ + result.append(",lazy"); + } + result.append('<'); + result.append(name); + result.append(':'); + + if (fieldsData != null && lazy == false) { + result.append(fieldsData); + } + + result.append('>'); + return result.toString(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/DateField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/DateField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/DateField.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,106 @@ +package org.apache.lucene.document; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.RangeQuery; + +import java.util.Date; // for javadoc + +/** + * Provides support for converting dates to strings and vice-versa. + * The strings are structured so that lexicographic sorting orders by date, + * which makes them suitable for use as field values and search terms. + * + *

Note that this class saves dates with millisecond granularity, + * which is bad for {@link RangeQuery} and {@link PrefixQuery}, as those + * queries are expanded to a BooleanQuery with a potentially large number + * of terms when searching. Thus you might want to use + * {@link DateTools} instead. + * + *

+ * Note: dates before 1970 cannot be used, and therefore cannot be + * indexed when using this class. See {@link DateTools} for an + * alternative without such a limitation. + * + * @deprecated If you build a new index, use {@link DateTools} instead. This class is included for use with existing + * indices and will be removed in a future release. + */ +public class DateField { + + private DateField() {} + + // make date strings long enough to last a millenium + private static int DATE_LEN = Long.toString(1000L*365*24*60*60*1000, + Character.MAX_RADIX).length(); + + public static String MIN_DATE_STRING() { + return timeToString(0); + } + + public static String MAX_DATE_STRING() { + char[] buffer = new char[DATE_LEN]; + char c = Character.forDigit(Character.MAX_RADIX-1, Character.MAX_RADIX); + for (int i = 0 ; i < DATE_LEN; i++) + buffer[i] = c; + return new String(buffer); + } + + /** + * Converts a Date to a string suitable for indexing. + * @throws RuntimeException if the date specified in the + * method argument is before 1970 + */ + public static String dateToString(Date date) { + return timeToString(date.getTime()); + } + /** + * Converts a millisecond time to a string suitable for indexing. + * @throws RuntimeException if the time specified in the + * method argument is negative, that is, before 1970 + */ + public static String timeToString(long time) { + if (time < 0) + throw new RuntimeException("time '" + time + "' is too early, must be >= 0"); + + String s = Long.toString(time, Character.MAX_RADIX); + + if (s.length() > DATE_LEN) + throw new RuntimeException("time '" + time + "' is too late, length of string " + + "representation must be <= " + DATE_LEN); + + // Pad with leading zeros + if (s.length() < DATE_LEN) { + StringBuffer sb = new StringBuffer(s); + while (sb.length() < DATE_LEN) + sb.insert(0, 0); + s = sb.toString(); + } + + return s; + } + + /** Converts a string-encoded date into a millisecond time. */ + public static long stringToTime(String s) { + return Long.parseLong(s, Character.MAX_RADIX); + } + /** Converts a string-encoded date into a Date object. */ + public static Date stringToDate(String s) { + return new Date(stringToTime(s)); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/DateTools.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/DateTools.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/DateTools.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,283 @@ +package org.apache.lucene.document; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +/** + * Provides support for converting dates to strings and vice-versa. + * The strings are structured so that lexicographic sorting orders + * them by date, which makes them suitable for use as field values + * and search terms. + * + *

This class also helps you to limit the resolution of your dates. Do not + * save dates with a finer resolution than you really need, as then + * RangeQuery and PrefixQuery will require more memory and become slower. + * + *

Compared to {@link DateField} the strings generated by the methods + * in this class take slightly more space, unless your selected resolution + * is set to Resolution.DAY or lower. + */ +public class DateTools { + + private final static TimeZone GMT = TimeZone.getTimeZone("GMT"); + + private static final SimpleDateFormat YEAR_FORMAT = new SimpleDateFormat("yyyy"); + private static final SimpleDateFormat MONTH_FORMAT = new SimpleDateFormat("yyyyMM"); + private static final SimpleDateFormat DAY_FORMAT = new SimpleDateFormat("yyyyMMdd"); + private static final SimpleDateFormat HOUR_FORMAT = new SimpleDateFormat("yyyyMMddHH"); + private static final SimpleDateFormat MINUTE_FORMAT = new SimpleDateFormat("yyyyMMddHHmm"); + private static final SimpleDateFormat SECOND_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); + private static final SimpleDateFormat MILLISECOND_FORMAT = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + static { + // times need to be normalized so the value doesn't depend on the + // location the index is created/used: + YEAR_FORMAT.setTimeZone(GMT); + MONTH_FORMAT.setTimeZone(GMT); + DAY_FORMAT.setTimeZone(GMT); + HOUR_FORMAT.setTimeZone(GMT); + MINUTE_FORMAT.setTimeZone(GMT); + SECOND_FORMAT.setTimeZone(GMT); + MILLISECOND_FORMAT.setTimeZone(GMT); + } + + // cannot create, the class has static methods only + private DateTools() {} + + /** + * Converts a Date to a string suitable for indexing. + * + * @param date the date to be converted + * @param resolution the desired resolution, see + * {@link #round(Date, DateTools.Resolution)} + * @return a string in format yyyyMMddHHmmssSSS or shorter, + * depeding on resolution; using GMT as timezone + */ + public static String dateToString(Date date, Resolution resolution) { + return timeToString(date.getTime(), resolution); + } + + /** + * Converts a millisecond time to a string suitable for indexing. + * + * @param time the date expressed as milliseconds since January 1, 1970, 00:00:00 GMT + * @param resolution the desired resolution, see + * {@link #round(long, DateTools.Resolution)} + * @return a string in format yyyyMMddHHmmssSSS or shorter, + * depeding on resolution; using GMT as timezone + */ + public static String timeToString(long time, Resolution resolution) { + Calendar cal = Calendar.getInstance(GMT); + + //protected in JDK's prior to 1.4 + //cal.setTimeInMillis(round(time, resolution)); + + cal.setTime(new Date(round(time, resolution))); + + String result; + if (resolution == Resolution.YEAR) { + synchronized (YEAR_FORMAT) { + result = YEAR_FORMAT.format(cal.getTime()); + } + } else if (resolution == Resolution.MONTH) { + synchronized (MONTH_FORMAT) { + result = MONTH_FORMAT.format(cal.getTime()); + } + } else if (resolution == Resolution.DAY) { + synchronized (DAY_FORMAT) { + result = DAY_FORMAT.format(cal.getTime()); + } + } else if (resolution == Resolution.HOUR) { + synchronized (HOUR_FORMAT) { + result = HOUR_FORMAT.format(cal.getTime()); + } + } else if (resolution == Resolution.MINUTE) { + synchronized (MINUTE_FORMAT) { + result = MINUTE_FORMAT.format(cal.getTime()); + } + } else if (resolution == Resolution.SECOND) { + synchronized (SECOND_FORMAT) { + result = SECOND_FORMAT.format(cal.getTime()); + } + } else if (resolution == Resolution.MILLISECOND) { + synchronized (MILLISECOND_FORMAT) { + result = MILLISECOND_FORMAT.format(cal.getTime()); + } + } else { + throw new IllegalArgumentException("unknown resolution " + resolution); + } + return result; + } + + /** + * Converts a string produced by timeToString or + * dateToString back to a time, represented as the + * number of milliseconds since January 1, 1970, 00:00:00 GMT. + * + * @param dateString the date string to be converted + * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT + * @throws ParseException if dateString is not in the + * expected format + */ + public static long stringToTime(String dateString) throws ParseException { + return stringToDate(dateString).getTime(); + } + + /** + * Converts a string produced by timeToString or + * dateToString back to a time, represented as a + * Date object. + * + * @param dateString the date string to be converted + * @return the parsed time as a Date object + * @throws ParseException if dateString is not in the + * expected format + */ + public static Date stringToDate(String dateString) throws ParseException { + Date date; + if (dateString.length() == 4) { + synchronized (YEAR_FORMAT) { + date = YEAR_FORMAT.parse(dateString); + } + } else if (dateString.length() == 6) { + synchronized (MONTH_FORMAT) { + date = MONTH_FORMAT.parse(dateString); + } + } else if (dateString.length() == 8) { + synchronized (DAY_FORMAT) { + date = DAY_FORMAT.parse(dateString); + } + } else if (dateString.length() == 10) { + synchronized (HOUR_FORMAT) { + date = HOUR_FORMAT.parse(dateString); + } + } else if (dateString.length() == 12) { + synchronized (MINUTE_FORMAT) { + date = MINUTE_FORMAT.parse(dateString); + } + } else if (dateString.length() == 14) { + synchronized (SECOND_FORMAT) { + date = SECOND_FORMAT.parse(dateString); + } + } else if (dateString.length() == 17) { + synchronized (MILLISECOND_FORMAT) { + date = MILLISECOND_FORMAT.parse(dateString); + } + } else { + throw new ParseException("Input is not valid date string: " + dateString, 0); + } + return date; + } + + /** + * Limit a date's resolution. For example, the date 2004-09-21 13:50:11 + * will be changed to 2004-09-01 00:00:00 when using + * Resolution.MONTH. + * + * @param resolution The desired resolution of the date to be returned + * @return the date with all values more precise than resolution + * set to 0 or 1 + */ + public static Date round(Date date, Resolution resolution) { + return new Date(round(date.getTime(), resolution)); + } + + /** + * Limit a date's resolution. For example, the date 1095767411000 + * (which represents 2004-09-21 13:50:11) will be changed to + * 1093989600000 (2004-09-01 00:00:00) when using + * Resolution.MONTH. + * + * @param resolution The desired resolution of the date to be returned + * @return the date with all values more precise than resolution + * set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT + */ + public static long round(long time, Resolution resolution) { + Calendar cal = Calendar.getInstance(GMT); + + // protected in JDK's prior to 1.4 + //cal.setTimeInMillis(time); + + cal.setTime(new Date(time)); + + if (resolution == Resolution.YEAR) { + cal.set(Calendar.MONTH, 0); + cal.set(Calendar.DAY_OF_MONTH, 1); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + } else if (resolution == Resolution.MONTH) { + cal.set(Calendar.DAY_OF_MONTH, 1); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + } else if (resolution == Resolution.DAY) { + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + } else if (resolution == Resolution.HOUR) { + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + } else if (resolution == Resolution.MINUTE) { + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + } else if (resolution == Resolution.SECOND) { + cal.set(Calendar.MILLISECOND, 0); + } else if (resolution == Resolution.MILLISECOND) { + // don't cut off anything + } else { + throw new IllegalArgumentException("unknown resolution " + resolution); + } + return cal.getTime().getTime(); + } + + /** Specifies the time granularity. */ + public static class Resolution { + + public static final Resolution YEAR = new Resolution("year"); + public static final Resolution MONTH = new Resolution("month"); + public static final Resolution DAY = new Resolution("day"); + public static final Resolution HOUR = new Resolution("hour"); + public static final Resolution MINUTE = new Resolution("minute"); + public static final Resolution SECOND = new Resolution("second"); + public static final Resolution MILLISECOND = new Resolution("millisecond"); + + private String resolution; + + private Resolution() { + } + + private Resolution(String resolution) { + this.resolution = resolution; + } + + public String toString() { + return resolution; + } + + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/Document.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/Document.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/Document.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,331 @@ +package org.apache.lucene.document; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.*; // for javadoc +import org.apache.lucene.search.ScoreDoc; // for javadoc +import org.apache.lucene.search.Searcher; // for javadoc +import org.apache.lucene.index.IndexReader; // for javadoc + +/** Documents are the unit of indexing and search. + * + * A Document is a set of fields. Each field has a name and a textual value. + * A field may be {@link Fieldable#isStored() stored} with the document, in which + * case it is returned with search hits on the document. Thus each document + * should typically contain one or more stored fields which uniquely identify + * it. + * + *

Note that fields which are not {@link Fieldable#isStored() stored} are + * not available in documents retrieved from the index, e.g. with {@link + * ScoreDoc#doc}, {@link Searcher#doc(int)} or {@link + * IndexReader#document(int)}. + */ + +public final class Document implements java.io.Serializable { + List fields = new ArrayList(); + private float boost = 1.0f; + + /** Constructs a new document with no fields. */ + public Document() {} + + + /** Sets a boost factor for hits on any field of this document. This value + * will be multiplied into the score of all hits on this document. + * + *

The default value is 1.0. + * + *

Values are multiplied into the value of {@link Fieldable#getBoost()} of + * each field in this document. Thus, this method in effect sets a default + * boost for the fields of this document. + * + * @see Fieldable#setBoost(float) + */ + public void setBoost(float boost) { + this.boost = boost; + } + + /** Returns, at indexing time, the boost factor as set by {@link #setBoost(float)}. + * + *

Note that once a document is indexed this value is no longer available + * from the index. At search time, for retrieved documents, this method always + * returns 1. This however does not mean that the boost value set at indexing + * time was ignored - it was just combined with other indexing time factors and + * stored elsewhere, for better indexing and search performance. (For more + * information see the "norm(t,d)" part of the scoring formula in + * {@link org.apache.lucene.search.Similarity Similarity}.) + * + * @see #setBoost(float) + */ + public float getBoost() { + return boost; + } + + /** + *

Adds a field to a document. Several fields may be added with + * the same name. In this case, if the fields are indexed, their text is + * treated as though appended for the purposes of search.

+ *

Note that add like the removeField(s) methods only makes sense + * prior to adding a document to an index. These methods cannot + * be used to change the content of an existing index! In order to achieve this, + * a document has to be deleted from an index and a new changed version of that + * document has to be added.

+ */ + public final void add(Fieldable field) { + fields.add(field); + } + + /** + *

Removes field with the specified name from the document. + * If multiple fields exist with this name, this method removes the first field that has been added. + * If there is no field with the specified name, the document remains unchanged.

+ *

Note that the removeField(s) methods like the add method only make sense + * prior to adding a document to an index. These methods cannot + * be used to change the content of an existing index! In order to achieve this, + * a document has to be deleted from an index and a new changed version of that + * document has to be added.

+ */ + public final void removeField(String name) { + Iterator it = fields.iterator(); + while (it.hasNext()) { + Fieldable field = (Fieldable)it.next(); + if (field.name().equals(name)) { + it.remove(); + return; + } + } + } + + /** + *

Removes all fields with the given name from the document. + * If there is no field with the specified name, the document remains unchanged.

+ *

Note that the removeField(s) methods like the add method only make sense + * prior to adding a document to an index. These methods cannot + * be used to change the content of an existing index! In order to achieve this, + * a document has to be deleted from an index and a new changed version of that + * document has to be added.

+ */ + public final void removeFields(String name) { + Iterator it = fields.iterator(); + while (it.hasNext()) { + Fieldable field = (Fieldable)it.next(); + if (field.name().equals(name)) { + it.remove(); + } + } + } + + /** Returns a field with the given name if any exist in this document, or + * null. If multiple fields exists with this name, this method returns the + * first value added. + * Do not use this method with lazy loaded fields. + */ + public final Field getField(String name) { + for (int i = 0; i < fields.size(); i++) { + Field field = (Field)fields.get(i); + if (field.name().equals(name)) + return field; + } + return null; + } + + + /** Returns a field with the given name if any exist in this document, or + * null. If multiple fields exists with this name, this method returns the + * first value added. + */ + public Fieldable getFieldable(String name) { + for (int i = 0; i < fields.size(); i++) { + Fieldable field = (Fieldable)fields.get(i); + if (field.name().equals(name)) + return field; + } + return null; + } + + /** Returns the string value of the field with the given name if any exist in + * this document, or null. If multiple fields exist with this name, this + * method returns the first value added. If only binary fields with this name + * exist, returns null. + */ + public final String get(String name) { + for (int i = 0; i < fields.size(); i++) { + Fieldable field = (Fieldable)fields.get(i); + if (field.name().equals(name) && (!field.isBinary())) + return field.stringValue(); + } + return null; + } + + /** Returns an Enumeration of all the fields in a document. + * @deprecated use {@link #getFields()} instead + */ + public final Enumeration fields() { + return new Enumeration() { + final Iterator iter = fields.iterator(); + public boolean hasMoreElements() { + return iter.hasNext(); + } + public Object nextElement() { + return iter.next(); + } + }; + } + + /** Returns a List of all the fields in a document. + *

Note that fields which are not {@link Fieldable#isStored() stored} are + * not available in documents retrieved from the + * index, e.g. {@link Searcher#doc(int)} or {@link + * IndexReader#document(int)}. + */ + public final List getFields() { + return fields; + } + + private final static Field[] NO_FIELDS = new Field[0]; + + /** + * Returns an array of {@link Field}s with the given name. + * Do not use with lazy loaded fields. + * This method returns an empty array when there are no + * matching fields. It never returns null. + * + * @param name the name of the field + * @return a Field[] array + */ + public final Field[] getFields(String name) { + List result = new ArrayList(); + for (int i = 0; i < fields.size(); i++) { + Field field = (Field)fields.get(i); + if (field.name().equals(name)) { + result.add(field); + } + } + + if (result.size() == 0) + return NO_FIELDS; + + return (Field[])result.toArray(new Field[result.size()]); + } + + + private final static Fieldable[] NO_FIELDABLES = new Fieldable[0]; + + /** + * Returns an array of {@link Fieldable}s with the given name. + * This method returns an empty array when there are no + * matching fields. It never returns null. + * + * @param name the name of the field + * @return a Fieldable[] array + */ + public Fieldable[] getFieldables(String name) { + List result = new ArrayList(); + for (int i = 0; i < fields.size(); i++) { + Fieldable field = (Fieldable)fields.get(i); + if (field.name().equals(name)) { + result.add(field); + } + } + + if (result.size() == 0) + return NO_FIELDABLES; + + return (Fieldable[])result.toArray(new Fieldable[result.size()]); + } + + + private final static String[] NO_STRINGS = new String[0]; + + /** + * Returns an array of values of the field specified as the method parameter. + * This method returns an empty array when there are no + * matching fields. It never returns null. + * @param name the name of the field + * @return a String[] of field values + */ + public final String[] getValues(String name) { + List result = new ArrayList(); + for (int i = 0; i < fields.size(); i++) { + Fieldable field = (Fieldable)fields.get(i); + if (field.name().equals(name) && (!field.isBinary())) + result.add(field.stringValue()); + } + + if (result.size() == 0) + return NO_STRINGS; + + return (String[])result.toArray(new String[result.size()]); + } + + private final static byte[][] NO_BYTES = new byte[0][]; + + /** + * Returns an array of byte arrays for of the fields that have the name specified + * as the method parameter. This method returns an empty + * array when there are no matching fields. It never + * returns null. + * + * @param name the name of the field + * @return a byte[][] of binary field values + */ + public final byte[][] getBinaryValues(String name) { + List result = new ArrayList(); + for (int i = 0; i < fields.size(); i++) { + Fieldable field = (Fieldable)fields.get(i); + if (field.name().equals(name) && (field.isBinary())) + result.add(field.binaryValue()); + } + + if (result.size() == 0) + return NO_BYTES; + + return (byte[][])result.toArray(new byte[result.size()][]); + } + + /** + * Returns an array of bytes for the first (or only) field that has the name + * specified as the method parameter. This method will return null + * if no binary fields with the specified name are available. + * There may be non-binary fields with the same name. + * + * @param name the name of the field. + * @return a byte[] containing the binary field value or null + */ + public final byte[] getBinaryValue(String name) { + for (int i=0; i < fields.size(); i++) { + Fieldable field = (Fieldable)fields.get(i); + if (field.name().equals(name) && (field.isBinary())) + return field.binaryValue(); + } + return null; + } + + /** Prints the fields of a document for human consumption. */ + public final String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("Document<"); + for (int i = 0; i < fields.size(); i++) { + Fieldable field = (Fieldable)fields.get(i); + buffer.append(field.toString()); + if (i != fields.size()-1) + buffer.append(" "); + } + buffer.append(">"); + return buffer.toString(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/Field.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/Field.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/Field.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,476 @@ +package org.apache.lucene.document; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.index.IndexWriter; // for javadoc +import org.apache.lucene.util.Parameter; + +import java.io.Reader; +import java.io.Serializable; + +/** + A field is a section of a Document. Each field has two parts, a name and a + value. Values may be free text, provided as a String or as a Reader, or they + may be atomic keywords, which are not further processed. Such keywords may + be used to represent dates, urls, etc. Fields are optionally stored in the + index, so that they may be returned with hits on the document. + */ + +public final class Field extends AbstractField implements Fieldable, Serializable { + + /** Specifies whether and how a field should be stored. */ + public static final class Store extends Parameter implements Serializable { + + private Store(String name) { + super(name); + } + + /** Store the original field value in the index in a compressed form. This is + * useful for long documents and for binary valued fields. + */ + public static final Store COMPRESS = new Store("COMPRESS"); + + /** Store the original field value in the index. This is useful for short texts + * like a document's title which should be displayed with the results. The + * value is stored in its original form, i.e. no analyzer is used before it is + * stored. + */ + public static final Store YES = new Store("YES"); + + /** Do not store the field value in the index. */ + public static final Store NO = new Store("NO"); + } + + /** Specifies whether and how a field should be indexed. */ + public static final class Index extends Parameter implements Serializable { + + private Index(String name) { + super(name); + } + + /** Do not index the field value. This field can thus not be searched, + * but one can still access its contents provided it is + * {@link Field.Store stored}. */ + public static final Index NO = new Index("NO"); + + /** Index the tokens produced by running the field's + * value through an Analyzer. This is useful for + * common text. */ + public static final Index ANALYZED = new Index("ANALYZED"); + + /** @deprecated this has been renamed to {@link #ANALYZED} */ + public static final Index TOKENIZED = ANALYZED; + + /** Index the field's value without using an Analyzer, so it can be searched. + * As no analyzer is used the value will be stored as a single term. This is + * useful for unique Ids like product numbers. + */ + public static final Index NOT_ANALYZED = new Index("NOT_ANALYZED"); + + /** @deprecated This has been renamed to {@link #NOT_ANALYZED} */ + public static final Index UN_TOKENIZED = NOT_ANALYZED; + + /** Expert: Index the field's value without an Analyzer, + * and also disable the storing of norms. Note that you + * can also separately enable/disable norms by calling + * {@link #setOmitNorms}. No norms means that + * index-time field and document boosting and field + * length normalization are disabled. The benefit is + * less memory usage as norms take up one byte of RAM + * per indexed field for every document in the index, + * during searching. Note that once you index a given + * field with norms enabled, disabling norms will + * have no effect. In other words, for this to have the + * above described effect on a field, all instances of + * that field must be indexed with NOT_ANALYZED_NO_NORMS + * from the beginning. */ + public static final Index NOT_ANALYZED_NO_NORMS = new Index("NOT_ANALYZED_NO_NORMS"); + + /** @deprecated This has been renamed to + * {@link #NOT_ANALYZED_NO_NORMS} */ + public static final Index NO_NORMS = NOT_ANALYZED_NO_NORMS; + + /** Expert: Index the tokens produced by running the + * field's value through an Analyzer, and also + * separately disable the storing of norms. See + * {@link #NOT_ANALYZED_NO_NORMS} for what norms are + * and why you may want to disable them. */ + public static final Index ANALYZED_NO_NORMS = new Index("ANALYZED_NO_NORMS"); + } + + /** Specifies whether and how a field should have term vectors. */ + public static final class TermVector extends Parameter implements Serializable { + + private TermVector(String name) { + super(name); + } + + /** Do not store term vectors. + */ + public static final TermVector NO = new TermVector("NO"); + + /** Store the term vectors of each document. A term vector is a list + * of the document's terms and their number of occurences in that document. */ + public static final TermVector YES = new TermVector("YES"); + + /** + * Store the term vector + token position information + * + * @see #YES + */ + public static final TermVector WITH_POSITIONS = new TermVector("WITH_POSITIONS"); + + /** + * Store the term vector + Token offset information + * + * @see #YES + */ + public static final TermVector WITH_OFFSETS = new TermVector("WITH_OFFSETS"); + + /** + * Store the term vector + Token position and offset information + * + * @see #YES + * @see #WITH_POSITIONS + * @see #WITH_OFFSETS + */ + public static final TermVector WITH_POSITIONS_OFFSETS = new TermVector("WITH_POSITIONS_OFFSETS"); + } + + + /** The value of the field as a String, or null. If null, the Reader value, + * binary value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), getBinaryValue(), and tokenStreamValue() must be set. */ + public String stringValue() { return fieldsData instanceof String ? (String)fieldsData : null; } + + /** The value of the field as a Reader, or null. If null, the String value, + * binary value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), getBinaryValue(), and tokenStreamValue() must be set. */ + public Reader readerValue() { return fieldsData instanceof Reader ? (Reader)fieldsData : null; } + + /** The value of the field in Binary, or null. If null, the Reader value, + * String value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), getBinaryValue(), and tokenStreamValue() must be set. + * @deprecated This method must allocate a new byte[] if + * the {@link AbstractField#getBinaryOffset()} is non-zero + * or {@link AbstractField#getBinaryLength()} is not the + * full length of the byte[]. Please use {@link + * AbstractField#getBinaryValue()} instead, which simply + * returns the byte[]. + */ + public byte[] binaryValue() { + if (!isBinary) + return null; + final byte[] data = (byte[]) fieldsData; + if (binaryOffset == 0 && data.length == binaryLength) + return data; //Optimization + + final byte[] ret = new byte[binaryLength]; + System.arraycopy(data, binaryOffset, ret, 0, binaryLength); + return ret; + } + + /** The value of the field as a TokesStream, or null. If null, the Reader value, + * String value, or binary value is used. Exactly one of stringValue(), + * readerValue(), getBinaryValue(), and tokenStreamValue() must be set. */ + public TokenStream tokenStreamValue() { return fieldsData instanceof TokenStream ? (TokenStream)fieldsData : null; } + + + /**

Expert: change the value of this field. This can + * be used during indexing to re-use a single Field + * instance to improve indexing speed by avoiding GC cost + * of new'ing and reclaiming Field instances. Typically + * a single {@link Document} instance is re-used as + * well. This helps most on small documents.

+ * + *

Note that you should only use this method after the + * Field has been consumed (ie, the {@link Document} + * containing this Field has been added to the index). + * Also, each Field instance should only be used once + * within a single {@link Document} instance. See ImproveIndexingSpeed + * for details.

*/ + public void setValue(String value) { + fieldsData = value; + } + + /** Expert: change the value of this field. See setValue(String). */ + public void setValue(Reader value) { + fieldsData = value; + } + + /** Expert: change the value of this field. See setValue(String). */ + public void setValue(byte[] value) { + fieldsData = value; + binaryLength = value.length; + binaryOffset = 0; + } + + /** Expert: change the value of this field. See setValue(String). */ + public void setValue(byte[] value, int offset, int length) { + fieldsData = value; + binaryLength = length; + binaryOffset = offset; + } + + + /** Expert: change the value of this field. See setValue(String). */ + public void setValue(TokenStream value) { + fieldsData = value; + } + + /** + * Create a field by specifying its name, value and how it will + * be saved in the index. Term vectors will not be stored in the index. + * + * @param name The name of the field + * @param value The string to process + * @param store Whether value should be stored in the index + * @param index Whether the field should be indexed, and if so, if it should + * be tokenized before indexing + * @throws NullPointerException if name or value is null + * @throws IllegalArgumentException if the field is neither stored nor indexed + */ + public Field(String name, String value, Store store, Index index) { + this(name, value, store, index, TermVector.NO); + } + + /** + * Create a field by specifying its name, value and how it will + * be saved in the index. + * + * @param name The name of the field + * @param value The string to process + * @param store Whether value should be stored in the index + * @param index Whether the field should be indexed, and if so, if it should + * be tokenized before indexing + * @param termVector Whether term vector should be stored + * @throws NullPointerException if name or value is null + * @throws IllegalArgumentException in any of the following situations: + *
    + *
  • the field is neither stored nor indexed
  • + *
  • the field is not indexed but termVector is TermVector.YES
  • + *
+ */ + public Field(String name, String value, Store store, Index index, TermVector termVector) { + if (name == null) + throw new NullPointerException("name cannot be null"); + if (value == null) + throw new NullPointerException("value cannot be null"); + if (name.length() == 0 && value.length() == 0) + throw new IllegalArgumentException("name and value cannot both be empty"); + if (index == Index.NO && store == Store.NO) + throw new IllegalArgumentException("it doesn't make sense to have a field that " + + "is neither indexed nor stored"); + if (index == Index.NO && termVector != TermVector.NO) + throw new IllegalArgumentException("cannot store term vector information " + + "for a field that is not indexed"); + + this.name = name.intern(); // field names are interned + this.fieldsData = value; + + if (store == Store.YES){ + this.isStored = true; + this.isCompressed = false; + } + else if (store == Store.COMPRESS) { + this.isStored = true; + this.isCompressed = true; + } + else if (store == Store.NO){ + this.isStored = false; + this.isCompressed = false; + } + else + throw new IllegalArgumentException("unknown store parameter " + store); + + if (index == Index.NO) { + this.isIndexed = false; + this.isTokenized = false; + } else if (index == Index.ANALYZED) { + this.isIndexed = true; + this.isTokenized = true; + } else if (index == Index.NOT_ANALYZED) { + this.isIndexed = true; + this.isTokenized = false; + } else if (index == Index.NOT_ANALYZED_NO_NORMS) { + this.isIndexed = true; + this.isTokenized = false; + this.omitNorms = true; + } else if (index == Index.ANALYZED_NO_NORMS) { + this.isIndexed = true; + this.isTokenized = true; + this.omitNorms = true; + } else { + throw new IllegalArgumentException("unknown index parameter " + index); + } + + this.isBinary = false; + + setStoreTermVector(termVector); + } + + /** + * Create a tokenized and indexed field that is not stored. Term vectors will + * not be stored. The Reader is read only when the Document is added to the index, + * i.e. you may not close the Reader until {@link IndexWriter#addDocument(Document)} + * has been called. + * + * @param name The name of the field + * @param reader The reader with the content + * @throws NullPointerException if name or reader is null + */ + public Field(String name, Reader reader) { + this(name, reader, TermVector.NO); + } + + /** + * Create a tokenized and indexed field that is not stored, optionally with + * storing term vectors. The Reader is read only when the Document is added to the index, + * i.e. you may not close the Reader until {@link IndexWriter#addDocument(Document)} + * has been called. + * + * @param name The name of the field + * @param reader The reader with the content + * @param termVector Whether term vector should be stored + * @throws NullPointerException if name or reader is null + */ + public Field(String name, Reader reader, TermVector termVector) { + if (name == null) + throw new NullPointerException("name cannot be null"); + if (reader == null) + throw new NullPointerException("reader cannot be null"); + + this.name = name.intern(); // field names are interned + this.fieldsData = reader; + + this.isStored = false; + this.isCompressed = false; + + this.isIndexed = true; + this.isTokenized = true; + + this.isBinary = false; + + setStoreTermVector(termVector); + } + + /** + * Create a tokenized and indexed field that is not stored. Term vectors will + * not be stored. This is useful for pre-analyzed fields. + * The TokenStream is read only when the Document is added to the index, + * i.e. you may not close the TokenStream until {@link IndexWriter#addDocument(Document)} + * has been called. + * + * @param name The name of the field + * @param tokenStream The TokenStream with the content + * @throws NullPointerException if name or tokenStream is null + */ + public Field(String name, TokenStream tokenStream) { + this(name, tokenStream, TermVector.NO); + } + + /** + * Create a tokenized and indexed field that is not stored, optionally with + * storing term vectors. This is useful for pre-analyzed fields. + * The TokenStream is read only when the Document is added to the index, + * i.e. you may not close the TokenStream until {@link IndexWriter#addDocument(Document)} + * has been called. + * + * @param name The name of the field + * @param tokenStream The TokenStream with the content + * @param termVector Whether term vector should be stored + * @throws NullPointerException if name or tokenStream is null + */ + public Field(String name, TokenStream tokenStream, TermVector termVector) { + if (name == null) + throw new NullPointerException("name cannot be null"); + if (tokenStream == null) + throw new NullPointerException("tokenStream cannot be null"); + + this.name = name.intern(); // field names are interned + this.fieldsData = tokenStream; + + this.isStored = false; + this.isCompressed = false; + + this.isIndexed = true; + this.isTokenized = true; + + this.isBinary = false; + + setStoreTermVector(termVector); + } + + + /** + * Create a stored field with binary value. Optionally the value may be compressed. + * + * @param name The name of the field + * @param value The binary value + * @param store How value should be stored (compressed or not) + * @throws IllegalArgumentException if store is Store.NO + */ + public Field(String name, byte[] value, Store store) { + this(name, value, 0, value.length, store); + } + + /** + * Create a stored field with binary value. Optionally the value may be compressed. + * + * @param name The name of the field + * @param value The binary value + * @param offset Starting offset in value where this Field's bytes are + * @param length Number of bytes to use for this Field, starting at offset + * @param store How value should be stored (compressed or not) + * @throws IllegalArgumentException if store is Store.NO + */ + public Field(String name, byte[] value, int offset, int length, Store store) { + + if (name == null) + throw new IllegalArgumentException("name cannot be null"); + if (value == null) + throw new IllegalArgumentException("value cannot be null"); + + this.name = name.intern(); + fieldsData = value; + + if (store == Store.YES) { + isStored = true; + isCompressed = false; + } + else if (store == Store.COMPRESS) { + isStored = true; + isCompressed = true; + } + else if (store == Store.NO) + throw new IllegalArgumentException("binary values can't be unstored"); + else + throw new IllegalArgumentException("unknown store parameter " + store); + + isIndexed = false; + isTokenized = false; + + isBinary = true; + binaryLength = length; + binaryOffset = offset; + + setStoreTermVector(TermVector.NO); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/FieldSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/FieldSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/FieldSelector.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,34 @@ +package org.apache.lucene.document; + +import java.io.Serializable; +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Similar to a {@link java.io.FileFilter}, the FieldSelector allows one to make decisions about + * what Fields get loaded on a {@link Document} by {@link org.apache.lucene.index.IndexReader#document(int,org.apache.lucene.document.FieldSelector)} + * + **/ +public interface FieldSelector extends Serializable { + + /** + * + * @param fieldName the field to accept or reject + * @return an instance of {@link FieldSelectorResult} + * if the {@link Field} named fieldName should be loaded. + */ + FieldSelectorResult accept(String fieldName); +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/FieldSelectorResult.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/FieldSelectorResult.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/FieldSelectorResult.java 17 Aug 2012 14:54:52 -0000 1.1 @@ -0,0 +1,96 @@ +package org.apache.lucene.document; + +import java.io.Serializable; +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provides information about what should be done with this Field + * + **/ +//Replace with an enumerated type in 1.5 +public final class FieldSelectorResult implements Serializable { + + /** + * Load this {@link Field} every time the {@link Document} is loaded, reading in the data as it is encounterd. + * {@link Document#getField(String)} and {@link Document#getFieldable(String)} should not return null. + *

+ * {@link Document#add(Fieldable)} should be called by the Reader. + */ + public transient static final FieldSelectorResult LOAD = new FieldSelectorResult(0); + /** + * Lazily load this {@link Field}. This means the {@link Field} is valid, but it may not actually contain its data until + * invoked. {@link Document#getField(String)} SHOULD NOT BE USED. {@link Document#getFieldable(String)} is safe to use and should + * return a valid instance of a {@link Fieldable}. + *

+ * {@link Document#add(Fieldable)} should be called by the Reader. + */ + public transient static final FieldSelectorResult LAZY_LOAD = new FieldSelectorResult(1); + /** + * Do not load the {@link Field}. {@link Document#getField(String)} and {@link Document#getFieldable(String)} should return null. + * {@link Document#add(Fieldable)} is not called. + *

+ * {@link Document#add(Fieldable)} should not be called by the Reader. + */ + public transient static final FieldSelectorResult NO_LOAD = new FieldSelectorResult(2); + /** + * Load this field as in the {@link #LOAD} case, but immediately return from {@link Field} loading for the {@link Document}. Thus, the + * Document may not have its complete set of Fields. {@link Document#getField(String)} and {@link Document#getFieldable(String)} should + * both be valid for this {@link Field} + *

+ * {@link Document#add(Fieldable)} should be called by the Reader. + */ + public transient static final FieldSelectorResult LOAD_AND_BREAK = new FieldSelectorResult(3); + /** + * Behaves much like {@link #LOAD} but does not uncompress any compressed data. This is used for internal purposes. + * {@link Document#getField(String)} and {@link Document#getFieldable(String)} should not return null. + *

+ * {@link Document#add(Fieldable)} should be called by the Reader. + */ + public transient static final FieldSelectorResult LOAD_FOR_MERGE = new FieldSelectorResult(4); + + /** Expert: Load the size of this {@link Field} rather than its value. + * Size is measured as number of bytes required to store the field == bytes for a binary or any compressed value, and 2*chars for a String value. + * The size is stored as a binary value, represented as an int in a byte[], with the higher order byte first in [0] + */ + public transient static final FieldSelectorResult SIZE = new FieldSelectorResult(5); + + /** Expert: Like {@link #SIZE} but immediately break from the field loading loop, i.e., stop loading further fields, after the size is loaded */ + public transient static final FieldSelectorResult SIZE_AND_BREAK = new FieldSelectorResult(6); + + + + private int id; + + private FieldSelectorResult(int id) { + this.id = id; + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + final FieldSelectorResult that = (FieldSelectorResult) o; + + if (id != that.id) return false; + + return true; + } + + public int hashCode() { + return id; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/Fieldable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/Fieldable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/Fieldable.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,200 @@ +package org.apache.lucene.document; + +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.TokenStream; + +import java.io.Reader; +import java.io.Serializable; + +/** + * Synonymous with {@link Field}. + * + *

WARNING: This interface may change within minor versions, despite Lucene's backward compatibility requirements. + * This means new methods may be added from version to version. This change only affects the Fieldable API; other backwards + * compatibility promises remain intact. For example, Lucene can still + * read and write indices created within the same major version. + *

+ * + **/ +public interface Fieldable extends Serializable { + /** Sets the boost factor hits on this field. This value will be + * multiplied into the score of all hits on this this field of this + * document. + * + *

The boost is multiplied by {@link org.apache.lucene.document.Document#getBoost()} of the document + * containing this field. If a document has multiple fields with the same + * name, all such values are multiplied together. This product is then + * multipled by the value {@link org.apache.lucene.search.Similarity#lengthNorm(String,int)}, and + * rounded by {@link org.apache.lucene.search.Similarity#encodeNorm(float)} before it is stored in the + * index. One should attempt to ensure that this product does not overflow + * the range of that encoding. + * + * @see org.apache.lucene.document.Document#setBoost(float) + * @see org.apache.lucene.search.Similarity#lengthNorm(String, int) + * @see org.apache.lucene.search.Similarity#encodeNorm(float) + */ + void setBoost(float boost); + + /** Returns the boost factor for hits for this field. + * + *

The default value is 1.0. + * + *

Note: this value is not stored directly with the document in the index. + * Documents returned from {@link org.apache.lucene.index.IndexReader#document(int)} and + * {@link org.apache.lucene.search.Hits#doc(int)} may thus not have the same value present as when + * this field was indexed. + * + * @see #setBoost(float) + */ + float getBoost(); + + /** Returns the name of the field as an interned string. + * For example "date", "title", "body", ... + */ + String name(); + + /** The value of the field as a String, or null. If null, the Reader value, + * binary value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public String stringValue(); + + /** The value of the field as a Reader, or null. If null, the String value, + * binary value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public Reader readerValue(); + + /** The value of the field in Binary, or null. If null, the Reader value, + * String value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public byte[] binaryValue(); + + /** The value of the field as a TokenStream, or null. If null, the Reader value, + * String value, or binary value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public TokenStream tokenStreamValue(); + + /** True iff the value of the field is to be stored in the index for return + with search hits. It is an error for this to be true if a field is + Reader-valued. */ + boolean isStored(); + + /** True iff the value of the field is to be indexed, so that it may be + searched on. */ + boolean isIndexed(); + + /** True iff the value of the field should be tokenized as text prior to + indexing. Un-tokenized fields are indexed as a single word and may not be + Reader-valued. */ + boolean isTokenized(); + + /** True if the value of the field is stored and compressed within the index */ + boolean isCompressed(); + + /** True iff the term or terms used to index this field are stored as a term + * vector, available from {@link org.apache.lucene.index.IndexReader#getTermFreqVector(int,String)}. + * These methods do not provide access to the original content of the field, + * only to terms used to index it. If the original content must be + * preserved, use the stored attribute instead. + * + * @see org.apache.lucene.index.IndexReader#getTermFreqVector(int, String) + */ + boolean isTermVectorStored(); + + /** + * True iff terms are stored as term vector together with their offsets + * (start and end positon in source text). + */ + boolean isStoreOffsetWithTermVector(); + + /** + * True iff terms are stored as term vector together with their token positions. + */ + boolean isStorePositionWithTermVector(); + + /** True iff the value of the filed is stored as binary */ + boolean isBinary(); + + /** True if norms are omitted for this indexed field */ + boolean getOmitNorms(); + + /** Expert: + * + * If set, omit normalization factors associated with this indexed field. + * This effectively disables indexing boosts and length normalization for this field. + */ + void setOmitNorms(boolean omitNorms); + + /** Expert: + * + * If set, omit term freq, positions and payloads from postings for this field. + */ + void setOmitTf(boolean omitTf); + + /** True if tf is omitted for this indexed field */ + boolean getOmitTf(); + + /** + * Indicates whether a Field is Lazy or not. The semantics of Lazy loading are such that if a Field is lazily loaded, retrieving + * it's values via {@link #stringValue()} or {@link #binaryValue()} is only valid as long as the {@link org.apache.lucene.index.IndexReader} that + * retrieved the {@link Document} is still open. + * + * @return true if this field can be loaded lazily + */ + boolean isLazy(); + + /** + * Returns offset into byte[] segment that is used as value, if Field is not binary + * returned value is undefined + * @return index of the first character in byte[] segment that represents this Field value + */ + abstract int getBinaryOffset(); + + /** + * Returns length of byte[] segment that is used as value, if Field is not binary + * returned value is undefined + * @return length of byte[] segment that represents this Field value + */ + abstract int getBinaryLength(); + + /** + * Return the raw byte[] for the binary field. Note that + * you must also call {@link #getBinaryLength} and {@link + * #getBinaryOffset} to know which range of bytes in this + * returned array belong to the field. + * @return reference to the Field value as byte[]. + */ + abstract byte[] getBinaryValue(); + + /** + * Return the raw byte[] for the binary field. Note that + * you must also call {@link #getBinaryLength} and {@link + * #getBinaryOffset} to know which range of bytes in this + * returned array belong to the field.

+ * About reuse: if you pass in the result byte[] and it is + * used, likely the underlying implementation will hold + * onto this byte[] and return it in future calls to + * {@link #binaryValue()} or {@link #getBinaryValue()}. + * So if you subsequently re-use the same byte[] elsewhere + * it will alter this Fieldable's value. + * @param result User defined buffer that will be used if + * possible. If this is null or not large enough, a new + * buffer is allocated + * @return reference to the Field value as byte[]. + */ + abstract byte[] getBinaryValue(byte[] result); +} Index: 3rdParty_sources/lucene/org/apache/lucene/document/LoadFirstFieldSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/LoadFirstFieldSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/LoadFirstFieldSelector.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,29 @@ +package org.apache.lucene.document; +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Load the First field and break. + *

+ * See {@link FieldSelectorResult#LOAD_AND_BREAK} + */ +public class LoadFirstFieldSelector implements FieldSelector { + + public FieldSelectorResult accept(String fieldName) { + return FieldSelectorResult.LOAD_AND_BREAK; + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/document/MapFieldSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/MapFieldSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/MapFieldSelector.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,66 @@ +package org.apache.lucene.document; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * A FieldSelector based on a Map of field names to FieldSelectorResults + * + */ +public class MapFieldSelector implements FieldSelector { + + Map fieldSelections; + + /** Create a a MapFieldSelector + * @param fieldSelections maps from field names (String) to FieldSelectorResults + */ + public MapFieldSelector(Map fieldSelections) { + this.fieldSelections = fieldSelections; + } + + /** Create a a MapFieldSelector + * @param fields fields to LOAD. List of Strings. All other fields are NO_LOAD. + */ + public MapFieldSelector(List fields) { + fieldSelections = new HashMap(fields.size()*5/3); + for (int i=0; i + * That is, if l1 is less than l2 for any two longs l1 and l2, then + * NumberTools.longToString(l1) is lexicographically less than + * NumberTools.longToString(l2). (Similarly for "greater than" and "equals".) + * + *

+ * This class handles all long values (unlike + * {@link org.apache.lucene.document.DateField}). + * + * + */ +public class NumberTools { + + private static final int RADIX = 36; + + private static final char NEGATIVE_PREFIX = '-'; + + // NB: NEGATIVE_PREFIX must be < POSITIVE_PREFIX + private static final char POSITIVE_PREFIX = '0'; + + //NB: this must be less than + /** + * Equivalent to longToString(Long.MIN_VALUE) + */ + public static final String MIN_STRING_VALUE = NEGATIVE_PREFIX + + "0000000000000"; + + /** + * Equivalent to longToString(Long.MAX_VALUE) + */ + public static final String MAX_STRING_VALUE = POSITIVE_PREFIX + + "1y2p0ij32e8e7"; + + /** + * The length of (all) strings returned by {@link #longToString} + */ + public static final int STR_SIZE = MIN_STRING_VALUE.length(); + + /** + * Converts a long to a String suitable for indexing. + */ + public static String longToString(long l) { + + if (l == Long.MIN_VALUE) { + // special case, because long is not symetric around zero + return MIN_STRING_VALUE; + } + + StringBuffer buf = new StringBuffer(STR_SIZE); + + if (l < 0) { + buf.append(NEGATIVE_PREFIX); + l = Long.MAX_VALUE + l + 1; + } else { + buf.append(POSITIVE_PREFIX); + } + String num = Long.toString(l, RADIX); + + int padLen = STR_SIZE - num.length() - buf.length(); + while (padLen-- > 0) { + buf.append('0'); + } + buf.append(num); + + return buf.toString(); + } + + /** + * Converts a String that was returned by {@link #longToString} back to a + * long. + * + * @throws IllegalArgumentException + * if the input is null + * @throws NumberFormatException + * if the input does not parse (it was not a String returned by + * longToString()). + */ + public static long stringToLong(String str) { + if (str == null) { + throw new NullPointerException("string cannot be null"); + } + if (str.length() != STR_SIZE) { + throw new NumberFormatException("string is the wrong size"); + } + + if (str.equals(MIN_STRING_VALUE)) { + return Long.MIN_VALUE; + } + + char prefix = str.charAt(0); + long l = Long.parseLong(str.substring(1), RADIX); + + if (prefix == POSITIVE_PREFIX) { + // nop + } else if (prefix == NEGATIVE_PREFIX) { + l = l - Long.MAX_VALUE - 1; + } else { + throw new NumberFormatException( + "string does not begin with the correct prefix"); + } + + return l; + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/document/SetBasedFieldSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/SetBasedFieldSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/SetBasedFieldSelector.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,60 @@ +package org.apache.lucene.document; + +import java.util.Set; +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Declare what fields to load normally and what fields to load lazily + * + **/ +public class SetBasedFieldSelector implements FieldSelector { + + private Set fieldsToLoad; + private Set lazyFieldsToLoad; + + + + /** + * Pass in the Set of {@link Field} names to load and the Set of {@link Field} names to load lazily. If both are null, the + * Document will not have any {@link Field} on it. + * @param fieldsToLoad A Set of {@link String} field names to load. May be empty, but not null + * @param lazyFieldsToLoad A Set of {@link String} field names to load lazily. May be empty, but not null + */ + public SetBasedFieldSelector(Set fieldsToLoad, Set lazyFieldsToLoad) { + this.fieldsToLoad = fieldsToLoad; + this.lazyFieldsToLoad = lazyFieldsToLoad; + } + + /** + * Indicate whether to load the field with the given name or not. If the {@link Field#name()} is not in either of the + * initializing Sets, then {@link org.apache.lucene.document.FieldSelectorResult#NO_LOAD} is returned. If a Field name + * is in both fieldsToLoad and lazyFieldsToLoad, lazy has precedence. + * + * @param fieldName The {@link Field} name to check + * @return The {@link FieldSelectorResult} + */ + public FieldSelectorResult accept(String fieldName) { + FieldSelectorResult result = FieldSelectorResult.NO_LOAD; + if (fieldsToLoad.contains(fieldName) == true){ + result = FieldSelectorResult.LOAD; + } + if (lazyFieldsToLoad.contains(fieldName) == true){ + result = FieldSelectorResult.LAZY_LOAD; + } + return result; + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/document/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/document/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/document/package.html 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,54 @@ + + + + + + + +

The logical representation of a {@link org.apache.lucene.document.Document} for indexing and searching.

+

The document package provides the user level logical representation of content to be indexed and searched. The +package also provides utilities for working with {@link org.apache.lucene.document.Document}s and {@link org.apache.lucene.document.Fieldable}s.

+

Document and Fieldable

+

A {@link org.apache.lucene.document.Document} is a collection of {@link org.apache.lucene.document.Fieldable}s. A + {@link org.apache.lucene.document.Fieldable} is a logical representation of a user's content that needs to be indexed or stored. + {@link org.apache.lucene.document.Fieldable}s have a number of properties that tell Lucene how to treat the content (like indexed, tokenized, + stored, etc.) See the {@link org.apache.lucene.document.Field} implementation of {@link org.apache.lucene.document.Fieldable} + for specifics on these properties. +

+

Note: it is common to refer to {@link org.apache.lucene.document.Document}s having {@link org.apache.lucene.document.Field}s, even though technically they have +{@link org.apache.lucene.document.Fieldable}s.

+

Working with Documents

+

First and foremost, a {@link org.apache.lucene.document.Document} is something created by the user application. It is your job + to create Documents based on the content of the files you are working with in your application (Word, txt, PDF, Excel or any other format.) + How this is done is completely up to you. That being said, there are many tools available in other projects that can make + the process of taking a file and converting it into a Lucene {@link org.apache.lucene.document.Document}. To see an example of this, + take a look at the Lucene demo and the associated source code + for extracting content from HTML. +

+

The {@link org.apache.lucene.document.DateTools} and {@link org.apache.lucene.document.NumberTools} classes are utility +classes to make dates, times and longs searchable (remember, Lucene only searches text).

+

The {@link org.apache.lucene.document.FieldSelector} class provides a mechanism to tell Lucene how to load Documents from +storage. If no FieldSelector is used, all Fieldables on a Document will be loaded. As an example of the FieldSelector usage, consider + the common use case of +displaying search results on a web page and then having users click through to see the full document. In this scenario, it is often + the case that there are many small fields and one or two large fields (containing the contents of the original file). Before the FieldSelector, +the full Document had to be loaded, including the large fields, in order to display the results. Now, using the FieldSelector, one +can {@link org.apache.lucene.document.FieldSelectorResult#LAZY_LOAD} the large fields, thus only loading the large fields +when a user clicks on the actual link to view the original content.

+ + Index: 3rdParty_sources/lucene/org/apache/lucene/index/BufferedDeletes.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/BufferedDeletes.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/BufferedDeletes.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,146 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Iterator; +import java.util.Map.Entry; + +/** Holds buffered deletes, by docID, term or query. We + * hold two instances of this class: one for the deletes + * prior to the last flush, the other for deletes after + * the last flush. This is so if we need to abort + * (discard all buffered docs) we can also discard the + * buffered deletes yet keep the deletes done during + * previously flushed segments. */ +class BufferedDeletes { + int numTerms; + HashMap terms = new HashMap(); + HashMap queries = new HashMap(); + List docIDs = new ArrayList(); + + // Number of documents a delete term applies to. + final static class Num { + private int num; + + Num(int num) { + this.num = num; + } + + int getNum() { + return num; + } + + void setNum(int num) { + // Only record the new number if it's greater than the + // current one. This is important because if multiple + // threads are replacing the same doc at nearly the + // same time, it's possible that one thread that got a + // higher docID is scheduled before the other + // threads. + if (num > this.num) + this.num = num; + } + } + + + + void update(BufferedDeletes in) { + numTerms += in.numTerms; + terms.putAll(in.terms); + queries.putAll(in.queries); + docIDs.addAll(in.docIDs); + in.terms.clear(); + in.numTerms = 0; + in.queries.clear(); + in.docIDs.clear(); + } + + void clear() { + terms.clear(); + queries.clear(); + docIDs.clear(); + numTerms = 0; + } + + boolean any() { + return terms.size() > 0 || docIDs.size() > 0 || queries.size() > 0; + } + + // Remaps all buffered deletes based on a completed + // merge + synchronized void remap(MergeDocIDRemapper mapper, + SegmentInfos infos, + int[][] docMaps, + int[] delCounts, + MergePolicy.OneMerge merge, + int mergeDocCount) { + + final HashMap newDeleteTerms; + + // Remap delete-by-term + if (terms.size() > 0) { + newDeleteTerms = new HashMap(); + Iterator iter = terms.entrySet().iterator(); + while(iter.hasNext()) { + Entry entry = (Entry) iter.next(); + Num num = (Num) entry.getValue(); + newDeleteTerms.put(entry.getKey(), + new Num(mapper.remap(num.getNum()))); + } + } else + newDeleteTerms = null; + + // Remap delete-by-docID + final List newDeleteDocIDs; + + if (docIDs.size() > 0) { + newDeleteDocIDs = new ArrayList(docIDs.size()); + Iterator iter = docIDs.iterator(); + while(iter.hasNext()) { + Integer num = (Integer) iter.next(); + newDeleteDocIDs.add(new Integer(mapper.remap(num.intValue()))); + } + } else + newDeleteDocIDs = null; + + // Remap delete-by-query + final HashMap newDeleteQueries; + + if (queries.size() > 0) { + newDeleteQueries = new HashMap(queries.size()); + Iterator iter = queries.entrySet().iterator(); + while(iter.hasNext()) { + Entry entry = (Entry) iter.next(); + Integer num = (Integer) entry.getValue(); + newDeleteQueries.put(entry.getKey(), + new Integer(mapper.remap(num.intValue()))); + } + } else + newDeleteQueries = null; + + if (newDeleteTerms != null) + terms = newDeleteTerms; + if (newDeleteDocIDs != null) + docIDs = newDeleteDocIDs; + if (newDeleteQueries != null) + queries = newDeleteQueries; + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/index/ByteBlockPool.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/ByteBlockPool.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/ByteBlockPool.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,147 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Class that Posting and PostingVector use to write byte + * streams into shared fixed-size byte[] arrays. The idea + * is to allocate slices of increasing lengths For + * example, the first slice is 5 bytes, the next slice is + * 14, etc. We start by writing our bytes into the first + * 5 bytes. When we hit the end of the slice, we allocate + * the next slice and then write the address of the new + * slice into the last 4 bytes of the previous slice (the + * "forwarding address"). + * + * Each slice is filled with 0's initially, and we mark + * the end with a non-zero byte. This way the methods + * that are writing into the slice don't need to record + * its length and instead allocate a new slice once they + * hit a non-zero byte. */ + +import java.util.Arrays; + +final class ByteBlockPool { + + abstract static class Allocator { + abstract void recycleByteBlocks(byte[][] blocks, int start, int end); + abstract byte[] getByteBlock(boolean trackAllocations); + } + + public byte[][] buffers = new byte[10][]; + + int bufferUpto = -1; // Which buffer we are upto + public int byteUpto = DocumentsWriter.BYTE_BLOCK_SIZE; // Where we are in head buffer + + public byte[] buffer; // Current head buffer + public int byteOffset = -DocumentsWriter.BYTE_BLOCK_SIZE; // Current head offset + + private final boolean trackAllocations; + private final Allocator allocator; + + public ByteBlockPool(Allocator allocator, boolean trackAllocations) { + this.allocator = allocator; + this.trackAllocations = trackAllocations; + } + + public void reset() { + if (bufferUpto != -1) { + // We allocated at least one buffer + + for(int i=0;i 0) + // Recycle all but the first buffer + allocator.recycleByteBlocks(buffers, 1, 1+bufferUpto); + + // Re-use the first buffer + bufferUpto = 0; + byteUpto = 0; + byteOffset = 0; + buffer = buffers[0]; + } + } + + public void nextBuffer() { + if (1+bufferUpto == buffers.length) { + byte[][] newBuffers = new byte[(int) (buffers.length*1.5)][]; + System.arraycopy(buffers, 0, newBuffers, 0, buffers.length); + buffers = newBuffers; + } + buffer = buffers[1+bufferUpto] = allocator.getByteBlock(trackAllocations); + bufferUpto++; + + byteUpto = 0; + byteOffset += DocumentsWriter.BYTE_BLOCK_SIZE; + } + + public int newSlice(final int size) { + if (byteUpto > DocumentsWriter.BYTE_BLOCK_SIZE-size) + nextBuffer(); + final int upto = byteUpto; + byteUpto += size; + buffer[byteUpto-1] = 16; + return upto; + } + + // Size of each slice. These arrays should be at most 16 + // elements (index is encoded with 4 bits). First array + // is just a compact way to encode X+1 with a max. Second + // array is the length of each slice, ie first slice is 5 + // bytes, next slice is 14 bytes, etc. + final static int[] nextLevelArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 9}; + final static int[] levelSizeArray = {5, 14, 20, 30, 40, 40, 80, 80, 120, 200}; + final static int FIRST_LEVEL_SIZE = levelSizeArray[0]; + + public int allocSlice(final byte[] slice, final int upto) { + + final int level = slice[upto] & 15; + final int newLevel = nextLevelArray[level]; + final int newSize = levelSizeArray[newLevel]; + + // Maybe allocate another block + if (byteUpto > DocumentsWriter.BYTE_BLOCK_SIZE-newSize) + nextBuffer(); + + final int newUpto = byteUpto; + final int offset = newUpto + byteOffset; + byteUpto += newSize; + + // Copy forward the past 3 bytes (which we are about + // to overwrite with the forwarding address): + buffer[newUpto] = slice[upto-3]; + buffer[newUpto+1] = slice[upto-2]; + buffer[newUpto+2] = slice[upto-1]; + + // Write forwarding address at end of last slice: + slice[upto-3] = (byte) (offset >>> 24); + slice[upto-2] = (byte) (offset >>> 16); + slice[upto-1] = (byte) (offset >>> 8); + slice[upto] = (byte) offset; + + // Write new level: + buffer[byteUpto-1] = (byte) (16|newLevel); + + return newUpto+3; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/ByteSliceReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/ByteSliceReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/ByteSliceReader.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,143 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import java.io.IOException; + +/* IndexInput that knows how to read the byte slices written + * by Posting and PostingVector. We read the bytes in + * each slice until we hit the end of that slice at which + * point we read the forwarding address of the next slice + * and then jump to it.*/ +final class ByteSliceReader extends IndexInput { + ByteBlockPool pool; + int bufferUpto; + byte[] buffer; + public int upto; + int limit; + int level; + public int bufferOffset; + + public int endIndex; + + public void init(ByteBlockPool pool, int startIndex, int endIndex) { + + assert endIndex-startIndex >= 0; + assert startIndex >= 0; + assert endIndex >= 0; + + this.pool = pool; + this.endIndex = endIndex; + + level = 0; + bufferUpto = startIndex / DocumentsWriter.BYTE_BLOCK_SIZE; + bufferOffset = bufferUpto * DocumentsWriter.BYTE_BLOCK_SIZE; + buffer = pool.buffers[bufferUpto]; + upto = startIndex & DocumentsWriter.BYTE_BLOCK_MASK; + + final int firstSize = ByteBlockPool.levelSizeArray[0]; + + if (startIndex+firstSize >= endIndex) { + // There is only this one slice to read + limit = endIndex & DocumentsWriter.BYTE_BLOCK_MASK; + } else + limit = upto+firstSize-4; + } + + public boolean eof() { + assert upto + bufferOffset <= endIndex; + return upto + bufferOffset == endIndex; + } + + public byte readByte() { + assert !eof(); + assert upto <= limit; + if (upto == limit) + nextSlice(); + return buffer[upto++]; + } + + public long writeTo(IndexOutput out) throws IOException { + long size = 0; + while(true) { + if (limit + bufferOffset == endIndex) { + assert endIndex - bufferOffset >= upto; + out.writeBytes(buffer, upto, limit-upto); + size += limit-upto; + break; + } else { + out.writeBytes(buffer, upto, limit-upto); + size += limit-upto; + nextSlice(); + } + } + + return size; + } + + public void nextSlice() { + + // Skip to our next slice + final int nextIndex = ((buffer[limit]&0xff)<<24) + ((buffer[1+limit]&0xff)<<16) + ((buffer[2+limit]&0xff)<<8) + (buffer[3+limit]&0xff); + + level = ByteBlockPool.nextLevelArray[level]; + final int newSize = ByteBlockPool.levelSizeArray[level]; + + bufferUpto = nextIndex / DocumentsWriter.BYTE_BLOCK_SIZE; + bufferOffset = bufferUpto * DocumentsWriter.BYTE_BLOCK_SIZE; + + buffer = pool.buffers[bufferUpto]; + upto = nextIndex & DocumentsWriter.BYTE_BLOCK_MASK; + + if (nextIndex + newSize >= endIndex) { + // We are advancing to the final slice + assert endIndex - nextIndex > 0; + limit = endIndex - bufferOffset; + } else { + // This is not the final slice (subtract 4 for the + // forwarding address at the end of this new slice) + limit = upto+newSize-4; + } + } + + public void readBytes(byte[] b, int offset, int len) { + while(len > 0) { + final int numLeft = limit-upto; + if (numLeft < len) { + // Read entire slice + System.arraycopy(buffer, upto, b, offset, numLeft); + offset += numLeft; + len -= numLeft; + nextSlice(); + } else { + // This slice is the last one + System.arraycopy(buffer, upto, b, offset, len); + upto += len; + break; + } + } + } + + public long getFilePointer() {throw new RuntimeException("not implemented");} + public long length() {throw new RuntimeException("not implemented");} + public void seek(long pos) {throw new RuntimeException("not implemented");} + public void close() {throw new RuntimeException("not implemented");} +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/ByteSliceWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/ByteSliceWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/ByteSliceWriter.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,89 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Class to write byte streams into slices of shared + * byte[]. This is used by DocumentsWriter to hold the + * posting list for many terms in RAM. + */ + +final class ByteSliceWriter { + + private byte[] slice; + private int upto; + private final ByteBlockPool pool; + + int offset0; + + public ByteSliceWriter(ByteBlockPool pool) { + this.pool = pool; + } + + /** + * Set up the writer to write at address. + */ + public void init(int address) { + slice = pool.buffers[address >> DocumentsWriter.BYTE_BLOCK_SHIFT]; + assert slice != null; + upto = address & DocumentsWriter.BYTE_BLOCK_MASK; + offset0 = address; + assert upto < slice.length; + } + + /** Write byte into byte slice stream */ + public void writeByte(byte b) { + assert slice != null; + if (slice[upto] != 0) { + upto = pool.allocSlice(slice, upto); + slice = pool.buffer; + offset0 = pool.byteOffset; + assert slice != null; + } + slice[upto++] = b; + assert upto != slice.length; + } + + public void writeBytes(final byte[] b, int offset, final int len) { + final int offsetEnd = offset + len; + while(offset < offsetEnd) { + if (slice[upto] != 0) { + // End marker + upto = pool.allocSlice(slice, upto); + slice = pool.buffer; + offset0 = pool.byteOffset; + } + + slice[upto++] = b[offset++]; + assert upto != slice.length; + } + } + + public int getAddress() { + return upto + (offset0 & DocumentsWriter.BYTE_BLOCK_NOT_MASK); + } + + public void writeVInt(int i) { + while ((i & ~0x7F) != 0) { + writeByte((byte)((i & 0x7f) | 0x80)); + i >>>= 7; + } + writeByte((byte) i); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/CharBlockPool.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/CharBlockPool.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/CharBlockPool.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,56 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +final class CharBlockPool { + + public char[][] buffers = new char[10][]; + int numBuffer; + + int bufferUpto = -1; // Which buffer we are upto + public int charUpto = DocumentsWriter.CHAR_BLOCK_SIZE; // Where we are in head buffer + + public char[] buffer; // Current head buffer + public int charOffset = -DocumentsWriter.CHAR_BLOCK_SIZE; // Current head offset + final private DocumentsWriter docWriter; + + public CharBlockPool(DocumentsWriter docWriter) { + this.docWriter = docWriter; + } + + public void reset() { + docWriter.recycleCharBlocks(buffers, 1+bufferUpto); + bufferUpto = -1; + charUpto = DocumentsWriter.CHAR_BLOCK_SIZE; + charOffset = -DocumentsWriter.CHAR_BLOCK_SIZE; + } + + public void nextBuffer() { + if (1+bufferUpto == buffers.length) { + char[][] newBuffers = new char[(int) (buffers.length*1.5)][]; + System.arraycopy(buffers, 0, newBuffers, 0, buffers.length); + buffers = newBuffers; + } + buffer = buffers[1+bufferUpto] = docWriter.getCharBlock(); + bufferUpto++; + + charUpto = 0; + charOffset += DocumentsWriter.CHAR_BLOCK_SIZE; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/CheckIndex.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/CheckIndex.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/CheckIndex.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,709 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.FSDirectory; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.document.Document; + +import java.text.NumberFormat; +import java.io.PrintStream; +import java.io.IOException; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ArrayList; +import org.apache.lucene.document.Fieldable; // for javadoc + +/** + * Basic tool and API to check the health of an index and + * write a new segments file that removes reference to + * problematic segments. + * + *

As this tool checks every byte in the index, on a large + * index it can take quite a long time to run. + * + *

WARNING: this tool and API is new and + * experimental and is subject to suddenly change in the + * next release. Please make a complete backup of your + * index before using this to fix your index! + */ +public class CheckIndex { + + /** Default PrintStream for all CheckIndex instances. + * @deprecated Use {@link #setInfoStream} per instance, + * instead. */ + public static PrintStream out = null; + + private PrintStream infoStream; + private Directory dir; + + /** + * Returned from {@link #checkIndex()} detailing the health and status of the index. + * + *

WARNING: this API is new and experimental and is + * subject to suddenly change in the next release. + **/ + + public static class Status { + + /** True if no problems were found with the index. */ + public boolean clean; + + /** True if we were unable to locate and load the segments_N file. */ + public boolean missingSegments; + + /** True if we were unable to open the segments_N file. */ + public boolean cantOpenSegments; + + /** True if we were unable to read the version number from segments_N file. */ + public boolean missingSegmentVersion; + + /** Name of latest segments_N file in the index. */ + public String segmentsFileName; + + /** Number of segments in the index. */ + public int numSegments; + + /** String description of the version of the index. */ + public String segmentFormat; + + /** Empty unless you passed specific segments list to check as optional 3rd argument. + * @see CheckIndex#checkIndex(List) */ + public List/**/ segmentsChecked = new ArrayList(); + + /** True if the index was created with a newer version of Lucene than the CheckIndex tool. */ + public boolean toolOutOfDate; + + /** List of {@link SegmentInfoStatus} instances, detailing status of each segment. */ + public List/*WARNING: this API is new and experimental and is + * subject to suddenly change in the next release. + */ + public static class SegmentInfoStatus { + /** Name of the segment. */ + public String name; + + /** Document count (does not take deletions into account). */ + public int docCount; + + /** True if segment is compound file format. */ + public boolean compound; + + /** Number of files referenced by this segment. */ + public int numFiles; + + /** Net size (MB) of the files referenced by this + * segment. */ + public double sizeMB; + + /** Doc store offset, if this segment shares the doc + * store files (stored fields and term vectors) with + * other segments. This is -1 if it does not share. */ + public int docStoreOffset = -1; + + /** String of the shared doc store segment, or null if + * this segment does not share the doc store files. */ + public String docStoreSegment; + + /** True if the shared doc store files are compound file + * format. */ + public boolean docStoreCompoundFile; + + /** True if this segment has pending deletions. */ + public boolean hasDeletions; + + /** Name of the current deletions file name. */ + public String deletionsFileName; + + /** Number of deleted documents. */ + public int numDeleted; + + /** True if we were able to open a SegmentReader on this + * segment. */ + public boolean openReaderPassed; + + /** Number of fields in this segment. */ + int numFields; + + /** True if at least one of the fields in this segment + * does not omitTf. + * @see Fieldable#setOmitTf */ + public boolean hasProx; + } + } + + /** Create a new CheckIndex on the directory. */ + public CheckIndex(Directory dir) { + this.dir = dir; + infoStream = out; + } + + /** Set infoStream where messages should go. If null, no + * messages are printed */ + public void setInfoStream(PrintStream out) { + infoStream = out; + } + + private void msg(String msg) { + if (infoStream != null) + infoStream.println(msg); + } + + private static class MySegmentTermDocs extends SegmentTermDocs { + + int delCount; + + MySegmentTermDocs(SegmentReader p) { + super(p); + } + + public void seek(Term term) throws IOException { + super.seek(term); + delCount = 0; + } + + protected void skippingDoc() throws IOException { + delCount++; + } + } + + /** Returns true if index is clean, else false. + * @deprecated Please instantiate a CheckIndex and then use {@link #checkIndex()} instead */ + public static boolean check(Directory dir, boolean doFix) throws IOException { + return check(dir, doFix, null); + } + + /** Returns true if index is clean, else false. + * @deprecated Please instantiate a CheckIndex and then use {@link #checkIndex(List)} instead */ + public static boolean check(Directory dir, boolean doFix, List onlySegments) throws IOException { + CheckIndex checker = new CheckIndex(dir); + Status status = checker.checkIndex(onlySegments); + if (doFix && !status.clean) + checker.fixIndex(status); + + return status.clean; + } + + /** Returns a {@link Status} instance detailing + * the state of the index. + * + *

As this method checks every byte in the index, on a large + * index it can take quite a long time to run. + * + *

WARNING: make sure + * you only call this when the index is not opened by any + * writer. */ + public Status checkIndex() throws IOException { + return checkIndex(null); + } + + /** Returns a {@link Status} instance detailing + * the state of the index. + * + * @param onlySegments list of specific segment names to check + * + *

As this method checks every byte in the specified + * segments, on a large index it can take quite a long + * time to run. + * + *

WARNING: make sure + * you only call this when the index is not opened by any + * writer. */ + public Status checkIndex(List onlySegments) throws IOException { + NumberFormat nf = NumberFormat.getInstance(); + SegmentInfos sis = new SegmentInfos(); + Status result = new Status(); + result.dir = dir; + try { + sis.read(dir); + } catch (Throwable t) { + msg("ERROR: could not read any segments file in directory"); + result.missingSegments = true; + if (infoStream != null) + t.printStackTrace(infoStream); + return result; + } + + final int numSegments = sis.size(); + final String segmentsFileName = sis.getCurrentSegmentFileName(); + IndexInput input = null; + try { + input = dir.openInput(segmentsFileName); + } catch (Throwable t) { + msg("ERROR: could not open segments file in directory"); + if (infoStream != null) + t.printStackTrace(infoStream); + result.cantOpenSegments = true; + return result; + } + int format = 0; + try { + format = input.readInt(); + } catch (Throwable t) { + msg("ERROR: could not read segment file version in directory"); + if (infoStream != null) + t.printStackTrace(infoStream); + result.missingSegmentVersion = true; + return result; + } finally { + if (input != null) + input.close(); + } + + String sFormat = ""; + boolean skip = false; + + if (format == SegmentInfos.FORMAT) + sFormat = "FORMAT [Lucene Pre-2.1]"; + if (format == SegmentInfos.FORMAT_LOCKLESS) + sFormat = "FORMAT_LOCKLESS [Lucene 2.1]"; + else if (format == SegmentInfos.FORMAT_SINGLE_NORM_FILE) + sFormat = "FORMAT_SINGLE_NORM_FILE [Lucene 2.2]"; + else if (format == SegmentInfos.FORMAT_SHARED_DOC_STORE) + sFormat = "FORMAT_SHARED_DOC_STORE [Lucene 2.3]"; + else { + if (format == SegmentInfos.FORMAT_CHECKSUM) + sFormat = "FORMAT_CHECKSUM [Lucene 2.4]"; + else if (format == SegmentInfos.FORMAT_DEL_COUNT) + sFormat = "FORMAT_DEL_COUNT [Lucene 2.4]"; + else if (format == SegmentInfos.FORMAT_HAS_PROX) + sFormat = "FORMAT_HAS_PROX [Lucene 2.4]"; + else if (format < SegmentInfos.CURRENT_FORMAT) { + sFormat = "int=" + format + " [newer version of Lucene than this tool]"; + skip = true; + } else { + sFormat = format + " [Lucene 1.3 or prior]"; + } + } + + msg("Segments file=" + segmentsFileName + " numSegments=" + numSegments + " version=" + sFormat); + result.segmentsFileName = segmentsFileName; + result.numSegments = numSegments; + result.segmentFormat = sFormat; + + if (onlySegments != null) { + result.partial = true; + if (infoStream != null) + infoStream.print("\nChecking only these segments:"); + Iterator it = onlySegments.iterator(); + while (it.hasNext()) { + if (infoStream != null) + infoStream.print(" " + it.next()); + } + result.segmentsChecked.addAll(onlySegments); + msg(":"); + } + + if (skip) { + msg("\nERROR: this index appears to be created by a newer version of Lucene than this tool was compiled on; please re-compile this tool on the matching version of Lucene; exiting"); + result.toolOutOfDate = true; + return result; + } + + + result.newSegments = (SegmentInfos) sis.clone(); + result.newSegments.clear(); + + for(int i=0;iWARNING: this writes a + * new segments file into the index, effectively removing + * all documents in broken segments from the index. + * BE CAREFUL. + * + *

WARNING: Make sure you only call this when the + * index is not opened by any writer. */ + public void fixIndex(Status result) throws IOException { + if (result.partial) + throw new IllegalArgumentException("can only fix an index that was fully checked (this status checked a subset of segments)"); + result.newSegments.commit(result.dir); + } + + private static boolean assertsOn; + + private static boolean testAsserts() { + assertsOn = true; + return true; + } + + private static boolean assertsOn() { + assert testAsserts(); + return assertsOn; + } + + /** Command-line interface to check and fix an index. + +

+ Run it like this: +

+    java -ea:org.apache.lucene... org.apache.lucene.index.CheckIndex pathToIndex [-fix] [-segment X] [-segment Y]
+    
+
    +
  • -fix: actually write a new segments_N file, removing any problematic segments + +
  • -segment X: only check the specified + segment(s). This can be specified multiple times, + to check more than one segment, eg -segment _2 + -segment _a. You can't use this with the -fix + option. +
+ +

WARNING: -fix should only be used on an emergency basis as it will cause + documents (perhaps many) to be permanently removed from the index. Always make + a backup copy of your index before running this! Do not run this tool on an index + that is actively being written to. You have been warned! + +

Run without -fix, this tool will open the index, report version information + and report any exceptions it hits and what action it would take if -fix were + specified. With -fix, this tool will remove any segments that have issues and + write a new segments_N file. This means all documents contained in the affected + segments will be removed. + +

+ This tool exits with exit code 1 if the index cannot be opened or has any + corruption, else 0. + */ + public static void main(String[] args) throws IOException { + + boolean doFix = false; + List onlySegments = new ArrayList(); + String indexPath = null; + int i = 0; + while(i < args.length) { + if (args[i].equals("-fix")) { + doFix = true; + i++; + } else if (args[i].equals("-segment")) { + if (i == args.length-1) { + System.out.println("ERROR: missing name for -segment option"); + System.exit(1); + } + onlySegments.add(args[i+1]); + i += 2; + } else { + if (indexPath != null) { + System.out.println("ERROR: unexpected extra argument '" + args[i] + "'"); + System.exit(1); + } + indexPath = args[i]; + i++; + } + } + + if (indexPath == null) { + System.out.println("\nERROR: index path not specified"); + System.out.println("\nUsage: java org.apache.lucene.index.CheckIndex pathToIndex [-fix] [-segment X] [-segment Y]\n" + + "\n" + + " -fix: actually write a new segments_N file, removing any problematic segments\n" + + " -segment X: only check the specified segments. This can be specified multiple\n" + + " times, to check more than one segment, eg '-segment _2 -segment _a'.\n" + + " You can't use this with the -fix option\n" + + "\n" + + "**WARNING**: -fix should only be used on an emergency basis as it will cause\n" + + "documents (perhaps many) to be permanently removed from the index. Always make\n" + + "a backup copy of your index before running this! Do not run this tool on an index\n" + + "that is actively being written to. You have been warned!\n" + + "\n" + + "Run without -fix, this tool will open the index, report version information\n" + + "and report any exceptions it hits and what action it would take if -fix were\n" + + "specified. With -fix, this tool will remove any segments that have issues and\n" + + "write a new segments_N file. This means all documents contained in the affected\n" + + "segments will be removed.\n" + + "\n" + + "This tool exits with exit code 1 if the index cannot be opened or has any\n" + + "corruption, else 0.\n"); + System.exit(1); + } + + if (!assertsOn()) + System.out.println("\nNOTE: testing will be more thorough if you run java with '-ea:org.apache.lucene...', so assertions are enabled"); + + if (onlySegments.size() == 0) + onlySegments = null; + else if (doFix) { + System.out.println("ERROR: cannot specify both -fix and -segment"); + System.exit(1); + } + + System.out.println("\nOpening index @ " + indexPath + "\n"); + Directory dir = null; + try { + dir = FSDirectory.getDirectory(indexPath); + } catch (Throwable t) { + System.out.println("ERROR: could not open directory \"" + indexPath + "\"; exiting"); + t.printStackTrace(System.out); + System.exit(1); + } + + CheckIndex checker = new CheckIndex(dir); + checker.setInfoStream(System.out); + + Status result = checker.checkIndex(onlySegments); + + if (!result.clean) { + if (!doFix) { + System.out.println("WARNING: would write new segments file, and " + result.totLoseDocCount + " documents would be lost, if -fix were specified\n"); + } else { + System.out.println("WARNING: " + result.totLoseDocCount + " documents will be lost\n"); + System.out.println("NOTE: will write new segments file in 5 seconds; this will remove " + result.totLoseDocCount + " docs from the index. THIS IS YOUR LAST CHANCE TO CTRL+C!"); + for(int s=0;s<5;s++) { + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + s--; + continue; + } + System.out.println(" " + (5-s) + "..."); + } + System.out.println("Writing..."); + checker.fixIndex(result); + System.out.println("OK"); + System.out.println("Wrote new segments file \"" + result.newSegments.getCurrentSegmentFileName() + "\""); + } + } + System.out.println(""); + + final int exitCode; + if (result != null && result.clean == true) + exitCode = 0; + else + exitCode = 1; + System.exit(exitCode); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/CompoundFileReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/CompoundFileReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/CompoundFileReader.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,268 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.BufferedIndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.Lock; + +import java.util.HashMap; +import java.io.IOException; + + +/** + * Class for accessing a compound stream. + * This class implements a directory, but is limited to only read operations. + * Directory methods that would normally modify data throw an exception. + * + * + * @version $Id: CompoundFileReader.java,v 1.1 2012/08/17 14:55:02 marcin Exp $ + */ +class CompoundFileReader extends Directory { + + private int readBufferSize; + + private static final class FileEntry { + long offset; + long length; + } + + + // Base info + private Directory directory; + private String fileName; + + private IndexInput stream; + private HashMap entries = new HashMap(); + + + public CompoundFileReader(Directory dir, String name) throws IOException { + this(dir, name, BufferedIndexInput.BUFFER_SIZE); + } + + public CompoundFileReader(Directory dir, String name, int readBufferSize) + throws IOException + { + directory = dir; + fileName = name; + this.readBufferSize = readBufferSize; + + boolean success = false; + + try { + stream = dir.openInput(name, readBufferSize); + + // read the directory and init files + int count = stream.readVInt(); + FileEntry entry = null; + for (int i=0; i length) + throw new IOException("read past EOF"); + base.seek(fileOffset + start); + base.readBytes(b, offset, len, false); + } + + /** Expert: implements seek. Sets current position in this file, where + * the next {@link #readInternal(byte[],int,int)} will occur. + * @see #readInternal(byte[],int,int) + */ + protected void seekInternal(long pos) {} + + /** Closes the stream to further operations. */ + public void close() throws IOException { + base.close(); + } + + public long length() { + return length; + } + + + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/CompoundFileWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/CompoundFileWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/CompoundFileWriter.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,256 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.IndexInput; +import java.util.LinkedList; +import java.util.HashSet; +import java.util.Iterator; +import java.io.IOException; + + +/** + * Combines multiple files into a single compound file. + * The file format:
+ *

    + *
  • VInt fileCount
  • + *
  • {Directory} + * fileCount entries with the following structure:
  • + *
      + *
    • long dataOffset
    • + *
    • String fileName
    • + *
    + *
  • {File Data} + * fileCount entries with the raw data of the corresponding file
  • + *
+ * + * The fileCount integer indicates how many files are contained in this compound + * file. The {directory} that follows has that many entries. Each directory entry + * contains a long pointer to the start of this file's data section, and a String + * with that file's name. + * + * + * @version $Id: CompoundFileWriter.java,v 1.1 2012/08/17 14:55:00 marcin Exp $ + */ +final class CompoundFileWriter { + + private static final class FileEntry { + /** source file */ + String file; + + /** temporary holder for the start of directory entry for this file */ + long directoryOffset; + + /** temporary holder for the start of this file's data section */ + long dataOffset; + } + + + private Directory directory; + private String fileName; + private HashSet ids; + private LinkedList entries; + private boolean merged = false; + private SegmentMerger.CheckAbort checkAbort; + + /** Create the compound stream in the specified file. The file name is the + * entire name (no extensions are added). + * @throws NullPointerException if dir or name is null + */ + public CompoundFileWriter(Directory dir, String name) { + this(dir, name, null); + } + + CompoundFileWriter(Directory dir, String name, SegmentMerger.CheckAbort checkAbort) { + if (dir == null) + throw new NullPointerException("directory cannot be null"); + if (name == null) + throw new NullPointerException("name cannot be null"); + this.checkAbort = checkAbort; + directory = dir; + fileName = name; + ids = new HashSet(); + entries = new LinkedList(); + } + + /** Returns the directory of the compound file. */ + public Directory getDirectory() { + return directory; + } + + /** Returns the name of the compound file. */ + public String getName() { + return fileName; + } + + /** Add a source stream. file is the string by which the + * sub-stream will be known in the compound stream. + * + * @throws IllegalStateException if this writer is closed + * @throws NullPointerException if file is null + * @throws IllegalArgumentException if a file with the same name + * has been added already + */ + public void addFile(String file) { + if (merged) + throw new IllegalStateException( + "Can't add extensions after merge has been called"); + + if (file == null) + throw new NullPointerException( + "file cannot be null"); + + if (! ids.add(file)) + throw new IllegalArgumentException( + "File " + file + " already added"); + + FileEntry entry = new FileEntry(); + entry.file = file; + entries.add(entry); + } + + /** Merge files with the extensions added up to now. + * All files with these extensions are combined sequentially into the + * compound stream. After successful merge, the source files + * are deleted. + * @throws IllegalStateException if close() had been called before or + * if no file has been added to this object + */ + public void close() throws IOException { + if (merged) + throw new IllegalStateException( + "Merge already performed"); + + if (entries.isEmpty()) + throw new IllegalStateException( + "No entries to merge have been defined"); + + merged = true; + + // open the compound stream + IndexOutput os = null; + try { + os = directory.createOutput(fileName); + + // Write the number of entries + os.writeVInt(entries.size()); + + // Write the directory with all offsets at 0. + // Remember the positions of directory entries so that we can + // adjust the offsets later + Iterator it = entries.iterator(); + long totalSize = 0; + while(it.hasNext()) { + FileEntry fe = (FileEntry) it.next(); + fe.directoryOffset = os.getFilePointer(); + os.writeLong(0); // for now + os.writeString(fe.file); + totalSize += directory.fileLength(fe.file); + } + + // Pre-allocate size of file as optimization -- + // this can potentially help IO performance as + // we write the file and also later during + // searching. It also uncovers a disk-full + // situation earlier and hopefully without + // actually filling disk to 100%: + final long finalLength = totalSize+os.getFilePointer(); + os.setLength(finalLength); + + // Open the files and copy their data into the stream. + // Remember the locations of each file's data section. + byte buffer[] = new byte[16384]; + it = entries.iterator(); + while(it.hasNext()) { + FileEntry fe = (FileEntry) it.next(); + fe.dataOffset = os.getFilePointer(); + copyFile(fe, os, buffer); + } + + // Write the data offsets into the directory of the compound stream + it = entries.iterator(); + while(it.hasNext()) { + FileEntry fe = (FileEntry) it.next(); + os.seek(fe.directoryOffset); + os.writeLong(fe.dataOffset); + } + + assert finalLength == os.length(); + + // Close the output stream. Set the os to null before trying to + // close so that if an exception occurs during the close, the + // finally clause below will not attempt to close the stream + // the second time. + IndexOutput tmp = os; + os = null; + tmp.close(); + + } finally { + if (os != null) try { os.close(); } catch (IOException e) { } + } + } + + /** Copy the contents of the file with specified extension into the + * provided output stream. Use the provided buffer for moving data + * to reduce memory allocation. + */ + private void copyFile(FileEntry source, IndexOutput os, byte buffer[]) + throws IOException + { + IndexInput is = null; + try { + long startPtr = os.getFilePointer(); + + is = directory.openInput(source.file); + long length = is.length(); + long remainder = length; + int chunk = buffer.length; + + while(remainder > 0) { + int len = (int) Math.min(chunk, remainder); + is.readBytes(buffer, 0, len, false); + os.writeBytes(buffer, len); + remainder -= len; + if (checkAbort != null) + // Roughly every 2 MB we will check if + // it's time to abort + checkAbort.work(80); + } + + // Verify that remainder is 0 + if (remainder != 0) + throw new IOException( + "Non-zero remainder length after copying: " + remainder + + " (id: " + source.file + ", length: " + length + + ", buffer size: " + chunk + ")"); + + // Verify that the output length diff is equal to original file + long endPtr = os.getFilePointer(); + long diff = endPtr - startPtr; + if (diff != length) + throw new IOException( + "Difference in the output file offsets " + diff + + " does not match the original file length " + length); + + } finally { + if (is != null) is.close(); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/ConcurrentMergeScheduler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/ConcurrentMergeScheduler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/ConcurrentMergeScheduler.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,368 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; + +/** A {@link MergeScheduler} that runs each merge using a + * separate thread, up until a maximum number of threads + * ({@link #setMaxThreadCount}) at which when a merge is + * needed, the thread(s) that are updating the index will + * pause until one or more merges completes. This is a + * simple way to use concurrency in the indexing process + * without having to create and manage application level + * threads. */ + +public class ConcurrentMergeScheduler extends MergeScheduler { + + private int mergeThreadPriority = -1; + + protected List mergeThreads = new ArrayList(); + + // Max number of threads allowed to be merging at once + private int maxThreadCount = 3; + + private List exceptions = new ArrayList(); + protected Directory dir; + + private boolean closed; + protected IndexWriter writer; + protected int mergeThreadCount; + + public ConcurrentMergeScheduler() { + if (allInstances != null) { + // Only for testing + addMyself(); + } + } + + /** Sets the max # simultaneous threads that may be + * running. If a merge is necessary yet we already have + * this many threads running, the incoming thread (that + * is calling add/updateDocument) will block until + * a merge thread has completed. */ + public void setMaxThreadCount(int count) { + if (count < 1) + throw new IllegalArgumentException("count should be at least 1"); + maxThreadCount = count; + } + + /** Get the max # simultaneous threads that may be + * running. @see #setMaxThreadCount. */ + public int getMaxThreadCount() { + return maxThreadCount; + } + + /** Return the priority that merge threads run at. By + * default the priority is 1 plus the priority of (ie, + * slightly higher priority than) the first thread that + * calls merge. */ + public synchronized int getMergeThreadPriority() { + initMergeThreadPriority(); + return mergeThreadPriority; + } + + /** Return the priority that merge threads run at. */ + public synchronized void setMergeThreadPriority(int pri) { + if (pri > Thread.MAX_PRIORITY || pri < Thread.MIN_PRIORITY) + throw new IllegalArgumentException("priority must be in range " + Thread.MIN_PRIORITY + " .. " + Thread.MAX_PRIORITY + " inclusive"); + mergeThreadPriority = pri; + + final int numThreads = mergeThreadCount(); + for(int i=0;i Thread.MAX_PRIORITY) + mergeThreadPriority = Thread.MAX_PRIORITY; + } + } + + public void close() { + closed = true; + } + + public synchronized void sync() { + while(mergeThreadCount() > 0) { + message("now wait for threads; currently " + mergeThreads.size() + " still running"); + final int count = mergeThreads.size(); + for(int i=0;i= maxThreadCount) { + message(" too many merge threads running; stalling..."); + try { + wait(); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + } + + message(" consider merge " + merge.segString(dir)); + + assert mergeThreadCount() < maxThreadCount; + + // OK to spawn a new merge thread to handle this + // merge: + final MergeThread merger = getMergeThread(writer, merge); + mergeThreads.add(merger); + message(" launch new thread [" + merger.getName() + "]"); + merger.start(); + } + } + } + + /** Does the actual merge, by calling {@link IndexWriter#merge} */ + protected void doMerge(MergePolicy.OneMerge merge) + throws IOException { + writer.merge(merge); + } + + /** Create and return a new MergeThread */ + protected synchronized MergeThread getMergeThread(IndexWriter writer, MergePolicy.OneMerge merge) throws IOException { + final MergeThread thread = new MergeThread(writer, merge); + thread.setThreadPriority(mergeThreadPriority); + thread.setDaemon(true); + thread.setName("Lucene Merge Thread #" + mergeThreadCount++); + return thread; + } + + protected class MergeThread extends Thread { + + IndexWriter writer; + MergePolicy.OneMerge startMerge; + MergePolicy.OneMerge runningMerge; + + public MergeThread(IndexWriter writer, MergePolicy.OneMerge startMerge) throws IOException { + this.writer = writer; + this.startMerge = startMerge; + } + + public synchronized void setRunningMerge(MergePolicy.OneMerge merge) { + runningMerge = merge; + } + + public synchronized MergePolicy.OneMerge getRunningMerge() { + return runningMerge; + } + + public void setThreadPriority(int pri) { + try { + setPriority(pri); + } catch (NullPointerException npe) { + // Strangely, Sun's JDK 1.5 on Linux sometimes + // throws NPE out of here... + } catch (SecurityException se) { + // Ignore this because we will still run fine with + // normal thread priority + } + } + + public void run() { + + // First time through the while loop we do the merge + // that we were started with: + MergePolicy.OneMerge merge = this.startMerge; + + try { + + message(" merge thread: start"); + + while(true) { + setRunningMerge(merge); + doMerge(merge); + + // Subsequent times through the loop we do any new + // merge that writer says is necessary: + merge = writer.getNextMerge(); + if (merge != null) { + writer.mergeInit(merge); + message(" merge thread: do another merge " + merge.segString(dir)); + } else + break; + } + + message(" merge thread: done"); + + } catch (Throwable exc) { + + // Ignore the exception if it was due to abort: + if (!(exc instanceof MergePolicy.MergeAbortedException)) { + synchronized(ConcurrentMergeScheduler.this) { + exceptions.add(exc); + } + + if (!suppressExceptions) { + // suppressExceptions is normally only set during + // testing. + anyExceptions = true; + handleMergeException(exc); + } + } + } finally { + synchronized(ConcurrentMergeScheduler.this) { + ConcurrentMergeScheduler.this.notifyAll(); + boolean removed = mergeThreads.remove(this); + assert removed; + } + } + } + + public String toString() { + MergePolicy.OneMerge merge = getRunningMerge(); + if (merge == null) + merge = startMerge; + return "merge thread: " + merge.segString(dir); + } + } + + /** Called when an exception is hit in a background merge + * thread */ + protected void handleMergeException(Throwable exc) { + throw new MergePolicy.MergeException(exc, dir); + } + + static boolean anyExceptions = false; + + /** Used for testing */ + public static boolean anyUnhandledExceptions() { + synchronized(allInstances) { + final int count = allInstances.size(); + // Make sure all outstanding threads are done so we see + // any exceptions they may produce: + for(int i=0;i>>= 1; + } else { + delta = skipStream.readVInt(); + } + freqPointer[level] += skipStream.readVInt(); + proxPointer[level] += skipStream.readVInt(); + + return delta; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DefaultSkipListWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DefaultSkipListWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DefaultSkipListWriter.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,126 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Arrays; + +import org.apache.lucene.store.IndexOutput; + + +/** + * Implements the skip list writer for the default posting list format + * that stores positions and payloads. + * + */ +class DefaultSkipListWriter extends MultiLevelSkipListWriter { + private int[] lastSkipDoc; + private int[] lastSkipPayloadLength; + private long[] lastSkipFreqPointer; + private long[] lastSkipProxPointer; + + private IndexOutput freqOutput; + private IndexOutput proxOutput; + + private int curDoc; + private boolean curStorePayloads; + private int curPayloadLength; + private long curFreqPointer; + private long curProxPointer; + + DefaultSkipListWriter(int skipInterval, int numberOfSkipLevels, int docCount, IndexOutput freqOutput, IndexOutput proxOutput) { + super(skipInterval, numberOfSkipLevels, docCount); + this.freqOutput = freqOutput; + this.proxOutput = proxOutput; + + lastSkipDoc = new int[numberOfSkipLevels]; + lastSkipPayloadLength = new int[numberOfSkipLevels]; + lastSkipFreqPointer = new long[numberOfSkipLevels]; + lastSkipProxPointer = new long[numberOfSkipLevels]; + } + + /** + * Sets the values for the current skip data. + */ + void setSkipData(int doc, boolean storePayloads, int payloadLength) { + this.curDoc = doc; + this.curStorePayloads = storePayloads; + this.curPayloadLength = payloadLength; + this.curFreqPointer = freqOutput.getFilePointer(); + if (proxOutput != null) + this.curProxPointer = proxOutput.getFilePointer(); + } + + protected void resetSkip() { + super.resetSkip(); + Arrays.fill(lastSkipDoc, 0); + Arrays.fill(lastSkipPayloadLength, -1); // we don't have to write the first length in the skip list + Arrays.fill(lastSkipFreqPointer, freqOutput.getFilePointer()); + if (proxOutput != null) + Arrays.fill(lastSkipProxPointer, proxOutput.getFilePointer()); + } + + protected void writeSkipData(int level, IndexOutput skipBuffer) throws IOException { + // To efficiently store payloads in the posting lists we do not store the length of + // every payload. Instead we omit the length for a payload if the previous payload had + // the same length. + // However, in order to support skipping the payload length at every skip point must be known. + // So we use the same length encoding that we use for the posting lists for the skip data as well: + // Case 1: current field does not store payloads + // SkipDatum --> DocSkip, FreqSkip, ProxSkip + // DocSkip,FreqSkip,ProxSkip --> VInt + // DocSkip records the document number before every SkipInterval th document in TermFreqs. + // Document numbers are represented as differences from the previous value in the sequence. + // Case 2: current field stores payloads + // SkipDatum --> DocSkip, PayloadLength?, FreqSkip,ProxSkip + // DocSkip,FreqSkip,ProxSkip --> VInt + // PayloadLength --> VInt + // In this case DocSkip/2 is the difference between + // the current and the previous value. If DocSkip + // is odd, then a PayloadLength encoded as VInt follows, + // if DocSkip is even, then it is assumed that the + // current payload length equals the length at the previous + // skip point + if (curStorePayloads) { + int delta = curDoc - lastSkipDoc[level]; + if (curPayloadLength == lastSkipPayloadLength[level]) { + // the current payload length equals the length at the previous skip point, + // so we don't store the length again + skipBuffer.writeVInt(delta * 2); + } else { + // the payload length is different from the previous one. We shift the DocSkip, + // set the lowest bit and store the current payload length as VInt. + skipBuffer.writeVInt(delta * 2 + 1); + skipBuffer.writeVInt(curPayloadLength); + lastSkipPayloadLength[level] = curPayloadLength; + } + } else { + // current field does not store payloads + skipBuffer.writeVInt(curDoc - lastSkipDoc[level]); + } + skipBuffer.writeVInt((int) (curFreqPointer - lastSkipFreqPointer[level])); + skipBuffer.writeVInt((int) (curProxPointer - lastSkipProxPointer[level])); + + lastSkipDoc[level] = curDoc; + //System.out.println("write doc at level " + level + ": " + curDoc); + + lastSkipFreqPointer[level] = curFreqPointer; + lastSkipProxPointer[level] = curProxPointer; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DirectoryIndexReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DirectoryIndexReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DirectoryIndexReader.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,466 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.FileNotFoundException; + +import java.util.HashSet; +import java.util.Collection; +import java.util.ArrayList; +import java.util.List; + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.Lock; +import org.apache.lucene.store.LockObtainFailedException; + +/** + * IndexReader implementation that has access to a Directory. + * Instances that have a SegmentInfos object (i. e. segmentInfos != null) + * "own" the directory, which means that they try to acquire a write lock + * whenever index modifications are performed. + */ +abstract class DirectoryIndexReader extends IndexReader { + protected Directory directory; + protected boolean closeDirectory; + private IndexDeletionPolicy deletionPolicy; + + private SegmentInfos segmentInfos; + private Lock writeLock; + private boolean stale; + private final HashSet synced = new HashSet(); + + /** Used by commit() to record pre-commit state in case + * rollback is necessary */ + private boolean rollbackHasChanges; + private SegmentInfos rollbackSegmentInfos; + + protected boolean readOnly; + + + void init(Directory directory, SegmentInfos segmentInfos, boolean closeDirectory, boolean readOnly) + throws IOException { + this.directory = directory; + this.segmentInfos = segmentInfos; + this.closeDirectory = closeDirectory; + this.readOnly = readOnly; + + if (!readOnly && segmentInfos != null) { + // We assume that this segments_N was previously + // properly sync'd: + for(int i=0;ifalse, in which case you must open a new + * IndexReader in order to see the changes. See the + * description of the autoCommit + * flag which controls when the {@link IndexWriter} + * actually commits changes to the index. + * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public boolean isCurrent() throws CorruptIndexException, IOException { + ensureOpen(); + return SegmentInfos.readCurrentVersion(directory) == segmentInfos.getVersion(); + } + + /** + * Checks is the index is optimized (if it has a single segment and no deletions) + * @return true if the index is optimized; false otherwise + */ + public boolean isOptimized() { + ensureOpen(); + return segmentInfos.size() == 1 && hasDeletions() == false; + } + + protected void doClose() throws IOException { + if(closeDirectory) + directory.close(); + } + + /** + * Commit changes resulting from delete, undeleteAll, or + * setNorm operations + * + * If an exception is hit, then either no changes or all + * changes will have been committed to the index + * (transactional semantics). + * @throws IOException if there is a low-level IO error + */ + protected void doCommit() throws IOException { + if (hasChanges) { + if (segmentInfos != null) { + + // Default deleter (for backwards compatibility) is + // KeepOnlyLastCommitDeleter: + IndexFileDeleter deleter = new IndexFileDeleter(directory, + deletionPolicy == null ? new KeepOnlyLastCommitDeletionPolicy() : deletionPolicy, + segmentInfos, null, null); + + // Checkpoint the state we are about to change, in + // case we have to roll back: + startCommit(); + + boolean success = false; + try { + commitChanges(); + + // Sync all files we just wrote + for(int i=0;iwrite.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + protected void acquireWriteLock() throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + if (segmentInfos != null) { + ensureOpen(); + if (stale) + throw new StaleReaderException("IndexReader out of date and no longer valid for delete, undelete, or setNorm operations"); + + if (writeLock == null) { + Lock writeLock = directory.makeLock(IndexWriter.WRITE_LOCK_NAME); + if (!writeLock.obtain(IndexWriter.WRITE_LOCK_TIMEOUT)) // obtain write lock + throw new LockObtainFailedException("Index locked for write: " + writeLock); + this.writeLock = writeLock; + + // we have to check whether index has changed since this reader was opened. + // if so, this reader is no longer valid for deletion + if (SegmentInfos.readCurrentVersion(directory) > segmentInfos.getVersion()) { + stale = true; + this.writeLock.release(); + this.writeLock = null; + throw new StaleReaderException("IndexReader out of date and no longer valid for delete, undelete, or setNorm operations"); + } + } + } + } + + /** + * Should internally checkpoint state that will change + * during commit so that we can rollback if necessary. + */ + void startCommit() { + if (segmentInfos != null) { + rollbackSegmentInfos = (SegmentInfos) segmentInfos.clone(); + } + rollbackHasChanges = hasChanges; + } + + /** + * Rolls back state to just before the commit (this is + * called by commit() if there is some exception while + * committing). + */ + void rollbackCommit() { + if (segmentInfos != null) { + for(int i=0;iWARNING: this API is new and experimental and + * may suddenly change.

+ */ + public IndexCommit getIndexCommit() throws IOException { + return new ReaderCommit(segmentInfos, directory); + } + + /** @see IndexReader#listCommits */ + public static Collection listCommits(Directory dir) throws IOException { + + final String[] files = dir.list(); + if (files == null) + throw new IOException("cannot read directory " + dir + ": list() returned null"); + + Collection commits = new ArrayList(); + + SegmentInfos latest = new SegmentInfos(); + latest.read(dir); + final long currentGen = latest.getGeneration(); + + commits.add(new ReaderCommit(latest, dir)); + + for(int i=0;i docFreeList.length) { + // Grow our free list up front to make sure we have + // enough space to recycle all outstanding PerDoc + // instances + assert allocCount == 1+docFreeList.length; + docFreeList = new PerDoc[ArrayUtil.getNextSize(allocCount)]; + } + return new PerDoc(); + } else + return docFreeList[--freeCount]; + } + + synchronized void freePerDoc(PerDoc perDoc) { + assert freeCount < docFreeList.length; + docFreeList[freeCount++] = perDoc; + } + + class PerDoc extends DocumentsWriter.DocWriter { + + DocumentsWriter.DocWriter one; + DocumentsWriter.DocWriter two; + + public long sizeInBytes() { + return one.sizeInBytes() + two.sizeInBytes(); + } + + public void finish() throws IOException { + try { + try { + one.finish(); + } finally { + two.finish(); + } + } finally { + freePerDoc(this); + } + } + + public void abort() { + try { + try { + one.abort(); + } finally { + two.abort(); + } + } finally { + freePerDoc(this); + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldConsumersPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocFieldConsumersPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldConsumersPerField.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,47 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.document.Fieldable; + +final class DocFieldConsumersPerField extends DocFieldConsumerPerField { + + final DocFieldConsumerPerField one; + final DocFieldConsumerPerField two; + final DocFieldConsumersPerThread perThread; + + public DocFieldConsumersPerField(DocFieldConsumersPerThread perThread, DocFieldConsumerPerField one, DocFieldConsumerPerField two) { + this.perThread = perThread; + this.one = one; + this.two = two; + } + + public void processFields(Fieldable[] fields, int count) throws IOException { + one.processFields(fields, count); + two.processFields(fields, count); + } + + public void abort() { + try { + one.abort(); + } finally { + two.abort(); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldConsumersPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocFieldConsumersPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldConsumersPerThread.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,71 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +final class DocFieldConsumersPerThread extends DocFieldConsumerPerThread { + + final DocFieldConsumerPerThread one; + final DocFieldConsumerPerThread two; + final DocFieldConsumers parent; + final DocumentsWriter.DocState docState; + + public DocFieldConsumersPerThread(DocFieldProcessorPerThread docFieldProcessorPerThread, + DocFieldConsumers parent, DocFieldConsumerPerThread one, DocFieldConsumerPerThread two) { + this.parent = parent; + this.one = one; + this.two = two; + docState = docFieldProcessorPerThread.docState; + } + + public void startDocument() throws IOException { + one.startDocument(); + two.startDocument(); + } + + public void abort() { + try { + one.abort(); + } finally { + two.abort(); + } + } + + public DocumentsWriter.DocWriter finishDocument() throws IOException { + final DocumentsWriter.DocWriter oneDoc = one.finishDocument(); + final DocumentsWriter.DocWriter twoDoc = two.finishDocument(); + if (oneDoc == null) + return twoDoc; + else if (twoDoc == null) + return oneDoc; + else { + DocFieldConsumers.PerDoc both = parent.getPerDoc(); + both.docID = docState.docID; + assert oneDoc.docID == docState.docID; + assert twoDoc.docID == docState.docID; + both.one = oneDoc; + both.two = twoDoc; + return both; + } + } + + public DocFieldConsumerPerField addField(FieldInfo fi) { + return new DocFieldConsumersPerField(this, one.addField(fi), two.addField(fi)); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessor.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,80 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.HashMap; +import java.util.Iterator; + +/** + * This is a DocConsumer that gathers all fields under the + * same name, and calls per-field consumers to process field + * by field. This class doesn't doesn't do any "real" work + * of its own: it just forwards the fields to a + * DocFieldConsumer. + */ + +final class DocFieldProcessor extends DocConsumer { + + final DocumentsWriter docWriter; + final FieldInfos fieldInfos = new FieldInfos(); + final DocFieldConsumer consumer; + + public DocFieldProcessor(DocumentsWriter docWriter, DocFieldConsumer consumer) { + this.docWriter = docWriter; + this.consumer = consumer; + consumer.setFieldInfos(fieldInfos); + } + + public void closeDocStore(DocumentsWriter.FlushState state) throws IOException { + consumer.closeDocStore(state); + } + + public void flush(Collection threads, DocumentsWriter.FlushState state) throws IOException { + + Map childThreadsAndFields = new HashMap(); + Iterator it = threads.iterator(); + while(it.hasNext()) { + DocFieldProcessorPerThread perThread = (DocFieldProcessorPerThread) it.next(); + childThreadsAndFields.put(perThread.consumer, perThread.fields()); + perThread.trimFields(state); + } + + consumer.flush(childThreadsAndFields, state); + + // Important to save after asking consumer to flush so + // consumer can alter the FieldInfo* if necessary. EG, + // FreqProxTermsWriter does this with + // FieldInfo.storePayload. + fieldInfos.write(state.directory, state.segmentName + ".fnm"); + } + + public void abort() { + consumer.abort(); + } + + public boolean freeRAM() { + return consumer.freeRAM(); + } + + public DocConsumerPerThread addThread(DocumentsWriterThreadState threadState) throws IOException { + return new DocFieldProcessorPerThread(threadState, this); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessorPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessorPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessorPerField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,45 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Fieldable; + +/** + * Holds all per thread, per field state. + */ + +final class DocFieldProcessorPerField { + + final DocFieldConsumerPerField consumer; + final FieldInfo fieldInfo; + + DocFieldProcessorPerField next; + int lastGen = -1; + + int fieldCount; + Fieldable[] fields = new Fieldable[1]; + + public DocFieldProcessorPerField(final DocFieldProcessorPerThread perThread, final FieldInfo fieldInfo) { + this.consumer = perThread.consumer.addField(fieldInfo); + this.fieldInfo = fieldInfo; + } + + public void abort() { + consumer.abort(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessorPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessorPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocFieldProcessorPerThread.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,302 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.io.IOException; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Fieldable; + +/** + * Gathers all Fieldables for a document under the same + * name, updates FieldInfos, and calls per-field consumers + * to process field by field. + * + * Currently, only a single thread visits the fields, + * sequentially, for processing. + */ + +final class DocFieldProcessorPerThread extends DocConsumerPerThread { + + float docBoost; + int fieldGen; + final DocFieldProcessor docFieldProcessor; + final FieldInfos fieldInfos; + final DocFieldConsumerPerThread consumer; + + // Holds all fields seen in current doc + DocFieldProcessorPerField[] fields = new DocFieldProcessorPerField[1]; + int fieldCount; + + // Hash table for all fields ever seen + DocFieldProcessorPerField[] fieldHash = new DocFieldProcessorPerField[2]; + int hashMask = 1; + int totalFieldCount; + + final DocumentsWriter.DocState docState; + + public DocFieldProcessorPerThread(DocumentsWriterThreadState threadState, DocFieldProcessor docFieldProcessor) throws IOException { + this.docState = threadState.docState; + this.docFieldProcessor = docFieldProcessor; + this.fieldInfos = docFieldProcessor.fieldInfos; + this.consumer = docFieldProcessor.consumer.addThread(this); + } + + public void abort() { + for(int i=0;i= fieldHash.length/2) + rehash(); + } else + fp.fieldInfo.update(field.isIndexed(), field.isTermVectorStored(), + field.isStorePositionWithTermVector(), field.isStoreOffsetWithTermVector(), + field.getOmitNorms(), false, field.getOmitTf()); + + if (thisFieldGen != fp.lastGen) { + + // First time we're seeing this field for this doc + fp.fieldCount = 0; + + if (fieldCount == fields.length) { + final int newSize = fields.length*2; + DocFieldProcessorPerField newArray[] = new DocFieldProcessorPerField[newSize]; + System.arraycopy(fields, 0, newArray, 0, fieldCount); + fields = newArray; + } + + fields[fieldCount++] = fp; + fp.lastGen = thisFieldGen; + } + + if (fp.fieldCount == fp.fields.length) { + Fieldable[] newArray = new Fieldable[fp.fields.length*2]; + System.arraycopy(fp.fields, 0, newArray, 0, fp.fieldCount); + fp.fields = newArray; + } + + fp.fields[fp.fieldCount++] = field; + } + + // If we are writing vectors then we must visit + // fields in sorted order so they are written in + // sorted order. TODO: we actually only need to + // sort the subset of fields that have vectors + // enabled; we could save [small amount of] CPU + // here. + quickSort(fields, 0, fieldCount-1); + + for(int i=0;i= hi) + return; + else if (hi == 1+lo) { + if (array[lo].fieldInfo.name.compareTo(array[hi].fieldInfo.name) > 0) { + final DocFieldProcessorPerField tmp = array[lo]; + array[lo] = array[hi]; + array[hi] = tmp; + } + return; + } + + int mid = (lo + hi) >>> 1; + + if (array[lo].fieldInfo.name.compareTo(array[mid].fieldInfo.name) > 0) { + DocFieldProcessorPerField tmp = array[lo]; + array[lo] = array[mid]; + array[mid] = tmp; + } + + if (array[mid].fieldInfo.name.compareTo(array[hi].fieldInfo.name) > 0) { + DocFieldProcessorPerField tmp = array[mid]; + array[mid] = array[hi]; + array[hi] = tmp; + + if (array[lo].fieldInfo.name.compareTo(array[mid].fieldInfo.name) > 0) { + DocFieldProcessorPerField tmp2 = array[lo]; + array[lo] = array[mid]; + array[mid] = tmp2; + } + } + + int left = lo + 1; + int right = hi - 1; + + if (left >= right) + return; + + DocFieldProcessorPerField partition = array[mid]; + + for (; ;) { + while (array[right].fieldInfo.name.compareTo(partition.fieldInfo.name) > 0) + --right; + + while (left < right && array[left].fieldInfo.name.compareTo(partition.fieldInfo.name) <= 0) + ++left; + + if (left < right) { + DocFieldProcessorPerField tmp = array[left]; + array[left] = array[right]; + array[right] = tmp; + --right; + } else { + break; + } + } + + quickSort(array, lo, left); + quickSort(array, left + 1, hi); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocInverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocInverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocInverter.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,109 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Map; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Collection; +import java.util.Iterator; +import java.io.IOException; + +/** This is a DocFieldConsumer that inverts each field, + * separately, from a Document, and accepts a + * InvertedTermsConsumer to process those terms. */ + +final class DocInverter extends DocFieldConsumer { + + final InvertedDocConsumer consumer; + final InvertedDocEndConsumer endConsumer; + + public DocInverter(InvertedDocConsumer consumer, InvertedDocEndConsumer endConsumer) { + this.consumer = consumer; + this.endConsumer = endConsumer; + } + + void setFieldInfos(FieldInfos fieldInfos) { + super.setFieldInfos(fieldInfos); + consumer.setFieldInfos(fieldInfos); + endConsumer.setFieldInfos(fieldInfos); + } + + void flush(Map threadsAndFields, DocumentsWriter.FlushState state) throws IOException { + + Map childThreadsAndFields = new HashMap(); + Map endChildThreadsAndFields = new HashMap(); + + Iterator it = threadsAndFields.entrySet().iterator(); + while(it.hasNext()) { + + Map.Entry entry = (Map.Entry) it.next(); + + DocInverterPerThread perThread = (DocInverterPerThread) entry.getKey(); + + Collection fields = (Collection) entry.getValue(); + + Iterator fieldsIt = fields.iterator(); + Collection childFields = new HashSet(); + Collection endChildFields = new HashSet(); + while(fieldsIt.hasNext()) { + DocInverterPerField perField = (DocInverterPerField) fieldsIt.next(); + childFields.add(perField.consumer); + endChildFields.add(perField.endConsumer); + } + + childThreadsAndFields.put(perThread.consumer, childFields); + endChildThreadsAndFields.put(perThread.endConsumer, endChildFields); + } + + consumer.flush(childThreadsAndFields, state); + endConsumer.flush(endChildThreadsAndFields, state); + } + + public void closeDocStore(DocumentsWriter.FlushState state) throws IOException { + consumer.closeDocStore(state); + endConsumer.closeDocStore(state); + } + + void abort() { + consumer.abort(); + endConsumer.abort(); + } + + public boolean freeRAM() { + return consumer.freeRAM(); + } + + public DocFieldConsumerPerThread addThread(DocFieldProcessorPerThread docFieldProcessorPerThread) { + return new DocInverterPerThread(docFieldProcessorPerThread, this); + } + + final static class FieldInvertState { + int position; + int length; + int offset; + float boost; + + void reset(float docBoost) { + position = 0; + length = 0; + offset = 0; + boost = docBoost; + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocInverterPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocInverterPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocInverterPerField.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,173 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.Reader; +import org.apache.lucene.document.Fieldable; +import org.apache.lucene.analysis.Token; +import org.apache.lucene.analysis.TokenStream; + +/** + * Holds state for inverting all occurrences of a single + * field in the document. This class doesn't do anything + * itself; instead, it forwards the tokens produced by + * analysis to its own consumer + * (InvertedDocConsumerPerField). It also interacts with an + * endConsumer (InvertedDocEndConsumerPerField). + */ + +final class DocInverterPerField extends DocFieldConsumerPerField { + + final private DocInverterPerThread perThread; + final private FieldInfo fieldInfo; + final InvertedDocConsumerPerField consumer; + final InvertedDocEndConsumerPerField endConsumer; + final DocumentsWriter.DocState docState; + final DocInverter.FieldInvertState fieldState; + + public DocInverterPerField(DocInverterPerThread perThread, FieldInfo fieldInfo) { + this.perThread = perThread; + this.fieldInfo = fieldInfo; + docState = perThread.docState; + fieldState = perThread.fieldState; + this.consumer = perThread.consumer.addField(this, fieldInfo); + this.endConsumer = perThread.endConsumer.addField(this, fieldInfo); + } + + void abort() { + consumer.abort(); + endConsumer.abort(); + } + + public void processFields(final Fieldable[] fields, + final int count) throws IOException { + + fieldState.reset(docState.doc.getBoost()); + + final int maxFieldLength = docState.maxFieldLength; + + final boolean doInvert = consumer.start(fields, count); + + for(int i=0;i 0) + fieldState.position += docState.analyzer.getPositionIncrementGap(fieldInfo.name); + + if (!field.isTokenized()) { // un-tokenized field + String stringValue = field.stringValue(); + final int valueLength = stringValue.length(); + Token token = perThread.localToken.reinit(stringValue, fieldState.offset, fieldState.offset + valueLength); + boolean success = false; + try { + consumer.add(token); + success = true; + } finally { + if (!success) + docState.docWriter.setAborting(); + } + fieldState.offset += valueLength; + fieldState.length++; + fieldState.position++; + } else { // tokenized field + final TokenStream stream; + final TokenStream streamValue = field.tokenStreamValue(); + + if (streamValue != null) + stream = streamValue; + else { + // the field does not have a TokenStream, + // so we have to obtain one from the analyzer + final Reader reader; // find or make Reader + final Reader readerValue = field.readerValue(); + + if (readerValue != null) + reader = readerValue; + else { + String stringValue = field.stringValue(); + if (stringValue == null) + throw new IllegalArgumentException("field must have either TokenStream, String or Reader value"); + perThread.stringReader.init(stringValue); + reader = perThread.stringReader; + } + + // Tokenize field and add to postingTable + stream = docState.analyzer.reusableTokenStream(fieldInfo.name, reader); + } + + // reset the TokenStream to the first token + stream.reset(); + + try { + int offsetEnd = fieldState.offset-1; + final Token localToken = perThread.localToken; + for(;;) { + + // If we hit an exception in stream.next below + // (which is fairly common, eg if analyzer + // chokes on a given document), then it's + // non-aborting and (above) this one document + // will be marked as deleted, but still + // consume a docID + Token token = stream.next(localToken); + + if (token == null) break; + fieldState.position += (token.getPositionIncrement() - 1); + boolean success = false; + try { + // If we hit an exception in here, we abort + // all buffered documents since the last + // flush, on the likelihood that the + // internal state of the consumer is now + // corrupt and should not be flushed to a + // new segment: + consumer.add(token); + success = true; + } finally { + if (!success) + docState.docWriter.setAborting(); + } + fieldState.position++; + offsetEnd = fieldState.offset + token.endOffset(); + if (++fieldState.length >= maxFieldLength) { + if (docState.infoStream != null) + docState.infoStream.println("maxFieldLength " +maxFieldLength+ " reached for field " + fieldInfo.name + ", ignoring following tokens"); + break; + } + } + fieldState.offset = offsetEnd+1; + } finally { + stream.close(); + } + } + + fieldState.boost *= field.getBoost(); + } + } + + consumer.finish(); + endConsumer.finish(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocInverterPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocInverterPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocInverterPerThread.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,70 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.analysis.Token; + +/** This is a DocFieldConsumer that inverts each field, + * separately, from a Document, and accepts a + * InvertedTermsConsumer to process those terms. */ + +final class DocInverterPerThread extends DocFieldConsumerPerThread { + final DocInverter docInverter; + final InvertedDocConsumerPerThread consumer; + final InvertedDocEndConsumerPerThread endConsumer; + final Token localToken = new Token(); + final DocumentsWriter.DocState docState; + + final DocInverter.FieldInvertState fieldState = new DocInverter.FieldInvertState(); + + // Used to read a string value for a field + final ReusableStringReader stringReader = new ReusableStringReader(); + + public DocInverterPerThread(DocFieldProcessorPerThread docFieldProcessorPerThread, DocInverter docInverter) { + this.docInverter = docInverter; + docState = docFieldProcessorPerThread.docState; + consumer = docInverter.consumer.addThread(this); + endConsumer = docInverter.endConsumer.addThread(this); + } + + public void startDocument() throws IOException { + consumer.startDocument(); + endConsumer.startDocument(); + } + + public DocumentsWriter.DocWriter finishDocument() throws IOException { + // TODO: allow endConsumer.finishDocument to also return + // a DocWriter + endConsumer.finishDocument(); + return consumer.finishDocument(); + } + + void abort() { + try { + consumer.abort(); + } finally { + endConsumer.abort(); + } + } + + public DocFieldConsumerPerField addField(FieldInfo fi) { + return new DocInverterPerField(this, fi); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocumentsWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocumentsWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocumentsWriter.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,1475 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.search.Similarity; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Scorer; +import org.apache.lucene.search.Weight; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.AlreadyClosedException; +import org.apache.lucene.util.ArrayUtil; + +import java.io.IOException; +import java.io.PrintStream; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.HashMap; +import java.util.HashSet; +import java.util.ArrayList; +import java.util.Map.Entry; +import java.text.NumberFormat; + +/** + * This class accepts multiple added documents and directly + * writes a single segment file. It does this more + * efficiently than creating a single segment per document + * (with DocumentWriter) and doing standard merges on those + * segments. + * + * Each added document is passed to the {@link DocConsumer}, + * which in turn processes the document and interacts with + * other consumers in the indexing chain. Certain + * consumers, like {@link StoredFieldsWriter} and {@link + * TermVectorsTermsWriter}, digest a document and + * immediately write bytes to the "doc store" files (ie, + * they do not consume RAM per document, except while they + * are processing the document). + * + * Other consumers, eg {@link FreqProxTermsWriter} and + * {@link NormsWriter}, buffer bytes in RAM and flush only + * when a new segment is produced. + + * Once we have used our allowed RAM buffer, or the number + * of added docs is large enough (in the case we are + * flushing by doc count instead of RAM usage), we create a + * real segment and flush it to the Directory. + * + * Threads: + * + * Multiple threads are allowed into addDocument at once. + * There is an initial synchronized call to getThreadState + * which allocates a ThreadState for this thread. The same + * thread will get the same ThreadState over time (thread + * affinity) so that if there are consistent patterns (for + * example each thread is indexing a different content + * source) then we make better use of RAM. Then + * processDocument is called on that ThreadState without + * synchronization (most of the "heavy lifting" is in this + * call). Finally the synchronized "finishDocument" is + * called to flush changes to the directory. + * + * When flush is called by IndexWriter, or, we flush + * internally when autoCommit=false, we forcefully idle all + * threads and flush only once they are all idle. This + * means you can call flush with a given thread even while + * other threads are actively adding/deleting documents. + * + * + * Exceptions: + * + * Because this class directly updates in-memory posting + * lists, and flushes stored fields and term vectors + * directly to files in the directory, there are certain + * limited times when an exception can corrupt this state. + * For example, a disk full while flushing stored fields + * leaves this file in a corrupt state. Or, an OOM + * exception while appending to the in-memory posting lists + * can corrupt that posting list. We call such exceptions + * "aborting exceptions". In these cases we must call + * abort() to discard all docs added since the last flush. + * + * All other exceptions ("non-aborting exceptions") can + * still partially update the index structures. These + * updates are consistent, but, they represent only a part + * of the document seen up until the exception was hit. + * When this happens, we immediately mark the document as + * deleted so that the document is always atomically ("all + * or none") added to the index. + */ + +final class DocumentsWriter { + + IndexWriter writer; + Directory directory; + + String segment; // Current segment we are working on + private String docStoreSegment; // Current doc-store segment we are writing + private int docStoreOffset; // Current starting doc-store offset of current segment + + private int nextDocID; // Next docID to be added + private int numDocsInRAM; // # docs buffered in RAM + int numDocsInStore; // # docs written to doc stores + + // Max # ThreadState instances; if there are more threads + // than this they share ThreadStates + private final static int MAX_THREAD_STATE = 5; + private DocumentsWriterThreadState[] threadStates = new DocumentsWriterThreadState[0]; + private final HashMap threadBindings = new HashMap(); + + private int pauseThreads; // Non-zero when we need all threads to + // pause (eg to flush) + boolean flushPending; // True when a thread has decided to flush + boolean bufferIsFull; // True when it's time to write segment + private boolean aborting; // True if an abort is pending + + private DocFieldProcessor docFieldProcessor; + + PrintStream infoStream; + int maxFieldLength = IndexWriter.DEFAULT_MAX_FIELD_LENGTH; + Similarity similarity; + + List newFiles; + + static class DocState { + DocumentsWriter docWriter; + Analyzer analyzer; + int maxFieldLength; + PrintStream infoStream; + Similarity similarity; + int docID; + Document doc; + String maxTermPrefix; + + // Only called by asserts + public boolean testPoint(String name) { + return docWriter.writer.testPoint(name); + } + } + + static class FlushState { + DocumentsWriter docWriter; + Directory directory; + String segmentName; + String docStoreSegmentName; + int numDocsInRAM; + int numDocsInStore; + Collection flushedFiles; + + public String segmentFileName(String ext) { + return segmentName + "." + ext; + } + } + + /** Consumer returns this on each doc. This holds any + * state that must be flushed synchronized "in docID + * order". We gather these and flush them in order. */ + abstract static class DocWriter { + DocWriter next; + int docID; + abstract void finish() throws IOException; + abstract void abort(); + abstract long sizeInBytes(); + + void setNext(DocWriter next) { + this.next = next; + } + }; + + final DocConsumer consumer; + + // Deletes done after the last flush; these are discarded + // on abort + private BufferedDeletes deletesInRAM = new BufferedDeletes(); + + // Deletes done before the last flush; these are still + // kept on abort + private BufferedDeletes deletesFlushed = new BufferedDeletes(); + + // The max number of delete terms that can be buffered before + // they must be flushed to disk. + private int maxBufferedDeleteTerms = IndexWriter.DEFAULT_MAX_BUFFERED_DELETE_TERMS; + + // How much RAM we can use before flushing. This is 0 if + // we are flushing by doc count instead. + private long ramBufferSize = (long) (IndexWriter.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024); + private long waitQueuePauseBytes = (long) (ramBufferSize*0.1); + private long waitQueueResumeBytes = (long) (ramBufferSize*0.05); + + // If we've allocated 5% over our RAM budget, we then + // free down to 95% + private long freeTrigger = (long) (IndexWriter.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024*1.05); + private long freeLevel = (long) (IndexWriter.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024*0.95); + + // Flush @ this number of docs. If ramBufferSize is + // non-zero we will flush by RAM usage instead. + private int maxBufferedDocs = IndexWriter.DEFAULT_MAX_BUFFERED_DOCS; + + private int flushedDocCount; // How many docs already flushed to index + + synchronized void updateFlushedDocCount(int n) { + flushedDocCount += n; + } + synchronized int getFlushedDocCount() { + return flushedDocCount; + } + synchronized void setFlushedDocCount(int n) { + flushedDocCount = n; + } + + private boolean closed; + + DocumentsWriter(Directory directory, IndexWriter writer) throws IOException { + this.directory = directory; + this.writer = writer; + this.similarity = writer.getSimilarity(); + flushedDocCount = writer.maxDoc(); + + /* + This is the current indexing chain: + + DocConsumer / DocConsumerPerThread + --> code: DocFieldProcessor / DocFieldProcessorPerThread + --> DocFieldConsumer / DocFieldConsumerPerThread / DocFieldConsumerPerField + --> code: DocFieldConsumers / DocFieldConsumersPerThread / DocFieldConsumersPerField + --> code: DocInverter / DocInverterPerThread / DocInverterPerField + --> InvertedDocConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField + --> code: TermsHash / TermsHashPerThread / TermsHashPerField + --> TermsHashConsumer / TermsHashConsumerPerThread / TermsHashConsumerPerField + --> code: FreqProxTermsWriter / FreqProxTermsWriterPerThread / FreqProxTermsWriterPerField + --> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerThread / TermVectorsTermsWriterPerField + --> InvertedDocEndConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField + --> code: NormsWriter / NormsWriterPerThread / NormsWriterPerField + --> code: StoredFieldsWriter / StoredFieldsWriterPerThread / StoredFieldsWriterPerField + */ + + // TODO FI: this should be something the user can pass in + // Build up indexing chain: + final TermsHashConsumer termVectorsWriter = new TermVectorsTermsWriter(this); + final TermsHashConsumer freqProxWriter = new FreqProxTermsWriter(); + + final InvertedDocConsumer termsHash = new TermsHash(this, true, freqProxWriter, + new TermsHash(this, false, termVectorsWriter, null)); + final NormsWriter normsWriter = new NormsWriter(); + final DocInverter docInverter = new DocInverter(termsHash, normsWriter); + final StoredFieldsWriter fieldsWriter = new StoredFieldsWriter(this); + final DocFieldConsumers docFieldConsumers = new DocFieldConsumers(docInverter, fieldsWriter); + consumer = docFieldProcessor = new DocFieldProcessor(this, docFieldConsumers); + } + + /** Returns true if any of the fields in the current + * buffered docs have omitTf==false */ + boolean hasProx() { + return docFieldProcessor.fieldInfos.hasProx(); + } + + /** If non-null, various details of indexing are printed + * here. */ + synchronized void setInfoStream(PrintStream infoStream) { + this.infoStream = infoStream; + for(int i=0;i= 0; + if (0 == pauseThreads) + notifyAll(); + } + + private synchronized boolean allThreadsIdle() { + for(int i=0;i 0; + + assert nextDocID == numDocsInRAM; + assert waitQueue.numWaiting == 0; + assert waitQueue.waitingBytes == 0; + + initFlushState(false); + + docStoreOffset = numDocsInStore; + + if (infoStream != null) + message("flush postings as segment " + flushState.segmentName + " numDocs=" + numDocsInRAM); + + boolean success = false; + + try { + + if (closeDocStore) { + assert flushState.docStoreSegmentName != null; + assert flushState.docStoreSegmentName.equals(flushState.segmentName); + closeDocStore(); + flushState.numDocsInStore = 0; + } + + Collection threads = new HashSet(); + for(int i=0;i= MAX_THREAD_STATE)) { + state = minThreadState; + state.numThreads++; + } else { + // Just create a new "private" thread state + DocumentsWriterThreadState[] newArray = new DocumentsWriterThreadState[1+threadStates.length]; + if (threadStates.length > 0) + System.arraycopy(threadStates, 0, newArray, 0, threadStates.length); + state = newArray[threadStates.length] = new DocumentsWriterThreadState(this); + threadStates = newArray; + } + threadBindings.put(Thread.currentThread(), state); + } + + // Next, wait until my thread state is idle (in case + // it's shared with other threads) and for threads to + // not be paused nor a flush pending: + waitReady(state); + + // Allocate segment name if this is the first doc since + // last flush: + initSegmentName(false); + + state.isIdle = false; + + boolean success = false; + try { + state.docState.docID = nextDocID; + + assert writer.testPoint("DocumentsWriter.ThreadState.init start"); + + if (delTerm != null) { + addDeleteTerm(delTerm, state.docState.docID); + state.doFlushAfter = timeToFlushDeletes(); + } + + assert writer.testPoint("DocumentsWriter.ThreadState.init after delTerm"); + + nextDocID++; + numDocsInRAM++; + + // We must at this point commit to flushing to ensure we + // always get N docs when we flush by doc count, even if + // > 1 thread is adding documents: + if (!flushPending && + maxBufferedDocs != IndexWriter.DISABLE_AUTO_FLUSH + && numDocsInRAM >= maxBufferedDocs) { + flushPending = true; + state.doFlushAfter = true; + } + + success = true; + } finally { + if (!success) { + // Forcefully idle this ThreadState: + state.isIdle = true; + notifyAll(); + if (state.doFlushAfter) { + state.doFlushAfter = false; + flushPending = false; + } + } + } + + return state; + } + + /** Returns true if the caller (IndexWriter) should now + * flush. */ + boolean addDocument(Document doc, Analyzer analyzer) + throws CorruptIndexException, IOException { + return updateDocument(doc, analyzer, null); + } + + boolean updateDocument(Term t, Document doc, Analyzer analyzer) + throws CorruptIndexException, IOException { + return updateDocument(doc, analyzer, t); + } + + boolean updateDocument(Document doc, Analyzer analyzer, Term delTerm) + throws CorruptIndexException, IOException { + + // This call is synchronized but fast + final DocumentsWriterThreadState state = getThreadState(doc, delTerm); + + final DocState docState = state.docState; + docState.doc = doc; + docState.analyzer = analyzer; + + boolean success = false; + try { + // This call is not synchronized and does all the + // work + final DocWriter perDoc = state.consumer.processDocument(); + + // This call is synchronized but fast + finishDocument(state, perDoc); + success = true; + } finally { + if (!success) { + synchronized(this) { + + if (aborting) { + state.isIdle = true; + notifyAll(); + abort(); + } else { + skipDocWriter.docID = docState.docID; + boolean success2 = false; + try { + waitQueue.add(skipDocWriter); + success2 = true; + } finally { + if (!success2) { + state.isIdle = true; + notifyAll(); + abort(); + return false; + } + } + + state.isIdle = true; + notifyAll(); + + // If this thread state had decided to flush, we + // must clear it so another thread can flush + if (state.doFlushAfter) { + state.doFlushAfter = false; + flushPending = false; + notifyAll(); + } + + // Immediately mark this document as deleted + // since likely it was partially added. This + // keeps indexing as "all or none" (atomic) when + // adding a document: + addDeleteDocID(state.docState.docID); + } + } + } + } + + return state.doFlushAfter || timeToFlushDeletes(); + } + + // for testing + synchronized int getNumBufferedDeleteTerms() { + return deletesInRAM.numTerms; + } + + // for testing + synchronized HashMap getBufferedDeleteTerms() { + return deletesInRAM.terms; + } + + /** Called whenever a merge has completed and the merged segments had deletions */ + synchronized void remapDeletes(SegmentInfos infos, int[][] docMaps, int[] delCounts, MergePolicy.OneMerge merge, int mergeDocCount) { + if (docMaps == null) + // The merged segments had no deletes so docIDs did not change and we have nothing to do + return; + MergeDocIDRemapper mapper = new MergeDocIDRemapper(infos, docMaps, delCounts, merge, mergeDocCount); + deletesInRAM.remap(mapper, infos, docMaps, delCounts, merge, mergeDocCount); + deletesFlushed.remap(mapper, infos, docMaps, delCounts, merge, mergeDocCount); + flushedDocCount -= mapper.docShift; + } + + synchronized private void waitReady(DocumentsWriterThreadState state) { + + while (!closed && ((state != null && !state.isIdle) || pauseThreads != 0 || flushPending || aborting)) { + try { + wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + if (closed) + throw new AlreadyClosedException("this IndexWriter is closed"); + } + + synchronized boolean bufferDeleteTerms(Term[] terms) throws IOException { + waitReady(null); + for (int i = 0; i < terms.length; i++) + addDeleteTerm(terms[i], numDocsInRAM); + return timeToFlushDeletes(); + } + + synchronized boolean bufferDeleteTerm(Term term) throws IOException { + waitReady(null); + addDeleteTerm(term, numDocsInRAM); + return timeToFlushDeletes(); + } + + synchronized boolean bufferDeleteQueries(Query[] queries) throws IOException { + waitReady(null); + for (int i = 0; i < queries.length; i++) + addDeleteQuery(queries[i], numDocsInRAM); + return timeToFlushDeletes(); + } + + synchronized boolean bufferDeleteQuery(Query query) throws IOException { + waitReady(null); + addDeleteQuery(query, numDocsInRAM); + return timeToFlushDeletes(); + } + + synchronized boolean deletesFull() { + return maxBufferedDeleteTerms != IndexWriter.DISABLE_AUTO_FLUSH + && ((deletesInRAM.numTerms + deletesInRAM.queries.size() + deletesInRAM.docIDs.size()) >= maxBufferedDeleteTerms); + } + + synchronized private boolean timeToFlushDeletes() { + return (bufferIsFull || deletesFull()) && setFlushPending(); + } + + void setMaxBufferedDeleteTerms(int maxBufferedDeleteTerms) { + this.maxBufferedDeleteTerms = maxBufferedDeleteTerms; + } + + int getMaxBufferedDeleteTerms() { + return maxBufferedDeleteTerms; + } + + synchronized boolean hasDeletes() { + return deletesFlushed.any(); + } + + synchronized boolean applyDeletes(SegmentInfos infos) throws IOException { + + if (!hasDeletes()) + return false; + + if (infoStream != null) + message("apply " + deletesFlushed.numTerms + " buffered deleted terms and " + + deletesFlushed.docIDs.size() + " deleted docIDs and " + + deletesFlushed.queries.size() + " deleted queries on " + + + infos.size() + " segments."); + + final int infosEnd = infos.size(); + + int docStart = 0; + boolean any = false; + for (int i = 0; i < infosEnd; i++) { + IndexReader reader = SegmentReader.get(infos.info(i), false); + boolean success = false; + try { + any |= applyDeletes(reader, docStart); + docStart += reader.maxDoc(); + success = true; + } finally { + if (reader != null) { + try { + if (success) + reader.doCommit(); + } finally { + reader.doClose(); + } + } + } + } + + deletesFlushed.clear(); + + return any; + } + + // Apply buffered delete terms, queries and docIDs to the + // provided reader + private final synchronized boolean applyDeletes(IndexReader reader, int docIDStart) + throws CorruptIndexException, IOException { + + final int docEnd = docIDStart + reader.maxDoc(); + boolean any = false; + + // Delete by term + Iterator iter = deletesFlushed.terms.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = (Entry) iter.next(); + Term term = (Term) entry.getKey(); + + TermDocs docs = reader.termDocs(term); + if (docs != null) { + int limit = ((BufferedDeletes.Num) entry.getValue()).getNum(); + try { + while (docs.next()) { + int docID = docs.doc(); + if (docIDStart+docID >= limit) + break; + reader.deleteDocument(docID); + any = true; + } + } finally { + docs.close(); + } + } + } + + // Delete by docID + iter = deletesFlushed.docIDs.iterator(); + while(iter.hasNext()) { + int docID = ((Integer) iter.next()).intValue(); + if (docID >= docIDStart && docID < docEnd) { + reader.deleteDocument(docID-docIDStart); + any = true; + } + } + + // Delete by query + IndexSearcher searcher = new IndexSearcher(reader); + iter = deletesFlushed.queries.entrySet().iterator(); + while(iter.hasNext()) { + Entry entry = (Entry) iter.next(); + Query query = (Query) entry.getKey(); + int limit = ((Integer) entry.getValue()).intValue(); + Weight weight = query.weight(searcher); + Scorer scorer = weight.scorer(reader); + while(scorer.next()) { + final int docID = scorer.doc(); + if (docIDStart + docID >= limit) + break; + reader.deleteDocument(docID); + any = true; + } + } + searcher.close(); + return any; + } + + // Buffer a term in bufferedDeleteTerms, which records the + // current number of documents buffered in ram so that the + // delete term will be applied to those documents as well + // as the disk segments. + synchronized private void addDeleteTerm(Term term, int docCount) { + BufferedDeletes.Num num = (BufferedDeletes.Num) deletesInRAM.terms.get(term); + final int docIDUpto = flushedDocCount + docCount; + if (num == null) + deletesInRAM.terms.put(term, new BufferedDeletes.Num(docIDUpto)); + else + num.setNum(docIDUpto); + deletesInRAM.numTerms++; + } + + // Buffer a specific docID for deletion. Currently only + // used when we hit a exception when adding a document + synchronized private void addDeleteDocID(int docID) { + deletesInRAM.docIDs.add(new Integer(flushedDocCount+docID)); + } + + synchronized private void addDeleteQuery(Query query, int docID) { + deletesInRAM.queries.put(query, new Integer(flushedDocCount + docID)); + } + + synchronized boolean doBalanceRAM() { + return ramBufferSize != IndexWriter.DISABLE_AUTO_FLUSH && !bufferIsFull && (numBytesUsed >= ramBufferSize || numBytesAlloc >= freeTrigger); + } + + /** Does the synchronized work to finish/flush the + * inverted document. */ + private void finishDocument(DocumentsWriterThreadState perThread, DocWriter docWriter) throws IOException { + + if (doBalanceRAM()) + // Must call this w/o holding synchronized(this) else + // we'll hit deadlock: + balanceRAM(); + + synchronized(this) { + + assert docWriter == null || docWriter.docID == perThread.docState.docID; + + + if (aborting) { + + // We are currently aborting, and another thread is + // waiting for me to become idle. We just forcefully + // idle this threadState; it will be fully reset by + // abort() + if (docWriter != null) + try { + docWriter.abort(); + } catch (Throwable t) { + } + + perThread.isIdle = true; + notifyAll(); + return; + } + + final boolean doPause; + + if (docWriter != null) + doPause = waitQueue.add(docWriter); + else { + skipDocWriter.docID = perThread.docState.docID; + doPause = waitQueue.add(skipDocWriter); + } + + if (doPause) + waitForWaitQueue(); + + if (bufferIsFull && !flushPending) { + flushPending = true; + perThread.doFlushAfter = true; + } + + perThread.isIdle = true; + notifyAll(); + } + } + + synchronized void waitForWaitQueue() { + do { + try { + wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } while (!waitQueue.doResume()); + } + + private static class SkipDocWriter extends DocWriter { + void finish() { + } + void abort() { + } + long sizeInBytes() { + return 0; + } + } + final SkipDocWriter skipDocWriter = new SkipDocWriter(); + + long getRAMUsed() { + return numBytesUsed; + } + + long numBytesAlloc; + long numBytesUsed; + + NumberFormat nf = NumberFormat.getInstance(); + + // TODO FI: this is not flexible -- we can't hardwire + // extensions in here: + private long segmentSize(String segmentName) throws IOException { + // Used only when infoStream != null + assert infoStream != null; + + long size = directory.fileLength(segmentName + ".tii") + + directory.fileLength(segmentName + ".tis") + + directory.fileLength(segmentName + ".frq") + + directory.fileLength(segmentName + ".prx"); + + final String normFileName = segmentName + ".nrm"; + if (directory.fileExists(normFileName)) + size += directory.fileLength(normFileName); + + return size; + } + + // Coarse estimates used to measure RAM usage of buffered deletes + final static int OBJECT_HEADER_BYTES = 8; + final static int POINTER_NUM_BYTE = 4; + final static int INT_NUM_BYTE = 4; + final static int CHAR_NUM_BYTE = 2; + + /* Initial chunks size of the shared byte[] blocks used to + store postings data */ + final static int BYTE_BLOCK_SHIFT = 15; + final static int BYTE_BLOCK_SIZE = (int) (1 << BYTE_BLOCK_SHIFT); + final static int BYTE_BLOCK_MASK = BYTE_BLOCK_SIZE - 1; + final static int BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK; + + private class ByteBlockAllocator extends ByteBlockPool.Allocator { + + ArrayList freeByteBlocks = new ArrayList(); + + /* Allocate another byte[] from the shared pool */ + byte[] getByteBlock(boolean trackAllocations) { + synchronized(DocumentsWriter.this) { + final int size = freeByteBlocks.size(); + final byte[] b; + if (0 == size) { + // Always record a block allocated, even if + // trackAllocations is false. This is necessary + // because this block will be shared between + // things that don't track allocations (term + // vectors) and things that do (freq/prox + // postings). + numBytesAlloc += BYTE_BLOCK_SIZE; + b = new byte[BYTE_BLOCK_SIZE]; + } else + b = (byte[]) freeByteBlocks.remove(size-1); + if (trackAllocations) + numBytesUsed += BYTE_BLOCK_SIZE; + assert numBytesUsed <= numBytesAlloc; + return b; + } + } + + /* Return byte[]'s to the pool */ + void recycleByteBlocks(byte[][] blocks, int start, int end) { + synchronized(DocumentsWriter.this) { + for(int i=start;i freeTrigger) { + + if (infoStream != null) + message(" RAM: now balance allocations: usedMB=" + toMB(numBytesUsed) + + " vs trigger=" + toMB(flushTrigger) + + " allocMB=" + toMB(numBytesAlloc) + + " vs trigger=" + toMB(freeTrigger) + + " byteBlockFree=" + toMB(byteBlockAllocator.freeByteBlocks.size()*BYTE_BLOCK_SIZE) + + " charBlockFree=" + toMB(freeCharBlocks.size()*CHAR_BLOCK_SIZE*CHAR_NUM_BYTE)); + + final long startBytesAlloc = numBytesAlloc; + + int iter = 0; + + // We free equally from each pool in 32 KB + // chunks until we are below our threshold + // (freeLevel) + + boolean any = true; + + while(numBytesAlloc > freeLevel) { + + synchronized(this) { + if (0 == byteBlockAllocator.freeByteBlocks.size() && 0 == freeCharBlocks.size() && 0 == freeIntBlocks.size() && !any) { + // Nothing else to free -- must flush now. + bufferIsFull = numBytesUsed > flushTrigger; + if (infoStream != null) { + if (numBytesUsed > flushTrigger) + message(" nothing to free; now set bufferIsFull"); + else + message(" nothing to free"); + } + assert numBytesUsed <= numBytesAlloc; + break; + } + + if ((0 == iter % 4) && byteBlockAllocator.freeByteBlocks.size() > 0) { + byteBlockAllocator.freeByteBlocks.remove(byteBlockAllocator.freeByteBlocks.size()-1); + numBytesAlloc -= BYTE_BLOCK_SIZE; + } + + if ((1 == iter % 4) && freeCharBlocks.size() > 0) { + freeCharBlocks.remove(freeCharBlocks.size()-1); + numBytesAlloc -= CHAR_BLOCK_SIZE * CHAR_NUM_BYTE; + } + + if ((2 == iter % 4) && freeIntBlocks.size() > 0) { + freeIntBlocks.remove(freeIntBlocks.size()-1); + numBytesAlloc -= INT_BLOCK_SIZE * INT_NUM_BYTE; + } + } + + if ((3 == iter % 4) && any) + // Ask consumer to free any recycled state + any = consumer.freeRAM(); + + iter++; + } + + if (infoStream != null) + message(" after free: freedMB=" + nf.format((startBytesAlloc-numBytesAlloc)/1024./1024.) + " usedMB=" + nf.format(numBytesUsed/1024./1024.) + " allocMB=" + nf.format(numBytesAlloc/1024./1024.)); + + } else { + // If we have not crossed the 100% mark, but have + // crossed the 95% mark of RAM we are actually + // using, go ahead and flush. This prevents + // over-allocating and then freeing, with every + // flush. + synchronized(this) { + + if (numBytesUsed > flushTrigger) { + if (infoStream != null) + message(" RAM: now flush @ usedMB=" + nf.format(numBytesUsed/1024./1024.) + + " allocMB=" + nf.format(numBytesAlloc/1024./1024.) + + " triggerMB=" + nf.format(flushTrigger/1024./1024.)); + + bufferIsFull = true; + } + } + } + } + + final WaitQueue waitQueue = new WaitQueue(); + + private class WaitQueue { + DocWriter[] waiting; + int nextWriteDocID; + int nextWriteLoc; + int numWaiting; + long waitingBytes; + + public WaitQueue() { + waiting = new DocWriter[10]; + } + + synchronized void reset() { + // NOTE: nextWriteLoc doesn't need to be reset + assert numWaiting == 0; + assert waitingBytes == 0; + nextWriteDocID = 0; + } + + synchronized boolean doResume() { + return waitingBytes <= waitQueueResumeBytes; + } + + synchronized boolean doPause() { + return waitingBytes > waitQueuePauseBytes; + } + + synchronized void abort() { + int count = 0; + for(int i=0;i= nextWriteDocID; + + if (doc.docID == nextWriteDocID) { + writeDocument(doc); + while(true) { + doc = waiting[nextWriteLoc]; + if (doc != null) { + numWaiting--; + waiting[nextWriteLoc] = null; + waitingBytes -= doc.sizeInBytes(); + writeDocument(doc); + } else + break; + } + } else { + + // I finished before documents that were added + // before me. This can easily happen when I am a + // small doc and the docs before me were large, or, + // just due to luck in the thread scheduling. Just + // add myself to the queue and when that large doc + // finishes, it will flush me: + int gap = doc.docID - nextWriteDocID; + if (gap >= waiting.length) { + // Grow queue + DocWriter[] newArray = new DocWriter[ArrayUtil.getNextSize(gap)]; + assert nextWriteLoc >= 0; + System.arraycopy(waiting, nextWriteLoc, newArray, 0, waiting.length-nextWriteLoc); + System.arraycopy(waiting, 0, newArray, waiting.length-nextWriteLoc, nextWriteLoc); + nextWriteLoc = 0; + waiting = newArray; + gap = doc.docID - nextWriteDocID; + } + + int loc = nextWriteLoc + gap; + if (loc >= waiting.length) + loc -= waiting.length; + + // We should only wrap one time + assert loc < waiting.length; + + // Nobody should be in my spot! + assert waiting[loc] == null; + waiting[loc] = doc; + numWaiting++; + waitingBytes += doc.sizeInBytes(); + } + + return doPause(); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/DocumentsWriterThreadState.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/DocumentsWriterThreadState.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/DocumentsWriterThreadState.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,50 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** Used by DocumentsWriter to maintain per-thread state. + * We keep a separate Posting hash and other state for each + * thread and then merge postings hashes from all threads + * when writing the segment. */ +final class DocumentsWriterThreadState { + + boolean isIdle = true; // false if this is currently in use by a thread + int numThreads = 1; // Number of threads that share this instance + boolean doFlushAfter; // true if we should flush after processing current doc + final DocConsumerPerThread consumer; + final DocumentsWriter.DocState docState; + + final DocumentsWriter docWriter; + + public DocumentsWriterThreadState(DocumentsWriter docWriter) throws IOException { + this.docWriter = docWriter; + docState = new DocumentsWriter.DocState(); + docState.maxFieldLength = docWriter.maxFieldLength; + docState.infoStream = docWriter.infoStream; + docState.similarity = docWriter.similarity; + docState.docWriter = docWriter; + consumer = docWriter.consumer.addThread(this); + } + + void doAfterFlush() { + numThreads = 0; + doFlushAfter = false; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FieldInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FieldInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FieldInfo.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,102 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +final class FieldInfo { + String name; + boolean isIndexed; + int number; + + // true if term vector for this field should be stored + boolean storeTermVector; + boolean storeOffsetWithTermVector; + boolean storePositionWithTermVector; + + boolean omitNorms; // omit norms associated with indexed fields + boolean omitTf; // omit tf + + boolean storePayloads; // whether this field stores payloads together with term positions + + FieldInfo(String na, boolean tk, int nu, boolean storeTermVector, + boolean storePositionWithTermVector, boolean storeOffsetWithTermVector, + boolean omitNorms, boolean storePayloads, boolean omitTf) { + name = na; + isIndexed = tk; + number = nu; + this.storeTermVector = storeTermVector; + this.storeOffsetWithTermVector = storeOffsetWithTermVector; + this.storePositionWithTermVector = storePositionWithTermVector; + this.omitNorms = omitNorms; + this.storePayloads = storePayloads; + this.omitTf = omitTf; + } + + public Object clone() { + return new FieldInfo(name, isIndexed, number, storeTermVector, storePositionWithTermVector, + storeOffsetWithTermVector, omitNorms, storePayloads, omitTf); + } + + void update(boolean isIndexed, boolean storeTermVector, boolean storePositionWithTermVector, + boolean storeOffsetWithTermVector, boolean omitNorms, boolean storePayloads, boolean omitTf) { + if (this.isIndexed != isIndexed) { + this.isIndexed = true; // once indexed, always index + } + if (this.storeTermVector != storeTermVector) { + this.storeTermVector = true; // once vector, always vector + } + if (this.storePositionWithTermVector != storePositionWithTermVector) { + this.storePositionWithTermVector = true; // once vector, always vector + } + if (this.storeOffsetWithTermVector != storeOffsetWithTermVector) { + this.storeOffsetWithTermVector = true; // once vector, always vector + } + if (this.omitNorms != omitNorms) { + this.omitNorms = false; // once norms are stored, always store + } + if (this.omitTf != omitTf) { + this.omitTf = true; // if one require omitTf at least once, it remains off for life + } + if (this.storePayloads != storePayloads) { + this.storePayloads = true; + } + } + + void update(FieldInfo other) { + if (isIndexed != other.isIndexed) { + isIndexed = true; // once indexed, always index + } + if (storeTermVector != other.storeTermVector) { + storeTermVector = true; // once vector, always vector + } + if (storePositionWithTermVector != other.storePositionWithTermVector) { + storePositionWithTermVector = true; // once vector, always vector + } + if (storeOffsetWithTermVector != other.storeOffsetWithTermVector) { + storeOffsetWithTermVector = true; // once vector, always vector + } + if (omitNorms != other.omitNorms) { + omitNorms = false; // once norms are stored, always store + } + if (this.omitTf != omitTf) { + this.omitTf = true; // if one require omitTf at least once, it remains off for life + } + if (storePayloads != other.storePayloads) { + storePayloads = true; + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FieldInfos.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FieldInfos.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FieldInfos.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,327 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Fieldable; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; + +import java.io.IOException; +import java.util.*; + +/** Access to the Fieldable Info file that describes document fields and whether or + * not they are indexed. Each segment has a separate Fieldable Info file. Objects + * of this class are thread-safe for multiple readers, but only one thread can + * be adding documents at a time, with no other reader or writer threads + * accessing this object. + */ +final class FieldInfos { + + static final byte IS_INDEXED = 0x1; + static final byte STORE_TERMVECTOR = 0x2; + static final byte STORE_POSITIONS_WITH_TERMVECTOR = 0x4; + static final byte STORE_OFFSET_WITH_TERMVECTOR = 0x8; + static final byte OMIT_NORMS = 0x10; + static final byte STORE_PAYLOADS = 0x20; + static final byte OMIT_TF = 0x40; + + private ArrayList byNumber = new ArrayList(); + private HashMap byName = new HashMap(); + + FieldInfos() { } + + /** + * Construct a FieldInfos object using the directory and the name of the file + * IndexInput + * @param d The directory to open the IndexInput from + * @param name The name of the file to open the IndexInput from in the Directory + * @throws IOException + */ + FieldInfos(Directory d, String name) throws IOException { + IndexInput input = d.openInput(name); + try { + read(input); + } finally { + input.close(); + } + } + + /** + * Returns a deep clone of this FieldInfos instance. + */ + synchronized public Object clone() { + FieldInfos fis = new FieldInfos(); + final int numField = byNumber.size(); + for(int i=0;i= 0) ? (FieldInfo) byNumber.get(fieldNumber) : null; + } + + public int size() { + return byNumber.size(); + } + + public boolean hasVectors() { + boolean hasVectors = false; + for (int i = 0; i < size(); i++) { + if (fieldInfo(i).storeTermVector) { + hasVectors = true; + break; + } + } + return hasVectors; + } + + public void write(Directory d, String name) throws IOException { + IndexOutput output = d.createOutput(name); + try { + write(output); + } finally { + output.close(); + } + } + + public void write(IndexOutput output) throws IOException { + output.writeVInt(size()); + for (int i = 0; i < size(); i++) { + FieldInfo fi = fieldInfo(i); + byte bits = 0x0; + if (fi.isIndexed) bits |= IS_INDEXED; + if (fi.storeTermVector) bits |= STORE_TERMVECTOR; + if (fi.storePositionWithTermVector) bits |= STORE_POSITIONS_WITH_TERMVECTOR; + if (fi.storeOffsetWithTermVector) bits |= STORE_OFFSET_WITH_TERMVECTOR; + if (fi.omitNorms) bits |= OMIT_NORMS; + if (fi.storePayloads) bits |= STORE_PAYLOADS; + if (fi.omitTf) bits |= OMIT_TF; + + output.writeString(fi.name); + output.writeByte(bits); + } + } + + private void read(IndexInput input) throws IOException { + int size = input.readVInt();//read in the size + for (int i = 0; i < size; i++) { + String name = input.readString().intern(); + byte bits = input.readByte(); + boolean isIndexed = (bits & IS_INDEXED) != 0; + boolean storeTermVector = (bits & STORE_TERMVECTOR) != 0; + boolean storePositionsWithTermVector = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; + boolean storeOffsetWithTermVector = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; + boolean omitNorms = (bits & OMIT_NORMS) != 0; + boolean storePayloads = (bits & STORE_PAYLOADS) != 0; + boolean omitTf = (bits & OMIT_TF) != 0; + + addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTf); + } + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FieldReaderException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FieldReaderException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FieldReaderException.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,79 @@ +package org.apache.lucene.index; +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + * + **/ +public class FieldReaderException extends RuntimeException{ + /** + * Constructs a new runtime exception with null as its + * detail message. The cause is not initialized, and may subsequently be + * initialized by a call to {@link #initCause}. + */ + public FieldReaderException() { + } + + /** + * Constructs a new runtime exception with the specified cause and a + * detail message of (cause==null ? null : cause.toString()) + * (which typically contains the class and detail message of + * cause). + *

+ * This constructor is useful for runtime 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.4 + */ + public FieldReaderException(Throwable cause) { + super(cause); + } + + /** + * Constructs a new runtime exception with the specified detail message. + * The cause is not initialized, and may subsequently be initialized by a + * call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public FieldReaderException(String message) { + super(message); + } + + /** + * Constructs a new runtime exception with the specified detail message and + * cause.

Note that the detail message associated with + * cause is not automatically incorporated in + * this runtime 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.4 + */ + public FieldReaderException(String message, Throwable cause) { + super(message, cause); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FieldSortedTermVectorMapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FieldSortedTermVectorMapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FieldSortedTermVectorMapper.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,70 @@ +package org.apache.lucene.index; + +import java.util.*; + +/** + * Copyright 2007 The Apache Software Foundation + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * For each Field, store a sorted collection of {@link TermVectorEntry}s + *

+ * This is not thread-safe. + */ +public class FieldSortedTermVectorMapper extends TermVectorMapper{ + private Map fieldToTerms = new HashMap(); + private SortedSet currentSet; + private String currentField; + private Comparator comparator; + + /** + * + * @param comparator A Comparator for sorting {@link TermVectorEntry}s + */ + public FieldSortedTermVectorMapper(Comparator comparator) { + this(false, false, comparator); + } + + + public FieldSortedTermVectorMapper(boolean ignoringPositions, boolean ignoringOffsets, Comparator comparator) { + super(ignoringPositions, ignoringOffsets); + this.comparator = comparator; + } + + public void map(String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions) { + TermVectorEntry entry = new TermVectorEntry(currentField, term, frequency, offsets, positions); + currentSet.add(entry); + } + + public void setExpectations(String field, int numTerms, boolean storeOffsets, boolean storePositions) { + currentSet = new TreeSet(comparator); + currentField = field; + fieldToTerms.put(field, currentSet); + } + + /** + * Get the mapping between fields and terms, sorted by the comparator + * + * @return A map between field names and {@link java.util.SortedSet}s per field. SortedSet entries are {@link TermVectorEntry} + */ + public Map getFieldToTerms() { + return fieldToTerms; + } + + + public Comparator getComparator() { + return comparator; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FieldsReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FieldsReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FieldsReader.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,633 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.document.*; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.AlreadyClosedException; +import org.apache.lucene.store.BufferedIndexInput; +import org.apache.lucene.util.CloseableThreadLocal; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.Reader; +import java.util.zip.DataFormatException; +import java.util.zip.Inflater; + +/** + * Class responsible for access to stored document fields. + *

+ * It uses <segment>.fdt and <segment>.fdx; files. + * + * @version $Id: FieldsReader.java,v 1.1 2012/08/17 14:55:00 marcin Exp $ + */ +final class FieldsReader { + private final FieldInfos fieldInfos; + + // The main fieldStream, used only for cloning. + private final IndexInput cloneableFieldsStream; + + // This is a clone of cloneableFieldsStream used for reading documents. + // It should not be cloned outside of a synchronized context. + private final IndexInput fieldsStream; + + private final IndexInput indexStream; + private int numTotalDocs; + private int size; + private boolean closed; + private final int format; + private final int formatSize; + + // The docID offset where our docs begin in the index + // file. This will be 0 if we have our own private file. + private int docStoreOffset; + + private CloseableThreadLocal fieldsStreamTL = new CloseableThreadLocal(); + + FieldsReader(Directory d, String segment, FieldInfos fn) throws IOException { + this(d, segment, fn, BufferedIndexInput.BUFFER_SIZE, -1, 0); + } + + FieldsReader(Directory d, String segment, FieldInfos fn, int readBufferSize) throws IOException { + this(d, segment, fn, readBufferSize, -1, 0); + } + + FieldsReader(Directory d, String segment, FieldInfos fn, int readBufferSize, int docStoreOffset, int size) throws IOException { + boolean success = false; + + try { + fieldInfos = fn; + + cloneableFieldsStream = d.openInput(segment + "." + IndexFileNames.FIELDS_EXTENSION, readBufferSize); + indexStream = d.openInput(segment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION, readBufferSize); + + // First version of fdx did not include a format + // header, but, the first int will always be 0 in that + // case + int firstInt = indexStream.readInt(); + if (firstInt == 0) + format = 0; + else + format = firstInt; + + if (format > FieldsWriter.FORMAT_CURRENT) + throw new CorruptIndexException("Incompatible format version: " + format + " expected " + + FieldsWriter.FORMAT_CURRENT + " or lower"); + + if (format > FieldsWriter.FORMAT) + formatSize = 4; + else + formatSize = 0; + + if (format < FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) + cloneableFieldsStream.setModifiedUTF8StringsMode(); + + fieldsStream = (IndexInput) cloneableFieldsStream.clone(); + + final long indexSize = indexStream.length()-formatSize; + + if (docStoreOffset != -1) { + // We read only a slice out of this shared fields file + this.docStoreOffset = docStoreOffset; + this.size = size; + + // Verify the file is long enough to hold all of our + // docs + assert ((int) (indexSize / 8)) >= size + this.docStoreOffset: "indexSize=" + indexSize + " size=" + size + " docStoreOffset=" + docStoreOffset; + } else { + this.docStoreOffset = 0; + this.size = (int) (indexSize >> 3); + } + + numTotalDocs = (int) (indexSize >> 3); + success = true; + } finally { + // With lock-less commits, it's entirely possible (and + // fine) to hit a FileNotFound exception above. In + // this case, we want to explicitly close any subset + // of things that were opened so that we don't have to + // wait for a GC to do so. + if (!success) { + close(); + } + } + } + + /** + * @throws AlreadyClosedException if this FieldsReader is closed + */ + protected final void ensureOpen() throws AlreadyClosedException { + if (closed) { + throw new AlreadyClosedException("this FieldsReader is closed"); + } + } + + /** + * Closes the underlying {@link org.apache.lucene.store.IndexInput} streams, including any ones associated with a + * lazy implementation of a Field. This means that the Fields values will not be accessible. + * + * @throws IOException + */ + final void close() throws IOException { + if (!closed) { + if (fieldsStream != null) { + fieldsStream.close(); + } + if (cloneableFieldsStream != null) { + cloneableFieldsStream.close(); + } + if (indexStream != null) { + indexStream.close(); + } + fieldsStreamTL.close(); + closed = true; + } + } + + final int size() { + return size; + } + + private final void seekIndex(int docID) throws IOException { + indexStream.seek(formatSize + (docID + docStoreOffset) * 8L); + } + + boolean canReadRawDocs() { + return format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES; + } + + final Document doc(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + seekIndex(n); + long position = indexStream.readLong(); + fieldsStream.seek(position); + + Document doc = new Document(); + int numFields = fieldsStream.readVInt(); + for (int i = 0; i < numFields; i++) { + int fieldNumber = fieldsStream.readVInt(); + FieldInfo fi = fieldInfos.fieldInfo(fieldNumber); + FieldSelectorResult acceptField = fieldSelector == null ? FieldSelectorResult.LOAD : fieldSelector.accept(fi.name); + + byte bits = fieldsStream.readByte(); + assert bits <= FieldsWriter.FIELD_IS_COMPRESSED + FieldsWriter.FIELD_IS_TOKENIZED + FieldsWriter.FIELD_IS_BINARY; + + boolean compressed = (bits & FieldsWriter.FIELD_IS_COMPRESSED) != 0; + boolean tokenize = (bits & FieldsWriter.FIELD_IS_TOKENIZED) != 0; + boolean binary = (bits & FieldsWriter.FIELD_IS_BINARY) != 0; + //TODO: Find an alternative approach here if this list continues to grow beyond the + //list of 5 or 6 currently here. See Lucene 762 for discussion + if (acceptField.equals(FieldSelectorResult.LOAD)) { + addField(doc, fi, binary, compressed, tokenize); + } + else if (acceptField.equals(FieldSelectorResult.LOAD_FOR_MERGE)) { + addFieldForMerge(doc, fi, binary, compressed, tokenize); + } + else if (acceptField.equals(FieldSelectorResult.LOAD_AND_BREAK)){ + addField(doc, fi, binary, compressed, tokenize); + break;//Get out of this loop + } + else if (acceptField.equals(FieldSelectorResult.LAZY_LOAD)) { + addFieldLazy(doc, fi, binary, compressed, tokenize); + } + else if (acceptField.equals(FieldSelectorResult.SIZE)){ + skipField(binary, compressed, addFieldSize(doc, fi, binary, compressed)); + } + else if (acceptField.equals(FieldSelectorResult.SIZE_AND_BREAK)){ + addFieldSize(doc, fi, binary, compressed); + break; + } + else { + skipField(binary, compressed); + } + } + + return doc; + } + + /** Returns the length in bytes of each raw document in a + * contiguous range of length numDocs starting with + * startDocID. Returns the IndexInput (the fieldStream), + * already seeked to the starting point for startDocID.*/ + final IndexInput rawDocs(int[] lengths, int startDocID, int numDocs) throws IOException { + seekIndex(startDocID); + long startOffset = indexStream.readLong(); + long lastOffset = startOffset; + int count = 0; + while (count < numDocs) { + final long offset; + final int docID = docStoreOffset + startDocID + count + 1; + assert docID <= numTotalDocs; + if (docID < numTotalDocs) + offset = indexStream.readLong(); + else + offset = fieldsStream.length(); + lengths[count++] = (int) (offset-lastOffset); + lastOffset = offset; + } + + fieldsStream.seek(startOffset); + + return fieldsStream; + } + + /** + * Skip the field. We still have to read some of the information about the field, but can skip past the actual content. + * This will have the most payoff on large fields. + */ + private void skipField(boolean binary, boolean compressed) throws IOException { + skipField(binary, compressed, fieldsStream.readVInt()); + } + + private void skipField(boolean binary, boolean compressed, int toRead) throws IOException { + if (format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES || binary || compressed) { + fieldsStream.seek(fieldsStream.getFilePointer() + toRead); + } else { + // We need to skip chars. This will slow us down, but still better + fieldsStream.skipChars(toRead); + } + } + + private void addFieldLazy(Document doc, FieldInfo fi, boolean binary, boolean compressed, boolean tokenize) throws IOException { + if (binary) { + int toRead = fieldsStream.readVInt(); + long pointer = fieldsStream.getFilePointer(); + if (compressed) { + //was: doc.add(new Fieldable(fi.name, uncompress(b), Fieldable.Store.COMPRESS)); + doc.add(new LazyField(fi.name, Field.Store.COMPRESS, toRead, pointer, binary)); + } else { + //was: doc.add(new Fieldable(fi.name, b, Fieldable.Store.YES)); + doc.add(new LazyField(fi.name, Field.Store.YES, toRead, pointer, binary)); + } + //Need to move the pointer ahead by toRead positions + fieldsStream.seek(pointer + toRead); + } else { + Field.Store store = Field.Store.YES; + Field.Index index = getIndexType(fi, tokenize); + Field.TermVector termVector = getTermVectorType(fi); + + Fieldable f; + if (compressed) { + store = Field.Store.COMPRESS; + int toRead = fieldsStream.readVInt(); + long pointer = fieldsStream.getFilePointer(); + f = new LazyField(fi.name, store, toRead, pointer, binary); + //skip over the part that we aren't loading + fieldsStream.seek(pointer + toRead); + f.setOmitNorms(fi.omitNorms); + } else { + int length = fieldsStream.readVInt(); + long pointer = fieldsStream.getFilePointer(); + //Skip ahead of where we are by the length of what is stored + if (format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) + fieldsStream.seek(pointer+length); + else + fieldsStream.skipChars(length); + f = new LazyField(fi.name, store, index, termVector, length, pointer, binary); + f.setOmitNorms(fi.omitNorms); + } + doc.add(f); + } + + } + + // in merge mode we don't uncompress the data of a compressed field + private void addFieldForMerge(Document doc, FieldInfo fi, boolean binary, boolean compressed, boolean tokenize) throws IOException { + Object data; + + if (binary || compressed) { + int toRead = fieldsStream.readVInt(); + final byte[] b = new byte[toRead]; + fieldsStream.readBytes(b, 0, b.length); + data = b; + } else { + data = fieldsStream.readString(); + } + + doc.add(new FieldForMerge(data, fi, binary, compressed, tokenize)); + } + + private void addField(Document doc, FieldInfo fi, boolean binary, boolean compressed, boolean tokenize) throws CorruptIndexException, IOException { + + //we have a binary stored field, and it may be compressed + if (binary) { + int toRead = fieldsStream.readVInt(); + final byte[] b = new byte[toRead]; + fieldsStream.readBytes(b, 0, b.length); + if (compressed) + doc.add(new Field(fi.name, uncompress(b), Field.Store.COMPRESS)); + else + doc.add(new Field(fi.name, b, Field.Store.YES)); + + } else { + Field.Store store = Field.Store.YES; + Field.Index index = getIndexType(fi, tokenize); + Field.TermVector termVector = getTermVectorType(fi); + + Fieldable f; + if (compressed) { + store = Field.Store.COMPRESS; + int toRead = fieldsStream.readVInt(); + + final byte[] b = new byte[toRead]; + fieldsStream.readBytes(b, 0, b.length); + f = new Field(fi.name, // field name + new String(uncompress(b), "UTF-8"), // uncompress the value and add as string + store, + index, + termVector); + f.setOmitNorms(fi.omitNorms); + } else { + f = new Field(fi.name, // name + fieldsStream.readString(), // read value + store, + index, + termVector); + f.setOmitNorms(fi.omitNorms); + } + doc.add(f); + } + } + + // Add the size of field as a byte[] containing the 4 bytes of the integer byte size (high order byte first; char = 2 bytes) + // Read just the size -- caller must skip the field content to continue reading fields + // Return the size in bytes or chars, depending on field type + private int addFieldSize(Document doc, FieldInfo fi, boolean binary, boolean compressed) throws IOException { + int size = fieldsStream.readVInt(), bytesize = binary || compressed ? size : 2*size; + byte[] sizebytes = new byte[4]; + sizebytes[0] = (byte) (bytesize>>>24); + sizebytes[1] = (byte) (bytesize>>>16); + sizebytes[2] = (byte) (bytesize>>> 8); + sizebytes[3] = (byte) bytesize ; + doc.add(new Field(fi.name, sizebytes, Field.Store.YES)); + return size; + } + + private Field.TermVector getTermVectorType(FieldInfo fi) { + Field.TermVector termVector = null; + if (fi.storeTermVector) { + if (fi.storeOffsetWithTermVector) { + if (fi.storePositionWithTermVector) { + termVector = Field.TermVector.WITH_POSITIONS_OFFSETS; + } else { + termVector = Field.TermVector.WITH_OFFSETS; + } + } else if (fi.storePositionWithTermVector) { + termVector = Field.TermVector.WITH_POSITIONS; + } else { + termVector = Field.TermVector.YES; + } + } else { + termVector = Field.TermVector.NO; + } + return termVector; + } + + private Field.Index getIndexType(FieldInfo fi, boolean tokenize) { + Field.Index index; + if (fi.isIndexed && tokenize) + index = Field.Index.ANALYZED; + else if (fi.isIndexed && !tokenize) + index = Field.Index.NOT_ANALYZED; + else + index = Field.Index.NO; + return index; + } + + /** + * A Lazy implementation of Fieldable that differs loading of fields until asked for, instead of when the Document is + * loaded. + */ + private class LazyField extends AbstractField implements Fieldable { + private int toRead; + private long pointer; + + public LazyField(String name, Field.Store store, int toRead, long pointer, boolean isBinary) { + super(name, store, Field.Index.NO, Field.TermVector.NO); + this.toRead = toRead; + this.pointer = pointer; + this.isBinary = isBinary; + lazy = true; + } + + public LazyField(String name, Field.Store store, Field.Index index, Field.TermVector termVector, int toRead, long pointer, boolean isBinary) { + super(name, store, index, termVector); + this.toRead = toRead; + this.pointer = pointer; + this.isBinary = isBinary; + lazy = true; + } + + private IndexInput getFieldStream() { + IndexInput localFieldsStream = (IndexInput) fieldsStreamTL.get(); + if (localFieldsStream == null) { + localFieldsStream = (IndexInput) cloneableFieldsStream.clone(); + fieldsStreamTL.set(localFieldsStream); + } + return localFieldsStream; + } + + /** The value of the field in Binary, or null. If null, the Reader value, + * String value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public byte[] binaryValue() { + return getBinaryValue(null); + } + + /** The value of the field as a Reader, or null. If null, the String value, + * binary value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public Reader readerValue() { + ensureOpen(); + return null; + } + + /** The value of the field as a TokenStream, or null. If null, the Reader value, + * String value, or binary value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public TokenStream tokenStreamValue() { + ensureOpen(); + return null; + } + + /** The value of the field as a String, or null. If null, the Reader value, + * binary value, or TokenStream value is used. Exactly one of stringValue(), + * readerValue(), binaryValue(), and tokenStreamValue() must be set. */ + public String stringValue() { + ensureOpen(); + if (isBinary) + return null; + else { + if (fieldsData == null) { + IndexInput localFieldsStream = getFieldStream(); + try { + localFieldsStream.seek(pointer); + if (isCompressed) { + final byte[] b = new byte[toRead]; + localFieldsStream.readBytes(b, 0, b.length); + fieldsData = new String(uncompress(b), "UTF-8"); + } else { + if (format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) { + byte[] bytes = new byte[toRead]; + localFieldsStream.readBytes(bytes, 0, toRead); + fieldsData = new String(bytes, "UTF-8"); + } else { + //read in chars b/c we already know the length we need to read + char[] chars = new char[toRead]; + localFieldsStream.readChars(chars, 0, toRead); + fieldsData = new String(chars); + } + } + } catch (IOException e) { + throw new FieldReaderException(e); + } + } + return (String) fieldsData; + } + } + + public long getPointer() { + ensureOpen(); + return pointer; + } + + public void setPointer(long pointer) { + ensureOpen(); + this.pointer = pointer; + } + + public int getToRead() { + ensureOpen(); + return toRead; + } + + public void setToRead(int toRead) { + ensureOpen(); + this.toRead = toRead; + } + + public byte[] getBinaryValue(byte[] result) { + ensureOpen(); + + if (isBinary) { + if (fieldsData == null) { + // Allocate new buffer if result is null or too small + final byte[] b; + if (result == null || result.length < toRead) + b = new byte[toRead]; + else + b = result; + + IndexInput localFieldsStream = getFieldStream(); + + // Throw this IOException since IndexReader.document does so anyway, so probably not that big of a change for people + // since they are already handling this exception when getting the document + try { + localFieldsStream.seek(pointer); + localFieldsStream.readBytes(b, 0, toRead); + if (isCompressed == true) { + fieldsData = uncompress(b); + } else { + fieldsData = b; + } + } catch (IOException e) { + throw new FieldReaderException(e); + } + + binaryOffset = 0; + binaryLength = toRead; + } + + return (byte[]) fieldsData; + } else + return null; + } + } + + private final byte[] uncompress(final byte[] input) + throws CorruptIndexException, IOException { + + // Create an expandable byte array to hold the decompressed data + ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length); + + Inflater decompressor = new Inflater(); + + try { + decompressor.setInput(input); + + // Decompress the data + byte[] buf = new byte[1024]; + while (!decompressor.finished()) { + try { + int count = decompressor.inflate(buf); + bos.write(buf, 0, count); + } + catch (DataFormatException e) { + // this will happen if the field is not compressed + CorruptIndexException newException = new CorruptIndexException("field data are in wrong format: " + e.toString()); + newException.initCause(e); + throw newException; + } + } + } finally { + decompressor.end(); + } + + // Get the decompressed data + return bos.toByteArray(); + } + + // Instances of this class hold field properties and data + // for merge + final static class FieldForMerge extends AbstractField { + public String stringValue() { + return (String) this.fieldsData; + } + + public Reader readerValue() { + // not needed for merge + return null; + } + + public byte[] binaryValue() { + return (byte[]) this.fieldsData; + } + + public TokenStream tokenStreamValue() { + // not needed for merge + return null; + } + + public FieldForMerge(Object value, FieldInfo fi, boolean binary, boolean compressed, boolean tokenize) { + this.isStored = true; + this.fieldsData = value; + this.isCompressed = compressed; + this.isBinary = binary; + this.isTokenized = tokenize; + + this.name = fi.name.intern(); + this.isIndexed = fi.isIndexed; + this.omitNorms = fi.omitNorms; + this.storeOffsetWithTermVector = fi.storeOffsetWithTermVector; + this.storePositionWithTermVector = fi.storePositionWithTermVector; + this.storeTermVector = fi.storeTermVector; + } + + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FieldsWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FieldsWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FieldsWriter.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,311 @@ +package org.apache.lucene.index; + +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Iterator; +import java.util.zip.Deflater; + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Fieldable; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.RAMOutputStream; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.IndexInput; + +final class FieldsWriter +{ + static final byte FIELD_IS_TOKENIZED = 0x1; + static final byte FIELD_IS_BINARY = 0x2; + static final byte FIELD_IS_COMPRESSED = 0x4; + + // Original format + static final int FORMAT = 0; + + // Changed strings to UTF8 + static final int FORMAT_VERSION_UTF8_LENGTH_IN_BYTES = 1; + + // NOTE: if you introduce a new format, make it 1 higher + // than the current one, and always change this if you + // switch to a new format! + static final int FORMAT_CURRENT = FORMAT_VERSION_UTF8_LENGTH_IN_BYTES; + + private FieldInfos fieldInfos; + + private IndexOutput fieldsStream; + + private IndexOutput indexStream; + + private boolean doClose; + + FieldsWriter(Directory d, String segment, FieldInfos fn) throws IOException { + fieldInfos = fn; + + boolean success = false; + final String fieldsName = segment + "." + IndexFileNames.FIELDS_EXTENSION; + try { + fieldsStream = d.createOutput(fieldsName); + fieldsStream.writeInt(FORMAT_CURRENT); + success = true; + } finally { + if (!success) { + try { + close(); + } catch (Throwable t) { + // Suppress so we keep throwing the original exception + } + try { + d.deleteFile(fieldsName); + } catch (Throwable t) { + // Suppress so we keep throwing the original exception + } + } + } + + success = false; + final String indexName = segment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION; + try { + indexStream = d.createOutput(indexName); + indexStream.writeInt(FORMAT_CURRENT); + success = true; + } finally { + if (!success) { + try { + close(); + } catch (IOException ioe) { + } + try { + d.deleteFile(fieldsName); + } catch (Throwable t) { + // Suppress so we keep throwing the original exception + } + try { + d.deleteFile(indexName); + } catch (Throwable t) { + // Suppress so we keep throwing the original exception + } + } + } + + doClose = true; + } + + FieldsWriter(IndexOutput fdx, IndexOutput fdt, FieldInfos fn) { + fieldInfos = fn; + fieldsStream = fdt; + indexStream = fdx; + doClose = false; + } + + void setFieldsStream(IndexOutput stream) { + this.fieldsStream = stream; + } + + // Writes the contents of buffer into the fields stream + // and adds a new entry for this document into the index + // stream. This assumes the buffer was already written + // in the correct fields format. + void flushDocument(int numStoredFields, RAMOutputStream buffer) throws IOException { + indexStream.writeLong(fieldsStream.getFilePointer()); + fieldsStream.writeVInt(numStoredFields); + buffer.writeTo(fieldsStream); + } + + void skipDocument() throws IOException { + indexStream.writeLong(fieldsStream.getFilePointer()); + fieldsStream.writeVInt(0); + } + + void flush() throws IOException { + indexStream.flush(); + fieldsStream.flush(); + } + + final void close() throws IOException { + if (doClose) { + + try { + if (fieldsStream != null) { + try { + fieldsStream.close(); + } finally { + fieldsStream = null; + } + } + } catch (IOException ioe) { + try { + if (indexStream != null) { + try { + indexStream.close(); + } finally { + indexStream = null; + } + } + } catch (IOException ioe2) { + // Ignore so we throw only first IOException hit + } + throw ioe; + } finally { + if (indexStream != null) { + try { + indexStream.close(); + } finally { + indexStream = null; + } + } + } + } + } + + final void writeField(FieldInfo fi, Fieldable field) throws IOException { + // if the field as an instanceof FieldsReader.FieldForMerge, we're in merge mode + // and field.binaryValue() already returns the compressed value for a field + // with isCompressed()==true, so we disable compression in that case + boolean disableCompression = (field instanceof FieldsReader.FieldForMerge); + fieldsStream.writeVInt(fi.number); + byte bits = 0; + if (field.isTokenized()) + bits |= FieldsWriter.FIELD_IS_TOKENIZED; + if (field.isBinary()) + bits |= FieldsWriter.FIELD_IS_BINARY; + if (field.isCompressed()) + bits |= FieldsWriter.FIELD_IS_COMPRESSED; + + fieldsStream.writeByte(bits); + + if (field.isCompressed()) { + // compression is enabled for the current field + final byte[] data; + final int len; + final int offset; + if (disableCompression) { + // optimized case for merging, the data + // is already compressed + data = field.getBinaryValue(); + assert data != null; + len = field.getBinaryLength(); + offset = field.getBinaryOffset(); + } else { + // check if it is a binary field + if (field.isBinary()) { + data = compress(field.getBinaryValue(), field.getBinaryOffset(), field.getBinaryLength()); + } else { + byte x[] = field.stringValue().getBytes("UTF-8"); + data = compress(x, 0, x.length); + } + len = data.length; + offset = 0; + } + + fieldsStream.writeVInt(len); + fieldsStream.writeBytes(data, offset, len); + } + else { + // compression is disabled for the current field + if (field.isBinary()) { + final byte[] data; + final int len; + final int offset; + data = field.getBinaryValue(); + len = field.getBinaryLength(); + offset = field.getBinaryOffset(); + + fieldsStream.writeVInt(len); + fieldsStream.writeBytes(data, offset, len); + } + else { + fieldsStream.writeString(field.stringValue()); + } + } + } + + /** Bulk write a contiguous series of documents. The + * lengths array is the length (in bytes) of each raw + * document. The stream IndexInput is the + * fieldsStream from which we should bulk-copy all + * bytes. */ + final void addRawDocuments(IndexInput stream, int[] lengths, int numDocs) throws IOException { + long position = fieldsStream.getFilePointer(); + long start = position; + for(int i=0;iFilterIndexReader contains another IndexReader, which it + * uses as its basic source of data, possibly transforming the data along the + * way or providing additional functionality. The class + * FilterIndexReader itself simply implements all abstract methods + * of IndexReader with versions that pass all requests to the + * contained index reader. Subclasses of FilterIndexReader may + * further override some of these methods and may also provide additional + * methods and fields. + */ +public class FilterIndexReader extends IndexReader { + + /** Base class for filtering {@link TermDocs} implementations. */ + public static class FilterTermDocs implements TermDocs { + protected TermDocs in; + + public FilterTermDocs(TermDocs in) { this.in = in; } + + public void seek(Term term) throws IOException { in.seek(term); } + public void seek(TermEnum termEnum) throws IOException { in.seek(termEnum); } + public int doc() { return in.doc(); } + public int freq() { return in.freq(); } + public boolean next() throws IOException { return in.next(); } + public int read(int[] docs, int[] freqs) throws IOException { + return in.read(docs, freqs); + } + public boolean skipTo(int i) throws IOException { return in.skipTo(i); } + public void close() throws IOException { in.close(); } + } + + /** Base class for filtering {@link TermPositions} implementations. */ + public static class FilterTermPositions + extends FilterTermDocs implements TermPositions { + + public FilterTermPositions(TermPositions in) { super(in); } + + public int nextPosition() throws IOException { + return ((TermPositions) this.in).nextPosition(); + } + + public int getPayloadLength() { + return ((TermPositions) this.in).getPayloadLength(); + } + + public byte[] getPayload(byte[] data, int offset) throws IOException { + return ((TermPositions) this.in).getPayload(data, offset); + } + + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return ((TermPositions)this.in).isPayloadAvailable(); + } + } + + /** Base class for filtering {@link TermEnum} implementations. */ + public static class FilterTermEnum extends TermEnum { + protected TermEnum in; + + public FilterTermEnum(TermEnum in) { this.in = in; } + + public boolean next() throws IOException { return in.next(); } + public Term term() { return in.term(); } + public int docFreq() { return in.docFreq(); } + public void close() throws IOException { in.close(); } + } + + protected IndexReader in; + + /** + *

Construct a FilterIndexReader based on the specified base reader. + * Directory locking for delete, undeleteAll, and setNorm operations is + * left to the base reader.

+ *

Note that base reader is closed if this FilterIndexReader is closed.

+ * @param in specified base reader. + */ + public FilterIndexReader(IndexReader in) { + super(); + this.in = in; + } + + public Directory directory() { + return in.directory(); + } + + public TermFreqVector[] getTermFreqVectors(int docNumber) + throws IOException { + ensureOpen(); + return in.getTermFreqVectors(docNumber); + } + + public TermFreqVector getTermFreqVector(int docNumber, String field) + throws IOException { + ensureOpen(); + return in.getTermFreqVector(docNumber, field); + } + + + public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException { + ensureOpen(); + in.getTermFreqVector(docNumber, field, mapper); + + } + + public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException { + ensureOpen(); + in.getTermFreqVector(docNumber, mapper); + } + + public int numDocs() { + // Don't call ensureOpen() here (it could affect performance) + return in.numDocs(); + } + + public int maxDoc() { + // Don't call ensureOpen() here (it could affect performance) + return in.maxDoc(); + } + + public Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + ensureOpen(); + return in.document(n, fieldSelector); + } + + public boolean isDeleted(int n) { + // Don't call ensureOpen() here (it could affect performance) + return in.isDeleted(n); + } + + public boolean hasDeletions() { + // Don't call ensureOpen() here (it could affect performance) + return in.hasDeletions(); + } + + protected void doUndeleteAll() throws CorruptIndexException, IOException {in.undeleteAll();} + + public boolean hasNorms(String field) throws IOException { + ensureOpen(); + return in.hasNorms(field); + } + + public byte[] norms(String f) throws IOException { + ensureOpen(); + return in.norms(f); + } + + public void norms(String f, byte[] bytes, int offset) throws IOException { + ensureOpen(); + in.norms(f, bytes, offset); + } + + protected void doSetNorm(int d, String f, byte b) throws CorruptIndexException, IOException { + in.setNorm(d, f, b); + } + + public TermEnum terms() throws IOException { + ensureOpen(); + return in.terms(); + } + + public TermEnum terms(Term t) throws IOException { + ensureOpen(); + return in.terms(t); + } + + public int docFreq(Term t) throws IOException { + ensureOpen(); + return in.docFreq(t); + } + + public TermDocs termDocs() throws IOException { + ensureOpen(); + return in.termDocs(); + } + + public TermPositions termPositions() throws IOException { + ensureOpen(); + return in.termPositions(); + } + + protected void doDelete(int n) throws CorruptIndexException, IOException { in.deleteDocument(n); } + protected void doCommit() throws IOException { in.commit(); } + protected void doClose() throws IOException { in.close(); } + + + public Collection getFieldNames(IndexReader.FieldOption fieldNames) { + ensureOpen(); + return in.getFieldNames(fieldNames); + } + + public long getVersion() { + ensureOpen(); + return in.getVersion(); + } + + public boolean isCurrent() throws CorruptIndexException, IOException { + ensureOpen(); + return in.isCurrent(); + } + + public boolean isOptimized() { + ensureOpen(); + return in.isOptimized(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxFieldMergeState.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FreqProxFieldMergeState.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxFieldMergeState.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,105 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +// TODO FI: some of this is "generic" to TermsHash* so we +// should factor it out so other consumers don't have to +// duplicate this code + +/** Used by DocumentsWriter to merge the postings from + * multiple ThreadStates when creating a segment */ +final class FreqProxFieldMergeState { + + final FreqProxTermsWriterPerField field; + final int numPostings; + final CharBlockPool charPool; + final RawPostingList[] postings; + + private FreqProxTermsWriter.PostingList p; + char[] text; + int textOffset; + + private int postingUpto = -1; + + final ByteSliceReader freq = new ByteSliceReader(); + final ByteSliceReader prox = new ByteSliceReader(); + + int docID; + int termFreq; + + public FreqProxFieldMergeState(FreqProxTermsWriterPerField field) { + this.field = field; + this.charPool = field.perThread.termsHashPerThread.charPool; + this.numPostings = field.termsHashPerField.numPostings; + this.postings = field.termsHashPerField.sortPostings(); + } + + boolean nextTerm() throws IOException { + postingUpto++; + if (postingUpto == numPostings) + return false; + + p = (FreqProxTermsWriter.PostingList) postings[postingUpto]; + docID = 0; + + text = charPool.buffers[p.textStart >> DocumentsWriter.CHAR_BLOCK_SHIFT]; + textOffset = p.textStart & DocumentsWriter.CHAR_BLOCK_MASK; + + field.termsHashPerField.initReader(freq, p, 0); + if (!field.fieldInfo.omitTf) + field.termsHashPerField.initReader(prox, p, 1); + + // Should always be true + boolean result = nextDoc(); + assert result; + + return true; + } + + public boolean nextDoc() throws IOException { + if (freq.eof()) { + if (p.lastDocCode != -1) { + // Return last doc + docID = p.lastDocID; + if (!field.omitTf) + termFreq = p.docFreq; + p.lastDocCode = -1; + return true; + } else + // EOF + return false; + } + + final int code = freq.readVInt(); + if (field.omitTf) + docID += code; + else { + docID += code >>> 1; + if ((code & 1) != 0) + termFreq = 1; + else + termFreq = freq.readVInt(); + } + + assert docID != p.lastDocID; + + return true; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriter.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,386 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.util.UnicodeUtil; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; +import java.util.Iterator; + +final class FreqProxTermsWriter extends TermsHashConsumer { + + public TermsHashConsumerPerThread addThread(TermsHashPerThread perThread) { + return new FreqProxTermsWriterPerThread(perThread); + } + + void createPostings(RawPostingList[] postings, int start, int count) { + final int end = start + count; + for(int i=start;i 0) + allFields.add(perField); + } + } + + // Sort by field name + Collections.sort(allFields); + final int numAllFields = allFields.size(); + + final TermInfosWriter termsOut = new TermInfosWriter(state.directory, + state.segmentName, + fieldInfos, + state.docWriter.writer.getTermIndexInterval()); + + final IndexOutput freqOut = state.directory.createOutput(state.segmentFileName(IndexFileNames.FREQ_EXTENSION)); + final IndexOutput proxOut; + + if (fieldInfos.hasProx()) + proxOut = state.directory.createOutput(state.segmentFileName(IndexFileNames.PROX_EXTENSION)); + else + proxOut = null; + + final DefaultSkipListWriter skipListWriter = new DefaultSkipListWriter(termsOut.skipInterval, + termsOut.maxSkipLevels, + state.numDocsInRAM, freqOut, proxOut); + + int start = 0; + while(start < numAllFields) { + final FieldInfo fieldInfo = ((FreqProxTermsWriterPerField) allFields.get(start)).fieldInfo; + final String fieldName = fieldInfo.name; + + int end = start+1; + while(end < numAllFields && ((FreqProxTermsWriterPerField) allFields.get(end)).fieldInfo.name.equals(fieldName)) + end++; + + FreqProxTermsWriterPerField[] fields = new FreqProxTermsWriterPerField[end-start]; + for(int i=start;i + // IndexOutput + while(numBytes > 0) { + final int chunk; + if (numBytes > 4096) + chunk = 4096; + else + chunk = (int) numBytes; + srcIn.readBytes(copyByteBuffer, 0, chunk); + destIn.writeBytes(copyByteBuffer, 0, chunk); + numBytes -= chunk; + } + } + + /* Walk through all unique text tokens (Posting + * instances) found in this field and serialize them + * into a single RAM segment. */ + void appendPostings(final DocumentsWriter.FlushState flushState, + FreqProxTermsWriterPerField[] fields, + TermInfosWriter termsOut, + IndexOutput freqOut, + IndexOutput proxOut, + DefaultSkipListWriter skipListWriter) + throws CorruptIndexException, IOException { + + final int fieldNumber = fields[0].fieldInfo.number; + int numFields = fields.length; + + final FreqProxFieldMergeState[] mergeStates = new FreqProxFieldMergeState[numFields]; + + for(int i=0;i 0) { + + // Get the next term to merge + termStates[0] = mergeStates[0]; + int numToMerge = 1; + + for(int i=1;i 0) { + + if ((++df % skipInterval) == 0) { + skipListWriter.setSkipData(lastDoc, currentFieldStorePayloads, lastPayloadLength); + skipListWriter.bufferSkip(df); + } + + FreqProxFieldMergeState minState = termStates[0]; + for(int i=1;i lastDoc || df == 1; + + final ByteSliceReader prox = minState.prox; + + // Carefully copy over the prox + payload info, + // changing the format to match Lucene's segment + // format. + if (!currentFieldOmitTf) { + // omitTf == false so we do write positions & payload + assert proxOut != null; + for(int j=0;j 0) + copyBytes(prox, proxOut, payloadLength); + } else { + assert 0 == (code & 1); + proxOut.writeVInt(code>>1); + } + } //End for + + final int newDocCode = (doc-lastDoc)<<1; + + if (1 == termDocFreq) { + freqOut.writeVInt(newDocCode|1); + } else { + freqOut.writeVInt(newDocCode); + freqOut.writeVInt(termDocFreq); + } + } else { + // omitTf==true: we store only the docs, without + // term freq, positions, payloads + freqOut.writeVInt(doc-lastDoc); + } + + lastDoc = doc; + + if (!minState.nextDoc()) { + + // Remove from termStates + int upto = 0; + for(int i=0;i 0; + + // Done merging this term + + long skipPointer = skipListWriter.writeSkip(freqOut); + + // Write term + termInfo.set(df, freqPointer, proxPointer, (int) (skipPointer - freqPointer)); + + // TODO: we could do this incrementally + UnicodeUtil.UTF16toUTF8(text, start, termsUTF8); + + // TODO: we could save O(n) re-scan of the term by + // computing the shared prefix with the last term + // while during the UTF8 encoding + termsOut.add(fieldNumber, + termsUTF8.result, + termsUTF8.length, + termInfo); + } + } + + private final TermInfo termInfo = new TermInfo(); // minimize consing + + final UnicodeUtil.UTF8Result termsUTF8 = new UnicodeUtil.UTF8Result(); + + void files(Collection files) {} + + static final class PostingList extends RawPostingList { + int docFreq; // # times this term occurs in the current doc + int lastDocID; // Last docID where this term occurred + int lastDocCode; // Code for prior doc + int lastPosition; // Last position where this term occurred + } + + int bytesPerPosting() { + return RawPostingList.BYTES_SIZE + 4 * DocumentsWriter.INT_NUM_BYTE; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriterPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriterPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriterPerField.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,145 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.document.Fieldable; +import org.apache.lucene.analysis.Token; + +// TODO: break into separate freq and prox writers as +// codecs; make separate container (tii/tis/skip/*) that can +// be configured as any number of files 1..N +final class FreqProxTermsWriterPerField extends TermsHashConsumerPerField implements Comparable { + + final FreqProxTermsWriterPerThread perThread; + final TermsHashPerField termsHashPerField; + final FieldInfo fieldInfo; + final DocumentsWriter.DocState docState; + final DocInverter.FieldInvertState fieldState; + boolean omitTf; + + public FreqProxTermsWriterPerField(TermsHashPerField termsHashPerField, FreqProxTermsWriterPerThread perThread, FieldInfo fieldInfo) { + this.termsHashPerField = termsHashPerField; + this.perThread = perThread; + this.fieldInfo = fieldInfo; + docState = termsHashPerField.docState; + fieldState = termsHashPerField.fieldState; + omitTf = fieldInfo.omitTf; + } + + int getStreamCount() { + if (fieldInfo.omitTf) + return 1; + else + return 2; + } + + void finish() {} + + boolean hasPayloads; + + void skippingLongTerm(Token t) throws IOException {} + + public int compareTo(Object other0) { + FreqProxTermsWriterPerField other = (FreqProxTermsWriterPerField) other0; + return fieldInfo.name.compareTo(other.fieldInfo.name); + } + + void reset() { + // Record, up front, whether our in-RAM format will be + // with or without term freqs: + omitTf = fieldInfo.omitTf; + } + + boolean start(Fieldable[] fields, int count) { + for(int i=0;i 0) { + termsHashPerField.writeVInt(1, (proxCode<<1)|1); + termsHashPerField.writeVInt(1, payload.length); + termsHashPerField.writeBytes(1, payload.data, payload.offset, payload.length); + hasPayloads = true; + } else + termsHashPerField.writeVInt(1, proxCode<<1); + p.lastPosition = fieldState.position; + } + + final void newTerm(Token t, RawPostingList p0) { + // First time we're seeing this term since the last + // flush + assert docState.testPoint("FreqProxTermsWriterPerField.newTerm start"); + FreqProxTermsWriter.PostingList p = (FreqProxTermsWriter.PostingList) p0; + p.lastDocID = docState.docID; + if (omitTf) { + p.lastDocCode = docState.docID; + } else { + p.lastDocCode = docState.docID << 1; + p.docFreq = 1; + writeProx(t, p, fieldState.position); + } + } + + final void addTerm(Token t, RawPostingList p0) { + + assert docState.testPoint("FreqProxTermsWriterPerField.addTerm start"); + + FreqProxTermsWriter.PostingList p = (FreqProxTermsWriter.PostingList) p0; + + assert omitTf || p.docFreq > 0; + + if (omitTf) { + if (docState.docID != p.lastDocID) { + assert docState.docID > p.lastDocID; + termsHashPerField.writeVInt(0, p.lastDocCode); + p.lastDocCode = docState.docID - p.lastDocID; + p.lastDocID = docState.docID; + } + } else { + if (docState.docID != p.lastDocID) { + assert docState.docID > p.lastDocID; + // Term not yet seen in the current doc but previously + // seen in other doc(s) since the last flush + + // Now that we know doc freq for previous doc, + // write it & lastDocCode + if (1 == p.docFreq) + termsHashPerField.writeVInt(0, p.lastDocCode|1); + else { + termsHashPerField.writeVInt(0, p.lastDocCode); + termsHashPerField.writeVInt(0, p.docFreq); + } + p.docFreq = 1; + p.lastDocCode = (docState.docID - p.lastDocID) << 1; + p.lastDocID = docState.docID; + writeProx(t, p, fieldState.position); + } else { + p.docFreq++; + writeProx(t, p, fieldState.position-p.lastPosition); + } + } + } + + public void abort() {} +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriterPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriterPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/FreqProxTermsWriterPerThread.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,41 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +final class FreqProxTermsWriterPerThread extends TermsHashConsumerPerThread { + final TermsHashPerThread termsHashPerThread; + final DocumentsWriter.DocState docState; + + public FreqProxTermsWriterPerThread(TermsHashPerThread perThread) { + docState = perThread.docState; + termsHashPerThread = perThread; + } + + public TermsHashConsumerPerField addField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo) { + return new FreqProxTermsWriterPerField(termsHashPerField, this, fieldInfo); + } + + void startDocument() { + } + + DocumentsWriter.DocWriter finishDocument() { + return null; + } + + public void abort() {} +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexCommit.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexCommit.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexCommit.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,123 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +import java.util.Collection; +import java.io.IOException; +import org.apache.lucene.store.Directory; + +/** + *

Expert: represents a single commit into an index as seen by the + * {@link IndexDeletionPolicy} or {@link IndexReader}.

+ * + *

Changes to the content of an index are made visible + * only after the writer who made that change commits by + * writing a new segments file + * (segments_N). This point in time, when the + * action of writing of a new segments file to the directory + * is completed, is an index commit.

+ * + *

Each index commit point has a unique segments file + * associated with it. The segments file associated with a + * later index commit point would have a larger N.

+ * + *

WARNING: This API is a new and experimental and + * may suddenly change.

+*/ + +public abstract class IndexCommit implements IndexCommitPoint { + + /** + * Get the segments file (segments_N) associated + * with this commit point. + */ + public abstract String getSegmentsFileName(); + + /** + * Returns all index files referenced by this commit point. + */ + public abstract Collection getFileNames() throws IOException; + + /** + * Returns the {@link Directory} for the index. + */ + public abstract Directory getDirectory(); + + /** + * Delete this commit point. This only applies when using + * the commit point in the context of IndexWriter's + * IndexDeletionPolicy. + *

+ * Upon calling this, the writer is notified that this commit + * point should be deleted. + *

+ * Decision that a commit-point should be deleted is taken by the {@link IndexDeletionPolicy} in effect + * and therefore this should only be called by its {@link IndexDeletionPolicy#onInit onInit()} or + * {@link IndexDeletionPolicy#onCommit onCommit()} methods. + */ + public void delete() { + throw new UnsupportedOperationException("This IndexCommit does not support this method."); + } + + public boolean isDeleted() { + throw new UnsupportedOperationException("This IndexCommit does not support this method."); + } + + /** + * Returns true if this commit is an optimized index. + */ + public boolean isOptimized() { + throw new UnsupportedOperationException("This IndexCommit does not support this method."); + } + + /** + * Two IndexCommits are equal if both their Directory and versions are equal. + */ + public boolean equals(Object other) { + if (other instanceof IndexCommit) { + IndexCommit otherCommit = (IndexCommit) other; + return otherCommit.getDirectory().equals(getDirectory()) && otherCommit.getVersion() == getVersion(); + } else + return false; + } + + public int hashCode() { + return getDirectory().hashCode() + getSegmentsFileName().hashCode(); + } + + /** Returns the version for this IndexCommit. This is the + same value that {@link IndexReader#getVersion} would + return if it were opened on this commit. */ + public long getVersion() { + throw new UnsupportedOperationException("This IndexCommit does not support this method."); + } + + /** Returns the generation (the _N in segments_N) for this + IndexCommit */ + public long getGeneration() { + throw new UnsupportedOperationException("This IndexCommit does not support this method."); + } + + /** Convenience method that returns the last modified time + * of the segments_N file corresponding to this index + * commit, equivalent to + * getDirectory().fileModified(getSegmentsFileName()). */ + public long getTimestamp() throws IOException { + return getDirectory().fileModified(getSegmentsFileName()); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexCommitPoint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexCommitPoint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexCommitPoint.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,51 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Collection; +import java.io.IOException; + +/** + * @deprecated Please subclass IndexCommit class instead + */ + +public interface IndexCommitPoint { + + /** + * Get the segments file (segments_N) associated + * with this commit point. + */ + public String getSegmentsFileName(); + + /** + * Returns all index files referenced by this commit point. + */ + public Collection getFileNames() throws IOException; + + /** + * Delete this commit point. + *

+ * Upon calling this, the writer is notified that this commit + * point should be deleted. + *

+ * Decision that a commit-point should be deleted is taken by the {@link IndexDeletionPolicy} in effect + * and therefore this should only be called by its {@link IndexDeletionPolicy#onInit onInit()} or + * {@link IndexDeletionPolicy#onCommit onCommit()} methods. + */ + public void delete(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexDeletionPolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexDeletionPolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexDeletionPolicy.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,101 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.List; +import java.io.IOException; + +/** + *

Expert: policy for deletion of stale {@link IndexCommit index commits}. + * + *

Implement this interface, and pass it to one + * of the {@link IndexWriter} or {@link IndexReader} + * constructors, to customize when older + * {@link IndexCommit point-in-time commits} + * are deleted from the index directory. The default deletion policy + * is {@link KeepOnlyLastCommitDeletionPolicy}, which always + * removes old commits as soon as a new commit is done (this + * matches the behavior before 2.2).

+ * + *

One expected use case for this (and the reason why it + * was first created) is to work around problems with an + * index directory accessed via filesystems like NFS because + * NFS does not provide the "delete on last close" semantics + * that Lucene's "point in time" search normally relies on. + * By implementing a custom deletion policy, such as "a + * commit is only removed once it has been stale for more + * than X minutes", you can give your readers time to + * refresh to the new commit before {@link IndexWriter} + * removes the old commits. Note that doing so will + * increase the storage requirements of the index. See LUCENE-710 + * for details.

+ */ + +public interface IndexDeletionPolicy { + + /** + *

This is called once when a writer is first + * instantiated to give the policy a chance to remove old + * commit points.

+ * + *

The writer locates all index commits present in the + * index directory and calls this method. The policy may + * choose to delete some of the commit points, doing so by + * calling method {@link IndexCommit#delete delete()} + * of {@link IndexCommit}.

+ * + *

Note: the last CommitPoint is the most recent one, + * i.e. the "front index state". Be careful not to delete it, + * unless you know for sure what you are doing, and unless + * you can afford to lose the index content while doing that. + * + * @param commits List of current + * {@link IndexCommit point-in-time commits}, + * sorted by age (the 0th one is the oldest commit). + */ + public void onInit(List commits) throws IOException; + + /** + *

This is called each time the writer completed a commit. + * This gives the policy a chance to remove old commit points + * with each commit.

+ * + *

The policy may now choose to delete old commit points + * by calling method {@link IndexCommit#delete delete()} + * of {@link IndexCommit}.

+ * + *

If writer has autoCommit = true then + * this method will in general be called many times during + * one instance of {@link IndexWriter}. If + * autoCommit = false then this method is + * only called once when {@link IndexWriter#close} is + * called, or not at all if the {@link IndexWriter#abort} + * is called. + * + *

Note: the last CommitPoint is the most recent one, + * i.e. the "front index state". Be careful not to delete it, + * unless you know for sure what you are doing, and unless + * you can afford to lose the index content while doing that. + * + * @param commits List of {@link IndexCommit}, + * sorted by age (the 0th one is the oldest commit). + */ + public void onCommit(List commits) throws IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexFileDeleter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexFileDeleter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexFileDeleter.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,655 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; + +import java.io.IOException; +import java.io.FileNotFoundException; +import java.io.PrintStream; +import java.util.Map; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Collection; + +/* + * This class keeps track of each SegmentInfos instance that + * is still "live", either because it corresponds to a + * segments_N file in the Directory (a "commit", i.e. a + * committed SegmentInfos) or because it's an in-memory + * SegmentInfos that a writer is actively updating but has + * not yet committed. This class uses simple reference + * counting to map the live SegmentInfos instances to + * individual files in the Directory. + * + * When autoCommit=true, IndexWriter currently commits only + * on completion of a merge (though this may change with + * time: it is not a guarantee). When autoCommit=false, + * IndexWriter only commits when it is closed. Regardless + * of autoCommit, the user may call IndexWriter.commit() to + * force a blocking commit. + * + * The same directory file may be referenced by more than + * one IndexCommit, i.e. more than one SegmentInfos. + * Therefore we count how many commits reference each file. + * When all the commits referencing a certain file have been + * deleted, the refcount for that file becomes zero, and the + * file is deleted. + * + * A separate deletion policy interface + * (IndexDeletionPolicy) is consulted on creation (onInit) + * and once per commit (onCommit), to decide when a commit + * should be removed. + * + * It is the business of the IndexDeletionPolicy to choose + * when to delete commit points. The actual mechanics of + * file deletion, retrying, etc, derived from the deletion + * of commit points is the business of the IndexFileDeleter. + * + * The current default deletion policy is {@link + * KeepOnlyLastCommitDeletionPolicy}, which removes all + * prior commits when a new commit has completed. This + * matches the behavior before 2.2. + * + * Note that you must hold the write.lock before + * instantiating this class. It opens segments_N file(s) + * directly with no retry logic. + */ + +final class IndexFileDeleter { + + /* Files that we tried to delete but failed (likely + * because they are open and we are running on Windows), + * so we will retry them again later: */ + private List deletable; + + /* Reference count for all files in the index. + * Counts how many existing commits reference a file. + * Maps String to RefCount (class below) instances: */ + private Map refCounts = new HashMap(); + + /* Holds all commits (segments_N) currently in the index. + * This will have just 1 commit if you are using the + * default delete policy (KeepOnlyLastCommitDeletionPolicy). + * Other policies may leave commit points live for longer + * in which case this list would be longer than 1: */ + private List commits = new ArrayList(); + + /* Holds files we had incref'd from the previous + * non-commit checkpoint: */ + private List lastFiles = new ArrayList(); + + /* Commits that the IndexDeletionPolicy have decided to delete: */ + private List commitsToDelete = new ArrayList(); + + private PrintStream infoStream; + private Directory directory; + private IndexDeletionPolicy policy; + private DocumentsWriter docWriter; + + /** Change to true to see details of reference counts when + * infoStream != null */ + public static boolean VERBOSE_REF_COUNTS = false; + + void setInfoStream(PrintStream infoStream) { + this.infoStream = infoStream; + if (infoStream != null) + message("setInfoStream deletionPolicy=" + policy); + } + + private void message(String message) { + infoStream.println("IFD [" + Thread.currentThread().getName() + "]: " + message); + } + + /** + * Initialize the deleter: find all previous commits in + * the Directory, incref the files they reference, call + * the policy to let it delete commits. The incoming + * segmentInfos must have been loaded from a commit point + * and not yet modified. This will remove any files not + * referenced by any of the commits. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public IndexFileDeleter(Directory directory, IndexDeletionPolicy policy, SegmentInfos segmentInfos, PrintStream infoStream, DocumentsWriter docWriter) + throws CorruptIndexException, IOException { + + this.docWriter = docWriter; + this.infoStream = infoStream; + + if (infoStream != null) + message("init: current segments file is \"" + segmentInfos.getCurrentSegmentFileName() + "\"; deletionPolicy=" + policy); + + this.policy = policy; + this.directory = directory; + + // First pass: walk the files and initialize our ref + // counts: + long currentGen = segmentInfos.getGeneration(); + IndexFileNameFilter filter = IndexFileNameFilter.getFilter(); + + String[] files = directory.list(); + if (files == null) + throw new IOException("cannot read directory " + directory + ": list() returned null"); + + CommitPoint currentCommitPoint = null; + + for(int i=0;i 0) { + + // First decref all files that had been referred to by + // the now-deleted commits: + for(int i=0;i writeTo) { + commits.remove(size-1); + size--; + } + } + } + + /** + * Writer calls this when it has hit an error and had to + * roll back, to tell us that there may now be + * unreferenced files in the filesystem. So we re-list + * the filesystem and delete such files. If segmentName + * is non-null, we will only delete files corresponding to + * that segment. + */ + public void refresh(String segmentName) throws IOException { + String[] files = directory.list(); + if (files == null) + throw new IOException("cannot read directory " + directory + ": list() returned null"); + IndexFileNameFilter filter = IndexFileNameFilter.getFilter(); + String segmentPrefix1; + String segmentPrefix2; + if (segmentName != null) { + segmentPrefix1 = segmentName + "."; + segmentPrefix2 = segmentName + "_"; + } else { + segmentPrefix1 = null; + segmentPrefix2 = null; + } + + for(int i=0;i 0) { + for(int i=0;i 0; + return --count; + } + } + + /** + * Holds details for each commit point. This class is + * also passed to the deletion policy. Note: this class + * has a natural ordering that is inconsistent with + * equals. + */ + + final private static class CommitPoint extends IndexCommit implements Comparable { + + long gen; + List files; + String segmentsFileName; + boolean deleted; + Directory directory; + Collection commitsToDelete; + long version; + long generation; + final boolean isOptimized; + + public CommitPoint(Collection commitsToDelete, Directory directory, SegmentInfos segmentInfos) throws IOException { + this.directory = directory; + this.commitsToDelete = commitsToDelete; + segmentsFileName = segmentInfos.getCurrentSegmentFileName(); + version = segmentInfos.getVersion(); + generation = segmentInfos.getGeneration(); + int size = segmentInfos.size(); + files = new ArrayList(size); + files.add(segmentsFileName); + gen = segmentInfos.getGeneration(); + for(int i=0;i commit.gen) { + return 1; + } else { + return 0; + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexFileNameFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexFileNameFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexFileNameFilter.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,93 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.io.FilenameFilter; +import java.util.HashSet; + +/** + * Filename filter that accept filenames and extensions only created by Lucene. + * + * @version $rcs = ' $Id: IndexFileNameFilter.java,v 1.1 2012/08/17 14:55:03 marcin Exp $ ' ; + */ +public class IndexFileNameFilter implements FilenameFilter { + + static IndexFileNameFilter singleton = new IndexFileNameFilter(); + private HashSet extensions; + private HashSet extensionsInCFS; + + public IndexFileNameFilter() { + extensions = new HashSet(); + for (int i = 0; i < IndexFileNames.INDEX_EXTENSIONS.length; i++) { + extensions.add(IndexFileNames.INDEX_EXTENSIONS[i]); + } + extensionsInCFS = new HashSet(); + for (int i = 0; i < IndexFileNames.INDEX_EXTENSIONS_IN_COMPOUND_FILE.length; i++) { + extensionsInCFS.add(IndexFileNames.INDEX_EXTENSIONS_IN_COMPOUND_FILE[i]); + } + } + + /* (non-Javadoc) + * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String) + */ + public boolean accept(File dir, String name) { + int i = name.lastIndexOf('.'); + if (i != -1) { + String extension = name.substring(1+i); + if (extensions.contains(extension)) { + return true; + } else if (extension.startsWith("f") && + extension.matches("f\\d+")) { + return true; + } else if (extension.startsWith("s") && + extension.matches("s\\d+")) { + return true; + } + } else { + if (name.equals(IndexFileNames.DELETABLE)) return true; + else if (name.startsWith(IndexFileNames.SEGMENTS)) return true; + } + return false; + } + + /** + * Returns true if this is a file that would be contained + * in a CFS file. This function should only be called on + * files that pass the above "accept" (ie, are already + * known to be a Lucene index file). + */ + public boolean isCFSFile(String name) { + int i = name.lastIndexOf('.'); + if (i != -1) { + String extension = name.substring(1+i); + if (extensionsInCFS.contains(extension)) { + return true; + } + if (extension.startsWith("f") && + extension.matches("f\\d+")) { + return true; + } + } + return false; + } + + public static IndexFileNameFilter getFilter() { + return singleton; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexFileNames.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexFileNames.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexFileNames.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,198 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Useful constants representing filenames and extensions used by lucene + * + * @version $rcs = ' $Id: IndexFileNames.java,v 1.1 2012/08/17 14:55:01 marcin Exp $ ' ; + */ +final class IndexFileNames { + + /** Name of the index segment file */ + static final String SEGMENTS = "segments"; + + /** Name of the generation reference file name */ + static final String SEGMENTS_GEN = "segments.gen"; + + /** Name of the index deletable file (only used in + * pre-lockless indices) */ + static final String DELETABLE = "deletable"; + + /** Extension of norms file */ + static final String NORMS_EXTENSION = "nrm"; + + /** Extension of freq postings file */ + static final String FREQ_EXTENSION = "frq"; + + /** Extension of prox postings file */ + static final String PROX_EXTENSION = "prx"; + + /** Extension of terms file */ + static final String TERMS_EXTENSION = "tis"; + + /** Extension of terms index file */ + static final String TERMS_INDEX_EXTENSION = "tii"; + + /** Extension of stored fields index file */ + static final String FIELDS_INDEX_EXTENSION = "fdx"; + + /** Extension of stored fields file */ + static final String FIELDS_EXTENSION = "fdt"; + + /** Extension of vectors fields file */ + static final String VECTORS_FIELDS_EXTENSION = "tvf"; + + /** Extension of vectors documents file */ + static final String VECTORS_DOCUMENTS_EXTENSION = "tvd"; + + /** Extension of vectors index file */ + static final String VECTORS_INDEX_EXTENSION = "tvx"; + + /** Extension of compound file */ + static final String COMPOUND_FILE_EXTENSION = "cfs"; + + /** Extension of compound file for doc store files*/ + static final String COMPOUND_FILE_STORE_EXTENSION = "cfx"; + + /** Extension of deletes */ + static final String DELETES_EXTENSION = "del"; + + /** Extension of field infos */ + static final String FIELD_INFOS_EXTENSION = "fnm"; + + /** Extension of plain norms */ + static final String PLAIN_NORMS_EXTENSION = "f"; + + /** Extension of separate norms */ + static final String SEPARATE_NORMS_EXTENSION = "s"; + + /** Extension of gen file */ + static final String GEN_EXTENSION = "gen"; + + /** + * This array contains all filename extensions used by + * Lucene's index files, with two exceptions, namely the + * extension made up from .f + a number and + * from .s + a number. Also note that + * Lucene's segments_N files do not have any + * filename extension. + */ + static final String INDEX_EXTENSIONS[] = new String[] { + COMPOUND_FILE_EXTENSION, + FIELD_INFOS_EXTENSION, + FIELDS_INDEX_EXTENSION, + FIELDS_EXTENSION, + TERMS_INDEX_EXTENSION, + TERMS_EXTENSION, + FREQ_EXTENSION, + PROX_EXTENSION, + DELETES_EXTENSION, + VECTORS_INDEX_EXTENSION, + VECTORS_DOCUMENTS_EXTENSION, + VECTORS_FIELDS_EXTENSION, + GEN_EXTENSION, + NORMS_EXTENSION, + COMPOUND_FILE_STORE_EXTENSION, + }; + + /** File extensions that are added to a compound file + * (same as above, minus "del", "gen", "cfs"). */ + static final String[] INDEX_EXTENSIONS_IN_COMPOUND_FILE = new String[] { + FIELD_INFOS_EXTENSION, + FIELDS_INDEX_EXTENSION, + FIELDS_EXTENSION, + TERMS_INDEX_EXTENSION, + TERMS_EXTENSION, + FREQ_EXTENSION, + PROX_EXTENSION, + VECTORS_INDEX_EXTENSION, + VECTORS_DOCUMENTS_EXTENSION, + VECTORS_FIELDS_EXTENSION, + NORMS_EXTENSION + }; + + static final String[] STORE_INDEX_EXTENSIONS = new String[] { + VECTORS_INDEX_EXTENSION, + VECTORS_FIELDS_EXTENSION, + VECTORS_DOCUMENTS_EXTENSION, + FIELDS_INDEX_EXTENSION, + FIELDS_EXTENSION + }; + + static final String[] NON_STORE_INDEX_EXTENSIONS = new String[] { + FIELD_INFOS_EXTENSION, + FREQ_EXTENSION, + PROX_EXTENSION, + TERMS_EXTENSION, + TERMS_INDEX_EXTENSION, + NORMS_EXTENSION + }; + + /** File extensions of old-style index files */ + static final String COMPOUND_EXTENSIONS[] = new String[] { + FIELD_INFOS_EXTENSION, + FREQ_EXTENSION, + PROX_EXTENSION, + FIELDS_INDEX_EXTENSION, + FIELDS_EXTENSION, + TERMS_INDEX_EXTENSION, + TERMS_EXTENSION + }; + + /** File extensions for term vector support */ + static final String VECTOR_EXTENSIONS[] = new String[] { + VECTORS_INDEX_EXTENSION, + VECTORS_DOCUMENTS_EXTENSION, + VECTORS_FIELDS_EXTENSION + }; + + /** + * Computes the full file name from base, extension and + * generation. If the generation is -1, the file name is + * null. If it's 0, the file name is . + * If it's > 0, the file name is _. + * + * @param base -- main part of the file name + * @param extension -- extension of the filename (including .) + * @param gen -- generation + */ + static final String fileNameFromGeneration(String base, String extension, long gen) { + if (gen == SegmentInfo.NO) { + return null; + } else if (gen == SegmentInfo.WITHOUT_GEN) { + return base + extension; + } else { + return base + "_" + Long.toString(gen, Character.MAX_RADIX) + extension; + } + } + + /** + * Returns true if the provided filename is one of the doc + * store files (ends with an extension in + * STORE_INDEX_EXTENSIONS). + */ + static final boolean isDocStoreFile(String fileName) { + if (fileName.endsWith(COMPOUND_FILE_STORE_EXTENSION)) + return true; + for(int i=0;i[Note that as of 2.1, all but one of the + * methods in this class are available via {@link + * IndexWriter}. The one method that is not available is + * {@link #deleteDocument(int)}.]

+ * + * A class to modify an index, i.e. to delete and add documents. This + * class hides {@link IndexReader} and {@link IndexWriter} so that you + * do not need to care about implementation details such as that adding + * documents is done via IndexWriter and deletion is done via IndexReader. + * + *

Note that you cannot create more than one IndexModifier object + * on the same directory at the same time. + * + *

Example usage: + * + + + + +

+ + + + + + +
+ +    Analyzer analyzer = new StandardAnalyzer();
+    // create an index in /tmp/index, overwriting an existing one:
+    IndexModifier indexModifier = new IndexModifier("/tmp/index", analyzer, true);
+    Document doc = new Document();
+    doc.add(new Field("id""1", Field.Store.YES, Field.Index.NOT_ANALYZED));
+    doc.add(new Field("body""a simple test", Field.Store.YES, Field.Index.ANALYZED));
+    indexModifier.addDocument(doc);
+    int deleted = indexModifier.delete(new Term("id""1"));
+    System.out.println("Deleted " + deleted + " document");
+    indexModifier.flush();
+    System.out.println(indexModifier.docCount() " docs in index");
+    indexModifier.close();
+ +
+
+ + + * + *

Not all methods of IndexReader and IndexWriter are offered by this + * class. If you need access to additional methods, either use those classes + * directly or implement your own class that extends IndexModifier. + * + *

Although an instance of this class can be used from more than one + * thread, you will not get the best performance. You might want to use + * IndexReader and IndexWriter directly for that (but you will need to + * care about synchronization yourself then). + * + *

While you can freely mix calls to add() and delete() using this class, + * you should batch you calls for best performance. For example, if you + * want to update 20 documents, you should first delete all those documents, + * then add all the new documents. + * + * @deprecated Please use {@link IndexWriter} instead. + */ +public class IndexModifier { + + protected IndexWriter indexWriter = null; + protected IndexReader indexReader = null; + + protected Directory directory = null; + protected Analyzer analyzer = null; + protected boolean open = false; + + // Lucene defaults: + protected PrintStream infoStream = null; + protected boolean useCompoundFile = true; + protected int maxBufferedDocs = IndexWriter.DEFAULT_MAX_BUFFERED_DOCS; + protected int maxFieldLength = IndexWriter.DEFAULT_MAX_FIELD_LENGTH; + protected int mergeFactor = IndexWriter.DEFAULT_MERGE_FACTOR; + + /** + * Open an index with write access. + * + * @param directory the index directory + * @param analyzer the analyzer to use for adding new documents + * @param create true to create the index or overwrite the existing one; + * false to append to the existing index + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public IndexModifier(Directory directory, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException { + init(directory, analyzer, create); + } + + /** + * Open an index with write access. + * + * @param dirName the index directory + * @param analyzer the analyzer to use for adding new documents + * @param create true to create the index or overwrite the existing one; + * false to append to the existing index + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public IndexModifier(String dirName, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException { + Directory dir = FSDirectory.getDirectory(dirName); + init(dir, analyzer, create); + } + + /** + * Open an index with write access. + * + * @param file the index directory + * @param analyzer the analyzer to use for adding new documents + * @param create true to create the index or overwrite the existing one; + * false to append to the existing index + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public IndexModifier(File file, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException { + Directory dir = FSDirectory.getDirectory(file); + init(dir, analyzer, create); + } + + /** + * Initialize an IndexWriter. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + protected void init(Directory directory, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException { + this.directory = directory; + synchronized(this.directory) { + this.analyzer = analyzer; + indexWriter = new IndexWriter(directory, analyzer, create, IndexWriter.MaxFieldLength.LIMITED); + open = true; + } + } + + /** + * Throw an IllegalStateException if the index is closed. + * @throws IllegalStateException + */ + protected void assureOpen() { + if (!open) { + throw new IllegalStateException("Index is closed"); + } + } + + /** + * Close the IndexReader and open an IndexWriter. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + protected void createIndexWriter() throws CorruptIndexException, LockObtainFailedException, IOException { + if (indexWriter == null) { + if (indexReader != null) { + indexReader.close(); + indexReader = null; + } + indexWriter = new IndexWriter(directory, analyzer, false, new IndexWriter.MaxFieldLength(maxFieldLength)); + // IndexModifier cannot use ConcurrentMergeScheduler + // because it synchronizes on the directory which can + // cause deadlock + indexWriter.setMergeScheduler(new SerialMergeScheduler()); + indexWriter.setInfoStream(infoStream); + indexWriter.setUseCompoundFile(useCompoundFile); + if (maxBufferedDocs != IndexWriter.DISABLE_AUTO_FLUSH) + indexWriter.setMaxBufferedDocs(maxBufferedDocs); + indexWriter.setMergeFactor(mergeFactor); + } + } + + /** + * Close the IndexWriter and open an IndexReader. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + protected void createIndexReader() throws CorruptIndexException, IOException { + if (indexReader == null) { + if (indexWriter != null) { + indexWriter.close(); + indexWriter = null; + } + indexReader = IndexReader.open(directory); + } + } + + /** + * Make sure all changes are written to disk. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public void flush() throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + if (indexWriter != null) { + indexWriter.close(); + indexWriter = null; + createIndexWriter(); + } else { + indexReader.close(); + indexReader = null; + createIndexReader(); + } + } + } + + /** + * Adds a document to this index, using the provided analyzer instead of the + * one specific in the constructor. If the document contains more than + * {@link #setMaxFieldLength(int)} terms for a given field, the remainder are + * discarded. + * @see IndexWriter#addDocument(Document, Analyzer) + * @throws IllegalStateException if the index is closed + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public void addDocument(Document doc, Analyzer docAnalyzer) throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexWriter(); + if (docAnalyzer != null) + indexWriter.addDocument(doc, docAnalyzer); + else + indexWriter.addDocument(doc); + } + } + + /** + * Adds a document to this index. If the document contains more than + * {@link #setMaxFieldLength(int)} terms for a given field, the remainder are + * discarded. + * @see IndexWriter#addDocument(Document) + * @throws IllegalStateException if the index is closed + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public void addDocument(Document doc) throws CorruptIndexException, LockObtainFailedException, IOException { + addDocument(doc, null); + } + + /** + * Deletes all documents containing term. + * This is useful if one uses a document field to hold a unique ID string for + * the document. Then to delete such a document, one merely constructs a + * term with the appropriate field and the unique ID string as its text and + * passes it to this method. Returns the number of documents deleted. + * @return the number of documents deleted + * @see IndexReader#deleteDocuments(Term) + * @throws IllegalStateException if the index is closed + * @throws StaleReaderException if the index has changed + * since this reader was opened + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public int deleteDocuments(Term term) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexReader(); + return indexReader.deleteDocuments(term); + } + } + + /** + * Deletes the document numbered docNum. + * @see IndexReader#deleteDocument(int) + * @throws StaleReaderException if the index has changed + * since this reader was opened + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IllegalStateException if the index is closed + */ + public void deleteDocument(int docNum) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexReader(); + indexReader.deleteDocument(docNum); + } + } + + + /** + * Returns the number of documents currently in this + * index. If the writer is currently open, this returns + * {@link IndexWriter#docCount()}, else {@link + * IndexReader#numDocs()}. But, note that {@link + * IndexWriter#docCount()} does not take deletions into + * account, unlike {@link IndexReader#numDocs}. + * @throws IllegalStateException if the index is closed + */ + public int docCount() { + synchronized(directory) { + assureOpen(); + if (indexWriter != null) { + return indexWriter.docCount(); + } else { + return indexReader.numDocs(); + } + } + } + + /** + * Merges all segments together into a single segment, optimizing an index + * for search. + * @see IndexWriter#optimize() + * @throws IllegalStateException if the index is closed + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public void optimize() throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexWriter(); + indexWriter.optimize(); + } + } + + /** + * If non-null, information about merges and a message when + * {@link #getMaxFieldLength()} is reached will be printed to this. + *

Example: index.setInfoStream(System.err); + * @see IndexWriter#setInfoStream(PrintStream) + * @throws IllegalStateException if the index is closed + */ + public void setInfoStream(PrintStream infoStream) { + synchronized(directory) { + assureOpen(); + if (indexWriter != null) { + indexWriter.setInfoStream(infoStream); + } + this.infoStream = infoStream; + } + } + + /** + * @see IndexModifier#setInfoStream(PrintStream) + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public PrintStream getInfoStream() throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexWriter(); + return indexWriter.getInfoStream(); + } + } + + /** + * Setting to turn on usage of a compound file. When on, multiple files + * for each segment are merged into a single file once the segment creation + * is finished. This is done regardless of what directory is in use. + * @see IndexWriter#setUseCompoundFile(boolean) + * @throws IllegalStateException if the index is closed + */ + public void setUseCompoundFile(boolean useCompoundFile) { + synchronized(directory) { + assureOpen(); + if (indexWriter != null) { + indexWriter.setUseCompoundFile(useCompoundFile); + } + this.useCompoundFile = useCompoundFile; + } + } + + /** + * @see IndexModifier#setUseCompoundFile(boolean) + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public boolean getUseCompoundFile() throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexWriter(); + return indexWriter.getUseCompoundFile(); + } + } + + /** + * The maximum number of terms that will be indexed for a single field in a + * document. This limits the amount of memory required for indexing, so that + * collections with very large files will not crash the indexing process by + * running out of memory.

+ * Note that this effectively truncates large documents, excluding from the + * index terms that occur further in the document. If you know your source + * documents are large, be sure to set this value high enough to accomodate + * the expected size. If you set it to Integer.MAX_VALUE, then the only limit + * is your memory, but you should anticipate an OutOfMemoryError.

+ * By default, no more than 10,000 terms will be indexed for a field. + * @see IndexWriter#setMaxFieldLength(int) + * @throws IllegalStateException if the index is closed + */ + public void setMaxFieldLength(int maxFieldLength) { + synchronized(directory) { + assureOpen(); + if (indexWriter != null) { + indexWriter.setMaxFieldLength(maxFieldLength); + } + this.maxFieldLength = maxFieldLength; + } + } + + /** + * @see IndexModifier#setMaxFieldLength(int) + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public int getMaxFieldLength() throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexWriter(); + return indexWriter.getMaxFieldLength(); + } + } + + /** + * Determines the minimal number of documents required before the buffered + * in-memory documents are merging and a new Segment is created. + * Since Documents are merged in a {@link org.apache.lucene.store.RAMDirectory}, + * large value gives faster indexing. At the same time, mergeFactor limits + * the number of files open in a FSDirectory. + * + *

The default value is 10. + * + * @see IndexWriter#setMaxBufferedDocs(int) + * @throws IllegalStateException if the index is closed + * @throws IllegalArgumentException if maxBufferedDocs is smaller than 2 + */ + public void setMaxBufferedDocs(int maxBufferedDocs) { + synchronized(directory) { + assureOpen(); + if (indexWriter != null) { + indexWriter.setMaxBufferedDocs(maxBufferedDocs); + } + this.maxBufferedDocs = maxBufferedDocs; + } + } + + /** + * @see IndexModifier#setMaxBufferedDocs(int) + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public int getMaxBufferedDocs() throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexWriter(); + return indexWriter.getMaxBufferedDocs(); + } + } + + /** + * Determines how often segment indices are merged by addDocument(). With + * smaller values, less RAM is used while indexing, and searches on + * unoptimized indices are faster, but indexing speed is slower. With larger + * values, more RAM is used during indexing, and while searches on unoptimized + * indices are slower, indexing is faster. Thus larger values (> 10) are best + * for batch index creation, and smaller values (< 10) for indices that are + * interactively maintained. + *

This must never be less than 2. The default value is 10. + * + * @see IndexWriter#setMergeFactor(int) + * @throws IllegalStateException if the index is closed + */ + public void setMergeFactor(int mergeFactor) { + synchronized(directory) { + assureOpen(); + if (indexWriter != null) { + indexWriter.setMergeFactor(mergeFactor); + } + this.mergeFactor = mergeFactor; + } + } + + /** + * @see IndexModifier#setMergeFactor(int) + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public int getMergeFactor() throws CorruptIndexException, LockObtainFailedException, IOException { + synchronized(directory) { + assureOpen(); + createIndexWriter(); + return indexWriter.getMergeFactor(); + } + } + + /** + * Close this index, writing all pending changes to disk. + * + * @throws IllegalStateException if the index has been closed before already + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void close() throws CorruptIndexException, IOException { + synchronized(directory) { + if (!open) + throw new IllegalStateException("Index is closed already"); + if (indexWriter != null) { + indexWriter.close(); + indexWriter = null; + } else if (indexReader != null) { + indexReader.close(); + indexReader = null; + } + open = false; + } + } + + public String toString() { + return "Index@" + directory; + } + + /* + // used as an example in the javadoc: + public static void main(String[] args) throws IOException { + Analyzer analyzer = new StandardAnalyzer(); + // create an index in /tmp/index, overwriting an existing one: + IndexModifier indexModifier = new IndexModifier("/tmp/index", analyzer, true); + Document doc = new Document(); + doc.add(new Fieldable("id", "1", Fieldable.Store.YES, Fieldable.Index.NOT_ANALYZED)); + doc.add(new Fieldable("body", "a simple test", Fieldable.Store.YES, Fieldable.Index.ANALYZED)); + indexModifier.addDocument(doc); + int deleted = indexModifier.delete(new Term("id", "1")); + System.out.println("Deleted " + deleted + " document"); + indexModifier.flush(); + System.out.println(indexModifier.docCount() + " docs in index"); + indexModifier.close(); + }*/ + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexReader.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,1106 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.search.Similarity; +import org.apache.lucene.store.*; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; + +/** IndexReader is an abstract class, providing an interface for accessing an + index. Search of an index is done entirely through this abstract interface, + so that any subclass which implements it is searchable. + +

Concrete subclasses of IndexReader are usually constructed with a call to + one of the static open() methods, e.g. {@link #open(String)}. + +

For efficiency, in this API documents are often referred to via + document numbers, non-negative integers which each name a unique + document in the index. These document numbers are ephemeral--they may change + as documents are added to and deleted from an index. Clients should thus not + rely on a given document having the same number between sessions. + +

An IndexReader can be opened on a directory for which an IndexWriter is + opened already, but it cannot be used to delete documents from the index then. + +

+ NOTE: for backwards API compatibility, several methods are not listed + as abstract, but have no useful implementations in this base class and + instead always throw UnsupportedOperationException. Subclasses are + strongly encouraged to override these methods, but in many cases may not + need to. +

+ +

+ + NOTE: as of 2.4, it's possible to open a read-only + IndexReader using one of the static open methods that + accepts the boolean readOnly parameter. Such a reader has + better concurrency as it's not necessary to synchronize on + the isDeleted method. Currently the default for readOnly + is false, meaning if not specified you will get a + read/write IndexReader. But in 3.0 this default will + change to true, meaning you must explicitly specify false + if you want to make changes with the resulting IndexReader. +

+ + @version $Id: IndexReader.java,v 1.1 2012/08/17 14:55:03 marcin Exp $ +*/ +public abstract class IndexReader { + + // NOTE: in 3.0 this will change to true + final static boolean READ_ONLY_DEFAULT = false; + + /** + * Constants describing field properties, for example used for + * {@link IndexReader#getFieldNames(FieldOption)}. + */ + public static final class FieldOption { + private String option; + private FieldOption() { } + private FieldOption(String option) { + this.option = option; + } + public String toString() { + return this.option; + } + /** All fields */ + public static final FieldOption ALL = new FieldOption ("ALL"); + /** All indexed fields */ + public static final FieldOption INDEXED = new FieldOption ("INDEXED"); + /** All fields that store payloads */ + public static final FieldOption STORES_PAYLOADS = new FieldOption ("STORES_PAYLOADS"); + /** All fields that omit tf */ + public static final FieldOption OMIT_TF = new FieldOption ("OMIT_TF"); + /** All fields which are not indexed */ + public static final FieldOption UNINDEXED = new FieldOption ("UNINDEXED"); + /** All fields which are indexed with termvectors enabled */ + public static final FieldOption INDEXED_WITH_TERMVECTOR = new FieldOption ("INDEXED_WITH_TERMVECTOR"); + /** All fields which are indexed but don't have termvectors enabled */ + public static final FieldOption INDEXED_NO_TERMVECTOR = new FieldOption ("INDEXED_NO_TERMVECTOR"); + /** All fields with termvectors enabled. Please note that only standard termvector fields are returned */ + public static final FieldOption TERMVECTOR = new FieldOption ("TERMVECTOR"); + /** All fields with termvectors with position values enabled */ + public static final FieldOption TERMVECTOR_WITH_POSITION = new FieldOption ("TERMVECTOR_WITH_POSITION"); + /** All fields with termvectors with offset values enabled */ + public static final FieldOption TERMVECTOR_WITH_OFFSET = new FieldOption ("TERMVECTOR_WITH_OFFSET"); + /** All fields with termvectors with offset values and position values enabled */ + public static final FieldOption TERMVECTOR_WITH_POSITION_OFFSET = new FieldOption ("TERMVECTOR_WITH_POSITION_OFFSET"); + } + + private boolean closed; + protected boolean hasChanges; + + private volatile int refCount; + + // for testing + synchronized int getRefCount() { + return refCount; + } + + /** + * Expert: increments the refCount of this IndexReader + * instance. RefCounts are used to determine when a + * reader can be closed safely, i.e. as soon as there are + * no more references. Be sure to always call a + * corresponding {@link #decRef}, in a finally clause; + * otherwise the reader may never be closed. Note that + * {@link #close} simply calls decRef(), which means that + * the IndexReader will not really be closed until {@link + * #decRef} has been called for all outstanding + * references. + * + * @see #decRef + */ + public synchronized void incRef() { + assert refCount > 0; + ensureOpen(); + refCount++; + } + + /** + * Expert: decreases the refCount of this IndexReader + * instance. If the refCount drops to 0, then pending + * changes (if any) are committed to the index and this + * reader is closed. + * + * @throws IOException in case an IOException occurs in commit() or doClose() + * + * @see #incRef + */ + public synchronized void decRef() throws IOException { + assert refCount > 0; + ensureOpen(); + if (refCount == 1) { + commit(); + doClose(); + } + refCount--; + } + + /** + * @deprecated will be deleted when IndexReader(Directory) is deleted + * @see #directory() + */ + private Directory directory; + + /** + * Legacy Constructor for backwards compatibility. + * + *

+ * This Constructor should not be used, it exists for backwards + * compatibility only to support legacy subclasses that did not "own" + * a specific directory, but needed to specify something to be returned + * by the directory() method. Future subclasses should delegate to the + * no arg constructor and implement the directory() method as appropriate. + * + * @param directory Directory to be returned by the directory() method + * @see #directory() + * @deprecated - use IndexReader() + */ + protected IndexReader(Directory directory) { + this(); + this.directory = directory; + } + + protected IndexReader() { + refCount = 1; + } + + /** + * @throws AlreadyClosedException if this IndexReader is closed + */ + protected final void ensureOpen() throws AlreadyClosedException { + if (refCount <= 0) { + throw new AlreadyClosedException("this IndexReader is closed"); + } + } + + /** Returns a read/write IndexReader reading the index in an FSDirectory in the named + path. NOTE: starting in 3.0 this will return a readOnly IndexReader. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + * @param path the path to the index directory */ + public static IndexReader open(String path) throws CorruptIndexException, IOException { + return open(FSDirectory.getDirectory(path), true, null, null, READ_ONLY_DEFAULT); + } + + /** Returns a read/write IndexReader reading the index in an FSDirectory in the named + * path. NOTE: starting in 3.0 this will return a readOnly IndexReader. + * @param path the path to the index directory + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(File path) throws CorruptIndexException, IOException { + return open(FSDirectory.getDirectory(path), true, null, null, READ_ONLY_DEFAULT); + } + + /** Returns a read/write IndexReader reading the index in + * the given Directory. NOTE: starting in 3.0 this + * will return a readOnly IndexReader. + * @param directory the index directory + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(final Directory directory) throws CorruptIndexException, IOException { + return open(directory, false, null, null, READ_ONLY_DEFAULT); + } + + /** Returns a read/write or read only IndexReader reading the index in the given Directory. + * @param directory the index directory + * @param readOnly true if no changes (deletions, norms) will be made with this IndexReader + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(final Directory directory, boolean readOnly) throws CorruptIndexException, IOException { + return open(directory, false, null, null, readOnly); + } + + /** Expert: returns a read/write IndexReader reading the index in the given + * {@link IndexCommit}. NOTE: starting in 3.0 this + * will return a readOnly IndexReader. + * @param commit the commit point to open + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(final IndexCommit commit) throws CorruptIndexException, IOException { + return open(commit.getDirectory(), false, null, commit, READ_ONLY_DEFAULT); + } + + /** Expert: returns a read/write IndexReader reading the index in the given + * Directory, with a custom {@link IndexDeletionPolicy}. + * NOTE: starting in 3.0 this will return a + * readOnly IndexReader. + * @param directory the index directory + * @param deletionPolicy a custom deletion policy (only used + * if you use this reader to perform deletes or to set + * norms); see {@link IndexWriter} for details. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(final Directory directory, IndexDeletionPolicy deletionPolicy) throws CorruptIndexException, IOException { + return open(directory, false, deletionPolicy, null, READ_ONLY_DEFAULT); + } + + /** Expert: returns a read/write or read only IndexReader reading the index in the given + * Directory, with a custom {@link IndexDeletionPolicy}. + * NOTE: starting in 3.0 this will return a + * readOnly IndexReader. + * @param directory the index directory + * @param deletionPolicy a custom deletion policy (only used + * if you use this reader to perform deletes or to set + * norms); see {@link IndexWriter} for details. + * @param readOnly true if no changes (deletions, norms) will be made with this IndexReader + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(final Directory directory, IndexDeletionPolicy deletionPolicy, boolean readOnly) throws CorruptIndexException, IOException { + return open(directory, false, deletionPolicy, null, readOnly); + } + + /** Expert: returns a read/write IndexReader reading the index in the given + * Directory, using a specific commit and with a custom + * {@link IndexDeletionPolicy}. NOTE: starting in + * 3.0 this will return a readOnly IndexReader. + * @param commit the specific {@link IndexCommit} to open; + * see {@link IndexReader#listCommits} to list all commits + * in a directory + * @param deletionPolicy a custom deletion policy (only used + * if you use this reader to perform deletes or to set + * norms); see {@link IndexWriter} for details. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(final IndexCommit commit, IndexDeletionPolicy deletionPolicy) throws CorruptIndexException, IOException { + return open(commit.getDirectory(), false, deletionPolicy, commit, READ_ONLY_DEFAULT); + } + + /** Expert: returns a read/write or read only IndexReader reading the index in the given + * Directory, using a specific commit and with a custom {@link IndexDeletionPolicy}. + * @param commit the specific {@link IndexCommit} to open; + * see {@link IndexReader#listCommits} to list all commits + * in a directory + * @param deletionPolicy a custom deletion policy (only used + * if you use this reader to perform deletes or to set + * norms); see {@link IndexWriter} for details. + * @param readOnly true if no changes (deletions, norms) will be made with this IndexReader + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static IndexReader open(final IndexCommit commit, IndexDeletionPolicy deletionPolicy, boolean readOnly) throws CorruptIndexException, IOException { + return open(commit.getDirectory(), false, deletionPolicy, commit, readOnly); + } + + private static IndexReader open(final Directory directory, final boolean closeDirectory, final IndexDeletionPolicy deletionPolicy, final IndexCommit commit, final boolean readOnly) throws CorruptIndexException, IOException { + return DirectoryIndexReader.open(directory, closeDirectory, deletionPolicy, commit, readOnly); + } + + /** + * Refreshes an IndexReader if the index has changed since this instance + * was (re)opened. + *

+ * Opening an IndexReader is an expensive operation. This method can be used + * to refresh an existing IndexReader to reduce these costs. This method + * tries to only load segments that have changed or were created after the + * IndexReader was (re)opened. + *

+ * If the index has not changed since this instance was (re)opened, then this + * call is a NOOP and returns this instance. Otherwise, a new instance is + * returned. The old instance is not closed and remains usable.
+ * Note: The re-opened reader instance and the old instance might share + * the same resources. For this reason no index modification operations + * (e. g. {@link #deleteDocument(int)}, {@link #setNorm(int, String, byte)}) + * should be performed using one of the readers until the old reader instance + * is closed. Otherwise, the behavior of the readers is undefined. + *

+ * You can determine whether a reader was actually reopened by comparing the + * old instance with the instance returned by this method: + *

+   * IndexReader reader = ... 
+   * ...
+   * IndexReader new = r.reopen();
+   * if (new != reader) {
+   *   ...     // reader was reopened
+   *   reader.close(); 
+   * }
+   * reader = new;
+   * ...
+   * 
+ * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public synchronized IndexReader reopen() throws CorruptIndexException, IOException { + throw new UnsupportedOperationException("This reader does not support reopen()."); + } + + /** + * Returns the directory associated with this index. The Default + * implementation returns the directory specified by subclasses when + * delegating to the IndexReader(Directory) constructor, or throws an + * UnsupportedOperationException if one was not specified. + * @throws UnsupportedOperationException if no directory + */ + public Directory directory() { + ensureOpen(); + if (null != directory) { + return directory; + } else { + throw new UnsupportedOperationException("This reader does not support this method."); + } + } + + /** + * Returns the time the index in the named directory was last modified. + * Do not use this to check whether the reader is still up-to-date, use + * {@link #isCurrent()} instead. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static long lastModified(String directory) throws CorruptIndexException, IOException { + return lastModified(new File(directory)); + } + + /** + * Returns the time the index in the named directory was last modified. + * Do not use this to check whether the reader is still up-to-date, use + * {@link #isCurrent()} instead. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static long lastModified(File fileDirectory) throws CorruptIndexException, IOException { + return ((Long) new SegmentInfos.FindSegmentsFile(fileDirectory) { + public Object doBody(String segmentFileName) { + return new Long(FSDirectory.fileModified(fileDirectory, segmentFileName)); + } + }.run()).longValue(); + } + + /** + * Returns the time the index in the named directory was last modified. + * Do not use this to check whether the reader is still up-to-date, use + * {@link #isCurrent()} instead. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static long lastModified(final Directory directory2) throws CorruptIndexException, IOException { + return ((Long) new SegmentInfos.FindSegmentsFile(directory2) { + public Object doBody(String segmentFileName) throws IOException { + return new Long(directory2.fileModified(segmentFileName)); + } + }.run()).longValue(); + } + + /** + * Reads version number from segments files. The version number is + * initialized with a timestamp and then increased by one for each change of + * the index. + * + * @param directory where the index resides. + * @return version number. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static long getCurrentVersion(String directory) throws CorruptIndexException, IOException { + return getCurrentVersion(new File(directory)); + } + + /** + * Reads version number from segments files. The version number is + * initialized with a timestamp and then increased by one for each change of + * the index. + * + * @param directory where the index resides. + * @return version number. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static long getCurrentVersion(File directory) throws CorruptIndexException, IOException { + Directory dir = FSDirectory.getDirectory(directory); + long version = getCurrentVersion(dir); + dir.close(); + return version; + } + + /** + * Reads version number from segments files. The version number is + * initialized with a timestamp and then increased by one for each change of + * the index. + * + * @param directory where the index resides. + * @return version number. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static long getCurrentVersion(Directory directory) throws CorruptIndexException, IOException { + return SegmentInfos.readCurrentVersion(directory); + } + + /** + * Version number when this IndexReader was opened. Not implemented in the IndexReader base class. + * @throws UnsupportedOperationException unless overridden in subclass + */ + public long getVersion() { + throw new UnsupportedOperationException("This reader does not support this method."); + } + + /**

For IndexReader implementations that use + * TermInfosReader to read terms, this sets the + * indexDivisor to subsample the number of indexed terms + * loaded into memory. This has the same effect as {@link + * IndexWriter#setTermIndexInterval} except that setting + * must be done at indexing time while this setting can be + * set per reader. When set to N, then one in every + * N*termIndexInterval terms in the index is loaded into + * memory. By setting this to a value > 1 you can reduce + * memory usage, at the expense of higher latency when + * loading a TermInfo. The default value is 1.

+ * + * NOTE: you must call this before the term + * index is loaded. If the index is already loaded, + * an IllegalStateException is thrown. + * @throws IllegalStateException if the term index has already been loaded into memory + */ + public void setTermInfosIndexDivisor(int indexDivisor) throws IllegalStateException { + throw new UnsupportedOperationException("This reader does not support this method."); + } + + /**

For IndexReader implementations that use + * TermInfosReader to read terms, this returns the + * current indexDivisor. + * @see #setTermInfosIndexDivisor */ + public int getTermInfosIndexDivisor() { + throw new UnsupportedOperationException("This reader does not support this method."); + } + + /** + * Check whether this IndexReader is still using the + * current (i.e., most recently committed) version of the + * index. If a writer has committed any changes to the + * index since this reader was opened, this will return + * false, in which case you must open a new + * IndexReader in order to see the changes. See the + * description of the autoCommit + * flag which controls when the {@link IndexWriter} + * actually commits changes to the index. + * + *

+ * Not implemented in the IndexReader base class. + *

+ * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + * @throws UnsupportedOperationException unless overridden in subclass + */ + public boolean isCurrent() throws CorruptIndexException, IOException { + throw new UnsupportedOperationException("This reader does not support this method."); + } + + /** + * Checks is the index is optimized (if it has a single segment and + * no deletions). Not implemented in the IndexReader base class. + * @return true if the index is optimized; false otherwise + * @throws UnsupportedOperationException unless overridden in subclass + */ + public boolean isOptimized() { + throw new UnsupportedOperationException("This reader does not support this method."); + } + + /** + * Return an array of term frequency vectors for the specified document. + * The array contains a vector for each vectorized field in the document. + * Each vector contains terms and frequencies for all terms in a given vectorized field. + * If no such fields existed, the method returns null. The term vectors that are + * returned my either be of type TermFreqVector or of type TermPositionsVector if + * positions or offsets have been stored. + * + * @param docNumber document for which term frequency vectors are returned + * @return array of term frequency vectors. May be null if no term vectors have been + * stored for the specified document. + * @throws IOException if index cannot be accessed + * @see org.apache.lucene.document.Field.TermVector + */ + abstract public TermFreqVector[] getTermFreqVectors(int docNumber) + throws IOException; + + + /** + * Return a term frequency vector for the specified document and field. The + * returned vector contains terms and frequencies for the terms in + * the specified field of this document, if the field had the storeTermVector + * flag set. If termvectors had been stored with positions or offsets, a + * TermPositionsVector is returned. + * + * @param docNumber document for which the term frequency vector is returned + * @param field field for which the term frequency vector is returned. + * @return term frequency vector May be null if field does not exist in the specified + * document or term vector was not stored. + * @throws IOException if index cannot be accessed + * @see org.apache.lucene.document.Field.TermVector + */ + abstract public TermFreqVector getTermFreqVector(int docNumber, String field) + throws IOException; + + /** + * Load the Term Vector into a user-defined data structure instead of relying on the parallel arrays of + * the {@link TermFreqVector}. + * @param docNumber The number of the document to load the vector for + * @param field The name of the field to load + * @param mapper The {@link TermVectorMapper} to process the vector. Must not be null + * @throws IOException if term vectors cannot be accessed or if they do not exist on the field and doc. specified. + * + */ + abstract public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException; + + /** + * Map all the term vectors for all fields in a Document + * @param docNumber The number of the document to load the vector for + * @param mapper The {@link TermVectorMapper} to process the vector. Must not be null + * @throws IOException if term vectors cannot be accessed or if they do not exist on the field and doc. specified. + */ + abstract public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException; + + /** + * Returns true if an index exists at the specified directory. + * If the directory does not exist or if there is no index in it. + * false is returned. + * @param directory the directory to check for an index + * @return true if an index exists; false otherwise + */ + public static boolean indexExists(String directory) { + return indexExists(new File(directory)); + } + + /** + * Returns true if an index exists at the specified directory. + * If the directory does not exist or if there is no index in it. + * @param directory the directory to check for an index + * @return true if an index exists; false otherwise + */ + + public static boolean indexExists(File directory) { + return SegmentInfos.getCurrentSegmentGeneration(directory.list()) != -1; + } + + /** + * Returns true if an index exists at the specified directory. + * If the directory does not exist or if there is no index in it. + * @param directory the directory to check for an index + * @return true if an index exists; false otherwise + * @throws IOException if there is a problem with accessing the index + */ + public static boolean indexExists(Directory directory) throws IOException { + return SegmentInfos.getCurrentSegmentGeneration(directory) != -1; + } + + /** Returns the number of documents in this index. */ + public abstract int numDocs(); + + /** Returns one greater than the largest possible document number. + * This may be used to, e.g., determine how big to allocate an array which + * will have an element for every document number in an index. + */ + public abstract int maxDoc(); + + /** Returns the number of deleted documents. */ + public int numDeletedDocs() { + return maxDoc() - numDocs(); + } + + /** Returns the stored fields of the nth + Document in this index. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public Document document(int n) throws CorruptIndexException, IOException { + ensureOpen(); + return document(n, null); + } + + /** + * Get the {@link org.apache.lucene.document.Document} at the nth position. The {@link org.apache.lucene.document.FieldSelector} + * may be used to determine what {@link org.apache.lucene.document.Field}s to load and how they should be loaded. + * + * NOTE: If this Reader (more specifically, the underlying FieldsReader) is closed before the lazy {@link org.apache.lucene.document.Field} is + * loaded an exception may be thrown. If you want the value of a lazy {@link org.apache.lucene.document.Field} to be available after closing you must + * explicitly load it or fetch the Document again with a new loader. + * + * + * @param n Get the document at the nth position + * @param fieldSelector The {@link org.apache.lucene.document.FieldSelector} to use to determine what Fields should be loaded on the Document. May be null, in which case all Fields will be loaded. + * @return The stored fields of the {@link org.apache.lucene.document.Document} at the nth position + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + * + * @see org.apache.lucene.document.Fieldable + * @see org.apache.lucene.document.FieldSelector + * @see org.apache.lucene.document.SetBasedFieldSelector + * @see org.apache.lucene.document.LoadFirstFieldSelector + */ + //When we convert to JDK 1.5 make this Set + public abstract Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException; + + + + /** Returns true if document n has been deleted */ + public abstract boolean isDeleted(int n); + + /** Returns true if any documents have been deleted */ + public abstract boolean hasDeletions(); + + /** Returns true if there are norms stored for this field. */ + public boolean hasNorms(String field) throws IOException { + // backward compatible implementation. + // SegmentReader has an efficient implementation. + ensureOpen(); + return norms(field) != null; + } + + /** Returns the byte-encoded normalization factor for the named field of + * every document. This is used by the search code to score documents. + * + * @see org.apache.lucene.document.Field#setBoost(float) + */ + public abstract byte[] norms(String field) throws IOException; + + /** Reads the byte-encoded normalization factor for the named field of every + * document. This is used by the search code to score documents. + * + * @see org.apache.lucene.document.Field#setBoost(float) + */ + public abstract void norms(String field, byte[] bytes, int offset) + throws IOException; + + /** Expert: Resets the normalization factor for the named field of the named + * document. The norm represents the product of the field's {@link + * org.apache.lucene.document.Fieldable#setBoost(float) boost} and its {@link Similarity#lengthNorm(String, + * int) length normalization}. Thus, to preserve the length normalization + * values when resetting this, one should base the new value upon the old. + * + * @see #norms(String) + * @see Similarity#decodeNorm(byte) + * @throws StaleReaderException if the index has changed + * since this reader was opened + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public synchronized void setNorm(int doc, String field, byte value) + throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + ensureOpen(); + acquireWriteLock(); + hasChanges = true; + doSetNorm(doc, field, value); + } + + /** Implements setNorm in subclass.*/ + protected abstract void doSetNorm(int doc, String field, byte value) + throws CorruptIndexException, IOException; + + /** Expert: Resets the normalization factor for the named field of the named + * document. + * + * @see #norms(String) + * @see Similarity#decodeNorm(byte) + * + * @throws StaleReaderException if the index has changed + * since this reader was opened + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public void setNorm(int doc, String field, float value) + throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + ensureOpen(); + setNorm(doc, field, Similarity.encodeNorm(value)); + } + + /** Returns an enumeration of all the terms in the index. The + * enumeration is ordered by Term.compareTo(). Each term is greater + * than all that precede it in the enumeration. Note that after + * calling terms(), {@link TermEnum#next()} must be called + * on the resulting enumeration before calling other methods such as + * {@link TermEnum#term()}. + * @throws IOException if there is a low-level IO error + */ + public abstract TermEnum terms() throws IOException; + + /** Returns an enumeration of all terms starting at a given term. If + * the given term does not exist, the enumeration is positioned at the + * first term greater than the supplied term. The enumeration is + * ordered by Term.compareTo(). Each term is greater than all that + * precede it in the enumeration. + * @throws IOException if there is a low-level IO error + */ + public abstract TermEnum terms(Term t) throws IOException; + + /** Returns the number of documents containing the term t. + * @throws IOException if there is a low-level IO error + */ + public abstract int docFreq(Term t) throws IOException; + + /** Returns an enumeration of all the documents which contain + * term. For each document, the document number, the frequency of + * the term in that document is also provided, for use in search scoring. + * Thus, this method implements the mapping: + *

    + * Term    =>    <docNum, freq>* + *
+ *

The enumeration is ordered by document number. Each document number + * is greater than all that precede it in the enumeration. + * @throws IOException if there is a low-level IO error + */ + public TermDocs termDocs(Term term) throws IOException { + ensureOpen(); + TermDocs termDocs = termDocs(); + termDocs.seek(term); + return termDocs; + } + + /** Returns an unpositioned {@link TermDocs} enumerator. + * @throws IOException if there is a low-level IO error + */ + public abstract TermDocs termDocs() throws IOException; + + /** Returns an enumeration of all the documents which contain + * term. For each document, in addition to the document number + * and frequency of the term in that document, a list of all of the ordinal + * positions of the term in the document is available. Thus, this method + * implements the mapping: + * + *

    + * Term    =>    <docNum, freq, + * <pos1, pos2, ... + * posfreq-1> + * >* + *
+ *

This positional information facilitates phrase and proximity searching. + *

The enumeration is ordered by document number. Each document number is + * greater than all that precede it in the enumeration. + * @throws IOException if there is a low-level IO error + */ + public TermPositions termPositions(Term term) throws IOException { + ensureOpen(); + TermPositions termPositions = termPositions(); + termPositions.seek(term); + return termPositions; + } + + /** Returns an unpositioned {@link TermPositions} enumerator. + * @throws IOException if there is a low-level IO error + */ + public abstract TermPositions termPositions() throws IOException; + + + + /** Deletes the document numbered docNum. Once a document is + * deleted it will not appear in TermDocs or TermPostitions enumerations. + * Attempts to read its field with the {@link #document} + * method will result in an error. The presence of this document may still be + * reflected in the {@link #docFreq} statistic, though + * this will be corrected eventually as the index is further modified. + * + * @throws StaleReaderException if the index has changed + * since this reader was opened + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public synchronized void deleteDocument(int docNum) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + ensureOpen(); + acquireWriteLock(); + hasChanges = true; + doDelete(docNum); + } + + + /** Implements deletion of the document numbered docNum. + * Applications should call {@link #deleteDocument(int)} or {@link #deleteDocuments(Term)}. + */ + protected abstract void doDelete(int docNum) throws CorruptIndexException, IOException; + + + /** Deletes all documents that have a given term indexed. + * This is useful if one uses a document field to hold a unique ID string for + * the document. Then to delete such a document, one merely constructs a + * term with the appropriate field and the unique ID string as its text and + * passes it to this method. + * See {@link #deleteDocument(int)} for information about when this deletion will + * become effective. + * + * @return the number of documents deleted + * @throws StaleReaderException if the index has changed + * since this reader was opened + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if there is a low-level IO error + */ + public int deleteDocuments(Term term) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + ensureOpen(); + TermDocs docs = termDocs(term); + if (docs == null) return 0; + int n = 0; + try { + while (docs.next()) { + deleteDocument(docs.doc()); + n++; + } + } finally { + docs.close(); + } + return n; + } + + /** Undeletes all documents currently marked as deleted in this index. + * + * @throws StaleReaderException if the index has changed + * since this reader was opened + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public synchronized void undeleteAll() throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException { + ensureOpen(); + acquireWriteLock(); + hasChanges = true; + doUndeleteAll(); + } + + /** Implements actual undeleteAll() in subclass. */ + protected abstract void doUndeleteAll() throws CorruptIndexException, IOException; + + /** Does nothing by default. Subclasses that require a write lock for + * index modifications must implement this method. */ + protected synchronized void acquireWriteLock() throws IOException { + /* NOOP */ + } + + /** + * + * @throws IOException + */ + public final synchronized void flush() throws IOException { + ensureOpen(); + commit(); + } + + /** + * Commit changes resulting from delete, undeleteAll, or + * setNorm operations + * + * If an exception is hit, then either no changes or all + * changes will have been committed to the index + * (transactional semantics). + * @throws IOException if there is a low-level IO error + */ + protected final synchronized void commit() throws IOException { + if(hasChanges){ + doCommit(); + } + hasChanges = false; + } + + /** Implements commit. */ + protected abstract void doCommit() throws IOException; + + /** + * Closes files associated with this index. + * Also saves any new deletions to disk. + * No other methods should be called after this has been called. + * @throws IOException if there is a low-level IO error + */ + public final synchronized void close() throws IOException { + if (!closed) { + decRef(); + closed = true; + } + } + + /** Implements close. */ + protected abstract void doClose() throws IOException; + + + /** + * Get a list of unique field names that exist in this index and have the specified + * field option information. + * @param fldOption specifies which field option should be available for the returned fields + * @return Collection of Strings indicating the names of the fields. + * @see IndexReader.FieldOption + */ + public abstract Collection getFieldNames(FieldOption fldOption); + + /** + * Returns true iff the index in the named directory is + * currently locked. + * @param directory the directory to check for a lock + * @throws IOException if there is a low-level IO error + * @deprecated Please use {@link IndexWriter#isLocked(Directory)} instead + */ + public static boolean isLocked(Directory directory) throws IOException { + return + directory.makeLock(IndexWriter.WRITE_LOCK_NAME).isLocked(); + } + + /** + * Returns true iff the index in the named directory is + * currently locked. + * @param directory the directory to check for a lock + * @throws IOException if there is a low-level IO error + * @deprecated Please use {@link IndexWriter#isLocked(String)} instead + */ + public static boolean isLocked(String directory) throws IOException { + Directory dir = FSDirectory.getDirectory(directory); + boolean result = isLocked(dir); + dir.close(); + return result; + } + + /** + * Forcibly unlocks the index in the named directory. + *

+ * Caution: this should only be used by failure recovery code, + * when it is known that no other process nor thread is in fact + * currently accessing this index. + * @deprecated Please use {@link IndexWriter#unlock(Directory)} instead + */ + public static void unlock(Directory directory) throws IOException { + directory.makeLock(IndexWriter.WRITE_LOCK_NAME).release(); + } + + /** + * Expert: return the IndexCommit that this reader has + * opened. This method is only implemented by those + * readers that correspond to a Directory with its own + * segments_N file. + * + *

WARNING: this API is new and experimental and + * may suddenly change.

+ */ + public IndexCommit getIndexCommit() throws IOException { + throw new UnsupportedOperationException("This reader does not support this method."); + } + + /** + * Prints the filename and size of each file within a given compound file. + * Add the -extract flag to extract files to the current working directory. + * In order to make the extracted version of the index work, you have to copy + * the segments file from the compound index into the directory where the extracted files are stored. + * @param args Usage: org.apache.lucene.index.IndexReader [-extract] <cfsfile> + */ + public static void main(String [] args) { + String filename = null; + boolean extract = false; + + for (int i = 0; i < args.length; ++i) { + if (args[i].equals("-extract")) { + extract = true; + } else if (filename == null) { + filename = args[i]; + } + } + + if (filename == null) { + System.out.println("Usage: org.apache.lucene.index.IndexReader [-extract] "); + return; + } + + Directory dir = null; + CompoundFileReader cfr = null; + + try { + File file = new File(filename); + String dirname = file.getAbsoluteFile().getParent(); + filename = file.getName(); + dir = FSDirectory.getDirectory(dirname); + cfr = new CompoundFileReader(dir, filename); + + String [] files = cfr.list(); + Arrays.sort(files); // sort the array of filename so that the output is more readable + + for (int i = 0; i < files.length; ++i) { + long len = cfr.fileLength(files[i]); + + if (extract) { + System.out.println("extract " + files[i] + " with " + len + " bytes to local directory..."); + IndexInput ii = cfr.openInput(files[i]); + + FileOutputStream f = new FileOutputStream(files[i]); + + // read and write with a small buffer, which is more effectiv than reading byte by byte + byte[] buffer = new byte[1024]; + int chunk = buffer.length; + while(len > 0) { + final int bufLen = (int) Math.min(chunk, len); + ii.readBytes(buffer, 0, bufLen); + f.write(buffer, 0, bufLen); + len -= bufLen; + } + + f.close(); + ii.close(); + } + else + System.out.println(files[i] + ": " + len + " bytes"); + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + finally { + try { + if (dir != null) + dir.close(); + if (cfr != null) + cfr.close(); + } + catch (IOException ioe) { + ioe.printStackTrace(); + } + } + } + + /** Returns all commit points that exist in the Directory. + * Normally, because the default is {@link + * KeepOnlyLastCommitDeletionPolicy}, there would be only + * one commit point. But if you're using a custom {@link + * IndexDeletionPolicy} then there could be many commits. + * Once you have a given commit, you can open a reader on + * it by calling {@link IndexReader#open(IndexCommit)} + * There must be at least one commit in + * the Directory, else this method throws {@link + * java.io.IOException}. Note that if a commit is in + * progress while this method is running, that commit + * may or may not be returned array. */ + public static Collection listCommits(Directory dir) throws IOException { + return DirectoryIndexReader.listCommits(dir); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IndexWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IndexWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IndexWriter.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,4772 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.search.Similarity; +import org.apache.lucene.search.Query; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.FSDirectory; +import org.apache.lucene.store.Lock; +import org.apache.lucene.store.LockObtainFailedException; +import org.apache.lucene.store.AlreadyClosedException; +import org.apache.lucene.util.BitVector; +import org.apache.lucene.util.Constants; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.util.List; +import java.util.Collection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Set; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Iterator; + +/** + An IndexWriter creates and maintains an index. + +

The create argument to the + constructor + determines whether a new index is created, or whether an existing index is + opened. Note that you + can open an index with create=true even while readers are + using the index. The old readers will continue to search + the "point in time" snapshot they had opened, and won't + see the newly created index until they re-open. There are + also constructors + with no create argument which + will create a new index if there is not already an index at the + provided path and otherwise open the existing index.

+ +

In either case, documents are added with addDocument + and removed with deleteDocuments(Term) + or deleteDocuments(Query). + A document can be updated with updateDocument + (which just deletes and then adds the entire document). + When finished adding, deleting and updating documents, close should be called.

+ + +

These changes are buffered in memory and periodically + flushed to the {@link Directory} (during the above method + calls). A flush is triggered when there are enough + buffered deletes (see {@link #setMaxBufferedDeleteTerms}) + or enough added documents since the last flush, whichever + is sooner. For the added documents, flushing is triggered + either by RAM usage of the documents (see {@link + #setRAMBufferSizeMB}) or the number of added documents. + The default is to flush when RAM usage hits 16 MB. For + best indexing speed you should flush by RAM usage with a + large RAM buffer. Note that flushing just moves the + internal buffered state in IndexWriter into the index, but + these changes are not visible to IndexReader until either + {@link #commit()} or {@link #close} is called. A flush may + also trigger one or more segment merges which by default + run with a background thread so as not to block the + addDocument calls (see below + for changing the {@link MergeScheduler}).

+ + +

The optional autoCommit argument to the constructors + controls visibility of the changes to {@link IndexReader} + instances reading the same index. When this is + false, changes are not visible until {@link + #close()} or {@link #commit()} is called. Note that changes will still be + flushed to the {@link org.apache.lucene.store.Directory} + as new files, but are not committed (no new + segments_N file is written referencing the + new files, nor are the files sync'd to stable storage) + until {@link #close()} or {@link #commit()} is called. If something + goes terribly wrong (for example the JVM crashes), then + the index will reflect none of the changes made since the + last commit, or the starting state if commit was not called. + You can also call {@link #rollback}, which closes the writer + without committing any changes, and removes any index + files that had been flushed but are now unreferenced. + This mode is useful for preventing readers from refreshing + at a bad time (for example after you've done all your + deletes but before you've done your adds). It can also be + used to implement simple single-writer transactional + semantics ("all or none"). You can do a two-phase commit + by calling {@link #prepareCommit()} + followed by {@link #commit()}. This is necessary when + Lucene is working with an external resource (for example, + a database) and both must either commit or rollback the + transaction.

+ +

When autoCommit is true then + the writer will periodically commit on its own. [Deprecated: Note that in 3.0, IndexWriter will + no longer accept autoCommit=true (it will be hardwired to + false). You can always call {@link #commit()} yourself + when needed]. There is + no guarantee when exactly an auto commit will occur (it + used to be after every flush, but it is now after every + completed merge, as of 2.4). If you want to force a + commit, call {@link #commit()}, or, close the writer. Once + a commit has finished, newly opened {@link IndexReader} instances will + see the changes to the index as of that commit. When + running in this mode, be careful not to refresh your + readers while optimize or segment merges are taking place + as this can tie up substantial disk space.

+ +

Regardless of autoCommit, an {@link + IndexReader} or {@link org.apache.lucene.search.IndexSearcher} will only see the + index as of the "point in time" that it was opened. Any + changes committed to the index after the reader was opened + are not visible until the reader is re-opened.

+ +

If an index will not have more documents added for a while and optimal search + performance is desired, then either the full optimize + method or partial {@link #optimize(int)} method should be + called before the index is closed.

+ +

Opening an IndexWriter creates a lock file for the directory in use. Trying to open + another IndexWriter on the same directory will lead to a + {@link LockObtainFailedException}. The {@link LockObtainFailedException} + is also thrown if an IndexReader on the same directory is used to delete documents + from the index.

+ + +

Expert: IndexWriter allows an optional + {@link IndexDeletionPolicy} implementation to be + specified. You can use this to control when prior commits + are deleted from the index. The default policy is {@link + KeepOnlyLastCommitDeletionPolicy} which removes all prior + commits as soon as a new commit is done (this matches + behavior before 2.2). Creating your own policy can allow + you to explicitly keep previous "point in time" commits + alive in the index for some time, to allow readers to + refresh to the new commit without having the old commit + deleted out from under them. This is necessary on + filesystems like NFS that do not support "delete on last + close" semantics, which Lucene's "point in time" search + normally relies on.

+ +

Expert: + IndexWriter allows you to separately change + the {@link MergePolicy} and the {@link MergeScheduler}. + The {@link MergePolicy} is invoked whenever there are + changes to the segments in the index. Its role is to + select which merges to do, if any, and return a {@link + MergePolicy.MergeSpecification} describing the merges. It + also selects merges to do for optimize(). (The default is + {@link LogByteSizeMergePolicy}. Then, the {@link + MergeScheduler} is invoked with the requested merges and + it decides when and how to run the merges. The default is + {@link ConcurrentMergeScheduler}.

+*/ + +/* + * Clarification: Check Points (and commits) + * Being able to set autoCommit=false allows IndexWriter to flush and + * write new index files to the directory without writing a new segments_N + * file which references these new files. It also means that the state of + * the in memory SegmentInfos object is different than the most recent + * segments_N file written to the directory. + * + * Each time the SegmentInfos is changed, and matches the (possibly + * modified) directory files, we have a new "check point". + * If the modified/new SegmentInfos is written to disk - as a new + * (generation of) segments_N file - this check point is also an + * IndexCommit. + * + * With autoCommit=true, every checkPoint is also a CommitPoint. + * With autoCommit=false, some checkPoints may not be commits. + * + * A new checkpoint always replaces the previous checkpoint and + * becomes the new "front" of the index. This allows the IndexFileDeleter + * to delete files that are referenced only by stale checkpoints. + * (files that were created since the last commit, but are no longer + * referenced by the "front" of the index). For this, IndexFileDeleter + * keeps track of the last non commit checkpoint. + */ +public class IndexWriter { + + /** + * Default value for the write lock timeout (1,000). + * @see #setDefaultWriteLockTimeout + */ + public static long WRITE_LOCK_TIMEOUT = 1000; + + private long writeLockTimeout = WRITE_LOCK_TIMEOUT; + + /** + * Name of the write lock in the index. + */ + public static final String WRITE_LOCK_NAME = "write.lock"; + + /** + * @deprecated + * @see LogMergePolicy#DEFAULT_MERGE_FACTOR + */ + public final static int DEFAULT_MERGE_FACTOR = LogMergePolicy.DEFAULT_MERGE_FACTOR; + + /** + * Value to denote a flush trigger is disabled + */ + public final static int DISABLE_AUTO_FLUSH = -1; + + /** + * Disabled by default (because IndexWriter flushes by RAM usage + * by default). Change using {@link #setMaxBufferedDocs(int)}. + */ + public final static int DEFAULT_MAX_BUFFERED_DOCS = DISABLE_AUTO_FLUSH; + + /** + * Default value is 16 MB (which means flush when buffered + * docs consume 16 MB RAM). Change using {@link #setRAMBufferSizeMB}. + */ + public final static double DEFAULT_RAM_BUFFER_SIZE_MB = 16.0; + + /** + * Disabled by default (because IndexWriter flushes by RAM usage + * by default). Change using {@link #setMaxBufferedDeleteTerms(int)}. + */ + public final static int DEFAULT_MAX_BUFFERED_DELETE_TERMS = DISABLE_AUTO_FLUSH; + + /** + * @deprecated + * @see LogDocMergePolicy#DEFAULT_MAX_MERGE_DOCS + */ + public final static int DEFAULT_MAX_MERGE_DOCS = LogDocMergePolicy.DEFAULT_MAX_MERGE_DOCS; + + /** + * Default value is 10,000. Change using {@link #setMaxFieldLength(int)}. + */ + public final static int DEFAULT_MAX_FIELD_LENGTH = 10000; + + /** + * Default value is 128. Change using {@link #setTermIndexInterval(int)}. + */ + public final static int DEFAULT_TERM_INDEX_INTERVAL = 128; + + /** + * Absolute hard maximum length for a term. If a term + * arrives from the analyzer longer than this length, it + * is skipped and a message is printed to infoStream, if + * set (see {@link #setInfoStream}). + */ + public final static int MAX_TERM_LENGTH = DocumentsWriter.MAX_TERM_LENGTH; + + /** + * Default for {@link #getMaxSyncPauseSeconds}. On + * Windows this defaults to 10.0 seconds; elsewhere it's + * 0. + */ + public final static double DEFAULT_MAX_SYNC_PAUSE_SECONDS; + static { + if (Constants.WINDOWS) + DEFAULT_MAX_SYNC_PAUSE_SECONDS = 10.0; + else + DEFAULT_MAX_SYNC_PAUSE_SECONDS = 0.0; + } + + // The normal read buffer size defaults to 1024, but + // increasing this during merging seems to yield + // performance gains. However we don't want to increase + // it too much because there are quite a few + // BufferedIndexInputs created during merging. See + // LUCENE-888 for details. + private final static int MERGE_READ_BUFFER_SIZE = 4096; + + // Used for printing messages + private static Object MESSAGE_ID_LOCK = new Object(); + private static int MESSAGE_ID = 0; + private int messageID = -1; + volatile private boolean hitOOM; + + private Directory directory; // where this index resides + private Analyzer analyzer; // how to analyze text + + private Similarity similarity = Similarity.getDefault(); // how to normalize + + private volatile long changeCount; // increments every time a change is completed + private long lastCommitChangeCount; // last changeCount that was committed + + private SegmentInfos rollbackSegmentInfos; // segmentInfos we will fallback to if the commit fails + private HashMap rollbackSegments; + + volatile SegmentInfos pendingCommit; // set when a commit is pending (after prepareCommit() & before commit()) + volatile long pendingCommitChangeCount; + + private SegmentInfos localRollbackSegmentInfos; // segmentInfos we will fallback to if the commit fails + private boolean localAutoCommit; // saved autoCommit during local transaction + private int localFlushedDocCount; // saved docWriter.getFlushedDocCount during local transaction + private boolean autoCommit = true; // false if we should commit only on close + + private SegmentInfos segmentInfos = new SegmentInfos(); // the segments + + private DocumentsWriter docWriter; + private IndexFileDeleter deleter; + + private Set segmentsToOptimize = new HashSet(); // used by optimize to note those needing optimization + + private Lock writeLock; + + private int termIndexInterval = DEFAULT_TERM_INDEX_INTERVAL; + + private boolean closeDir; + private boolean closed; + private boolean closing; + + // Holds all SegmentInfo instances currently involved in + // merges + private HashSet mergingSegments = new HashSet(); + + private MergePolicy mergePolicy = new LogByteSizeMergePolicy(); + private MergeScheduler mergeScheduler = new ConcurrentMergeScheduler(); + private LinkedList pendingMerges = new LinkedList(); + private Set runningMerges = new HashSet(); + private List mergeExceptions = new ArrayList(); + private long mergeGen; + private boolean stopMerges; + + private int flushCount; + private int flushDeletesCount; + private double maxSyncPauseSeconds = DEFAULT_MAX_SYNC_PAUSE_SECONDS; + + // Used to only allow one addIndexes to proceed at once + // TODO: use ReadWriteLock once we are on 5.0 + private int readCount; // count of how many threads are holding read lock + private Thread writeThread; // non-null if any thread holds write lock + + synchronized void acquireWrite() { + while(writeThread != null || readCount > 0) + doWait(); + + // We could have been closed while we were waiting: + ensureOpen(); + + writeThread = Thread.currentThread(); + } + + synchronized void releaseWrite() { + assert Thread.currentThread() == writeThread; + writeThread = null; + notifyAll(); + } + + synchronized void acquireRead() { + final Thread current = Thread.currentThread(); + while(writeThread != null && writeThread != current) + doWait(); + + readCount++; + } + + synchronized void releaseRead() { + readCount--; + assert readCount >= 0; + if (0 == readCount) + notifyAll(); + } + + /** + * Used internally to throw an {@link + * AlreadyClosedException} if this IndexWriter has been + * closed. + * @throws AlreadyClosedException if this IndexWriter is + */ + protected synchronized final void ensureOpen(boolean includePendingClose) throws AlreadyClosedException { + if (closed || (includePendingClose && closing)) { + throw new AlreadyClosedException("this IndexWriter is closed"); + } + } + + protected synchronized final void ensureOpen() throws AlreadyClosedException { + ensureOpen(true); + } + + /** + * Prints a message to the infoStream (if non-null), + * prefixed with the identifying information for this + * writer and the thread that's calling it. + */ + public void message(String message) { + if (infoStream != null) + infoStream.println("IW " + messageID + " [" + Thread.currentThread().getName() + "]: " + message); + } + + private synchronized void setMessageID(PrintStream infoStream) { + if (infoStream != null && messageID == -1) { + synchronized(MESSAGE_ID_LOCK) { + messageID = MESSAGE_ID++; + } + } + this.infoStream = infoStream; + } + + /** + * Casts current mergePolicy to LogMergePolicy, and throws + * an exception if the mergePolicy is not a LogMergePolicy. + */ + private LogMergePolicy getLogMergePolicy() { + if (mergePolicy instanceof LogMergePolicy) + return (LogMergePolicy) mergePolicy; + else + throw new IllegalArgumentException("this method can only be called when the merge policy is the default LogMergePolicy"); + } + + /**

Get the current setting of whether newly flushed + * segments will use the compound file format. Note that + * this just returns the value previously set with + * setUseCompoundFile(boolean), or the default value + * (true). You cannot use this to query the status of + * previously flushed segments.

+ * + *

Note that this method is a convenience method: it + * just calls mergePolicy.getUseCompoundFile as long as + * mergePolicy is an instance of {@link LogMergePolicy}. + * Otherwise an IllegalArgumentException is thrown.

+ * + * @see #setUseCompoundFile(boolean) + */ + public boolean getUseCompoundFile() { + return getLogMergePolicy().getUseCompoundFile(); + } + + /**

Setting to turn on usage of a compound file. When on, + * multiple files for each segment are merged into a + * single file when a new segment is flushed.

+ * + *

Note that this method is a convenience method: it + * just calls mergePolicy.setUseCompoundFile as long as + * mergePolicy is an instance of {@link LogMergePolicy}. + * Otherwise an IllegalArgumentException is thrown.

+ */ + public void setUseCompoundFile(boolean value) { + getLogMergePolicy().setUseCompoundFile(value); + getLogMergePolicy().setUseCompoundDocStore(value); + } + + /** Expert: Set the Similarity implementation used by this IndexWriter. + * + * @see Similarity#setDefault(Similarity) + */ + public void setSimilarity(Similarity similarity) { + ensureOpen(); + this.similarity = similarity; + docWriter.setSimilarity(similarity); + } + + /** Expert: Return the Similarity implementation used by this IndexWriter. + * + *

This defaults to the current value of {@link Similarity#getDefault()}. + */ + public Similarity getSimilarity() { + ensureOpen(); + return this.similarity; + } + + /** Expert: Set the interval between indexed terms. Large values cause less + * memory to be used by IndexReader, but slow random-access to terms. Small + * values cause more memory to be used by an IndexReader, and speed + * random-access to terms. + * + * This parameter determines the amount of computation required per query + * term, regardless of the number of documents that contain that term. In + * particular, it is the maximum number of other terms that must be + * scanned before a term is located and its frequency and position information + * may be processed. In a large index with user-entered query terms, query + * processing time is likely to be dominated not by term lookup but rather + * by the processing of frequency and positional data. In a small index + * or when many uncommon query terms are generated (e.g., by wildcard + * queries) term lookup may become a dominant cost. + * + * In particular, numUniqueTerms/interval terms are read into + * memory by an IndexReader, and, on average, interval/2 terms + * must be scanned for each random term access. + * + * @see #DEFAULT_TERM_INDEX_INTERVAL + */ + public void setTermIndexInterval(int interval) { + ensureOpen(); + this.termIndexInterval = interval; + } + + /** Expert: Return the interval between indexed terms. + * + * @see #setTermIndexInterval(int) + */ + public int getTermIndexInterval() { + // We pass false because this method is called by SegmentMerger while we are in the process of closing + ensureOpen(false); + return termIndexInterval; + } + + /** + * Constructs an IndexWriter for the index in path. + * Text will be analyzed with a. If create + * is true, then a new, empty index will be created in + * path, replacing the index already there, + * if any. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @param mfl Maximum field length: LIMITED, UNLIMITED, or user-specified + * via the MaxFieldLength constructor. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + */ + public IndexWriter(String path, Analyzer a, boolean create, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, create, true, null, false, mfl.getLimit()); + } + + /** + * Constructs an IndexWriter for the index in path. + * Text will be analyzed with a. If create + * is true, then a new, empty index will be created in + * path, replacing the index already there, if any. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link + * #IndexWriter(String,Analyzer,boolean,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(String path, Analyzer a, boolean create) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, create, true, null, true, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Constructs an IndexWriter for the index in path. + * Text will be analyzed with a. If create + * is true, then a new, empty index will be created in + * path, replacing the index already there, if any. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @param mfl Maximum field length: LIMITED, UNLIMITED, or user-specified + * via the MaxFieldLength constructor. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + */ + public IndexWriter(File path, Analyzer a, boolean create, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, create, true, null, false, mfl.getLimit()); + } + + /** + * Constructs an IndexWriter for the index in path. + * Text will be analyzed with a. If create + * is true, then a new, empty index will be created in + * path, replacing the index already there, if any. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link + * #IndexWriter(File,Analyzer,boolean,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(File path, Analyzer a, boolean create) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, create, true, null, true, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Constructs an IndexWriter for the index in d. + * Text will be analyzed with a. If create + * is true, then a new, empty index will be created in + * d, replacing the index already there, if any. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param d the index directory + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @param mfl Maximum field length: LIMITED, UNLIMITED, or user-specified + * via the MaxFieldLength constructor. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + */ + public IndexWriter(Directory d, Analyzer a, boolean create, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, create, false, null, false, mfl.getLimit()); + } + + /** + * Constructs an IndexWriter for the index in d. + * Text will be analyzed with a. If create + * is true, then a new, empty index will be created in + * d, replacing the index already there, if any. + * + * @param d the index directory + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 + * release, and call {@link #commit()} when needed. + * Use {@link #IndexWriter(Directory,Analyzer,boolean,MaxFieldLength)} instead. + */ + public IndexWriter(Directory d, Analyzer a, boolean create) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, create, false, null, true, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Constructs an IndexWriter for the index in + * path, first creating it if it does not + * already exist. Text will be analyzed with + * a. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @param mfl Maximum field length: LIMITED, UNLIMITED, or user-specified + * via the MaxFieldLength constructor. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + */ + public IndexWriter(String path, Analyzer a, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, true, null, false, mfl.getLimit()); + } + + /** + * Constructs an IndexWriter for the index in + * path, first creating it if it does not + * already exist. Text will be analyzed with + * a. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 + * release, and call {@link #commit()} when needed. + * Use {@link #IndexWriter(String,Analyzer,MaxFieldLength)} instead. + */ + public IndexWriter(String path, Analyzer a) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, true, null, true, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Constructs an IndexWriter for the index in + * path, first creating it if it does not + * already exist. Text will be analyzed with + * a. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @param mfl Maximum field length: LIMITED, UNLIMITED, or user-specified + * via the MaxFieldLength constructor. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + */ + public IndexWriter(File path, Analyzer a, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, true, null, false, mfl.getLimit()); + } + + /** + * Constructs an IndexWriter for the index in + * path, first creating it if it does not + * already exist. Text will be analyzed with + * a. + * + * @param path the path to the index directory + * @param a the analyzer to use + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link #IndexWriter(File,Analyzer,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(File path, Analyzer a) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(FSDirectory.getDirectory(path), a, true, null, true, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Constructs an IndexWriter for the index in + * d, first creating it if it does not + * already exist. Text will be analyzed with + * a. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param d the index directory + * @param a the analyzer to use + * @param mfl Maximum field length: LIMITED, UNLIMITED, or user-specified + * via the MaxFieldLength constructor. + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + */ + public IndexWriter(Directory d, Analyzer a, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, false, null, false, mfl.getLimit()); + } + + /** + * Constructs an IndexWriter for the index in + * d, first creating it if it does not + * already exist. Text will be analyzed with + * a. + * + * @param d the index directory + * @param a the analyzer to use + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link + * #IndexWriter(Directory,Analyzer,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(Directory d, Analyzer a) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, false, null, true, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Constructs an IndexWriter for the index in + * d, first creating it if it does not + * already exist. Text will be analyzed with + * a. + * + * @param d the index directory + * @param autoCommit see above + * @param a the analyzer to use + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link + * #IndexWriter(Directory,Analyzer,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(Directory d, boolean autoCommit, Analyzer a) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, false, null, autoCommit, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Constructs an IndexWriter for the index in d. + * Text will be analyzed with a. If create + * is true, then a new, empty index will be created in + * d, replacing the index already there, if any. + * + * @param d the index directory + * @param autoCommit see above + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link + * #IndexWriter(Directory,Analyzer,boolean,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(Directory d, boolean autoCommit, Analyzer a, boolean create) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, create, false, null, autoCommit, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Expert: constructs an IndexWriter with a custom {@link + * IndexDeletionPolicy}, for the index in d, + * first creating it if it does not already exist. Text + * will be analyzed with a. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param d the index directory + * @param a the analyzer to use + * @param deletionPolicy see above + * @param mfl whether or not to limit field lengths + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + */ + public IndexWriter(Directory d, Analyzer a, IndexDeletionPolicy deletionPolicy, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, false, deletionPolicy, false, mfl.getLimit()); + } + + /** + * Expert: constructs an IndexWriter with a custom {@link + * IndexDeletionPolicy}, for the index in d, + * first creating it if it does not already exist. Text + * will be analyzed with a. + * + * @param d the index directory + * @param autoCommit see above + * @param a the analyzer to use + * @param deletionPolicy see above + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be + * read/written to or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link + * #IndexWriter(Directory,Analyzer,IndexDeletionPolicy,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(Directory d, boolean autoCommit, Analyzer a, IndexDeletionPolicy deletionPolicy) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, false, deletionPolicy, autoCommit, DEFAULT_MAX_FIELD_LENGTH); + } + + /** + * Expert: constructs an IndexWriter with a custom {@link + * IndexDeletionPolicy}, for the index in d. + * Text will be analyzed with a. If + * create is true, then a new, empty index + * will be created in d, replacing the index + * already there, if any. + * + *

NOTE: autoCommit (see above) is set to false with this + * constructor. + * + * @param d the index directory + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @param deletionPolicy see above + * @param mfl whether or not to limit field lengths + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + */ + public IndexWriter(Directory d, Analyzer a, boolean create, IndexDeletionPolicy deletionPolicy, MaxFieldLength mfl) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, create, false, deletionPolicy, false, mfl.getLimit()); + } + + /** + * Expert: constructs an IndexWriter with a custom {@link + * IndexDeletionPolicy}, for the index in d. + * Text will be analyzed with a. If + * create is true, then a new, empty index + * will be created in d, replacing the index + * already there, if any. + * + * @param d the index directory + * @param autoCommit see above + * @param a the analyzer to use + * @param create true to create the index or overwrite + * the existing one; false to append to the existing + * index + * @param deletionPolicy see above + * @throws CorruptIndexException if the index is corrupt + * @throws LockObtainFailedException if another writer + * has this index open (write.lock could not + * be obtained) + * @throws IOException if the directory cannot be read/written to, or + * if it does not exist and create is + * false or if there is any other low-level + * IO error + * @deprecated This constructor will be removed in the 3.0 release. + * Use {@link + * #IndexWriter(Directory,Analyzer,boolean,IndexDeletionPolicy,MaxFieldLength)} + * instead, and call {@link #commit()} when needed. + */ + public IndexWriter(Directory d, boolean autoCommit, Analyzer a, boolean create, IndexDeletionPolicy deletionPolicy) + throws CorruptIndexException, LockObtainFailedException, IOException { + init(d, a, create, false, deletionPolicy, autoCommit, DEFAULT_MAX_FIELD_LENGTH); + } + + private void init(Directory d, Analyzer a, boolean closeDir, IndexDeletionPolicy deletionPolicy, boolean autoCommit, int maxFieldLength) + throws CorruptIndexException, LockObtainFailedException, IOException { + if (IndexReader.indexExists(d)) { + init(d, a, false, closeDir, deletionPolicy, autoCommit, maxFieldLength); + } else { + init(d, a, true, closeDir, deletionPolicy, autoCommit, maxFieldLength); + } + } + + private void init(Directory d, Analyzer a, final boolean create, boolean closeDir, IndexDeletionPolicy deletionPolicy, boolean autoCommit, int maxFieldLength) + throws CorruptIndexException, LockObtainFailedException, IOException { + this.closeDir = closeDir; + directory = d; + analyzer = a; + setMessageID(defaultInfoStream); + this.maxFieldLength = maxFieldLength; + + if (create) { + // Clear the write lock in case it's leftover: + directory.clearLock(WRITE_LOCK_NAME); + } + + Lock writeLock = directory.makeLock(WRITE_LOCK_NAME); + if (!writeLock.obtain(writeLockTimeout)) // obtain write lock + throw new LockObtainFailedException("Index locked for write: " + writeLock); + this.writeLock = writeLock; // save it + + try { + if (create) { + // Try to read first. This is to allow create + // against an index that's currently open for + // searching. In this case we write the next + // segments_N file with no segments: + try { + segmentInfos.read(directory); + segmentInfos.clear(); + } catch (IOException e) { + // Likely this means it's a fresh directory + } + segmentInfos.commit(directory); + } else { + segmentInfos.read(directory); + + // We assume that this segments_N was previously + // properly sync'd: + for(int i=0;iDetermines the largest segment (measured by + * document count) that may be merged with other segments. + * Small values (e.g., less than 10,000) are best for + * interactive indexing, as this limits the length of + * pauses while indexing to a few seconds. Larger values + * are best for batched indexing and speedier + * searches.

+ * + *

The default value is {@link Integer#MAX_VALUE}.

+ * + *

Note that this method is a convenience method: it + * just calls mergePolicy.setMaxMergeDocs as long as + * mergePolicy is an instance of {@link LogMergePolicy}. + * Otherwise an IllegalArgumentException is thrown.

+ * + *

The default merge policy ({@link + * LogByteSizeMergePolicy}) also allows you to set this + * limit by net size (in MB) of the segment, using {@link + * LogByteSizeMergePolicy#setMaxMergeMB}.

+ */ + public void setMaxMergeDocs(int maxMergeDocs) { + getLogMergePolicy().setMaxMergeDocs(maxMergeDocs); + } + + /** + *

Returns the largest segment (measured by document + * count) that may be merged with other segments.

+ * + *

Note that this method is a convenience method: it + * just calls mergePolicy.getMaxMergeDocs as long as + * mergePolicy is an instance of {@link LogMergePolicy}. + * Otherwise an IllegalArgumentException is thrown.

+ * + * @see #setMaxMergeDocs + */ + public int getMaxMergeDocs() { + return getLogMergePolicy().getMaxMergeDocs(); + } + + /** + * The maximum number of terms that will be indexed for a single field in a + * document. This limits the amount of memory required for indexing, so that + * collections with very large files will not crash the indexing process by + * running out of memory. This setting refers to the number of running terms, + * not to the number of different terms.

+ * Note: this silently truncates large documents, excluding from the + * index all terms that occur further in the document. If you know your source + * documents are large, be sure to set this value high enough to accomodate + * the expected size. If you set it to Integer.MAX_VALUE, then the only limit + * is your memory, but you should anticipate an OutOfMemoryError.

+ * By default, no more than {@link #DEFAULT_MAX_FIELD_LENGTH} terms + * will be indexed for a field. + */ + public void setMaxFieldLength(int maxFieldLength) { + ensureOpen(); + this.maxFieldLength = maxFieldLength; + docWriter.setMaxFieldLength(maxFieldLength); + if (infoStream != null) + message("setMaxFieldLength " + maxFieldLength); + } + + /** + * Returns the maximum number of terms that will be + * indexed for a single field in a document. + * @see #setMaxFieldLength + */ + public int getMaxFieldLength() { + ensureOpen(); + return maxFieldLength; + } + + /** Determines the minimal number of documents required + * before the buffered in-memory documents are flushed as + * a new Segment. Large values generally gives faster + * indexing. + * + *

When this is set, the writer will flush every + * maxBufferedDocs added documents. Pass in {@link + * #DISABLE_AUTO_FLUSH} to prevent triggering a flush due + * to number of buffered documents. Note that if flushing + * by RAM usage is also enabled, then the flush will be + * triggered by whichever comes first.

+ * + *

Disabled by default (writer flushes by RAM usage).

+ * + * @throws IllegalArgumentException if maxBufferedDocs is + * enabled but smaller than 2, or it disables maxBufferedDocs + * when ramBufferSize is already disabled + * @see #setRAMBufferSizeMB + */ + public void setMaxBufferedDocs(int maxBufferedDocs) { + ensureOpen(); + if (maxBufferedDocs != DISABLE_AUTO_FLUSH && maxBufferedDocs < 2) + throw new IllegalArgumentException( + "maxBufferedDocs must at least be 2 when enabled"); + if (maxBufferedDocs == DISABLE_AUTO_FLUSH + && getRAMBufferSizeMB() == DISABLE_AUTO_FLUSH) + throw new IllegalArgumentException( + "at least one of ramBufferSize and maxBufferedDocs must be enabled"); + docWriter.setMaxBufferedDocs(maxBufferedDocs); + pushMaxBufferedDocs(); + if (infoStream != null) + message("setMaxBufferedDocs " + maxBufferedDocs); + } + + /** + * If we are flushing by doc count (not by RAM usage), and + * using LogDocMergePolicy then push maxBufferedDocs down + * as its minMergeDocs, to keep backwards compatibility. + */ + private void pushMaxBufferedDocs() { + if (docWriter.getMaxBufferedDocs() != DISABLE_AUTO_FLUSH) { + final MergePolicy mp = mergePolicy; + if (mp instanceof LogDocMergePolicy) { + LogDocMergePolicy lmp = (LogDocMergePolicy) mp; + final int maxBufferedDocs = docWriter.getMaxBufferedDocs(); + if (lmp.getMinMergeDocs() != maxBufferedDocs) { + if (infoStream != null) + message("now push maxBufferedDocs " + maxBufferedDocs + " to LogDocMergePolicy"); + lmp.setMinMergeDocs(maxBufferedDocs); + } + } + } + } + + /** + * Returns the number of buffered added documents that will + * trigger a flush if enabled. + * @see #setMaxBufferedDocs + */ + public int getMaxBufferedDocs() { + ensureOpen(); + return docWriter.getMaxBufferedDocs(); + } + + /** Determines the amount of RAM that may be used for + * buffering added documents before they are flushed as a + * new Segment. Generally for faster indexing performance + * it's best to flush by RAM usage instead of document + * count and use as large a RAM buffer as you can. + * + *

When this is set, the writer will flush whenever + * buffered documents use this much RAM. Pass in {@link + * #DISABLE_AUTO_FLUSH} to prevent triggering a flush due + * to RAM usage. Note that if flushing by document count + * is also enabled, then the flush will be triggered by + * whichever comes first.

+ * + *

The default value is {@link #DEFAULT_RAM_BUFFER_SIZE_MB}.

+ * + * @throws IllegalArgumentException if ramBufferSize is + * enabled but non-positive, or it disables ramBufferSize + * when maxBufferedDocs is already disabled + */ + public void setRAMBufferSizeMB(double mb) { + if (mb != DISABLE_AUTO_FLUSH && mb <= 0.0) + throw new IllegalArgumentException( + "ramBufferSize should be > 0.0 MB when enabled"); + if (mb == DISABLE_AUTO_FLUSH && getMaxBufferedDocs() == DISABLE_AUTO_FLUSH) + throw new IllegalArgumentException( + "at least one of ramBufferSize and maxBufferedDocs must be enabled"); + docWriter.setRAMBufferSizeMB(mb); + if (infoStream != null) + message("setRAMBufferSizeMB " + mb); + } + + /** + * Returns the value set by {@link #setRAMBufferSizeMB} if enabled. + */ + public double getRAMBufferSizeMB() { + return docWriter.getRAMBufferSizeMB(); + } + + /** + *

Determines the minimal number of delete terms required before the buffered + * in-memory delete terms are applied and flushed. If there are documents + * buffered in memory at the time, they are merged and a new segment is + * created.

+ + *

Disabled by default (writer flushes by RAM usage).

+ * + * @throws IllegalArgumentException if maxBufferedDeleteTerms + * is enabled but smaller than 1 + * @see #setRAMBufferSizeMB + */ + public void setMaxBufferedDeleteTerms(int maxBufferedDeleteTerms) { + ensureOpen(); + if (maxBufferedDeleteTerms != DISABLE_AUTO_FLUSH + && maxBufferedDeleteTerms < 1) + throw new IllegalArgumentException( + "maxBufferedDeleteTerms must at least be 1 when enabled"); + docWriter.setMaxBufferedDeleteTerms(maxBufferedDeleteTerms); + if (infoStream != null) + message("setMaxBufferedDeleteTerms " + maxBufferedDeleteTerms); + } + + /** + * Returns the number of buffered deleted terms that will + * trigger a flush if enabled. + * @see #setMaxBufferedDeleteTerms + */ + public int getMaxBufferedDeleteTerms() { + ensureOpen(); + return docWriter.getMaxBufferedDeleteTerms(); + } + + /** Determines how often segment indices are merged by addDocument(). With + * smaller values, less RAM is used while indexing, and searches on + * unoptimized indices are faster, but indexing speed is slower. With larger + * values, more RAM is used during indexing, and while searches on unoptimized + * indices are slower, indexing is faster. Thus larger values (> 10) are best + * for batch index creation, and smaller values (< 10) for indices that are + * interactively maintained. + * + *

Note that this method is a convenience method: it + * just calls mergePolicy.setMergeFactor as long as + * mergePolicy is an instance of {@link LogMergePolicy}. + * Otherwise an IllegalArgumentException is thrown.

+ * + *

This must never be less than 2. The default value is 10. + */ + public void setMergeFactor(int mergeFactor) { + getLogMergePolicy().setMergeFactor(mergeFactor); + } + + /** + *

Returns the number of segments that are merged at + * once and also controls the total number of segments + * allowed to accumulate in the index.

+ * + *

Note that this method is a convenience method: it + * just calls mergePolicy.getMergeFactor as long as + * mergePolicy is an instance of {@link LogMergePolicy}. + * Otherwise an IllegalArgumentException is thrown.

+ * + * @see #setMergeFactor + */ + public int getMergeFactor() { + return getLogMergePolicy().getMergeFactor(); + } + + /** + * Expert: returns max delay inserted before syncing a + * commit point. On Windows, at least, pausing before + * syncing can increase net indexing throughput. The + * delay is variable based on size of the segment's files, + * and is only inserted when using + * ConcurrentMergeScheduler for merges. + * @deprecated This will be removed in 3.0, when + * autoCommit=true is removed from IndexWriter. + */ + public double getMaxSyncPauseSeconds() { + return maxSyncPauseSeconds; + } + + /** + * Expert: sets the max delay before syncing a commit + * point. + * @see #getMaxSyncPauseSeconds + * @deprecated This will be removed in 3.0, when + * autoCommit=true is removed from IndexWriter. + */ + public void setMaxSyncPauseSeconds(double seconds) { + maxSyncPauseSeconds = seconds; + } + + /** If non-null, this will be the default infoStream used + * by a newly instantiated IndexWriter. + * @see #setInfoStream + */ + public static void setDefaultInfoStream(PrintStream infoStream) { + IndexWriter.defaultInfoStream = infoStream; + } + + /** + * Returns the current default infoStream for newly + * instantiated IndexWriters. + * @see #setDefaultInfoStream + */ + public static PrintStream getDefaultInfoStream() { + return IndexWriter.defaultInfoStream; + } + + /** If non-null, information about merges, deletes and a + * message when maxFieldLength is reached will be printed + * to this. + */ + public void setInfoStream(PrintStream infoStream) { + ensureOpen(); + setMessageID(infoStream); + docWriter.setInfoStream(infoStream); + deleter.setInfoStream(infoStream); + if (infoStream != null) + messageState(); + } + + private void messageState() { + message("setInfoStream: dir=" + directory + + " autoCommit=" + autoCommit + + " mergePolicy=" + mergePolicy + + " mergeScheduler=" + mergeScheduler + + " ramBufferSizeMB=" + docWriter.getRAMBufferSizeMB() + + " maxBufferedDocs=" + docWriter.getMaxBufferedDocs() + + " maxBuffereDeleteTerms=" + docWriter.getMaxBufferedDeleteTerms() + + " maxFieldLength=" + maxFieldLength + + " index=" + segString()); + } + + /** + * Returns the current infoStream in use by this writer. + * @see #setInfoStream + */ + public PrintStream getInfoStream() { + ensureOpen(); + return infoStream; + } + + /** + * Sets the maximum time to wait for a write lock (in milliseconds) for this instance of IndexWriter. @see + * @see #setDefaultWriteLockTimeout to change the default value for all instances of IndexWriter. + */ + public void setWriteLockTimeout(long writeLockTimeout) { + ensureOpen(); + this.writeLockTimeout = writeLockTimeout; + } + + /** + * Returns allowed timeout when acquiring the write lock. + * @see #setWriteLockTimeout + */ + public long getWriteLockTimeout() { + ensureOpen(); + return writeLockTimeout; + } + + /** + * Sets the default (for any instance of IndexWriter) maximum time to wait for a write lock (in + * milliseconds). + */ + public static void setDefaultWriteLockTimeout(long writeLockTimeout) { + IndexWriter.WRITE_LOCK_TIMEOUT = writeLockTimeout; + } + + /** + * Returns default write lock timeout for newly + * instantiated IndexWriters. + * @see #setDefaultWriteLockTimeout + */ + public static long getDefaultWriteLockTimeout() { + return IndexWriter.WRITE_LOCK_TIMEOUT; + } + + /** + * Commits all changes to an index and closes all + * associated files. Note that this may be a costly + * operation, so, try to re-use a single writer instead of + * closing and opening a new one. See {@link #commit()} for + * caveats about write caching done by some IO devices. + * + *

If an Exception is hit during close, eg due to disk + * full or some other reason, then both the on-disk index + * and the internal state of the IndexWriter instance will + * be consistent. However, the close will not be complete + * even though part of it (flushing buffered documents) + * may have succeeded, so the write lock will still be + * held.

+ * + *

If you can correct the underlying cause (eg free up + * some disk space) then you can call close() again. + * Failing that, if you want to force the write lock to be + * released (dangerous, because you may then lose buffered + * docs in the IndexWriter instance) then you can do + * something like this:

+ * + *
+   * try {
+   *   writer.close();
+   * } finally {
+   *   if (IndexWriter.isLocked(directory)) {
+   *     IndexWriter.unlock(directory);
+   *   }
+   * }
+   * 
+ * + * after which, you must be certain not to use the writer + * instance anymore.

+ * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void close() throws CorruptIndexException, IOException { + close(true); + } + + /** + * Closes the index with or without waiting for currently + * running merges to finish. This is only meaningful when + * using a MergeScheduler that runs merges in background + * threads. + * @param waitForMerges if true, this call will block + * until all merges complete; else, it will ask all + * running merges to abort, wait until those merges have + * finished (which should be at most a few seconds), and + * then return. + */ + public void close(boolean waitForMerges) throws CorruptIndexException, IOException { + + // If any methods have hit OutOfMemoryError, then abort + // on close, in case the internal state of IndexWriter + // or DocumentsWriter is corrupt + if (hitOOM) { + rollback(); + return; + } + + // Ensure that only one thread actually gets to do the closing: + if (shouldClose()) + closeInternal(waitForMerges); + } + + // Returns true if this thread should attempt to close, or + // false if IndexWriter is now closed; else, waits until + // another thread finishes closing + synchronized private boolean shouldClose() { + while(true) { + if (!closed) { + if (!closing) { + closing = true; + return true; + } else { + // Another thread is presently trying to close; + // wait until it finishes one way (closes + // successfully) or another (fails to close) + doWait(); + } + } else + return false; + } + } + + private void closeInternal(boolean waitForMerges) throws CorruptIndexException, IOException { + + docWriter.pauseAllThreads(); + + try { + if (infoStream != null) + message("now flush at close"); + + docWriter.close(); + + // Only allow a new merge to be triggered if we are + // going to wait for merges: + flush(waitForMerges, true, true); + + if (waitForMerges) + // Give merge scheduler last chance to run, in case + // any pending merges are waiting: + mergeScheduler.merge(this); + + mergePolicy.close(); + + finishMerges(waitForMerges); + + mergeScheduler.close(); + + if (infoStream != null) + message("now call final commit()"); + + commit(0); + + if (infoStream != null) + message("at close: " + segString()); + + synchronized(this) { + docWriter = null; + deleter.close(); + } + + if (closeDir) + directory.close(); + + if (writeLock != null) { + writeLock.release(); // release write lock + writeLock = null; + } + synchronized(this) { + closed = true; + } + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } finally { + synchronized(this) { + closing = false; + notifyAll(); + if (!closed) { + if (docWriter != null) + docWriter.resumeAllThreads(); + if (infoStream != null) + message("hit exception while closing"); + } + } + } + } + + /** Tells the docWriter to close its currently open shared + * doc stores (stored fields & vectors files). + * Return value specifices whether new doc store files are compound or not. + */ + private synchronized boolean flushDocStores() throws IOException { + + boolean useCompoundDocStore = false; + + String docStoreSegment; + + boolean success = false; + try { + docStoreSegment = docWriter.closeDocStore(); + success = true; + } finally { + if (!success) { + if (infoStream != null) + message("hit exception closing doc store segment"); + } + } + + useCompoundDocStore = mergePolicy.useCompoundDocStore(segmentInfos); + + if (useCompoundDocStore && docStoreSegment != null && docWriter.closedFiles().size() != 0) { + // Now build compound doc store file + + success = false; + + final int numSegments = segmentInfos.size(); + final String compoundFileName = docStoreSegment + "." + IndexFileNames.COMPOUND_FILE_STORE_EXTENSION; + + try { + CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, compoundFileName); + final Iterator it = docWriter.closedFiles().iterator(); + while(it.hasNext()) + cfsWriter.addFile((String) it.next()); + + // Perform the merge + cfsWriter.close(); + success = true; + + } finally { + if (!success) { + if (infoStream != null) + message("hit exception building compound file doc store for segment " + docStoreSegment); + deleter.deleteFile(compoundFileName); + } + } + + for(int i=0;iNOTE:
buffered deletions + * are not counted. If you really need these to be + * counted you should call {@link #commit()} first. + * @see #numDocs */ + public synchronized int numDocs() throws IOException { + int count; + if (docWriter != null) + count = docWriter.getNumDocsInRAM(); + else + count = 0; + + for (int i = 0; i < segmentInfos.size(); i++) { + final SegmentInfo info = segmentInfos.info(i); + count += info.docCount - info.getDelCount(); + } + return count; + } + + public synchronized boolean hasDeletions() throws IOException { + ensureOpen(); + if (docWriter.hasDeletes()) + return true; + for (int i = 0; i < segmentInfos.size(); i++) + if (segmentInfos.info(i).hasDeletions()) + return true; + return false; + } + + /** + * The maximum number of terms that will be indexed for a single field in a + * document. This limits the amount of memory required for indexing, so that + * collections with very large files will not crash the indexing process by + * running out of memory.

+ * Note that this effectively truncates large documents, excluding from the + * index terms that occur further in the document. If you know your source + * documents are large, be sure to set this value high enough to accomodate + * the expected size. If you set it to Integer.MAX_VALUE, then the only limit + * is your memory, but you should anticipate an OutOfMemoryError.

+ * By default, no more than 10,000 terms will be indexed for a field. + * + * @see MaxFieldLength + */ + private int maxFieldLength; + + /** + * Adds a document to this index. If the document contains more than + * {@link #setMaxFieldLength(int)} terms for a given field, the remainder are + * discarded. + * + *

Note that if an Exception is hit (for example disk full) + * then the index will be consistent, but this document + * may not have been added. Furthermore, it's possible + * the index will have one segment in non-compound format + * even when using compound files (when a merge has + * partially succeeded).

+ * + *

This method periodically flushes pending documents + * to the Directory (see above), and + * also periodically triggers segment merges in the index + * according to the {@link MergePolicy} in use.

+ * + *

Merges temporarily consume space in the + * directory. The amount of space required is up to 1X the + * size of all segments being merged, when no + * readers/searchers are open against the index, and up to + * 2X the size of all segments being merged when + * readers/searchers are open against the index (see + * {@link #optimize()} for details). The sequence of + * primitive merge operations performed is governed by the + * merge policy. + * + *

Note that each term in the document can be no longer + * than 16383 characters, otherwise an + * IllegalArgumentException will be thrown.

+ * + *

Note that it's possible to create an invalid Unicode + * string in java if a UTF16 surrogate pair is malformed. + * In this case, the invalid characters are silently + * replaced with the Unicode replacement character + * U+FFFD.

+ * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void addDocument(Document doc) throws CorruptIndexException, IOException { + addDocument(doc, analyzer); + } + + /** + * Adds a document to this index, using the provided analyzer instead of the + * value of {@link #getAnalyzer()}. If the document contains more than + * {@link #setMaxFieldLength(int)} terms for a given field, the remainder are + * discarded. + * + *

See {@link #addDocument(Document)} for details on + * index and IndexWriter state after an Exception, and + * flushing/merging temporary free space requirements.

+ * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException { + ensureOpen(); + boolean doFlush = false; + boolean success = false; + try { + try { + doFlush = docWriter.addDocument(doc, analyzer); + success = true; + } finally { + if (!success) { + + if (infoStream != null) + message("hit exception adding document"); + + synchronized (this) { + // If docWriter has some aborted files that were + // never incref'd, then we clean them up here + if (docWriter != null) { + final Collection files = docWriter.abortedFiles(); + if (files != null) + deleter.deleteNewFiles(files); + } + } + } + } + if (doFlush) + flush(true, false, false); + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } + } + + /** + * Deletes the document(s) containing term. + * @param term the term to identify the documents to be deleted + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void deleteDocuments(Term term) throws CorruptIndexException, IOException { + ensureOpen(); + try { + boolean doFlush = docWriter.bufferDeleteTerm(term); + if (doFlush) + flush(true, false, false); + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } + } + + /** + * Deletes the document(s) containing any of the + * terms. All deletes are flushed at the same time. + * @param terms array of terms to identify the documents + * to be deleted + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void deleteDocuments(Term[] terms) throws CorruptIndexException, IOException { + ensureOpen(); + try { + boolean doFlush = docWriter.bufferDeleteTerms(terms); + if (doFlush) + flush(true, false, false); + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } + } + + /** + * Deletes the document(s) matching the provided query. + * @param query the query to identify the documents to be deleted + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void deleteDocuments(Query query) throws CorruptIndexException, IOException { + ensureOpen(); + boolean doFlush = docWriter.bufferDeleteQuery(query); + if (doFlush) + flush(true, false, false); + } + + /** + * Deletes the document(s) matching any of the provided queries. + * All deletes are flushed at the same time. + * @param queries array of queries to identify the documents + * to be deleted + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void deleteDocuments(Query[] queries) throws CorruptIndexException, IOException { + ensureOpen(); + boolean doFlush = docWriter.bufferDeleteQueries(queries); + if (doFlush) + flush(true, false, false); + } + + /** + * Updates a document by first deleting the document(s) + * containing term and then adding the new + * document. The delete and then add are atomic as seen + * by a reader on the same index (flush may happen only after + * the add). + * @param term the term to identify the document(s) to be + * deleted + * @param doc the document to be added + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void updateDocument(Term term, Document doc) throws CorruptIndexException, IOException { + ensureOpen(); + updateDocument(term, doc, getAnalyzer()); + } + + /** + * Updates a document by first deleting the document(s) + * containing term and then adding the new + * document. The delete and then add are atomic as seen + * by a reader on the same index (flush may happen only after + * the add). + * @param term the term to identify the document(s) to be + * deleted + * @param doc the document to be added + * @param analyzer the analyzer to use when analyzing the document + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void updateDocument(Term term, Document doc, Analyzer analyzer) + throws CorruptIndexException, IOException { + ensureOpen(); + try { + boolean doFlush = false; + boolean success = false; + try { + doFlush = docWriter.updateDocument(term, doc, analyzer); + success = true; + } finally { + if (!success) { + + if (infoStream != null) + message("hit exception updating document"); + + synchronized (this) { + // If docWriter has some aborted files that were + // never incref'd, then we clean them up here + final Collection files = docWriter.abortedFiles(); + if (files != null) + deleter.deleteNewFiles(files); + } + } + } + if (doFlush) + flush(true, false, false); + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } + } + + // for test purpose + final synchronized int getSegmentCount(){ + return segmentInfos.size(); + } + + // for test purpose + final synchronized int getNumBufferedDocuments(){ + return docWriter.getNumDocsInRAM(); + } + + // for test purpose + final synchronized int getDocCount(int i) { + if (i >= 0 && i < segmentInfos.size()) { + return segmentInfos.info(i).docCount; + } else { + return -1; + } + } + + // for test purpose + final synchronized int getFlushCount() { + return flushCount; + } + + // for test purpose + final synchronized int getFlushDeletesCount() { + return flushDeletesCount; + } + + final String newSegmentName() { + // Cannot synchronize on IndexWriter because that causes + // deadlock + synchronized(segmentInfos) { + // Important to increment changeCount so that the + // segmentInfos is written on close. Otherwise we + // could close, re-open and re-return the same segment + // name that was previously returned which can cause + // problems at least with ConcurrentMergeScheduler. + changeCount++; + return "_" + Integer.toString(segmentInfos.counter++, Character.MAX_RADIX); + } + } + + /** If non-null, information about merges will be printed to this. + */ + private PrintStream infoStream = null; + private static PrintStream defaultInfoStream = null; + + /** + * Requests an "optimize" operation on an index, priming the index + * for the fastest available search. Traditionally this has meant + * merging all segments into a single segment as is done in the + * default merge policy, but individaul merge policies may implement + * optimize in different ways. + * + * @see LogMergePolicy#findMergesForOptimize + * + *

It is recommended that this method be called upon completion of indexing. In + * environments with frequent updates, optimize is best done during low volume times, if at all. + * + *

+ *

See http://www.gossamer-threads.com/lists/lucene/java-dev/47895 for more discussion.

+ * + *

Note that this can require substantial temporary free + * space in the Directory (see LUCENE-764 + * for details):

+ * + *
    + *
  • + * + *

    If no readers/searchers are open against the index, + * then free space required is up to 1X the total size of + * the starting index. For example, if the starting + * index is 10 GB, then you must have up to 10 GB of free + * space before calling optimize.

    + * + *
  • + * + *

    If readers/searchers are using the index, then free + * space required is up to 2X the size of the starting + * index. This is because in addition to the 1X used by + * optimize, the original 1X of the starting index is + * still consuming space in the Directory as the readers + * are holding the segments files open. Even on Unix, + * where it will appear as if the files are gone ("ls" + * won't list them), they still consume storage due to + * "delete on last close" semantics.

    + * + *

    Furthermore, if some but not all readers re-open + * while the optimize is underway, this will cause > 2X + * temporary space to be consumed as those new readers + * will then hold open the partially optimized segments at + * that time. It is best not to re-open readers while + * optimize is running.

    + * + *
+ * + *

The actual temporary usage could be much less than + * these figures (it depends on many factors).

+ * + *

In general, once the optimize completes, the total size of the + * index will be less than the size of the starting index. + * It could be quite a bit smaller (if there were many + * pending deletes) or just slightly smaller.

+ * + *

If an Exception is hit during optimize(), for example + * due to disk full, the index will not be corrupt and no + * documents will have been lost. However, it may have + * been partially optimized (some segments were merged but + * not all), and it's possible that one of the segments in + * the index will be in non-compound format even when + * using compound file format. This will occur when the + * Exception is hit during conversion of the segment into + * compound format.

+ * + *

This call will optimize those segments present in + * the index when the call started. If other threads are + * still adding documents and flushing segments, those + * newly created segments will not be optimized unless you + * call optimize again.

+ * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void optimize() throws CorruptIndexException, IOException { + optimize(true); + } + + /** + * Optimize the index down to <= maxNumSegments. If + * maxNumSegments==1 then this is the same as {@link + * #optimize()}. + * @param maxNumSegments maximum number of segments left + * in the index after optimization finishes + */ + public void optimize(int maxNumSegments) throws CorruptIndexException, IOException { + optimize(maxNumSegments, true); + } + + /** Just like {@link #optimize()}, except you can specify + * whether the call should block until the optimize + * completes. This is only meaningful with a + * {@link MergeScheduler} that is able to run merges in + * background threads. */ + public void optimize(boolean doWait) throws CorruptIndexException, IOException { + optimize(1, doWait); + } + + /** Just like {@link #optimize(int)}, except you can + * specify whether the call should block until the + * optimize completes. This is only meaningful with a + * {@link MergeScheduler} that is able to run merges in + * background threads. */ + public void optimize(int maxNumSegments, boolean doWait) throws CorruptIndexException, IOException { + ensureOpen(); + + if (maxNumSegments < 1) + throw new IllegalArgumentException("maxNumSegments must be >= 1; got " + maxNumSegments); + + if (infoStream != null) + message("optimize: index now " + segString()); + + flush(true, false, true); + + synchronized(this) { + resetMergeExceptions(); + segmentsToOptimize = new HashSet(); + final int numSegments = segmentInfos.size(); + for(int i=0;i 0) { + // Forward any exceptions in background merge + // threads to the current thread: + final int size = mergeExceptions.size(); + for(int i=0;i 0; + + if (stopMerges) + return; + + final MergePolicy.MergeSpecification spec; + if (optimize) { + spec = mergePolicy.findMergesForOptimize(segmentInfos, this, maxNumSegmentsOptimize, segmentsToOptimize); + + if (spec != null) { + final int numMerges = spec.merges.size(); + for(int i=0;iIndexWriter without committing + * any of the changes that have occurred since it was + * opened. This removes any temporary files that had been + * created, after which the state of the index will be the + * same as it was when this writer was first opened. This + * can only be called when this IndexWriter was opened + * with autoCommit=false. This also clears a + * previous call to {@link #prepareCommit}. + * @throws IllegalStateException if this is called when + * the writer was opened with autoCommit=true. + * @throws IOException if there is a low-level IO error + */ + public void rollback() throws IOException { + ensureOpen(); + if (autoCommit) + throw new IllegalStateException("rollback() can only be called when IndexWriter was opened with autoCommit=false"); + + // Ensure that only one thread actually gets to do the closing: + if (shouldClose()) + rollbackInternal(); + } + + private void rollbackInternal() throws IOException { + + boolean success = false; + + docWriter.pauseAllThreads(); + + try { + finishMerges(false); + + // Must pre-close these two, in case they increment + // changeCount so that we can then set it to false + // before calling closeInternal + mergePolicy.close(); + mergeScheduler.close(); + + synchronized(this) { + + if (pendingCommit != null) { + pendingCommit.rollbackCommit(directory); + deleter.decRef(pendingCommit); + pendingCommit = null; + notifyAll(); + } + + // Keep the same segmentInfos instance but replace all + // of its SegmentInfo instances. This is so the next + // attempt to commit using this instance of IndexWriter + // will always write to a new generation ("write + // once"). + segmentInfos.clear(); + segmentInfos.addAll(rollbackSegmentInfos); + + assert !hasExternalSegments(); + + docWriter.abort(); + + assert testPoint("rollback before checkpoint"); + + // Ask deleter to locate unreferenced files & remove + // them: + deleter.checkpoint(segmentInfos, false); + deleter.refresh(); + } + + lastCommitChangeCount = changeCount; + + success = true; + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } finally { + synchronized(this) { + if (!success) { + docWriter.resumeAllThreads(); + closing = false; + notifyAll(); + if (infoStream != null) + message("hit exception during rollback"); + } + } + } + + closeInternal(false); + } + + private synchronized void finishMerges(boolean waitForMerges) throws IOException { + if (!waitForMerges) { + + stopMerges = true; + + // Abort all pending & running merges: + Iterator it = pendingMerges.iterator(); + while(it.hasNext()) { + final MergePolicy.OneMerge merge = (MergePolicy.OneMerge) it.next(); + if (infoStream != null) + message("now abort pending merge " + merge.segString(directory)); + merge.abort(); + mergeFinish(merge); + } + pendingMerges.clear(); + + it = runningMerges.iterator(); + while(it.hasNext()) { + final MergePolicy.OneMerge merge = (MergePolicy.OneMerge) it.next(); + if (infoStream != null) + message("now abort running merge " + merge.segString(directory)); + merge.abort(); + } + + // Ensure any running addIndexes finishes. It's fine + // if a new one attempts to start because its merges + // will quickly see the stopMerges == true and abort. + acquireRead(); + releaseRead(); + + // These merges periodically check whether they have + // been aborted, and stop if so. We wait here to make + // sure they all stop. It should not take very long + // because the merge threads periodically check if + // they are aborted. + while(runningMerges.size() > 0) { + if (infoStream != null) + message("now wait for " + runningMerges.size() + " running merge to abort"); + doWait(); + } + + stopMerges = false; + notifyAll(); + + assert 0 == mergingSegments.size(); + + if (infoStream != null) + message("all running merges have aborted"); + + } else { + // Ensure any running addIndexes finishes. It's fine + // if a new one attempts to start because from our + // caller above the call will see that we are in the + // process of closing, and will throw an + // AlreadyClosedException. + acquireRead(); + releaseRead(); + while(pendingMerges.size() > 0 || runningMerges.size() > 0) + doWait(); + assert 0 == mergingSegments.size(); + } + } + + /* + * Called whenever the SegmentInfos has been updated and + * the index files referenced exist (correctly) in the + * index directory. + */ + private synchronized void checkpoint() throws IOException { + changeCount++; + deleter.checkpoint(segmentInfos, false); + } + + private void finishAddIndexes() { + releaseWrite(); + } + + private void blockAddIndexes(boolean includePendingClose) { + + acquireRead(); + + boolean success = false; + try { + + // Make sure we are still open since we could have + // waited quite a while for last addIndexes to finish + ensureOpen(includePendingClose); + success = true; + } finally { + if (!success) + releaseRead(); + } + } + + private void resumeAddIndexes() { + releaseRead(); + } + + /** Merges all segments from an array of indexes into this index. + * @deprecated Use {@link #addIndexesNoOptimize} instead, + * then separately call {@link #optimize} afterwards if + * you need to. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void addIndexes(Directory[] dirs) + throws CorruptIndexException, IOException { + + ensureOpen(); + + noDupDirs(dirs); + + // Do not allow add docs or deletes while we are running: + docWriter.pauseAllThreads(); + + try { + + if (infoStream != null) + message("flush at addIndexes"); + flush(true, false, true); + + boolean success = false; + + startTransaction(false); + + try { + + int docCount = 0; + synchronized(this) { + ensureOpen(); + for (int i = 0; i < dirs.length; i++) { + SegmentInfos sis = new SegmentInfos(); // read infos from dir + sis.read(dirs[i]); + for (int j = 0; j < sis.size(); j++) { + final SegmentInfo info = sis.info(j); + docCount += info.docCount; + assert !segmentInfos.contains(info); + segmentInfos.add(info); // add each info + } + } + } + + // Notify DocumentsWriter that the flushed count just increased + docWriter.updateFlushedDocCount(docCount); + + optimize(); + + success = true; + } finally { + if (success) { + commitTransaction(); + } else { + rollbackTransaction(); + } + } + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } finally { + docWriter.resumeAllThreads(); + } + } + + private synchronized void resetMergeExceptions() { + mergeExceptions = new ArrayList(); + mergeGen++; + } + + private void noDupDirs(Directory[] dirs) { + HashSet dups = new HashSet(); + for(int i=0;iThis may be used to parallelize batch indexing. A large document + * collection can be broken into sub-collections. Each sub-collection can be + * indexed in parallel, on a different thread, process or machine. The + * complete index can then be created by merging sub-collection indexes + * with this method. + * + *

NOTE: the index in each Directory must not be + * changed (opened by a writer) while this method is + * running. This method does not acquire a write lock in + * each input Directory, so it is up to the caller to + * enforce this. + * + *

NOTE: while this is running, any attempts to + * add or delete documents (with another thread) will be + * paused until this method completes. + * + *

This method is transactional in how Exceptions are + * handled: it does not commit a new segments_N file until + * all indexes are added. This means if an Exception + * occurs (for example disk full), then either no indexes + * will have been added or they all will have been.

+ * + *

Note that this requires temporary free space in the + * Directory up to 2X the sum of all input indexes + * (including the starting index). If readers/searchers + * are open against the starting index, then temporary + * free space required will be higher by the size of the + * starting index (see {@link #optimize()} for details). + *

+ * + *

Once this completes, the final size of the index + * will be less than the sum of all input index sizes + * (including the starting index). It could be quite a + * bit smaller (if there were many pending deletes) or + * just slightly smaller.

+ * + *

+ * This requires this index not be among those to be added. + * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void addIndexesNoOptimize(Directory[] dirs) + throws CorruptIndexException, IOException { + + ensureOpen(); + + noDupDirs(dirs); + + // Do not allow add docs or deletes while we are running: + docWriter.pauseAllThreads(); + + try { + if (infoStream != null) + message("flush at addIndexesNoOptimize"); + flush(true, false, true); + + boolean success = false; + + startTransaction(false); + + try { + + int docCount = 0; + synchronized(this) { + ensureOpen(); + + for (int i = 0; i < dirs.length; i++) { + if (directory == dirs[i]) { + // cannot add this index: segments may be deleted in merge before added + throw new IllegalArgumentException("Cannot add this index to itself"); + } + + SegmentInfos sis = new SegmentInfos(); // read infos from dir + sis.read(dirs[i]); + for (int j = 0; j < sis.size(); j++) { + SegmentInfo info = sis.info(j); + assert !segmentInfos.contains(info): "dup info dir=" + info.dir + " name=" + info.name; + docCount += info.docCount; + segmentInfos.add(info); // add each info + } + } + } + + // Notify DocumentsWriter that the flushed count just increased + docWriter.updateFlushedDocCount(docCount); + + maybeMerge(); + + ensureOpen(); + + // If after merging there remain segments in the index + // that are in a different directory, just copy these + // over into our index. This is necessary (before + // finishing the transaction) to avoid leaving the + // index in an unusable (inconsistent) state. + resolveExternalSegments(); + + ensureOpen(); + + success = true; + + } finally { + if (success) { + commitTransaction(); + } else { + rollbackTransaction(); + } + } + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } finally { + docWriter.resumeAllThreads(); + } + } + + private boolean hasExternalSegments() { + return hasExternalSegments(segmentInfos); + } + + private boolean hasExternalSegments(SegmentInfos infos) { + final int numSegments = infos.size(); + for(int i=0;iAfter this completes, the index is optimized.

+ *

The provided IndexReaders are not closed.

+ + *

NOTE: the index in each Directory must not be + * changed (opened by a writer) while this method is + * running. This method does not acquire a write lock in + * each input Directory, so it is up to the caller to + * enforce this. + * + *

NOTE: while this is running, any attempts to + * add or delete documents (with another thread) will be + * paused until this method completes. + * + *

See {@link #addIndexesNoOptimize(Directory[])} for + * details on transactional semantics, temporary free + * space required in the Directory, and non-CFS segments + * on an Exception.

+ * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public void addIndexes(IndexReader[] readers) + throws CorruptIndexException, IOException { + + ensureOpen(); + + // Do not allow add docs or deletes while we are running: + docWriter.pauseAllThreads(); + + // We must pre-acquire the write lock here (and not in + // startTransaction below) so that no other addIndexes + // is allowed to start up after we have flushed & + // optimized but before we then start our transaction. + // This is because the merging below requires that only + // one segment is present in the index: + acquireWrite(); + + try { + + boolean success = false; + SegmentInfo info = null; + String mergedName = null; + SegmentMerger merger = null; + + try { + flush(true, false, true); + optimize(); // start with zero or 1 seg + success = true; + } finally { + // Take care to release the write lock if we hit an + // exception before starting the transaction + if (!success) + releaseWrite(); + } + + // true means we already have write lock; if this call + // hits an exception it will release the write lock: + startTransaction(true); + + try { + mergedName = newSegmentName(); + merger = new SegmentMerger(this, mergedName, null); + + IndexReader sReader = null; + synchronized(this) { + if (segmentInfos.size() == 1) { // add existing index, if any + sReader = SegmentReader.get(true, segmentInfos.info(0)); + } + } + + try { + if (sReader != null) + merger.add(sReader); + + for (int i = 0; i < readers.length; i++) // add new indexes + merger.add(readers[i]); + + int docCount = merger.merge(); // merge 'em + + if(sReader != null) { + sReader.close(); + sReader = null; + } + + synchronized(this) { + segmentInfos.clear(); // pop old infos & add new + info = new SegmentInfo(mergedName, docCount, directory, false, true, + -1, null, false, merger.hasProx()); + segmentInfos.add(info); + } + + // Notify DocumentsWriter that the flushed count just increased + docWriter.updateFlushedDocCount(docCount); + + success = true; + + } finally { + if (sReader != null) { + sReader.close(); + } + } + } finally { + if (!success) { + if (infoStream != null) + message("hit exception in addIndexes during merge"); + rollbackTransaction(); + } else { + commitTransaction(); + } + } + + if (mergePolicy instanceof LogMergePolicy && getUseCompoundFile()) { + + List files = null; + + synchronized(this) { + // Must incRef our files so that if another thread + // is running merge/optimize, it doesn't delete our + // segment's files before we have a change to + // finish making the compound file. + if (segmentInfos.contains(info)) { + files = info.files(); + deleter.incRef(files); + } + } + + if (files != null) { + + success = false; + + startTransaction(false); + + try { + merger.createCompoundFile(mergedName + ".cfs"); + synchronized(this) { + info.setUseCompoundFile(true); + } + + success = true; + + } finally { + + deleter.decRef(files); + + if (!success) { + if (infoStream != null) + message("hit exception building compound file in addIndexes during merge"); + + rollbackTransaction(); + } else { + commitTransaction(); + } + } + } + } + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } finally { + docWriter.resumeAllThreads(); + } + } + + // This is called after pending added and deleted + // documents have been flushed to the Directory but before + // the change is committed (new segments_N file written). + void doAfterFlush() + throws IOException { + } + + /** + * Flush all in-memory buffered updates (adds and deletes) + * to the Directory. + *

Note: while this will force buffered docs to be + * pushed into the index, it will not make these docs + * visible to a reader. Use {@link #commit()} instead + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + * @deprecated please call {@link #commit()}) instead + */ + public final void flush() throws CorruptIndexException, IOException { + flush(true, false, true); + } + + /**

Expert: prepare for commit. This does the first + * phase of 2-phase commit. You can only call this when + * autoCommit is false. This method does all steps + * necessary to commit changes since this writer was + * opened: flushes pending added and deleted docs, syncs + * the index files, writes most of next segments_N file. + * After calling this you must call either {@link + * #commit()} to finish the commit, or {@link + * #rollback()} to revert the commit and undo all changes + * done since the writer was opened.

+ * + * You can also just call {@link #commit()} directly + * without prepareCommit first in which case that method + * will internally call prepareCommit. + */ + public final void prepareCommit() throws CorruptIndexException, IOException { + ensureOpen(); + prepareCommit(false); + } + + private final void prepareCommit(boolean internal) throws CorruptIndexException, IOException { + + if (hitOOM) + throw new IllegalStateException("this writer hit an OutOfMemoryError; cannot commit"); + + if (autoCommit && !internal) + throw new IllegalStateException("this method can only be used when autoCommit is false"); + + if (!autoCommit && pendingCommit != null) + throw new IllegalStateException("prepareCommit was already called with no corresponding call to commit"); + + message("prepareCommit: flush"); + + flush(true, true, true); + + startCommit(0); + } + + private void commit(long sizeInBytes) throws IOException { + startCommit(sizeInBytes); + finishCommit(); + } + + private boolean committing; + + synchronized private void waitForCommit() { + // Only allow a single thread to do the commit, at a time: + while(committing) + doWait(); + committing = true; + } + + synchronized private void doneCommit() { + committing = false; + notifyAll(); + } + + /** + *

Commits all pending updates (added & deleted + * documents) to the index, and syncs all referenced index + * files, such that a reader will see the changes and the + * index updates will survive an OS or machine crash or + * power loss. Note that this does not wait for any + * running background merges to finish. This may be a + * costly operation, so you should test the cost in your + * application and do it only when really necessary.

+ * + *

Note that this operation calls Directory.sync on + * the index files. That call should not return until the + * file contents & metadata are on stable storage. For + * FSDirectory, this calls the OS's fsync. But, beware: + * some hardware devices may in fact cache writes even + * during fsync, and return before the bits are actually + * on stable storage, to give the appearance of faster + * performance. If you have such a device, and it does + * not have a battery backup (for example) then on power + * loss it may still lose data. Lucene cannot guarantee + * consistency on such devices.

+ * + * @see #prepareCommit + */ + + public final void commit() throws CorruptIndexException, IOException { + + ensureOpen(); + + // Only let one thread do the prepare/finish at a time + waitForCommit(); + + try { + message("commit: start"); + + if (autoCommit || pendingCommit == null) { + message("commit: now prepare"); + prepareCommit(true); + } else + message("commit: already prepared"); + + finishCommit(); + } finally { + doneCommit(); + } + } + + private synchronized final void finishCommit() throws CorruptIndexException, IOException { + + if (pendingCommit != null) { + try { + message("commit: pendingCommit != null"); + pendingCommit.finishCommit(directory); + lastCommitChangeCount = pendingCommitChangeCount; + segmentInfos.updateGeneration(pendingCommit); + setRollbackSegmentInfos(pendingCommit); + deleter.checkpoint(pendingCommit, true); + } finally { + deleter.decRef(pendingCommit); + pendingCommit = null; + notifyAll(); + } + + } else + message("commit: pendingCommit == null; skip"); + + message("commit: done"); + } + + /** + * Flush all in-memory buffered udpates (adds and deletes) + * to the Directory. + * @param triggerMerge if true, we may merge segments (if + * deletes or docs were flushed) if necessary + * @param flushDocStores if false we are allowed to keep + * doc stores open to share with the next segment + * @param flushDeletes whether pending deletes should also + * be flushed + */ + protected final void flush(boolean triggerMerge, boolean flushDocStores, boolean flushDeletes) throws CorruptIndexException, IOException { + // We can be called during close, when closing==true, so we must pass false to ensureOpen: + ensureOpen(false); + if (doFlush(flushDocStores, flushDeletes) && triggerMerge) + maybeMerge(); + } + + // TODO: this method should not have to be entirely + // synchronized, ie, merges should be allowed to commit + // even while a flush is happening + private synchronized final boolean doFlush(boolean flushDocStores, boolean flushDeletes) throws CorruptIndexException, IOException { + + ensureOpen(false); + + assert testPoint("startDoFlush"); + + flushCount++; + + // Make sure no threads are actively adding a document + + flushDeletes |= docWriter.deletesFull(); + + // When autoCommit=true we must always flush deletes + // when flushing a segment; otherwise deletes may become + // visible before their corresponding added document + // from an updateDocument call + flushDeletes |= autoCommit; + + // Returns true if docWriter is currently aborting, in + // which case we skip flushing this segment + if (docWriter.pauseAllThreads()) { + docWriter.resumeAllThreads(); + return false; + } + + try { + + SegmentInfo newSegment = null; + + final int numDocs = docWriter.getNumDocsInRAM(); + + // Always flush docs if there are any + boolean flushDocs = numDocs > 0; + + // With autoCommit=true we always must flush the doc + // stores when we flush + flushDocStores |= autoCommit; + String docStoreSegment = docWriter.getDocStoreSegment(); + if (docStoreSegment == null) + flushDocStores = false; + + int docStoreOffset = docWriter.getDocStoreOffset(); + + // docStoreOffset should only be non-zero when + // autoCommit == false + assert !autoCommit || 0 == docStoreOffset; + + boolean docStoreIsCompoundFile = false; + + if (infoStream != null) { + message(" flush: segment=" + docWriter.getSegment() + + " docStoreSegment=" + docWriter.getDocStoreSegment() + + " docStoreOffset=" + docStoreOffset + + " flushDocs=" + flushDocs + + " flushDeletes=" + flushDeletes + + " flushDocStores=" + flushDocStores + + " numDocs=" + numDocs + + " numBufDelTerms=" + docWriter.getNumBufferedDeleteTerms()); + message(" index before flush " + segString()); + } + + // Check if the doc stores must be separately flushed + // because other segments, besides the one we are about + // to flush, reference it + if (flushDocStores && (!flushDocs || !docWriter.getSegment().equals(docWriter.getDocStoreSegment()))) { + // We must separately flush the doc store + if (infoStream != null) + message(" flush shared docStore segment " + docStoreSegment); + + docStoreIsCompoundFile = flushDocStores(); + flushDocStores = false; + } + + String segment = docWriter.getSegment(); + + // If we are flushing docs, segment must not be null: + assert segment != null || !flushDocs; + + if (flushDocs) { + + boolean success = false; + final int flushedDocCount; + + try { + flushedDocCount = docWriter.flush(flushDocStores); + success = true; + } finally { + if (!success) { + if (infoStream != null) + message("hit exception flushing segment " + segment); + deleter.refresh(segment); + } + } + + if (0 == docStoreOffset && flushDocStores) { + // This means we are flushing private doc stores + // with this segment, so it will not be shared + // with other segments + assert docStoreSegment != null; + assert docStoreSegment.equals(segment); + docStoreOffset = -1; + docStoreIsCompoundFile = false; + docStoreSegment = null; + } + + // Create new SegmentInfo, but do not add to our + // segmentInfos until deletes are flushed + // successfully. + newSegment = new SegmentInfo(segment, + flushedDocCount, + directory, false, true, + docStoreOffset, docStoreSegment, + docStoreIsCompoundFile, + docWriter.hasProx()); + } + + docWriter.pushDeletes(); + + if (flushDocs) + segmentInfos.add(newSegment); + + if (flushDeletes) { + flushDeletesCount++; + applyDeletes(); + } + + doAfterFlush(); + + if (flushDocs) + checkpoint(); + + if (flushDocs && mergePolicy.useCompoundFile(segmentInfos, newSegment)) { + // Now build compound file + boolean success = false; + try { + docWriter.createCompoundFile(segment); + success = true; + } finally { + if (!success) { + if (infoStream != null) + message("hit exception creating compound file for newly flushed segment " + segment); + deleter.deleteFile(segment + "." + IndexFileNames.COMPOUND_FILE_EXTENSION); + } + } + + newSegment.setUseCompoundFile(true); + checkpoint(); + } + + return flushDocs; + + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } finally { + docWriter.clearFlushPending(); + docWriter.resumeAllThreads(); + } + } + + /** Expert: Return the total size of all index files currently cached in memory. + * Useful for size management with flushRamDocs() + */ + public final long ramSizeInBytes() { + ensureOpen(); + return docWriter.getRAMUsed(); + } + + /** Expert: Return the number of documents currently + * buffered in RAM. */ + public final synchronized int numRamDocs() { + ensureOpen(); + return docWriter.getNumDocsInRAM(); + } + + private int ensureContiguousMerge(MergePolicy.OneMerge merge) { + + int first = segmentInfos.indexOf(merge.segments.info(0)); + if (first == -1) + throw new MergePolicy.MergeException("could not find segment " + merge.segments.info(0).name + " in current segments", directory); + + final int numSegments = segmentInfos.size(); + + final int numSegmentsToMerge = merge.segments.size(); + for(int i=0;i= numSegments || !segmentInfos.info(first+i).equals(info)) { + if (segmentInfos.indexOf(info) == -1) + throw new MergePolicy.MergeException("MergePolicy selected a segment (" + info.name + ") that is not in the index", directory); + else + throw new MergePolicy.MergeException("MergePolicy selected non-contiguous segments to merge (" + merge.segString(directory) + " vs " + segString() + "), which IndexWriter (currently) cannot handle", + directory); + } + } + + return first; + } + + /** Carefully merges deletes for the segments we just + * merged. This is tricky because, although merging will + * clear all deletes (compacts the documents), new + * deletes may have been flushed to the segments since + * the merge was started. This method "carries over" + * such new deletes onto the newly merged segment, and + * saves the resulting deletes file (incrementing the + * delete generation for merge.info). If no deletes were + * flushed, no new deletes file is saved. */ + synchronized private void commitMergedDeletes(MergePolicy.OneMerge merge) throws IOException { + + assert testPoint("startCommitMergeDeletes"); + + final SegmentInfos sourceSegmentsClone = merge.segmentsClone; + final SegmentInfos sourceSegments = merge.segments; + + if (infoStream != null) + message("commitMergeDeletes " + merge.segString(directory)); + + // Carefully merge deletes that occurred after we + // started merging: + + BitVector deletes = null; + int docUpto = 0; + int delCount = 0; + + final int numSegmentsToMerge = sourceSegments.size(); + for(int i=0;i 0; + + if (merge.info != null) + // mergeInit already done + return; + + if (merge.isAborted()) + return; + + boolean changed = applyDeletes(); + + // If autoCommit == true then all deletes should have + // been flushed when we flushed the last segment + assert !changed || !autoCommit; + + final SegmentInfos sourceSegments = merge.segments; + final int end = sourceSegments.size(); + + // Check whether this merge will allow us to skip + // merging the doc stores (stored field & vectors). + // This is a very substantial optimization (saves tons + // of IO) that can only be applied with + // autoCommit=false. + + Directory lastDir = directory; + String lastDocStoreSegment = null; + int next = -1; + + boolean mergeDocStores = false; + boolean doFlushDocStore = false; + final String currentDocStoreSegment = docWriter.getDocStoreSegment(); + + // Test each segment to be merged: check if we need to + // flush/merge doc stores + for (int i = 0; i < end; i++) { + SegmentInfo si = sourceSegments.info(i); + + // If it has deletions we must merge the doc stores + if (si.hasDeletions()) + mergeDocStores = true; + + // If it has its own (private) doc stores we must + // merge the doc stores + if (-1 == si.getDocStoreOffset()) + mergeDocStores = true; + + // If it has a different doc store segment than + // previous segments, we must merge the doc stores + String docStoreSegment = si.getDocStoreSegment(); + if (docStoreSegment == null) + mergeDocStores = true; + else if (lastDocStoreSegment == null) + lastDocStoreSegment = docStoreSegment; + else if (!lastDocStoreSegment.equals(docStoreSegment)) + mergeDocStores = true; + + // Segments' docScoreOffsets must be in-order, + // contiguous. For the default merge policy now + // this will always be the case but for an arbitrary + // merge policy this may not be the case + if (-1 == next) + next = si.getDocStoreOffset() + si.docCount; + else if (next != si.getDocStoreOffset()) + mergeDocStores = true; + else + next = si.getDocStoreOffset() + si.docCount; + + // If the segment comes from a different directory + // we must merge + if (lastDir != si.dir) + mergeDocStores = true; + + // If the segment is referencing the current "live" + // doc store outputs then we must merge + if (si.getDocStoreOffset() != -1 && currentDocStoreSegment != null && si.getDocStoreSegment().equals(currentDocStoreSegment)) { + doFlushDocStore = true; + } + } + + final int docStoreOffset; + final String docStoreSegment; + final boolean docStoreIsCompoundFile; + + if (mergeDocStores) { + docStoreOffset = -1; + docStoreSegment = null; + docStoreIsCompoundFile = false; + } else { + SegmentInfo si = sourceSegments.info(0); + docStoreOffset = si.getDocStoreOffset(); + docStoreSegment = si.getDocStoreSegment(); + docStoreIsCompoundFile = si.getDocStoreIsCompoundFile(); + } + + if (mergeDocStores && doFlushDocStore) { + // SegmentMerger intends to merge the doc stores + // (stored fields, vectors), and at least one of the + // segments to be merged refers to the currently + // live doc stores. + + // TODO: if we know we are about to merge away these + // newly flushed doc store files then we should not + // make compound file out of them... + if (infoStream != null) + message("now flush at merge"); + doFlush(true, false); + //flush(false, true, false); + } + + // We must take a full copy at this point so that we can + // properly merge deletes in commitMerge() + merge.segmentsClone = (SegmentInfos) merge.segments.clone(); + + for (int i = 0; i < end; i++) { + SegmentInfo si = merge.segmentsClone.info(i); + + // IncRef all files for this segment info to make sure + // they are not removed while we are trying to merge. + if (si.dir == directory) + deleter.incRef(si.files()); + } + + merge.increfDone = true; + + merge.mergeDocStores = mergeDocStores; + + // Bind a new segment name here so even with + // ConcurrentMergePolicy we keep deterministic segment + // names. + merge.info = new SegmentInfo(newSegmentName(), 0, + directory, false, true, + docStoreOffset, + docStoreSegment, + docStoreIsCompoundFile, + false); + + // Also enroll the merged segment into mergingSegments; + // this prevents it from getting selected for a merge + // after our merge is done but while we are building the + // CFS: + mergingSegments.add(merge.info); + } + + /** This is called after merging a segment and before + * building its CFS. Return true if the files should be + * sync'd. If you return false, then the source segment + * files that were merged cannot be deleted until the CFS + * file is built & sync'd. So, returning false consumes + * more transient disk space, but saves performance of + * not having to sync files which will shortly be deleted + * anyway. + * @deprecated -- this will be removed in 3.0 when + * autoCommit is hardwired to false */ + private synchronized boolean doCommitBeforeMergeCFS(MergePolicy.OneMerge merge) throws IOException { + long freeableBytes = 0; + final int size = merge.segments.size(); + for(int i=0;i totalBytes) + return true; + else + return false; + } + + /** Does fininishing for a merge, which is fast but holds + * the synchronized lock on IndexWriter instance. */ + final synchronized void mergeFinish(MergePolicy.OneMerge merge) throws IOException { + + // Optimize, addIndexes or finishMerges may be waiting + // on merges to finish. + notifyAll(); + + if (merge.increfDone) + decrefMergeSegments(merge); + + assert merge.registerDone; + + final SegmentInfos sourceSegments = merge.segments; + final int end = sourceSegments.size(); + for(int i=0;i X minutes or + // more than Y bytes have been written, etc. + if (autoCommit) { + final long size; + synchronized(this) { + size = merge.info.sizeInBytes(); + } + commit(size); + } + + return mergedDocCount; + } + + synchronized void addMergeException(MergePolicy.OneMerge merge) { + assert merge.getException() != null; + if (!mergeExceptions.contains(merge) && mergeGen == merge.mergeGen) + mergeExceptions.add(merge); + } + + // Apply buffered deletes to all segments. + private final synchronized boolean applyDeletes() throws CorruptIndexException, IOException { + assert testPoint("startApplyDeletes"); + SegmentInfos rollback = (SegmentInfos) segmentInfos.clone(); + boolean success = false; + boolean changed; + try { + changed = docWriter.applyDeletes(segmentInfos); + success = true; + } finally { + if (!success) { + if (infoStream != null) + message("hit exception flushing deletes"); + + // Carefully remove any partially written .del + // files + final int size = rollback.size(); + for(int i=0;i 0) { + buffer.append(' '); + } + final SegmentInfo info = infos.info(i); + buffer.append(info.segString(directory)); + if (info.dir != directory) + buffer.append("**"); + } + return buffer.toString(); + } + + // Files that have been sync'd already + private HashSet synced = new HashSet(); + + // Files that are now being sync'd + private HashSet syncing = new HashSet(); + + private boolean startSync(String fileName, Collection pending) { + synchronized(synced) { + if (!synced.contains(fileName)) { + if (!syncing.contains(fileName)) { + syncing.add(fileName); + return true; + } else { + pending.add(fileName); + return false; + } + } else + return false; + } + } + + private void finishSync(String fileName, boolean success) { + synchronized(synced) { + assert syncing.contains(fileName); + syncing.remove(fileName); + if (success) + synced.add(fileName); + synced.notifyAll(); + } + } + + /** Blocks until all files in syncing are sync'd */ + private boolean waitForAllSynced(Collection syncing) throws IOException { + synchronized(synced) { + Iterator it = syncing.iterator(); + while(it.hasNext()) { + final String fileName = (String) it.next(); + while(!synced.contains(fileName)) { + if (!syncing.contains(fileName)) + // There was an error because a file that was + // previously syncing failed to appear in synced + return false; + else + try { + synced.wait(); + } catch (InterruptedException ie) { + continue; + } + } + } + return true; + } + } + + /** Pauses before syncing. On Windows, at least, it's + * best (performance-wise) to pause in order to let OS + * flush writes to disk on its own, before forcing a + * sync. + * @deprecated -- this will be removed in 3.0 when + * autoCommit is hardwired to false */ + private void syncPause(long sizeInBytes) { + if (mergeScheduler instanceof ConcurrentMergeScheduler && maxSyncPauseSeconds > 0) { + // Rough heuristic: for every 10 MB, we pause for 1 + // second, up until the max + long pauseTime = (long) (1000*sizeInBytes/10/1024/1024); + final long maxPauseTime = (long) (maxSyncPauseSeconds*1000); + if (pauseTime > maxPauseTime) + pauseTime = maxPauseTime; + final int sleepCount = (int) (pauseTime / 100); + for(int i=0;i lastCommitChangeCount && (pendingCommit == null || myChangeCount > pendingCommitChangeCount)) { + + // Wait now for any current pending commit to complete: + while(pendingCommit != null) { + message("wait for existing pendingCommit to finish..."); + doWait(); + } + + if (segmentInfos.getGeneration() > toSync.getGeneration()) + toSync.updateGeneration(segmentInfos); + + boolean success = false; + try { + + // Exception here means nothing is prepared + // (this method unwinds everything it did on + // an exception) + try { + toSync.prepareCommit(directory); + } finally { + // Have our master segmentInfos record the + // generations we just prepared. We do this + // on error or success so we don't + // double-write a segments_N file. + segmentInfos.updateGeneration(toSync); + } + + assert pendingCommit == null; + setPending = true; + pendingCommit = toSync; + pendingCommitChangeCount = myChangeCount; + success = true; + } finally { + if (!success) + message("hit exception committing segments file"); + } + } else + message("sync superseded by newer infos"); + } + + message("done all syncs"); + + assert testPoint("midStartCommitSuccess"); + + } finally { + synchronized(this) { + if (!setPending) + deleter.decRef(toSync); + } + } + } catch (OutOfMemoryError oom) { + hitOOM = true; + throw oom; + } + assert testPoint("finishStartCommit"); + } + + /** + * Returns true iff the index in the named directory is + * currently locked. + * @param directory the directory to check for a lock + * @throws IOException if there is a low-level IO error + */ + public static boolean isLocked(Directory directory) throws IOException { + return directory.makeLock(WRITE_LOCK_NAME).isLocked(); + } + + /** + * Returns true iff the index in the named directory is + * currently locked. + * @param directory the directory to check for a lock + * @throws IOException if there is a low-level IO error + */ + public static boolean isLocked(String directory) throws IOException { + Directory dir = FSDirectory.getDirectory(directory); + try { + return isLocked(dir); + } finally { + dir.close(); + } + } + + /** + * Forcibly unlocks the index in the named directory. + *

+ * Caution: this should only be used by failure recovery code, + * when it is known that no other process nor thread is in fact + * currently accessing this index. + */ + public static void unlock(Directory directory) throws IOException { + directory.makeLock(IndexWriter.WRITE_LOCK_NAME).release(); + } + + /** + * Specifies maximum field length in {@link IndexWriter} constructors. + * {@link #setMaxFieldLength(int)} overrides the value set by + * the constructor. + */ + public static final class MaxFieldLength { + + private int limit; + private String name; + + /** + * Private type-safe-enum-pattern constructor. + * + * @param name instance name + * @param limit maximum field length + */ + private MaxFieldLength(String name, int limit) { + this.name = name; + this.limit = limit; + } + + /** + * Public constructor to allow users to specify the maximum field size limit. + * + * @param limit The maximum field length + */ + public MaxFieldLength(int limit) { + this("User-specified", limit); + } + + public int getLimit() { + return limit; + } + + public String toString() + { + return name + ":" + limit; + } + + /** Sets the maximum field length to {@link Integer#MAX_VALUE}. */ + public static final MaxFieldLength UNLIMITED + = new MaxFieldLength("UNLIMITED", Integer.MAX_VALUE); + + /** + * Sets the maximum field length to + * {@link #DEFAULT_MAX_FIELD_LENGTH} + * */ + public static final MaxFieldLength LIMITED + = new MaxFieldLength("LIMITED", DEFAULT_MAX_FIELD_LENGTH); + } + + // Used only by assert for testing. Current points: + // startDoFlush + // startCommitMerge + // startStartCommit + // midStartCommit + // midStartCommit2 + // midStartCommitSuccess + // finishStartCommit + // startCommitMergeDeletes + // startMergeInit + // startApplyDeletes + // DocumentsWriter.ThreadState.init start + boolean testPoint(String name) { + return true; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/IntBlockPool.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/IntBlockPool.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/IntBlockPool.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,65 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +final class IntBlockPool { + + public int[][] buffers = new int[10][]; + + int bufferUpto = -1; // Which buffer we are upto + public int intUpto = DocumentsWriter.INT_BLOCK_SIZE; // Where we are in head buffer + + public int[] buffer; // Current head buffer + public int intOffset = -DocumentsWriter.INT_BLOCK_SIZE; // Current head offset + + final private DocumentsWriter docWriter; + final boolean trackAllocations; + + public IntBlockPool(DocumentsWriter docWriter, boolean trackAllocations) { + this.docWriter = docWriter; + this.trackAllocations = trackAllocations; + } + + public void reset() { + if (bufferUpto != -1) { + if (bufferUpto > 0) + // Recycle all but the first buffer + docWriter.recycleIntBlocks(buffers, 1, 1+bufferUpto); + + // Reuse first buffer + bufferUpto = 0; + intUpto = 0; + intOffset = 0; + buffer = buffers[0]; + } + } + + public void nextBuffer() { + if (1+bufferUpto == buffers.length) { + int[][] newBuffers = new int[(int) (buffers.length*1.5)][]; + System.arraycopy(buffers, 0, newBuffers, 0, buffers.length); + buffers = newBuffers; + } + buffer = buffers[1+bufferUpto] = docWriter.getIntBlock(trackAllocations); + bufferUpto++; + + intUpto = 0; + intOffset += DocumentsWriter.INT_BLOCK_SIZE; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumer.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,46 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Map; +import java.io.IOException; + +abstract class InvertedDocConsumer { + + /** Add a new thread */ + abstract InvertedDocConsumerPerThread addThread(DocInverterPerThread docInverterPerThread); + + /** Abort (called after hitting AbortException) */ + abstract void abort(); + + /** Flush a new segment */ + abstract void flush(Map threadsAndFields, DocumentsWriter.FlushState state) throws IOException; + + /** Close doc stores */ + abstract void closeDocStore(DocumentsWriter.FlushState state) throws IOException; + + /** Attempt to free RAM, returning true if any RAM was + * freed */ + abstract boolean freeRAM(); + + FieldInfos fieldInfos; + + void setFieldInfos(FieldInfos fieldInfos) { + this.fieldInfos = fieldInfos; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumerPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumerPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumerPerField.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,41 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Fieldable; +import org.apache.lucene.analysis.Token; +import java.io.IOException; + +abstract class InvertedDocConsumerPerField { + + // Called once per field, and is given all Fieldable + // occurrences for this field in the document. Return + // true if you wish to see inverted tokens for these + // fields: + abstract boolean start(Fieldable[] fields, int count) throws IOException; + + // Called once per inverted token + abstract void add(Token token) throws IOException; + + // Called once per field per document, after all Fieldable + // occurrences are inverted + abstract void finish() throws IOException; + + // Called on hitting an aborting exception + abstract void abort(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumerPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumerPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocConsumerPerThread.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,27 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +abstract class InvertedDocConsumerPerThread { + abstract void startDocument() throws IOException; + abstract InvertedDocConsumerPerField addField(DocInverterPerField docInverterPerField, FieldInfo fieldInfo); + abstract DocumentsWriter.DocWriter finishDocument() throws IOException; + abstract void abort(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumer.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,29 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Map; +import java.io.IOException; + +abstract class InvertedDocEndConsumer { + abstract InvertedDocEndConsumerPerThread addThread(DocInverterPerThread docInverterPerThread); + abstract void flush(Map threadsAndFields, DocumentsWriter.FlushState state) throws IOException; + abstract void closeDocStore(DocumentsWriter.FlushState state) throws IOException; + abstract void abort(); + abstract void setFieldInfos(FieldInfos fieldInfos); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumerPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumerPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumerPerField.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,23 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +abstract class InvertedDocEndConsumerPerField { + abstract void finish(); + abstract void abort(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumerPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumerPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/InvertedDocEndConsumerPerThread.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,25 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +abstract class InvertedDocEndConsumerPerThread { + abstract void startDocument(); + abstract InvertedDocEndConsumerPerField addField(DocInverterPerField docInverterPerField, FieldInfo fieldInfo); + abstract void finishDocument(); + abstract void abort(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/KeepOnlyLastCommitDeletionPolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/KeepOnlyLastCommitDeletionPolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/KeepOnlyLastCommitDeletionPolicy.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,50 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.List; + +/** + * This {@link IndexDeletionPolicy} implementation that + * keeps only the most recent commit and immediately removes + * all prior commits after a new commit is done. This is + * the default deletion policy. + */ + +public final class KeepOnlyLastCommitDeletionPolicy implements IndexDeletionPolicy { + + /** + * Deletes all commits except the most recent one. + */ + public void onInit(List commits) { + // Note that commits.size() should normally be 1: + onCommit(commits); + } + + /** + * Deletes all commits except the most recent one. + */ + public void onCommit(List commits) { + // Note that commits.size() should normally be 2 (if not + // called by onInit above): + int size = commits.size(); + for(int i=0;iDetermines the largest segment (measured by total + * byte size of the segment's files, in MB) that may be + * merged with other segments. Small values (e.g., less + * than 50 MB) are best for interactive indexing, as this + * limits the length of pauses while indexing to a few + * seconds. Larger values are best for batched indexing + * and speedier searches.

+ * + *

Note that {@link #setMaxMergeDocs} is also + * used to check whether a segment is too large for + * merging (it's either or).

*/ + public void setMaxMergeMB(double mb) { + maxMergeSize = (long) (mb*1024*1024); + } + + /** Returns the largest segment (meaured by total byte + * size of the segment's files, in MB) that may be merged + * with other segments. + * @see #setMaxMergeMB */ + public double getMaxMergeMB() { + return ((double) maxMergeSize)/1024/1024; + } + + /** Sets the minimum size for the lowest level segments. + * Any segments below this size are considered to be on + * the same level (even if they vary drastically in size) + * and will be merged whenever there are mergeFactor of + * them. This effectively truncates the "long tail" of + * small segments that would otherwise be created into a + * single level. If you set this too large, it could + * greatly increase the merging cost during indexing (if + * you flush many small segments). */ + public void setMinMergeMB(double mb) { + minMergeSize = (long) (mb*1024*1024); + } + + /** Get the minimum size for a segment to remain + * un-merged. + * @see #setMinMergeMB **/ + public double getMinMergeMB() { + return ((double) minMergeSize)/1024/1024; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/LogDocMergePolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/LogDocMergePolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/LogDocMergePolicy.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,61 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** This is a {@link LogMergePolicy} that measures size of a + * segment as the number of documents (not taking deletions + * into account). */ + +public class LogDocMergePolicy extends LogMergePolicy { + + /** Default minimum segment size. @see setMinMergeDocs */ + public static final int DEFAULT_MIN_MERGE_DOCS = 1000; + + public LogDocMergePolicy() { + super(); + minMergeSize = DEFAULT_MIN_MERGE_DOCS; + + // maxMergeSize is never used by LogDocMergePolicy; set + // it to Long.MAX_VALUE to disable it + maxMergeSize = Long.MAX_VALUE; + } + protected long size(SegmentInfo info) { + return info.docCount; + } + + /** Sets the minimum size for the lowest level segments. + * Any segments below this size are considered to be on + * the same level (even if they vary drastically in size) + * and will be merged whenever there are mergeFactor of + * them. This effectively truncates the "long tail" of + * small segments that would otherwise be created into a + * single level. If you set this too large, it could + * greatly increase the merging cost during indexing (if + * you flush many small segments). */ + public void setMinMergeDocs(int minMergeDocs) { + minMergeSize = minMergeDocs; + } + + /** Get the minimum size for a segment to remain + * un-merged. + * @see #setMinMergeDocs **/ + public int getMinMergeDocs() { + return (int) minMergeSize; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/LogMergePolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/LogMergePolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/LogMergePolicy.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,429 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Set; + +import org.apache.lucene.store.Directory; + +/**

This class implements a {@link MergePolicy} that tries + * to merge segments into levels of exponentially + * increasing size, where each level has < mergeFactor + * segments in it. Whenever a given levle has mergeFactor + * segments or more in it, they will be merged.

+ * + *

This class is abstract and requires a subclass to + * define the {@link #size} method which specifies how a + * segment's size is determined. {@link LogDocMergePolicy} + * is one subclass that measures size by document count in + * the segment. {@link LogByteSizeMergePolicy} is another + * subclass that measures size as the total byte size of the + * file(s) for the segment.

+ */ + +public abstract class LogMergePolicy extends MergePolicy { + + /** Defines the allowed range of log(size) for each + * level. A level is computed by taking the max segment + * log size, minuse LEVEL_LOG_SPAN, and finding all + * segments falling within that range. */ + public static final double LEVEL_LOG_SPAN = 0.75; + + /** Default merge factor, which is how many segments are + * merged at a time */ + public static final int DEFAULT_MERGE_FACTOR = 10; + + /** Default maximum segment size. A segment of this size + * or larger will never be merged. @see setMaxMergeDocs */ + public static final int DEFAULT_MAX_MERGE_DOCS = Integer.MAX_VALUE; + + private int mergeFactor = DEFAULT_MERGE_FACTOR; + + long minMergeSize; + long maxMergeSize; + int maxMergeDocs = DEFAULT_MAX_MERGE_DOCS; + + private boolean useCompoundFile = true; + private boolean useCompoundDocStore = true; + private IndexWriter writer; + + private void message(String message) { + if (writer != null) + writer.message("LMP: " + message); + } + + /**

Returns the number of segments that are merged at + * once and also controls the total number of segments + * allowed to accumulate in the index.

*/ + public int getMergeFactor() { + return mergeFactor; + } + + /** Determines how often segment indices are merged by + * addDocument(). With smaller values, less RAM is used + * while indexing, and searches on unoptimized indices are + * faster, but indexing speed is slower. With larger + * values, more RAM is used during indexing, and while + * searches on unoptimized indices are slower, indexing is + * faster. Thus larger values (> 10) are best for batch + * index creation, and smaller values (< 10) for indices + * that are interactively maintained. */ + public void setMergeFactor(int mergeFactor) { + if (mergeFactor < 2) + throw new IllegalArgumentException("mergeFactor cannot be less than 2"); + this.mergeFactor = mergeFactor; + } + + // Javadoc inherited + public boolean useCompoundFile(SegmentInfos infos, SegmentInfo info) { + return useCompoundFile; + } + + /** Sets whether compound file format should be used for + * newly flushed and newly merged segments. */ + public void setUseCompoundFile(boolean useCompoundFile) { + this.useCompoundFile = useCompoundFile; + } + + /** Returns true if newly flushed and newly merge segments + * are written in compound file format. @see + * #setUseCompoundFile */ + public boolean getUseCompoundFile() { + return useCompoundFile; + } + + // Javadoc inherited + public boolean useCompoundDocStore(SegmentInfos infos) { + return useCompoundDocStore; + } + + /** Sets whether compound file format should be used for + * newly flushed and newly merged doc store + * segment files (term vectors and stored fields). */ + public void setUseCompoundDocStore(boolean useCompoundDocStore) { + this.useCompoundDocStore = useCompoundDocStore; + } + + /** Returns true if newly flushed and newly merge doc + * store segment files (term vectors and stored fields) + * are written in compound file format. @see + * #setUseCompoundDocStore */ + public boolean getUseCompoundDocStore() { + return useCompoundDocStore; + } + + public void close() {} + + abstract protected long size(SegmentInfo info) throws IOException; + + private boolean isOptimized(SegmentInfos infos, IndexWriter writer, int maxNumSegments, Set segmentsToOptimize) throws IOException { + final int numSegments = infos.size(); + int numToOptimize = 0; + SegmentInfo optimizeInfo = null; + for(int i=0;i 0; + + if (!isOptimized(infos, writer, maxNumSegments, segmentsToOptimize)) { + + // Find the newest (rightmost) segment that needs to + // be optimized (other segments may have been flushed + // since optimize started): + int last = infos.size(); + while(last > 0) { + final SegmentInfo info = infos.info(--last); + if (segmentsToOptimize.contains(info)) { + last++; + break; + } + } + + if (last > 0) { + + spec = new MergeSpecification(); + + // First, enroll all "full" merges (size + // mergeFactor) to potentially be run concurrently: + while (last - maxNumSegments + 1 >= mergeFactor) { + spec.add(new OneMerge(infos.range(last-mergeFactor, last), useCompoundFile)); + last -= mergeFactor; + } + + // Only if there are no full merges pending do we + // add a final partial (< mergeFactor segments) merge: + if (0 == spec.merges.size()) { + if (maxNumSegments == 1) { + + // Since we must optimize down to 1 segment, the + // choice is simple: + if (last > 1 || !isOptimized(writer, infos.info(0))) + spec.add(new OneMerge(infos.range(0, last), useCompoundFile)); + } else if (last > maxNumSegments) { + + // Take care to pick a partial merge that is + // least cost, but does not make the index too + // lopsided. If we always just picked the + // partial tail then we could produce a highly + // lopsided index over time: + + // We must merge this many segments to leave + // maxNumSegments in the index (from when + // optimize was first kicked off): + final int finalMergeSize = last - maxNumSegments + 1; + + // Consider all possible starting points: + long bestSize = 0; + int bestStart = 0; + + for(int i=0;i maxLevel) + maxLevel = level; + } + + // Now search backwards for the rightmost segment that + // falls into this level: + float levelBottom; + if (maxLevel < levelFloor) + // All remaining segments fall into the min level + levelBottom = -1.0F; + else { + levelBottom = (float) (maxLevel - LEVEL_LOG_SPAN); + + // Force a boundary at the level floor + if (levelBottom < levelFloor && maxLevel >= levelFloor) + levelBottom = levelFloor; + } + + int upto = numSegments-1; + while(upto >= start) { + if (levels[upto] >= levelBottom) { + break; + } + upto--; + } + message(" level " + levelBottom + " to " + maxLevel + ": " + (1+upto-start) + " segments"); + + // Finally, record all merges that are viable at this level: + int end = start + mergeFactor; + while(end <= 1+upto) { + boolean anyTooLarge = false; + for(int i=start;i= maxMergeSize || info.docCount >= maxMergeDocs); + } + + if (!anyTooLarge) { + if (spec == null) + spec = new MergeSpecification(); + message(" " + start + " to " + end + ": add this merge"); + spec.add(new OneMerge(infos.range(start, end), useCompoundFile)); + } else + message(" " + start + " to " + end + ": contains segment over maxMergeSize or maxMergeDocs; skipping"); + + start = end; + end = start + mergeFactor; + } + + start = 1+upto; + } + + return spec; + } + + /**

Determines the largest segment (measured by + * document count) that may be merged with other segments. + * Small values (e.g., less than 10,000) are best for + * interactive indexing, as this limits the length of + * pauses while indexing to a few seconds. Larger values + * are best for batched indexing and speedier + * searches.

+ * + *

The default value is {@link Integer#MAX_VALUE}.

+ * + *

The default merge policy ({@link + * LogByteSizeMergePolicy}) also allows you to set this + * limit by net size (in MB) of the segment, using {@link + * LogByteSizeMergePolicy#setMaxMergeMB}.

+ */ + public void setMaxMergeDocs(int maxMergeDocs) { + this.maxMergeDocs = maxMergeDocs; + } + + /** Returns the largest segment (measured by document + * count) that may be merged with other segments. + * @see #setMaxMergeDocs */ + public int getMaxMergeDocs() { + return maxMergeDocs; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/MergeDocIDRemapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/MergeDocIDRemapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/MergeDocIDRemapper.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,110 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Remaps docIDs after a merge has completed, where the + * merged segments had at least one deletion. This is used + * to renumber the buffered deletes in IndexWriter when a + * merge of segments with deletions commits. */ + +final class MergeDocIDRemapper { + int[] starts; // used for binary search of mapped docID + int[] newStarts; // starts, minus the deletes + int[][] docMaps; // maps docIDs in the merged set + int minDocID; // minimum docID that needs renumbering + int maxDocID; // 1+ the max docID that needs renumbering + int docShift; // total # deleted docs that were compacted by this merge + + public MergeDocIDRemapper(SegmentInfos infos, int[][] docMaps, int[] delCounts, MergePolicy.OneMerge merge, int mergedDocCount) { + this.docMaps = docMaps; + SegmentInfo firstSegment = merge.segments.info(0); + int i = 0; + while(true) { + SegmentInfo info = infos.info(i); + if (info.equals(firstSegment)) + break; + minDocID += info.docCount; + i++; + } + + int numDocs = 0; + for(int j=0;j 0; + + // Make sure it all adds up: + assert docShift == maxDocID - (newStarts[docMaps.length-1] + merge.segments.info(docMaps.length-1).docCount - delCounts[docMaps.length-1]); + } + + public int remap(int oldDocID) { + if (oldDocID < minDocID) + // Unaffected by merge + return oldDocID; + else if (oldDocID >= maxDocID) + // This doc was "after" the merge, so simple shift + return oldDocID - docShift; + else { + // Binary search to locate this document & find its new docID + int lo = 0; // search starts array + int hi = docMaps.length - 1; // for first element less + + while (hi >= lo) { + int mid = (lo + hi) >> 1; + int midValue = starts[mid]; + if (oldDocID < midValue) + hi = mid - 1; + else if (oldDocID > midValue) + lo = mid + 1; + else { // found a match + while (mid+1 < docMaps.length && starts[mid+1] == midValue) { + mid++; // scan to last match + } + if (docMaps[mid] != null) + return newStarts[mid] + docMaps[mid][oldDocID-starts[mid]]; + else + return newStarts[mid] + oldDocID-starts[mid]; + } + } + if (docMaps[hi] != null) + return newStarts[hi] + docMaps[hi][oldDocID-starts[hi]]; + else + return newStarts[hi] + oldDocID-starts[hi]; + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/MergePolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/MergePolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/MergePolicy.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,263 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; + +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Set; + +/** + *

Expert: a MergePolicy determines the sequence of + * primitive merge operations to be used for overall merge + * and optimize operations.

+ * + *

Whenever the segments in an index have been altered by + * {@link IndexWriter}, either the addition of a newly + * flushed segment, addition of many segments from + * addIndexes* calls, or a previous merge that may now need + * to cascade, {@link IndexWriter} invokes {@link + * #findMerges} to give the MergePolicy a chance to pick + * merges that are now required. This method returns a + * {@link MergeSpecification} instance describing the set of + * merges that should be done, or null if no merges are + * necessary. When IndexWriter.optimize is called, it calls + * {@link #findMergesForOptimize} and the MergePolicy should + * then return the necessary merges.

+ * + *

Note that the policy can return more than one merge at + * a time. In this case, if the writer is using {@link + * SerialMergeScheduler}, the merges will be run + * sequentially but if it is using {@link + * ConcurrentMergeScheduler} they will be run concurrently.

+ * + *

The default MergePolicy is {@link + * LogByteSizeMergePolicy}.

+ *

NOTE: This API is new and still experimental + * (subject to change suddenly in the next release)

+ */ + +public abstract class MergePolicy { + + /** OneMerge provides the information necessary to perform + * an individual primitive merge operation, resulting in + * a single new segment. The merge spec includes the + * subset of segments to be merged as well as whether the + * new segment should use the compound file format. */ + + public static class OneMerge { + + SegmentInfo info; // used by IndexWriter + boolean mergeDocStores; // used by IndexWriter + boolean optimize; // used by IndexWriter + SegmentInfos segmentsClone; // used by IndexWriter + boolean increfDone; // used by IndexWriter + boolean registerDone; // used by IndexWriter + long mergeGen; // used by IndexWriter + boolean isExternal; // used by IndexWriter + int maxNumSegmentsOptimize; // used by IndexWriter + + final SegmentInfos segments; + final boolean useCompoundFile; + boolean aborted; + Throwable error; + + public OneMerge(SegmentInfos segments, boolean useCompoundFile) { + if (0 == segments.size()) + throw new RuntimeException("segments must include at least one segment"); + this.segments = segments; + this.useCompoundFile = useCompoundFile; + } + + /** Record that an exception occurred while executing + * this merge */ + synchronized void setException(Throwable error) { + this.error = error; + } + + /** Retrieve previous exception set by {@link + * #setException}. */ + synchronized Throwable getException() { + return error; + } + + /** Mark this merge as aborted. If this is called + * before the merge is committed then the merge will + * not be committed. */ + synchronized void abort() { + aborted = true; + } + + /** Returns true if this merge was aborted. */ + synchronized boolean isAborted() { + return aborted; + } + + synchronized void checkAborted(Directory dir) throws MergeAbortedException { + if (aborted) + throw new MergeAbortedException("merge is aborted: " + segString(dir)); + } + + String segString(Directory dir) { + StringBuffer b = new StringBuffer(); + final int numSegments = segments.size(); + for(int i=0;i 0) b.append(' '); + b.append(segments.info(i).segString(dir)); + } + if (info != null) + b.append(" into ").append(info.name); + if (optimize) + b.append(" [optimize]"); + return b.toString(); + } + } + + /** + * A MergeSpecification instance provides the information + * necessary to perform multiple merges. It simply + * contains a list of {@link OneMerge} instances. + */ + + public static class MergeSpecification { + + /** + * The subset of segments to be included in the primitive merge. + */ + + public List merges = new ArrayList(); + + public void add(OneMerge merge) { + merges.add(merge); + } + + public String segString(Directory dir) { + StringBuffer b = new StringBuffer(); + b.append("MergeSpec:\n"); + final int count = merges.size(); + for(int i=0;iExpert: {@link IndexWriter} uses an instance + * implementing this interface to execute the merges + * selected by a {@link MergePolicy}. The default + * MergeScheduler is {@link ConcurrentMergeScheduler}.

+ *

NOTE: This API is new and still experimental + * (subject to change suddenly in the next release)

+*/ + +public abstract class MergeScheduler { + + /** Run the merges provided by {@link IndexWriter#getNextMerge()}. */ + abstract void merge(IndexWriter writer) + throws CorruptIndexException, IOException; + + /** Close this MergeScheduler. */ + abstract void close() + throws CorruptIndexException, IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/MultiLevelSkipListReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/MultiLevelSkipListReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/MultiLevelSkipListReader.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,273 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Arrays; + +import org.apache.lucene.store.BufferedIndexInput; +import org.apache.lucene.store.IndexInput; + +/** + * This abstract class reads skip lists with multiple levels. + * + * See {@link MultiLevelSkipListWriter} for the information about the encoding + * of the multi level skip lists. + * + * Subclasses must implement the abstract method {@link #readSkipData(int, IndexInput)} + * which defines the actual format of the skip data. + */ +abstract class MultiLevelSkipListReader { + // the maximum number of skip levels possible for this index + private int maxNumberOfSkipLevels; + + // number of levels in this skip list + private int numberOfSkipLevels; + + // Expert: defines the number of top skip levels to buffer in memory. + // Reducing this number results in less memory usage, but possibly + // slower performance due to more random I/Os. + // Please notice that the space each level occupies is limited by + // the skipInterval. The top level can not contain more than + // skipLevel entries, the second top level can not contain more + // than skipLevel^2 entries and so forth. + private int numberOfLevelsToBuffer = 1; + + private int docCount; + private boolean haveSkipped; + + private IndexInput[] skipStream; // skipStream for each level + private long skipPointer[]; // the start pointer of each skip level + private int skipInterval[]; // skipInterval of each level + private int[] numSkipped; // number of docs skipped per level + + private int[] skipDoc; // doc id of current skip entry per level + private int lastDoc; // doc id of last read skip entry with docId <= target + private long[] childPointer; // child pointer of current skip entry per level + private long lastChildPointer; // childPointer of last read skip entry with docId <= target + + private boolean inputIsBuffered; + + public MultiLevelSkipListReader(IndexInput skipStream, int maxSkipLevels, int skipInterval) { + this.skipStream = new IndexInput[maxSkipLevels]; + this.skipPointer = new long[maxSkipLevels]; + this.childPointer = new long[maxSkipLevels]; + this.numSkipped = new int[maxSkipLevels]; + this.maxNumberOfSkipLevels = maxSkipLevels; + this.skipInterval = new int[maxSkipLevels]; + this.skipStream [0]= skipStream; + this.inputIsBuffered = (skipStream instanceof BufferedIndexInput); + this.skipInterval[0] = skipInterval; + for (int i = 1; i < maxSkipLevels; i++) { + // cache skip intervals + this.skipInterval[i] = this.skipInterval[i - 1] * skipInterval; + } + skipDoc = new int[maxSkipLevels]; + } + + + /** Returns the id of the doc to which the last call of {@link #skipTo(int)} + * has skipped. */ + int getDoc() { + return lastDoc; + } + + + /** Skips entries to the first beyond the current whose document number is + * greater than or equal to target. Returns the current doc count. + */ + int skipTo(int target) throws IOException { + if (!haveSkipped) { + // first time, load skip levels + loadSkipLevels(); + haveSkipped = true; + } + + // walk up the levels until highest level is found that has a skip + // for this target + int level = 0; + while (level < numberOfSkipLevels - 1 && target > skipDoc[level + 1]) { + level++; + } + + while (level >= 0) { + if (target > skipDoc[level]) { + if (!loadNextSkip(level)) { + continue; + } + } else { + // no more skips on this level, go down one level + if (level > 0 && lastChildPointer > skipStream[level - 1].getFilePointer()) { + seekChild(level - 1); + } + level--; + } + } + + return numSkipped[0] - skipInterval[0] - 1; + } + + private boolean loadNextSkip(int level) throws IOException { + // we have to skip, the target document is greater than the current + // skip list entry + setLastSkipData(level); + + numSkipped[level] += skipInterval[level]; + + if (numSkipped[level] > docCount) { + // this skip list is exhausted + skipDoc[level] = Integer.MAX_VALUE; + if (numberOfSkipLevels > level) numberOfSkipLevels = level; + return false; + } + + // read next skip entry + skipDoc[level] += readSkipData(level, skipStream[level]); + + if (level != 0) { + // read the child pointer if we are not on the leaf level + childPointer[level] = skipStream[level].readVLong() + skipPointer[level - 1]; + } + + return true; + + } + + /** Seeks the skip entry on the given level */ + protected void seekChild(int level) throws IOException { + skipStream[level].seek(lastChildPointer); + numSkipped[level] = numSkipped[level + 1] - skipInterval[level + 1]; + skipDoc[level] = lastDoc; + if (level > 0) { + childPointer[level] = skipStream[level].readVLong() + skipPointer[level - 1]; + } + } + + void close() throws IOException { + for (int i = 1; i < skipStream.length; i++) { + if (skipStream[i] != null) { + skipStream[i].close(); + } + } + } + + /** initializes the reader */ + void init(long skipPointer, int df) { + this.skipPointer[0] = skipPointer; + this.docCount = df; + Arrays.fill(skipDoc, 0); + Arrays.fill(numSkipped, 0); + Arrays.fill(childPointer, 0); + + haveSkipped = false; + for (int i = 1; i < numberOfSkipLevels; i++) { + skipStream[i] = null; + } + } + + /** Loads the skip levels */ + private void loadSkipLevels() throws IOException { + numberOfSkipLevels = docCount == 0 ? 0 : (int) Math.floor(Math.log(docCount) / Math.log(skipInterval[0])); + if (numberOfSkipLevels > maxNumberOfSkipLevels) { + numberOfSkipLevels = maxNumberOfSkipLevels; + } + + skipStream[0].seek(skipPointer[0]); + + int toBuffer = numberOfLevelsToBuffer; + + for (int i = numberOfSkipLevels - 1; i > 0; i--) { + // the length of the current level + long length = skipStream[0].readVLong(); + + // the start pointer of the current level + skipPointer[i] = skipStream[0].getFilePointer(); + if (toBuffer > 0) { + // buffer this level + skipStream[i] = new SkipBuffer(skipStream[0], (int) length); + toBuffer--; + } else { + // clone this stream, it is already at the start of the current level + skipStream[i] = (IndexInput) skipStream[0].clone(); + if (inputIsBuffered && length < BufferedIndexInput.BUFFER_SIZE) { + ((BufferedIndexInput) skipStream[i]).setBufferSize((int) length); + } + + // move base stream beyond the current level + skipStream[0].seek(skipStream[0].getFilePointer() + length); + } + } + + // use base stream for the lowest level + skipPointer[0] = skipStream[0].getFilePointer(); + } + + /** + * Subclasses must implement the actual skip data encoding in this method. + * + * @param level the level skip data shall be read from + * @param skipStream the skip stream to read from + */ + protected abstract int readSkipData(int level, IndexInput skipStream) throws IOException; + + /** Copies the values of the last read skip entry on this level */ + protected void setLastSkipData(int level) { + lastDoc = skipDoc[level]; + lastChildPointer = childPointer[level]; + } + + + /** used to buffer the top skip levels */ + private final static class SkipBuffer extends IndexInput { + private byte[] data; + private long pointer; + private int pos; + + SkipBuffer(IndexInput input, int length) throws IOException { + data = new byte[length]; + pointer = input.getFilePointer(); + input.readBytes(data, 0, length); + } + + public void close() throws IOException { + data = null; + } + + public long getFilePointer() { + return pointer + pos; + } + + public long length() { + return data.length; + } + + public byte readByte() throws IOException { + return data[pos++]; + } + + public void readBytes(byte[] b, int offset, int len) throws IOException { + System.arraycopy(data, pos, b, offset, len); + pos += len; + } + + public void seek(long pos) throws IOException { + this.pos = (int) (pos - pointer); + } + + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/MultiLevelSkipListWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/MultiLevelSkipListWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/MultiLevelSkipListWriter.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,151 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.RAMOutputStream; + +/** + * This abstract class writes skip lists with multiple levels. + * + * Example for skipInterval = 3: + * c (skip level 2) + * c c c (skip level 1) + * x x x x x x x x x x (skip level 0) + * d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d (posting list) + * 3 6 9 12 15 18 21 24 27 30 (df) + * + * d - document + * x - skip data + * c - skip data with child pointer + * + * Skip level i contains every skipInterval-th entry from skip level i-1. + * Therefore the number of entries on level i is: floor(df / ((skipInterval ^ (i + 1))). + * + * Each skip entry on a level i>0 contains a pointer to the corresponding skip entry in list i-1. + * This guarantess a logarithmic amount of skips to find the target document. + * + * While this class takes care of writing the different skip levels, + * subclasses must define the actual format of the skip data. + * + */ +abstract class MultiLevelSkipListWriter { + // number of levels in this skip list + private int numberOfSkipLevels; + + // the skip interval in the list with level = 0 + private int skipInterval; + + // for every skip level a different buffer is used + private RAMOutputStream[] skipBuffer; + + protected MultiLevelSkipListWriter(int skipInterval, int maxSkipLevels, int df) { + this.skipInterval = skipInterval; + + // calculate the maximum number of skip levels for this document frequency + numberOfSkipLevels = df == 0 ? 0 : (int) Math.floor(Math.log(df) / Math.log(skipInterval)); + + // make sure it does not exceed maxSkipLevels + if (numberOfSkipLevels > maxSkipLevels) { + numberOfSkipLevels = maxSkipLevels; + } + } + + protected void init() { + skipBuffer = new RAMOutputStream[numberOfSkipLevels]; + for (int i = 0; i < numberOfSkipLevels; i++) { + skipBuffer[i] = new RAMOutputStream(); + } + } + + protected void resetSkip() { + // creates new buffers or empties the existing ones + if (skipBuffer == null) { + init(); + } else { + for (int i = 0; i < skipBuffer.length; i++) { + skipBuffer[i].reset(); + } + } + } + + /** + * Subclasses must implement the actual skip data encoding in this method. + * + * @param level the level skip data shall be writting for + * @param skipBuffer the skip buffer to write to + */ + protected abstract void writeSkipData(int level, IndexOutput skipBuffer) throws IOException; + + /** + * Writes the current skip data to the buffers. The current document frequency determines + * the max level is skip data is to be written to. + * + * @param df the current document frequency + * @throws IOException + */ + void bufferSkip(int df) throws IOException { + int numLevels; + + // determine max level + for (numLevels = 0; (df % skipInterval) == 0 && numLevels < numberOfSkipLevels; df /= skipInterval) { + numLevels++; + } + + long childPointer = 0; + + for (int level = 0; level < numLevels; level++) { + writeSkipData(level, skipBuffer[level]); + + long newChildPointer = skipBuffer[level].getFilePointer(); + + if (level != 0) { + // store child pointers for all levels except the lowest + skipBuffer[level].writeVLong(childPointer); + } + + //remember the childPointer for the next level + childPointer = newChildPointer; + } + } + + /** + * Writes the buffered skip lists to the given output. + * + * @param output the IndexOutput the skip lists shall be written to + * @return the pointer the skip list starts + */ + long writeSkip(IndexOutput output) throws IOException { + long skipPointer = output.getFilePointer(); + if (skipBuffer == null || skipBuffer.length == 0) return skipPointer; + + for (int level = numberOfSkipLevels - 1; level > 0; level--) { + long length = skipBuffer[level].getFilePointer(); + if (length > 0) { + output.writeVLong(length); + skipBuffer[level].writeTo(output); + } + } + skipBuffer[0].writeTo(output); + + return skipPointer; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/MultiReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/MultiReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/MultiReader.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,372 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.index.MultiSegmentReader.MultiTermDocs; +import org.apache.lucene.index.MultiSegmentReader.MultiTermEnum; +import org.apache.lucene.index.MultiSegmentReader.MultiTermPositions; + +/** An IndexReader which reads multiple indexes, appending their content. + * + * @version $Id: MultiReader.java,v 1.1 2012/08/17 14:55:02 marcin Exp $ + */ +public class MultiReader extends IndexReader { + protected IndexReader[] subReaders; + private int[] starts; // 1st docno for each segment + private boolean[] decrefOnClose; // remember which subreaders to decRef on close + private Map normsCache = new HashMap(); + private int maxDoc = 0; + private int numDocs = -1; + private boolean hasDeletions = false; + + /** + *

Construct a MultiReader aggregating the named set of (sub)readers. + * Directory locking for delete, undeleteAll, and setNorm operations is + * left to the subreaders.

+ *

Note that all subreaders are closed if this Multireader is closed.

+ * @param subReaders set of (sub)readers + * @throws IOException + */ + public MultiReader(IndexReader[] subReaders) { + initialize(subReaders, true); + } + + /** + *

Construct a MultiReader aggregating the named set of (sub)readers. + * Directory locking for delete, undeleteAll, and setNorm operations is + * left to the subreaders.

+ * @param closeSubReaders indicates whether the subreaders should be closed + * when this MultiReader is closed + * @param subReaders set of (sub)readers + * @throws IOException + */ + public MultiReader(IndexReader[] subReaders, boolean closeSubReaders) { + initialize(subReaders, closeSubReaders); + } + + private void initialize(IndexReader[] subReaders, boolean closeSubReaders) { + this.subReaders = (IndexReader[]) subReaders.clone(); + starts = new int[subReaders.length + 1]; // build starts array + decrefOnClose = new boolean[subReaders.length]; + for (int i = 0; i < subReaders.length; i++) { + starts[i] = maxDoc; + maxDoc += subReaders[i].maxDoc(); // compute maxDocs + + if (!closeSubReaders) { + subReaders[i].incRef(); + decrefOnClose[i] = true; + } else { + decrefOnClose[i] = false; + } + + if (subReaders[i].hasDeletions()) + hasDeletions = true; + } + starts[subReaders.length] = maxDoc; + } + + /** + * Tries to reopen the subreaders. + *
+ * If one or more subreaders could be re-opened (i. e. subReader.reopen() + * returned a new instance != subReader), then a new MultiReader instance + * is returned, otherwise this instance is returned. + *

+ * A re-opened instance might share one or more subreaders with the old + * instance. Index modification operations result in undefined behavior + * when performed before the old instance is closed. + * (see {@link IndexReader#reopen()}). + *

+ * If subreaders are shared, then the reference count of those + * readers is increased to ensure that the subreaders remain open + * until the last referring reader is closed. + * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public IndexReader reopen() throws CorruptIndexException, IOException { + ensureOpen(); + + boolean reopened = false; + IndexReader[] newSubReaders = new IndexReader[subReaders.length]; + boolean[] newDecrefOnClose = new boolean[subReaders.length]; + + boolean success = false; + try { + for (int i = 0; i < subReaders.length; i++) { + newSubReaders[i] = subReaders[i].reopen(); + // if at least one of the subreaders was updated we remember that + // and return a new MultiReader + if (newSubReaders[i] != subReaders[i]) { + reopened = true; + // this is a new subreader instance, so on close() we don't + // decRef but close it + newDecrefOnClose[i] = false; + } + } + + if (reopened) { + for (int i = 0; i < subReaders.length; i++) { + if (newSubReaders[i] == subReaders[i]) { + newSubReaders[i].incRef(); + newDecrefOnClose[i] = true; + } + } + + MultiReader mr = new MultiReader(newSubReaders); + mr.decrefOnClose = newDecrefOnClose; + success = true; + return mr; + } else { + success = true; + return this; + } + } finally { + if (!success && reopened) { + for (int i = 0; i < newSubReaders.length; i++) { + if (newSubReaders[i] != null) { + try { + if (newDecrefOnClose[i]) { + newSubReaders[i].decRef(); + } else { + newSubReaders[i].close(); + } + } catch (IOException ignore) { + // keep going - we want to clean up as much as possible + } + } + } + } + } + } + + public TermFreqVector[] getTermFreqVectors(int n) throws IOException { + ensureOpen(); + int i = readerIndex(n); // find segment num + return subReaders[i].getTermFreqVectors(n - starts[i]); // dispatch to segment + } + + public TermFreqVector getTermFreqVector(int n, String field) + throws IOException { + ensureOpen(); + int i = readerIndex(n); // find segment num + return subReaders[i].getTermFreqVector(n - starts[i], field); + } + + + public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException { + ensureOpen(); + int i = readerIndex(docNumber); // find segment num + subReaders[i].getTermFreqVector(docNumber - starts[i], field, mapper); + } + + public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException { + ensureOpen(); + int i = readerIndex(docNumber); // find segment num + subReaders[i].getTermFreqVector(docNumber - starts[i], mapper); + } + + public boolean isOptimized() { + return false; + } + + public synchronized int numDocs() { + // Don't call ensureOpen() here (it could affect performance) + if (numDocs == -1) { // check cache + int n = 0; // cache miss--recompute + for (int i = 0; i < subReaders.length; i++) + n += subReaders[i].numDocs(); // sum from readers + numDocs = n; + } + return numDocs; + } + + public int maxDoc() { + // Don't call ensureOpen() here (it could affect performance) + return maxDoc; + } + + // inherit javadoc + public Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + ensureOpen(); + int i = readerIndex(n); // find segment num + return subReaders[i].document(n - starts[i], fieldSelector); // dispatch to segment reader + } + + public boolean isDeleted(int n) { + // Don't call ensureOpen() here (it could affect performance) + int i = readerIndex(n); // find segment num + return subReaders[i].isDeleted(n - starts[i]); // dispatch to segment reader + } + + public boolean hasDeletions() { + // Don't call ensureOpen() here (it could affect performance) + return hasDeletions; + } + + protected void doDelete(int n) throws CorruptIndexException, IOException { + numDocs = -1; // invalidate cache + int i = readerIndex(n); // find segment num + subReaders[i].deleteDocument(n - starts[i]); // dispatch to segment reader + hasDeletions = true; + } + + protected void doUndeleteAll() throws CorruptIndexException, IOException { + for (int i = 0; i < subReaders.length; i++) + subReaders[i].undeleteAll(); + + hasDeletions = false; + numDocs = -1; // invalidate cache + } + + private int readerIndex(int n) { // find reader for doc n: + return MultiSegmentReader.readerIndex(n, this.starts, this.subReaders.length); + } + + public boolean hasNorms(String field) throws IOException { + ensureOpen(); + for (int i = 0; i < subReaders.length; i++) { + if (subReaders[i].hasNorms(field)) return true; + } + return false; + } + + private byte[] ones; + private byte[] fakeNorms() { + if (ones==null) ones=SegmentReader.createFakeNorms(maxDoc()); + return ones; + } + + public synchronized byte[] norms(String field) throws IOException { + ensureOpen(); + byte[] bytes = (byte[])normsCache.get(field); + if (bytes != null) + return bytes; // cache hit + if (!hasNorms(field)) + return fakeNorms(); + + bytes = new byte[maxDoc()]; + for (int i = 0; i < subReaders.length; i++) + subReaders[i].norms(field, bytes, starts[i]); + normsCache.put(field, bytes); // update cache + return bytes; + } + + public synchronized void norms(String field, byte[] result, int offset) + throws IOException { + ensureOpen(); + byte[] bytes = (byte[])normsCache.get(field); + if (bytes==null && !hasNorms(field)) bytes=fakeNorms(); + if (bytes != null) // cache hit + System.arraycopy(bytes, 0, result, offset, maxDoc()); + + for (int i = 0; i < subReaders.length; i++) // read from segments + subReaders[i].norms(field, result, offset + starts[i]); + } + + protected void doSetNorm(int n, String field, byte value) + throws CorruptIndexException, IOException { + synchronized (normsCache) { + normsCache.remove(field); // clear cache + } + int i = readerIndex(n); // find segment num + subReaders[i].setNorm(n-starts[i], field, value); // dispatch + } + + public TermEnum terms() throws IOException { + ensureOpen(); + return new MultiTermEnum(subReaders, starts, null); + } + + public TermEnum terms(Term term) throws IOException { + ensureOpen(); + return new MultiTermEnum(subReaders, starts, term); + } + + public int docFreq(Term t) throws IOException { + ensureOpen(); + int total = 0; // sum freqs in segments + for (int i = 0; i < subReaders.length; i++) + total += subReaders[i].docFreq(t); + return total; + } + + public TermDocs termDocs() throws IOException { + ensureOpen(); + return new MultiTermDocs(subReaders, starts); + } + + public TermPositions termPositions() throws IOException { + ensureOpen(); + return new MultiTermPositions(subReaders, starts); + } + + protected void doCommit() throws IOException { + for (int i = 0; i < subReaders.length; i++) + subReaders[i].commit(); + } + + protected synchronized void doClose() throws IOException { + for (int i = 0; i < subReaders.length; i++) { + if (decrefOnClose[i]) { + subReaders[i].decRef(); + } else { + subReaders[i].close(); + } + } + } + + public Collection getFieldNames (IndexReader.FieldOption fieldNames) { + ensureOpen(); + return MultiSegmentReader.getFieldNames(fieldNames, this.subReaders); + } + + /** + * Checks recursively if all subreaders are up to date. + */ + public boolean isCurrent() throws CorruptIndexException, IOException { + for (int i = 0; i < subReaders.length; i++) { + if (!subReaders[i].isCurrent()) { + return false; + } + } + + // all subreaders are up to date + return true; + } + + /** Not implemented. + * @throws UnsupportedOperationException + */ + public long getVersion() { + throw new UnsupportedOperationException("MultiReader does not support this method."); + } + + // for testing + IndexReader[] getSubReaders() { + return subReaders; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/MultiSegmentReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/MultiSegmentReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/MultiSegmentReader.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,653 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.store.Directory; + +/** + * An IndexReader which reads indexes with multiple segments. + */ +class MultiSegmentReader extends DirectoryIndexReader { + protected SegmentReader[] subReaders; + private int[] starts; // 1st docno for each segment + private Map normsCache = new HashMap(); + private int maxDoc = 0; + private int numDocs = -1; + private boolean hasDeletions = false; + + /** Construct reading the named set of readers. */ + MultiSegmentReader(Directory directory, SegmentInfos sis, boolean closeDirectory, boolean readOnly) throws IOException { + super(directory, sis, closeDirectory, readOnly); + + // To reduce the chance of hitting FileNotFound + // (and having to retry), we open segments in + // reverse because IndexWriter merges & deletes + // the newest segments first. + + SegmentReader[] readers = new SegmentReader[sis.size()]; + for (int i = sis.size()-1; i >= 0; i--) { + try { + readers[i] = SegmentReader.get(readOnly, sis.info(i)); + } catch (IOException e) { + // Close all readers we had opened: + for(i++;iSegmentReader + for (int i = 0; i < oldReaders.length; i++) { + segmentReaders.put(oldReaders[i].getSegmentName(), new Integer(i)); + } + } + + SegmentReader[] newReaders = new SegmentReader[infos.size()]; + + // remember which readers are shared between the old and the re-opened + // MultiSegmentReader - we have to incRef those readers + boolean[] readerShared = new boolean[infos.size()]; + + for (int i = infos.size() - 1; i>=0; i--) { + // find SegmentReader for this segment + Integer oldReaderIndex = (Integer) segmentReaders.get(infos.info(i).name); + if (oldReaderIndex == null) { + // this is a new segment, no old SegmentReader can be reused + newReaders[i] = null; + } else { + // there is an old reader for this segment - we'll try to reopen it + newReaders[i] = oldReaders[oldReaderIndex.intValue()]; + } + + boolean success = false; + try { + SegmentReader newReader; + if (newReaders[i] == null || infos.info(i).getUseCompoundFile() != newReaders[i].getSegmentInfo().getUseCompoundFile()) { + // this is a new reader; in case we hit an exception we can close it safely + newReader = SegmentReader.get(readOnly, infos.info(i)); + } else { + newReader = (SegmentReader) newReaders[i].reopenSegment(infos.info(i)); + } + if (newReader == newReaders[i]) { + // this reader will be shared between the old and the new one, + // so we must incRef it + readerShared[i] = true; + newReader.incRef(); + } else { + readerShared[i] = false; + newReaders[i] = newReader; + } + success = true; + } finally { + if (!success) { + for (i++; i < infos.size(); i++) { + if (newReaders[i] != null) { + try { + if (!readerShared[i]) { + // this is a new subReader that is not used by the old one, + // we can close it + newReaders[i].close(); + } else { + // this subReader is also used by the old reader, so instead + // closing we must decRef it + newReaders[i].decRef(); + } + } catch (IOException ignore) { + // keep going - we want to clean up as much as possible + } + } + } + } + } + } + + // initialize the readers to calculate maxDoc before we try to reuse the old normsCache + initialize(newReaders); + + // try to copy unchanged norms from the old normsCache to the new one + if (oldNormsCache != null) { + Iterator it = oldNormsCache.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String field = (String) entry.getKey(); + if (!hasNorms(field)) { + continue; + } + + byte[] oldBytes = (byte[]) entry.getValue(); + + byte[] bytes = new byte[maxDoc()]; + + for (int i = 0; i < subReaders.length; i++) { + Integer oldReaderIndex = ((Integer) segmentReaders.get(subReaders[i].getSegmentName())); + + // this SegmentReader was not re-opened, we can copy all of its norms + if (oldReaderIndex != null && + (oldReaders[oldReaderIndex.intValue()] == subReaders[i] + || oldReaders[oldReaderIndex.intValue()].norms.get(field) == subReaders[i].norms.get(field))) { + // we don't have to synchronize here: either this constructor is called from a SegmentReader, + // in which case no old norms cache is present, or it is called from MultiReader.reopen(), + // which is synchronized + System.arraycopy(oldBytes, oldStarts[oldReaderIndex.intValue()], bytes, starts[i], starts[i+1] - starts[i]); + } else { + subReaders[i].norms(field, bytes, starts[i]); + } + } + + normsCache.put(field, bytes); // update cache + } + } + } + + private void initialize(SegmentReader[] subReaders) { + this.subReaders = subReaders; + starts = new int[subReaders.length + 1]; // build starts array + for (int i = 0; i < subReaders.length; i++) { + starts[i] = maxDoc; + maxDoc += subReaders[i].maxDoc(); // compute maxDocs + + if (subReaders[i].hasDeletions()) + hasDeletions = true; + } + starts[subReaders.length] = maxDoc; + } + + protected synchronized DirectoryIndexReader doReopen(SegmentInfos infos) throws CorruptIndexException, IOException { + if (infos.size() == 1) { + // The index has only one segment now, so we can't refresh the MultiSegmentReader. + // Return a new [ReadOnly]SegmentReader instead + return SegmentReader.get(readOnly, infos, infos.info(0), false); + } else if (readOnly) { + return new ReadOnlyMultiSegmentReader(directory, infos, closeDirectory, subReaders, starts, normsCache); + } else { + return new MultiSegmentReader(directory, infos, closeDirectory, subReaders, starts, normsCache, false); + } + } + + public TermFreqVector[] getTermFreqVectors(int n) throws IOException { + ensureOpen(); + int i = readerIndex(n); // find segment num + return subReaders[i].getTermFreqVectors(n - starts[i]); // dispatch to segment + } + + public TermFreqVector getTermFreqVector(int n, String field) + throws IOException { + ensureOpen(); + int i = readerIndex(n); // find segment num + return subReaders[i].getTermFreqVector(n - starts[i], field); + } + + + public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException { + ensureOpen(); + int i = readerIndex(docNumber); // find segment num + subReaders[i].getTermFreqVector(docNumber - starts[i], field, mapper); + } + + public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException { + ensureOpen(); + int i = readerIndex(docNumber); // find segment num + subReaders[i].getTermFreqVector(docNumber - starts[i], mapper); + } + + public boolean isOptimized() { + return false; + } + + public synchronized int numDocs() { + // Don't call ensureOpen() here (it could affect performance) + if (numDocs == -1) { // check cache + int n = 0; // cache miss--recompute + for (int i = 0; i < subReaders.length; i++) + n += subReaders[i].numDocs(); // sum from readers + numDocs = n; + } + return numDocs; + } + + public int maxDoc() { + // Don't call ensureOpen() here (it could affect performance) + return maxDoc; + } + + // inherit javadoc + public Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + ensureOpen(); + int i = readerIndex(n); // find segment num + return subReaders[i].document(n - starts[i], fieldSelector); // dispatch to segment reader + } + + public boolean isDeleted(int n) { + // Don't call ensureOpen() here (it could affect performance) + final int i = readerIndex(n); // find segment num + return subReaders[i].isDeleted(n - starts[i]); // dispatch to segment reader + } + + public boolean hasDeletions() { + // Don't call ensureOpen() here (it could affect performance) + return hasDeletions; + } + + protected void doDelete(int n) throws CorruptIndexException, IOException { + numDocs = -1; // invalidate cache + int i = readerIndex(n); // find segment num + subReaders[i].deleteDocument(n - starts[i]); // dispatch to segment reader + hasDeletions = true; + } + + protected void doUndeleteAll() throws CorruptIndexException, IOException { + for (int i = 0; i < subReaders.length; i++) + subReaders[i].undeleteAll(); + + hasDeletions = false; + numDocs = -1; // invalidate cache + } + + private int readerIndex(int n) { // find reader for doc n: + return readerIndex(n, this.starts, this.subReaders.length); + } + + final static int readerIndex(int n, int[] starts, int numSubReaders) { // find reader for doc n: + int lo = 0; // search starts array + int hi = numSubReaders - 1; // for first element less + + while (hi >= lo) { + int mid = (lo + hi) >> 1; + int midValue = starts[mid]; + if (n < midValue) + hi = mid - 1; + else if (n > midValue) + lo = mid + 1; + else { // found a match + while (mid+1 < numSubReaders && starts[mid+1] == midValue) { + mid++; // scan to last match + } + return mid; + } + } + return hi; + } + + public boolean hasNorms(String field) throws IOException { + ensureOpen(); + for (int i = 0; i < subReaders.length; i++) { + if (subReaders[i].hasNorms(field)) return true; + } + return false; + } + + private byte[] ones; + private byte[] fakeNorms() { + if (ones==null) ones=SegmentReader.createFakeNorms(maxDoc()); + return ones; + } + + public synchronized byte[] norms(String field) throws IOException { + ensureOpen(); + byte[] bytes = (byte[])normsCache.get(field); + if (bytes != null) + return bytes; // cache hit + if (!hasNorms(field)) + return fakeNorms(); + + bytes = new byte[maxDoc()]; + for (int i = 0; i < subReaders.length; i++) + subReaders[i].norms(field, bytes, starts[i]); + normsCache.put(field, bytes); // update cache + return bytes; + } + + public synchronized void norms(String field, byte[] result, int offset) + throws IOException { + ensureOpen(); + byte[] bytes = (byte[])normsCache.get(field); + if (bytes==null && !hasNorms(field)) bytes=fakeNorms(); + if (bytes != null) // cache hit + System.arraycopy(bytes, 0, result, offset, maxDoc()); + + for (int i = 0; i < subReaders.length; i++) // read from segments + subReaders[i].norms(field, result, offset + starts[i]); + } + + protected void doSetNorm(int n, String field, byte value) + throws CorruptIndexException, IOException { + synchronized (normsCache) { + normsCache.remove(field); // clear cache + } + int i = readerIndex(n); // find segment num + subReaders[i].setNorm(n-starts[i], field, value); // dispatch + } + + public TermEnum terms() throws IOException { + ensureOpen(); + return new MultiTermEnum(subReaders, starts, null); + } + + public TermEnum terms(Term term) throws IOException { + ensureOpen(); + return new MultiTermEnum(subReaders, starts, term); + } + + public int docFreq(Term t) throws IOException { + ensureOpen(); + int total = 0; // sum freqs in segments + for (int i = 0; i < subReaders.length; i++) + total += subReaders[i].docFreq(t); + return total; + } + + public TermDocs termDocs() throws IOException { + ensureOpen(); + return new MultiTermDocs(subReaders, starts); + } + + public TermPositions termPositions() throws IOException { + ensureOpen(); + return new MultiTermPositions(subReaders, starts); + } + + protected void commitChanges() throws IOException { + for (int i = 0; i < subReaders.length; i++) + subReaders[i].commit(); + } + + void startCommit() { + super.startCommit(); + for (int i = 0; i < subReaders.length; i++) { + subReaders[i].startCommit(); + } + } + + void rollbackCommit() { + super.rollbackCommit(); + for (int i = 0; i < subReaders.length; i++) { + subReaders[i].rollbackCommit(); + } + } + + protected synchronized void doClose() throws IOException { + for (int i = 0; i < subReaders.length; i++) + subReaders[i].decRef(); + + // maybe close directory + super.doClose(); + } + + public Collection getFieldNames (IndexReader.FieldOption fieldNames) { + ensureOpen(); + return getFieldNames(fieldNames, this.subReaders); + } + + static Collection getFieldNames (IndexReader.FieldOption fieldNames, IndexReader[] subReaders) { + // maintain a unique set of field names + Set fieldSet = new HashSet(); + for (int i = 0; i < subReaders.length; i++) { + IndexReader reader = subReaders[i]; + Collection names = reader.getFieldNames(fieldNames); + fieldSet.addAll(names); + } + return fieldSet; + } + + // for testing + SegmentReader[] getSubReaders() { + return subReaders; + } + + public void setTermInfosIndexDivisor(int indexDivisor) throws IllegalStateException { + for (int i = 0; i < subReaders.length; i++) + subReaders[i].setTermInfosIndexDivisor(indexDivisor); + } + + public int getTermInfosIndexDivisor() throws IllegalStateException { + if (subReaders.length > 0) + return subReaders[0].getTermInfosIndexDivisor(); + else + throw new IllegalStateException("no readers"); + } + + static class MultiTermEnum extends TermEnum { + private SegmentMergeQueue queue; + + private Term term; + private int docFreq; + + public MultiTermEnum(IndexReader[] readers, int[] starts, Term t) + throws IOException { + queue = new SegmentMergeQueue(readers.length); + for (int i = 0; i < readers.length; i++) { + IndexReader reader = readers[i]; + TermEnum termEnum; + + if (t != null) { + termEnum = reader.terms(t); + } else + termEnum = reader.terms(); + + SegmentMergeInfo smi = new SegmentMergeInfo(starts[i], termEnum, reader); + if (t == null ? smi.next() : termEnum.term() != null) + queue.put(smi); // initialize queue + else + smi.close(); + } + + if (t != null && queue.size() > 0) { + next(); + } + } + + public boolean next() throws IOException { + SegmentMergeInfo top = (SegmentMergeInfo)queue.top(); + if (top == null) { + term = null; + return false; + } + + term = top.term; + docFreq = 0; + + while (top != null && term.compareTo(top.term) == 0) { + queue.pop(); + docFreq += top.termEnum.docFreq(); // increment freq + if (top.next()) + queue.put(top); // restore queue + else + top.close(); // done with a segment + top = (SegmentMergeInfo)queue.top(); + } + return true; + } + + public Term term() { + return term; + } + + public int docFreq() { + return docFreq; + } + + public void close() throws IOException { + queue.close(); + } + } + + static class MultiTermDocs implements TermDocs { + protected IndexReader[] readers; + protected int[] starts; + protected Term term; + + protected int base = 0; + protected int pointer = 0; + + private TermDocs[] readerTermDocs; + protected TermDocs current; // == readerTermDocs[pointer] + + public MultiTermDocs(IndexReader[] r, int[] s) { + readers = r; + starts = s; + + readerTermDocs = new TermDocs[r.length]; + } + + public int doc() { + return base + current.doc(); + } + public int freq() { + return current.freq(); + } + + public void seek(Term term) { + this.term = term; + this.base = 0; + this.pointer = 0; + this.current = null; + } + + public void seek(TermEnum termEnum) throws IOException { + seek(termEnum.term()); + } + + public boolean next() throws IOException { + for(;;) { + if (current!=null && current.next()) { + return true; + } + else if (pointer < readers.length) { + base = starts[pointer]; + current = termDocs(pointer++); + } else { + return false; + } + } + } + + /** Optimized implementation. */ + public int read(final int[] docs, final int[] freqs) throws IOException { + while (true) { + while (current == null) { + if (pointer < readers.length) { // try next segment + base = starts[pointer]; + current = termDocs(pointer++); + } else { + return 0; + } + } + int end = current.read(docs, freqs); + if (end == 0) { // none left in segment + current = null; + } else { // got some + final int b = base; // adjust doc numbers + for (int i = 0; i < end; i++) + docs[i] += b; + return end; + } + } + } + + /* A Possible future optimization could skip entire segments */ + public boolean skipTo(int target) throws IOException { + for(;;) { + if (current != null && current.skipTo(target-base)) { + return true; + } else if (pointer < readers.length) { + base = starts[pointer]; + current = termDocs(pointer++); + } else + return false; + } + } + + private TermDocs termDocs(int i) throws IOException { + if (term == null) + return null; + TermDocs result = readerTermDocs[i]; + if (result == null) + result = readerTermDocs[i] = termDocs(readers[i]); + result.seek(term); + return result; + } + + protected TermDocs termDocs(IndexReader reader) + throws IOException { + return reader.termDocs(); + } + + public void close() throws IOException { + for (int i = 0; i < readerTermDocs.length; i++) { + if (readerTermDocs[i] != null) + readerTermDocs[i].close(); + } + } + } + + static class MultiTermPositions extends MultiTermDocs implements TermPositions { + public MultiTermPositions(IndexReader[] r, int[] s) { + super(r,s); + } + + protected TermDocs termDocs(IndexReader reader) throws IOException { + return (TermDocs)reader.termPositions(); + } + + public int nextPosition() throws IOException { + return ((TermPositions)current).nextPosition(); + } + + public int getPayloadLength() { + return ((TermPositions)current).getPayloadLength(); + } + + public byte[] getPayload(byte[] data, int offset) throws IOException { + return ((TermPositions)current).getPayload(data, offset); + } + + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return ((TermPositions) current).isPayloadAvailable(); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/MultipleTermPositions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/MultipleTermPositions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/MultipleTermPositions.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,219 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.util.PriorityQueue; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/** + * Describe class MultipleTermPositions here. + * + * @version 1.0 + */ +public class MultipleTermPositions implements TermPositions { + + private static final class TermPositionsQueue extends PriorityQueue { + TermPositionsQueue(List termPositions) throws IOException { + initialize(termPositions.size()); + + Iterator i = termPositions.iterator(); + while (i.hasNext()) { + TermPositions tp = (TermPositions) i.next(); + if (tp.next()) + put(tp); + } + } + + final TermPositions peek() { + return (TermPositions) top(); + } + + public final boolean lessThan(Object a, Object b) { + return ((TermPositions) a).doc() < ((TermPositions) b).doc(); + } + } + + private static final class IntQueue { + private int _arraySize = 16; + private int _index = 0; + private int _lastIndex = 0; + private int[] _array = new int[_arraySize]; + + final void add(int i) { + if (_lastIndex == _arraySize) + growArray(); + + _array[_lastIndex++] = i; + } + + final int next() { + return _array[_index++]; + } + + final void sort() { + Arrays.sort(_array, _index, _lastIndex); + } + + final void clear() { + _index = 0; + _lastIndex = 0; + } + + final int size() { + return (_lastIndex - _index); + } + + private void growArray() { + int[] newArray = new int[_arraySize * 2]; + System.arraycopy(_array, 0, newArray, 0, _arraySize); + _array = newArray; + _arraySize *= 2; + } + } + + private int _doc; + private int _freq; + private TermPositionsQueue _termPositionsQueue; + private IntQueue _posList; + + /** + * Creates a new MultipleTermPositions instance. + * + * @exception IOException + */ + public MultipleTermPositions(IndexReader indexReader, Term[] terms) throws IOException { + List termPositions = new LinkedList(); + + for (int i = 0; i < terms.length; i++) + termPositions.add(indexReader.termPositions(terms[i])); + + _termPositionsQueue = new TermPositionsQueue(termPositions); + _posList = new IntQueue(); + } + + public final boolean next() throws IOException { + if (_termPositionsQueue.size() == 0) + return false; + + _posList.clear(); + _doc = _termPositionsQueue.peek().doc(); + + TermPositions tp; + do { + tp = _termPositionsQueue.peek(); + + for (int i = 0; i < tp.freq(); i++) + _posList.add(tp.nextPosition()); + + if (tp.next()) + _termPositionsQueue.adjustTop(); + else { + _termPositionsQueue.pop(); + tp.close(); + } + } while (_termPositionsQueue.size() > 0 && _termPositionsQueue.peek().doc() == _doc); + + _posList.sort(); + _freq = _posList.size(); + + return true; + } + + public final int nextPosition() { + return _posList.next(); + } + + public final boolean skipTo(int target) throws IOException { + while (_termPositionsQueue.peek() != null && target > _termPositionsQueue.peek().doc()) { + TermPositions tp = (TermPositions) _termPositionsQueue.pop(); + if (tp.skipTo(target)) + _termPositionsQueue.put(tp); + else + tp.close(); + } + return next(); + } + + public final int doc() { + return _doc; + } + + public final int freq() { + return _freq; + } + + public final void close() throws IOException { + while (_termPositionsQueue.size() > 0) + ((TermPositions) _termPositionsQueue.pop()).close(); + } + + /** + * Not implemented. + * @throws UnsupportedOperationException + */ + public void seek(Term arg0) throws IOException { + throw new UnsupportedOperationException(); + } + + /** + * Not implemented. + * @throws UnsupportedOperationException + */ + public void seek(TermEnum termEnum) throws IOException { + throw new UnsupportedOperationException(); + } + + /** + * Not implemented. + * @throws UnsupportedOperationException + */ + public int read(int[] arg0, int[] arg1) throws IOException { + throw new UnsupportedOperationException(); + } + + + /** + * Not implemented. + * @throws UnsupportedOperationException + */ + public int getPayloadLength() { + throw new UnsupportedOperationException(); + } + + /** + * Not implemented. + * @throws UnsupportedOperationException + */ + public byte[] getPayload(byte[] data, int offset) throws IOException { + throw new UnsupportedOperationException(); + } + + /** + * + * @return false + */ + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return false; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/NormsWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/NormsWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/NormsWriter.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,175 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Collection; +import java.util.Iterator; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.ArrayList; + +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.search.Similarity; + +// TODO FI: norms could actually be stored as doc store + +/** Writes norms. Each thread X field accumulates the norms + * for the doc/fields it saw, then the flush method below + * merges all of these together into a single _X.nrm file. + */ + +final class NormsWriter extends InvertedDocEndConsumer { + + private static final byte defaultNorm = Similarity.encodeNorm(1.0f); + private FieldInfos fieldInfos; + public InvertedDocEndConsumerPerThread addThread(DocInverterPerThread docInverterPerThread) { + return new NormsWriterPerThread(docInverterPerThread, this); + } + + public void abort() {} + + // We only write the _X.nrm file at flush + void files(Collection files) {} + + void setFieldInfos(FieldInfos fieldInfos) { + this.fieldInfos = fieldInfos; + } + + /** Produce _X.nrm if any document had a field with norms + * not disabled */ + public void flush(Map threadsAndFields, DocumentsWriter.FlushState state) throws IOException { + + final Map byField = new HashMap(); + + // Typically, each thread will have encountered the same + // field. So first we collate by field, ie, all + // per-thread field instances that correspond to the + // same FieldInfo + final Iterator it = threadsAndFields.entrySet().iterator(); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + + Collection fields = (Collection) entry.getValue(); + Iterator fieldsIt = fields.iterator(); + + while(fieldsIt.hasNext()) { + NormsWriterPerField perField = (NormsWriterPerField) fieldsIt.next(); + + if (perField.upto > 0) { + // It has some norms + List l = (List) byField.get(perField.fieldInfo); + if (l == null) { + l = new ArrayList(); + byField.put(perField.fieldInfo, l); + } + l.add(perField); + } else + // Remove this field since we haven't seen it + // since the previous flush + fieldsIt.remove(); + } + } + + final String normsFileName = state.segmentName + "." + IndexFileNames.NORMS_EXTENSION; + state.flushedFiles.add(normsFileName); + IndexOutput normsOut = state.directory.createOutput(normsFileName); + + try { + normsOut.writeBytes(SegmentMerger.NORMS_HEADER, 0, SegmentMerger.NORMS_HEADER.length); + + final int numField = fieldInfos.size(); + + int normCount = 0; + + for(int fieldNumber=0;fieldNumber 0) { + + assert uptos[0] < fields[0].docIDs.length : " uptos[0]=" + uptos[0] + " len=" + (fields[0].docIDs.length); + + int minLoc = 0; + int minDocID = fields[0].docIDs[uptos[0]]; + + for(int j=1;jThis is useful, e.g., with collections that have large fields which + * change rarely and small fields that change more frequently. The smaller + * fields may be re-indexed in a new index and both indexes may be searched + * together. + * + *

Warning: It is up to you to make sure all indexes + * are created and modified the same way. For example, if you add + * documents to one index, you need to add the same documents in the + * same order to the other indexes. Failure to do so will result in + * undefined behavior. + */ +public class ParallelReader extends IndexReader { + private List readers = new ArrayList(); + private List decrefOnClose = new ArrayList(); // remember which subreaders to decRef on close + boolean incRefReaders = false; + private SortedMap fieldToReader = new TreeMap(); + private Map readerToFields = new HashMap(); + private List storedFieldReaders = new ArrayList(); + + private int maxDoc; + private int numDocs; + private boolean hasDeletions; + + /** Construct a ParallelReader. + *

Note that all subreaders are closed if this ParallelReader is closed.

+ */ + public ParallelReader() throws IOException { this(true); } + + /** Construct a ParallelReader. + * @param closeSubReaders indicates whether the subreaders should be closed + * when this ParallelReader is closed + */ + public ParallelReader(boolean closeSubReaders) throws IOException { + super(); + this.incRefReaders = !closeSubReaders; + } + + /** Add an IndexReader. + * @throws IOException if there is a low-level IO error + */ + public void add(IndexReader reader) throws IOException { + ensureOpen(); + add(reader, false); + } + + /** Add an IndexReader whose stored fields will not be returned. This can + * accellerate search when stored fields are only needed from a subset of + * the IndexReaders. + * + * @throws IllegalArgumentException if not all indexes contain the same number + * of documents + * @throws IllegalArgumentException if not all indexes have the same value + * of {@link IndexReader#maxDoc()} + * @throws IOException if there is a low-level IO error + */ + public void add(IndexReader reader, boolean ignoreStoredFields) + throws IOException { + + ensureOpen(); + if (readers.size() == 0) { + this.maxDoc = reader.maxDoc(); + this.numDocs = reader.numDocs(); + this.hasDeletions = reader.hasDeletions(); + } + + if (reader.maxDoc() != maxDoc) // check compatibility + throw new IllegalArgumentException + ("All readers must have same maxDoc: "+maxDoc+"!="+reader.maxDoc()); + if (reader.numDocs() != numDocs) + throw new IllegalArgumentException + ("All readers must have same numDocs: "+numDocs+"!="+reader.numDocs()); + + Collection fields = reader.getFieldNames(IndexReader.FieldOption.ALL); + readerToFields.put(reader, fields); + Iterator i = fields.iterator(); + while (i.hasNext()) { // update fieldToReader map + String field = (String)i.next(); + if (fieldToReader.get(field) == null) + fieldToReader.put(field, reader); + } + + if (!ignoreStoredFields) + storedFieldReaders.add(reader); // add to storedFieldReaders + readers.add(reader); + + if (incRefReaders) { + reader.incRef(); + } + decrefOnClose.add(Boolean.valueOf(incRefReaders)); + } + + /** + * Tries to reopen the subreaders. + *
+ * If one or more subreaders could be re-opened (i. e. subReader.reopen() + * returned a new instance != subReader), then a new ParallelReader instance + * is returned, otherwise this instance is returned. + *

+ * A re-opened instance might share one or more subreaders with the old + * instance. Index modification operations result in undefined behavior + * when performed before the old instance is closed. + * (see {@link IndexReader#reopen()}). + *

+ * If subreaders are shared, then the reference count of those + * readers is increased to ensure that the subreaders remain open + * until the last referring reader is closed. + * + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public IndexReader reopen() throws CorruptIndexException, IOException { + ensureOpen(); + + boolean reopened = false; + List newReaders = new ArrayList(); + List newDecrefOnClose = new ArrayList(); + + boolean success = false; + + try { + + for (int i = 0; i < readers.size(); i++) { + IndexReader oldReader = (IndexReader) readers.get(i); + IndexReader newReader = oldReader.reopen(); + newReaders.add(newReader); + // if at least one of the subreaders was updated we remember that + // and return a new MultiReader + if (newReader != oldReader) { + reopened = true; + } + } + + if (reopened) { + ParallelReader pr = new ParallelReader(); + for (int i = 0; i < readers.size(); i++) { + IndexReader oldReader = (IndexReader) readers.get(i); + IndexReader newReader = (IndexReader) newReaders.get(i); + if (newReader == oldReader) { + newDecrefOnClose.add(Boolean.TRUE); + newReader.incRef(); + } else { + // this is a new subreader instance, so on close() we don't + // decRef but close it + newDecrefOnClose.add(Boolean.FALSE); + } + pr.add(newReader, !storedFieldReaders.contains(oldReader)); + } + pr.decrefOnClose = newDecrefOnClose; + pr.incRefReaders = incRefReaders; + success = true; + return pr; + } else { + success = true; + // No subreader was refreshed + return this; + } + } finally { + if (!success && reopened) { + for (int i = 0; i < newReaders.size(); i++) { + IndexReader r = (IndexReader) newReaders.get(i); + if (r != null) { + try { + if (((Boolean) newDecrefOnClose.get(i)).booleanValue()) { + r.decRef(); + } else { + r.close(); + } + } catch (IOException ignore) { + // keep going - we want to clean up as much as possible + } + } + } + } + } + } + + + public int numDocs() { + // Don't call ensureOpen() here (it could affect performance) + return numDocs; + } + + public int maxDoc() { + // Don't call ensureOpen() here (it could affect performance) + return maxDoc; + } + + public boolean hasDeletions() { + // Don't call ensureOpen() here (it could affect performance) + return hasDeletions; + } + + // check first reader + public boolean isDeleted(int n) { + // Don't call ensureOpen() here (it could affect performance) + if (readers.size() > 0) + return ((IndexReader)readers.get(0)).isDeleted(n); + return false; + } + + // delete in all readers + protected void doDelete(int n) throws CorruptIndexException, IOException { + for (int i = 0; i < readers.size(); i++) { + ((IndexReader)readers.get(i)).deleteDocument(n); + } + hasDeletions = true; + } + + // undeleteAll in all readers + protected void doUndeleteAll() throws CorruptIndexException, IOException { + for (int i = 0; i < readers.size(); i++) { + ((IndexReader)readers.get(i)).undeleteAll(); + } + hasDeletions = false; + } + + // append fields from storedFieldReaders + public Document document(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + ensureOpen(); + Document result = new Document(); + for (int i = 0; i < storedFieldReaders.size(); i++) { + IndexReader reader = (IndexReader)storedFieldReaders.get(i); + + boolean include = (fieldSelector==null); + if (!include) { + Iterator it = ((Collection) readerToFields.get(reader)).iterator(); + while (it.hasNext()) + if (fieldSelector.accept((String)it.next())!=FieldSelectorResult.NO_LOAD) { + include = true; + break; + } + } + if (include) { + Iterator fieldIterator = reader.document(n, fieldSelector).getFields().iterator(); + while (fieldIterator.hasNext()) { + result.add((Fieldable)fieldIterator.next()); + } + } + } + return result; + } + + // get all vectors + public TermFreqVector[] getTermFreqVectors(int n) throws IOException { + ensureOpen(); + ArrayList results = new ArrayList(); + Iterator i = fieldToReader.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry e = (Map.Entry)i.next(); + String field = (String)e.getKey(); + IndexReader reader = (IndexReader)e.getValue(); + TermFreqVector vector = reader.getTermFreqVector(n, field); + if (vector != null) + results.add(vector); + } + return (TermFreqVector[]) + results.toArray(new TermFreqVector[results.size()]); + } + + public TermFreqVector getTermFreqVector(int n, String field) + throws IOException { + ensureOpen(); + IndexReader reader = ((IndexReader)fieldToReader.get(field)); + return reader==null ? null : reader.getTermFreqVector(n, field); + } + + + public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException { + ensureOpen(); + IndexReader reader = ((IndexReader)fieldToReader.get(field)); + if (reader != null) { + reader.getTermFreqVector(docNumber, field, mapper); + } + } + + public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException { + ensureOpen(); + ensureOpen(); + + Iterator i = fieldToReader.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry e = (Map.Entry)i.next(); + String field = (String)e.getKey(); + IndexReader reader = (IndexReader)e.getValue(); + reader.getTermFreqVector(docNumber, field, mapper); + } + + } + + public boolean hasNorms(String field) throws IOException { + ensureOpen(); + IndexReader reader = ((IndexReader)fieldToReader.get(field)); + return reader==null ? false : reader.hasNorms(field); + } + + public byte[] norms(String field) throws IOException { + ensureOpen(); + IndexReader reader = ((IndexReader)fieldToReader.get(field)); + return reader==null ? null : reader.norms(field); + } + + public void norms(String field, byte[] result, int offset) + throws IOException { + ensureOpen(); + IndexReader reader = ((IndexReader)fieldToReader.get(field)); + if (reader!=null) + reader.norms(field, result, offset); + } + + protected void doSetNorm(int n, String field, byte value) + throws CorruptIndexException, IOException { + IndexReader reader = ((IndexReader)fieldToReader.get(field)); + if (reader!=null) + reader.doSetNorm(n, field, value); + } + + public TermEnum terms() throws IOException { + ensureOpen(); + return new ParallelTermEnum(); + } + + public TermEnum terms(Term term) throws IOException { + ensureOpen(); + return new ParallelTermEnum(term); + } + + public int docFreq(Term term) throws IOException { + ensureOpen(); + IndexReader reader = ((IndexReader)fieldToReader.get(term.field())); + return reader==null ? 0 : reader.docFreq(term); + } + + public TermDocs termDocs(Term term) throws IOException { + ensureOpen(); + return new ParallelTermDocs(term); + } + + public TermDocs termDocs() throws IOException { + ensureOpen(); + return new ParallelTermDocs(); + } + + public TermPositions termPositions(Term term) throws IOException { + ensureOpen(); + return new ParallelTermPositions(term); + } + + public TermPositions termPositions() throws IOException { + ensureOpen(); + return new ParallelTermPositions(); + } + + /** + * Checks recursively if all subreaders are up to date. + */ + public boolean isCurrent() throws CorruptIndexException, IOException { + for (int i = 0; i < readers.size(); i++) { + if (!((IndexReader)readers.get(i)).isCurrent()) { + return false; + } + } + + // all subreaders are up to date + return true; + } + + /** + * Checks recursively if all subindexes are optimized + */ + public boolean isOptimized() { + for (int i = 0; i < readers.size(); i++) { + if (!((IndexReader)readers.get(i)).isOptimized()) { + return false; + } + } + + // all subindexes are optimized + return true; + } + + + /** Not implemented. + * @throws UnsupportedOperationException + */ + public long getVersion() { + throw new UnsupportedOperationException("ParallelReader does not support this method."); + } + + // for testing + IndexReader[] getSubReaders() { + return (IndexReader[]) readers.toArray(new IndexReader[readers.size()]); + } + + protected void doCommit() throws IOException { + for (int i = 0; i < readers.size(); i++) + ((IndexReader)readers.get(i)).commit(); + } + + protected synchronized void doClose() throws IOException { + for (int i = 0; i < readers.size(); i++) { + if (((Boolean) decrefOnClose.get(i)).booleanValue()) { + ((IndexReader)readers.get(i)).decRef(); + } else { + ((IndexReader)readers.get(i)).close(); + } + } + } + + public Collection getFieldNames (IndexReader.FieldOption fieldNames) { + ensureOpen(); + Set fieldSet = new HashSet(); + for (int i = 0; i < readers.size(); i++) { + IndexReader reader = ((IndexReader)readers.get(i)); + Collection names = reader.getFieldNames(fieldNames); + fieldSet.addAll(names); + } + return fieldSet; + } + + private class ParallelTermEnum extends TermEnum { + private String field; + private Iterator fieldIterator; + private TermEnum termEnum; + + public ParallelTermEnum() throws IOException { + field = (String)fieldToReader.firstKey(); + if (field != null) + termEnum = ((IndexReader)fieldToReader.get(field)).terms(); + } + + public ParallelTermEnum(Term term) throws IOException { + field = term.field(); + IndexReader reader = ((IndexReader)fieldToReader.get(field)); + if (reader!=null) + termEnum = reader.terms(term); + } + + public boolean next() throws IOException { + if (termEnum==null) + return false; + + // another term in this field? + if (termEnum.next() && termEnum.term().field()==field) + return true; // yes, keep going + + termEnum.close(); // close old termEnum + + // find the next field with terms, if any + if (fieldIterator==null) { + fieldIterator = fieldToReader.tailMap(field).keySet().iterator(); + fieldIterator.next(); // Skip field to get next one + } + while (fieldIterator.hasNext()) { + field = (String) fieldIterator.next(); + termEnum = ((IndexReader)fieldToReader.get(field)).terms(new Term(field)); + Term term = termEnum.term(); + if (term!=null && term.field()==field) + return true; + else + termEnum.close(); + } + + return false; // no more fields + } + + public Term term() { + if (termEnum==null) + return null; + + return termEnum.term(); + } + + public int docFreq() { + if (termEnum==null) + return 0; + + return termEnum.docFreq(); + } + + public void close() throws IOException { + if (termEnum!=null) + termEnum.close(); + } + + } + + // wrap a TermDocs in order to support seek(Term) + private class ParallelTermDocs implements TermDocs { + protected TermDocs termDocs; + + public ParallelTermDocs() {} + public ParallelTermDocs(Term term) throws IOException { seek(term); } + + public int doc() { return termDocs.doc(); } + public int freq() { return termDocs.freq(); } + + public void seek(Term term) throws IOException { + IndexReader reader = ((IndexReader)fieldToReader.get(term.field())); + termDocs = reader!=null ? reader.termDocs(term) : null; + } + + public void seek(TermEnum termEnum) throws IOException { + seek(termEnum.term()); + } + + public boolean next() throws IOException { + if (termDocs==null) + return false; + + return termDocs.next(); + } + + public int read(final int[] docs, final int[] freqs) throws IOException { + if (termDocs==null) + return 0; + + return termDocs.read(docs, freqs); + } + + public boolean skipTo(int target) throws IOException { + if (termDocs==null) + return false; + + return termDocs.skipTo(target); + } + + public void close() throws IOException { + if (termDocs!=null) + termDocs.close(); + } + + } + + private class ParallelTermPositions + extends ParallelTermDocs implements TermPositions { + + public ParallelTermPositions() {} + public ParallelTermPositions(Term term) throws IOException { seek(term); } + + public void seek(Term term) throws IOException { + IndexReader reader = ((IndexReader)fieldToReader.get(term.field())); + termDocs = reader!=null ? reader.termPositions(term) : null; + } + + public int nextPosition() throws IOException { + // It is an error to call this if there is no next position, e.g. if termDocs==null + return ((TermPositions)termDocs).nextPosition(); + } + + public int getPayloadLength() { + return ((TermPositions)termDocs).getPayloadLength(); + } + + public byte[] getPayload(byte[] data, int offset) throws IOException { + return ((TermPositions)termDocs).getPayload(data, offset); + } + + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return ((TermPositions) termDocs).isPayloadAvailable(); + } + } + +} + + + + + Index: 3rdParty_sources/lucene/org/apache/lucene/index/Payload.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/Payload.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/Payload.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,199 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Serializable; + +import org.apache.lucene.analysis.Token; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.util.ArrayUtil; + +/** + * A Payload is metadata that can be stored together with each occurrence + * of a term. This metadata is stored inline in the posting list of the + * specific term. + *

+ * To store payloads in the index a {@link TokenStream} has to be used that + * produces {@link Token}s containing payload data. + *

+ * Use {@link TermPositions#getPayloadLength()} and {@link TermPositions#getPayload(byte[], int)} + * to retrieve the payloads from the index.
+ * + */ +public class Payload implements Serializable, Cloneable { + /** the byte array containing the payload data */ + protected byte[] data; + + /** the offset within the byte array */ + protected int offset; + + /** the length of the payload data */ + protected int length; + + /** Creates an empty payload and does not allocate a byte array. */ + public Payload() { + // nothing to do + } + + /** + * Creates a new payload with the the given array as data. + * A reference to the passed-in array is held, i. e. no + * copy is made. + * + * @param data the data of this payload + */ + public Payload(byte[] data) { + this(data, 0, data.length); + } + + /** + * Creates a new payload with the the given array as data. + * A reference to the passed-in array is held, i. e. no + * copy is made. + * + * @param data the data of this payload + * @param offset the offset in the data byte array + * @param length the length of the data + */ + public Payload(byte[] data, int offset, int length) { + if (offset < 0 || offset + length > data.length) { + throw new IllegalArgumentException(); + } + this.data = data; + this.offset = offset; + this.length = length; + } + + /** + * Sets this payloads data. + * A reference to the passed-in array is held, i. e. no + * copy is made. + */ + public void setData(byte[] data) { + setData(data, 0, data.length); + } + + /** + * Sets this payloads data. + * A reference to the passed-in array is held, i. e. no + * copy is made. + */ + public void setData(byte[] data, int offset, int length) { + this.data = data; + this.offset = offset; + this.length = length; + } + + /** + * Returns a reference to the underlying byte array + * that holds this payloads data. + */ + public byte[] getData() { + return this.data; + } + + /** + * Returns the offset in the underlying byte array + */ + public int getOffset() { + return this.offset; + } + + /** + * Returns the length of the payload data. + */ + public int length() { + return this.length; + } + + /** + * Returns the byte at the given index. + */ + public byte byteAt(int index) { + if (0 <= index && index < this.length) { + return this.data[this.offset + index]; + } + throw new ArrayIndexOutOfBoundsException(index); + } + + /** + * Allocates a new byte array, copies the payload data into it and returns it. + */ + public byte[] toByteArray() { + byte[] retArray = new byte[this.length]; + System.arraycopy(this.data, this.offset, retArray, 0, this.length); + return retArray; + } + + /** + * Copies the payload data to a byte array. + * + * @param target the target byte array + * @param targetOffset the offset in the target byte array + */ + public void copyTo(byte[] target, int targetOffset) { + if (this.length > target.length + targetOffset) { + throw new ArrayIndexOutOfBoundsException(); + } + System.arraycopy(this.data, this.offset, target, targetOffset, this.length); + } + + /** + * Clones this payload by creating a copy of the underlying + * byte array. + */ + public Object clone() { + try { + // Start with a shallow copy of data + Payload clone = (Payload) super.clone(); + // Only copy the part of data that belongs to this Payload + if (offset == 0 && length == data.length) { + // It is the whole thing, so just clone it. + clone.data = (byte[]) data.clone(); + } + else { + // Just get the part + clone.data = this.toByteArray(); + clone.offset = 0; + } + return clone; + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); // shouldn't happen + } + } + + public boolean equals(Object obj) { + if (obj == this) + return true; + if (obj instanceof Payload) { + Payload other = (Payload) obj; + if (length == other.length) { + for(int i=0;i + * This is not thread-safe. + */ +public class PositionBasedTermVectorMapper extends TermVectorMapper{ + private Map/*>*/ fieldToTerms; + + private String currentField; + /** + * A Map of Integer and TVPositionInfo + */ + private Map/**/ currentPositions; + private boolean storeOffsets; + + + + + /** + * + * + */ + public PositionBasedTermVectorMapper() { + super(false, false); + } + + public PositionBasedTermVectorMapper(boolean ignoringOffsets) + { + super(false, ignoringOffsets); + } + + /** + * Never ignores positions. This mapper doesn't make much sense unless there are positions + * @return false + */ + public boolean isIgnoringPositions() { + return false; + } + + /** + * Callback for the TermVectorReader. + * @param term + * @param frequency + * @param offsets + * @param positions + */ + public void map(String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions) { + for (int i = 0; i < positions.length; i++) { + Integer posVal = new Integer(positions[i]); + TVPositionInfo pos = (TVPositionInfo) currentPositions.get(posVal); + if (pos == null) { + pos = new TVPositionInfo(positions[i], storeOffsets); + currentPositions.put(posVal, pos); + } + pos.addTerm(term, offsets != null ? offsets[i] : null); + } + } + + /** + * Callback mechanism used by the TermVectorReader + * @param field The field being read + * @param numTerms The number of terms in the vector + * @param storeOffsets Whether offsets are available + * @param storePositions Whether positions are available + */ + public void setExpectations(String field, int numTerms, boolean storeOffsets, boolean storePositions) { + if (storePositions == false) + { + throw new RuntimeException("You must store positions in order to use this Mapper"); + } + if (storeOffsets == true) + { + //ignoring offsets + } + fieldToTerms = new HashMap(numTerms); + this.storeOffsets = storeOffsets; + currentField = field; + currentPositions = new HashMap(); + fieldToTerms.put(currentField, currentPositions); + } + + /** + * Get the mapping between fields and terms, sorted by the comparator + * + * @return A map between field names and a Map. The sub-Map key is the position as the integer, the value is {@link org.apache.lucene.index.PositionBasedTermVectorMapper.TVPositionInfo}. + */ + public Map getFieldToTerms() { + return fieldToTerms; + } + + /** + * Container for a term at a position + */ + public static class TVPositionInfo{ + private int position; + //a list of Strings + private List terms; + //A list of TermVectorOffsetInfo + private List offsets; + + + public TVPositionInfo(int position, boolean storeOffsets) { + this.position = position; + terms = new ArrayList(); + if (storeOffsets) { + offsets = new ArrayList(); + } + } + + void addTerm(String term, TermVectorOffsetInfo info) + { + terms.add(term); + if (offsets != null) { + offsets.add(info); + } + } + + /** + * + * @return The position of the term + */ + public int getPosition() { + return position; + } + + /** + * Note, there may be multiple terms at the same position + * @return A List of Strings + */ + public List getTerms() { + return terms; + } + + /** + * Parallel list (to {@link #getTerms()}) of TermVectorOffsetInfo objects. There may be multiple entries since there may be multiple terms at a position + * @return A List of TermVectorOffsetInfo objects, if offsets are store. + */ + public List getOffsets() { + return offsets; + } + } + + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/RawPostingList.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/RawPostingList.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/RawPostingList.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,36 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** This is the base class for an in-memory posting list, + * keyed by a Token. {@link TermsHash} maintains a hash + * table holding one instance of this per unique Token. + * Consumers of TermsHash (@link TermsHashConsumer} must + * subclass this class with its own concrete class. + * {@link FreqProxTermsWriter.RawPostingList} is the + * subclass used for the freq/prox postings, and {@link + * TermVectorsTermsWriter.PostingList} is the subclass + * used to hold TermVectors postings. */ + +abstract class RawPostingList { + final static int BYTES_SIZE = DocumentsWriter.OBJECT_HEADER_BYTES + 3*DocumentsWriter.INT_NUM_BYTE; + int textStart; + int intStart; + int byteStart; +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/ReadOnlyMultiSegmentReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/ReadOnlyMultiSegmentReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/ReadOnlyMultiSegmentReader.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,37 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; + +import java.io.IOException; +import java.util.Map; + +class ReadOnlyMultiSegmentReader extends MultiSegmentReader { + ReadOnlyMultiSegmentReader(Directory directory, SegmentInfos sis, boolean closeDirectory) throws IOException { + super(directory, sis, closeDirectory, true); + } + + ReadOnlyMultiSegmentReader(Directory directory, SegmentInfos infos, boolean closeDirectory, SegmentReader[] oldReaders, int[] oldStarts, Map oldNormsCache) throws IOException { + super(directory, infos, closeDirectory, oldReaders, oldStarts, oldNormsCache, true); + } + + protected void acquireWriteLock() { + ReadOnlySegmentReader.noWrite(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/ReadOnlySegmentReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/ReadOnlySegmentReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/ReadOnlySegmentReader.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,34 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class ReadOnlySegmentReader extends SegmentReader { + + static void noWrite() { + throw new UnsupportedOperationException("This IndexReader cannot make any changes to the index (it was opened with readOnly = true)"); + } + + protected void acquireWriteLock() { + noWrite(); + } + + // Not synchronized + public boolean isDeleted(int n) { + return deletedDocs != null && deletedDocs.get(n); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/ReusableStringReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/ReusableStringReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/ReusableStringReader.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,55 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Reader; + +/** Used by DocumentsWriter to implemented a StringReader + * that can be reset to a new string; we use this when + * tokenizing the string value from a Field. */ +final class ReusableStringReader extends Reader { + int upto; + int left; + String s; + void init(String s) { + this.s = s; + left = s.length(); + this.upto = 0; + } + public int read(char[] c) { + return read(c, 0, c.length); + } + public int read(char[] c, int off, int len) { + if (left > len) { + s.getChars(upto, upto+len, c, off); + upto += len; + left -= len; + return len; + } else if (0 == left) { + return -1; + } else { + s.getChars(upto, upto+left, c, off); + int r = left; + left = 0; + upto = s.length(); + return r; + } + } + public void close() {}; +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentInfo.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,683 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.util.BitVector; +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; + +final class SegmentInfo { + + static final int NO = -1; // e.g. no norms; no deletes; + static final int YES = 1; // e.g. have norms; have deletes; + static final int CHECK_DIR = 0; // e.g. must check dir to see if there are norms/deletions + static final int WITHOUT_GEN = 0; // a file name that has no GEN in it. + + public String name; // unique name in dir + public int docCount; // number of docs in seg + public Directory dir; // where segment resides + + private boolean preLockless; // true if this is a segments file written before + // lock-less commits (2.1) + + private long delGen; // current generation of del file; NO if there + // are no deletes; CHECK_DIR if it's a pre-2.1 segment + // (and we must check filesystem); YES or higher if + // there are deletes at generation N + + private long[] normGen; // current generation of each field's norm file. + // If this array is null, for lockLess this means no + // separate norms. For preLockLess this means we must + // check filesystem. If this array is not null, its + // values mean: NO says this field has no separate + // norms; CHECK_DIR says it is a preLockLess segment and + // filesystem must be checked; >= YES says this field + // has separate norms with the specified generation + + private byte isCompoundFile; // NO if it is not; YES if it is; CHECK_DIR if it's + // pre-2.1 (ie, must check file system to see + // if .cfs and .nrm exist) + + private boolean hasSingleNormFile; // true if this segment maintains norms in a single file; + // false otherwise + // this is currently false for segments populated by DocumentWriter + // and true for newly created merged segments (both + // compound and non compound). + + private List files; // cached list of files that this segment uses + // in the Directory + + long sizeInBytes = -1; // total byte size of all of our files (computed on demand) + + private int docStoreOffset; // if this segment shares stored fields & vectors, this + // offset is where in that file this segment's docs begin + private String docStoreSegment; // name used to derive fields/vectors file we share with + // other segments + private boolean docStoreIsCompoundFile; // whether doc store files are stored in compound file (*.cfx) + + private int delCount; // How many deleted docs in this segment, or -1 if not yet known + // (if it's an older index) + + private boolean hasProx; // True if this segment has any fields with omitTf==false + + public SegmentInfo(String name, int docCount, Directory dir) { + this.name = name; + this.docCount = docCount; + this.dir = dir; + delGen = NO; + isCompoundFile = CHECK_DIR; + preLockless = true; + hasSingleNormFile = false; + docStoreOffset = -1; + docStoreSegment = name; + docStoreIsCompoundFile = false; + delCount = 0; + hasProx = true; + } + + public SegmentInfo(String name, int docCount, Directory dir, boolean isCompoundFile, boolean hasSingleNormFile) { + this(name, docCount, dir, isCompoundFile, hasSingleNormFile, -1, null, false, true); + } + + public SegmentInfo(String name, int docCount, Directory dir, boolean isCompoundFile, boolean hasSingleNormFile, + int docStoreOffset, String docStoreSegment, boolean docStoreIsCompoundFile, boolean hasProx) { + this(name, docCount, dir); + this.isCompoundFile = (byte) (isCompoundFile ? YES : NO); + this.hasSingleNormFile = hasSingleNormFile; + preLockless = false; + this.docStoreOffset = docStoreOffset; + this.docStoreSegment = docStoreSegment; + this.docStoreIsCompoundFile = docStoreIsCompoundFile; + this.hasProx = hasProx; + delCount = 0; + assert docStoreOffset == -1 || docStoreSegment != null: "dso=" + docStoreOffset + " dss=" + docStoreSegment + " docCount=" + docCount; + } + + /** + * Copy everything from src SegmentInfo into our instance. + */ + void reset(SegmentInfo src) { + clearFiles(); + name = src.name; + docCount = src.docCount; + dir = src.dir; + preLockless = src.preLockless; + delGen = src.delGen; + docStoreOffset = src.docStoreOffset; + docStoreIsCompoundFile = src.docStoreIsCompoundFile; + if (src.normGen == null) { + normGen = null; + } else { + normGen = new long[src.normGen.length]; + System.arraycopy(src.normGen, 0, normGen, 0, src.normGen.length); + } + isCompoundFile = src.isCompoundFile; + hasSingleNormFile = src.hasSingleNormFile; + delCount = src.delCount; + } + + /** + * Construct a new SegmentInfo instance by reading a + * previously saved SegmentInfo from input. + * + * @param dir directory to load from + * @param format format of the segments info file + * @param input input handle to read segment info from + */ + SegmentInfo(Directory dir, int format, IndexInput input) throws IOException { + this.dir = dir; + name = input.readString(); + docCount = input.readInt(); + if (format <= SegmentInfos.FORMAT_LOCKLESS) { + delGen = input.readLong(); + if (format <= SegmentInfos.FORMAT_SHARED_DOC_STORE) { + docStoreOffset = input.readInt(); + if (docStoreOffset != -1) { + docStoreSegment = input.readString(); + docStoreIsCompoundFile = (1 == input.readByte()); + } else { + docStoreSegment = name; + docStoreIsCompoundFile = false; + } + } else { + docStoreOffset = -1; + docStoreSegment = name; + docStoreIsCompoundFile = false; + } + if (format <= SegmentInfos.FORMAT_SINGLE_NORM_FILE) { + hasSingleNormFile = (1 == input.readByte()); + } else { + hasSingleNormFile = false; + } + int numNormGen = input.readInt(); + if (numNormGen == NO) { + normGen = null; + } else { + normGen = new long[numNormGen]; + for(int j=0;j= YES: this means this segment was written by + // the LOCKLESS code and for certain has + // deletions + // + if (delGen == NO) { + return false; + } else if (delGen >= YES) { + return true; + } else { + return dir.fileExists(getDelFileName()); + } + } + + void advanceDelGen() { + // delGen 0 is reserved for pre-LOCKLESS format + if (delGen == NO) { + delGen = YES; + } else { + delGen++; + } + clearFiles(); + } + + void clearDelGen() { + delGen = NO; + clearFiles(); + } + + public Object clone () { + SegmentInfo si = new SegmentInfo(name, docCount, dir); + si.isCompoundFile = isCompoundFile; + si.delGen = delGen; + si.delCount = delCount; + si.preLockless = preLockless; + si.hasSingleNormFile = hasSingleNormFile; + if (normGen != null) { + si.normGen = (long[]) normGen.clone(); + } + si.docStoreOffset = docStoreOffset; + si.docStoreSegment = docStoreSegment; + si.docStoreIsCompoundFile = docStoreIsCompoundFile; + return si; + } + + String getDelFileName() { + if (delGen == NO) { + // In this case we know there is no deletion filename + // against this segment + return null; + } else { + // If delGen is CHECK_DIR, it's the pre-lockless-commit file format + return IndexFileNames.fileNameFromGeneration(name, "." + IndexFileNames.DELETES_EXTENSION, delGen); + } + } + + /** + * Returns true if this field for this segment has saved a separate norms file (__N.sX). + * + * @param fieldNumber the field index to check + */ + boolean hasSeparateNorms(int fieldNumber) + throws IOException { + if ((normGen == null && preLockless) || (normGen != null && normGen[fieldNumber] == CHECK_DIR)) { + // Must fallback to directory file exists check: + String fileName = name + ".s" + fieldNumber; + return dir.fileExists(fileName); + } else if (normGen == null || normGen[fieldNumber] == NO) { + return false; + } else { + return true; + } + } + + /** + * Returns true if any fields in this segment have separate norms. + */ + boolean hasSeparateNorms() + throws IOException { + if (normGen == null) { + if (!preLockless) { + // This means we were created w/ LOCKLESS code and no + // norms are written yet: + return false; + } else { + // This means this segment was saved with pre-LOCKLESS + // code. So we must fallback to the original + // directory list check: + String[] result = dir.list(); + if (result == null) + throw new IOException("cannot read directory " + dir + ": list() returned null"); + + String pattern; + pattern = name + ".s"; + int patternLength = pattern.length(); + for(int i = 0; i < result.length; i++){ + if(result[i].startsWith(pattern) && Character.isDigit(result[i].charAt(patternLength))) + return true; + } + return false; + } + } else { + // This means this segment was saved with LOCKLESS + // code so we first check whether any normGen's are >= 1 + // (meaning they definitely have separate norms): + for(int i=0;i= YES) { + return true; + } + } + // Next we look for any == 0. These cases were + // pre-LOCKLESS and must be checked in directory: + for(int i=0;i= YES || dir.fileExists(delFileName))) { + files.add(delFileName); + } + + // Careful logic for norms files + if (normGen != null) { + for(int i=0;i= YES) { + // Definitely a separate norm file, with generation: + files.add(IndexFileNames.fileNameFromGeneration(name, "." + IndexFileNames.SEPARATE_NORMS_EXTENSION + i, gen)); + } else if (NO == gen) { + // No separate norms but maybe plain norms + // in the non compound file case: + if (!hasSingleNormFile && !useCompoundFile) { + String fileName = name + "." + IndexFileNames.PLAIN_NORMS_EXTENSION + i; + if (dir.fileExists(fileName)) { + files.add(fileName); + } + } + } else if (CHECK_DIR == gen) { + // Pre-2.1: we have to check file existence + String fileName = null; + if (useCompoundFile) { + fileName = name + "." + IndexFileNames.SEPARATE_NORMS_EXTENSION + i; + } else if (!hasSingleNormFile) { + fileName = name + "." + IndexFileNames.PLAIN_NORMS_EXTENSION + i; + } + if (fileName != null && dir.fileExists(fileName)) { + files.add(fileName); + } + } + } + } else if (preLockless || (!hasSingleNormFile && !useCompoundFile)) { + // Pre-2.1: we have to scan the dir to find all + // matching _X.sN/_X.fN files for our segment: + String prefix; + if (useCompoundFile) + prefix = name + "." + IndexFileNames.SEPARATE_NORMS_EXTENSION; + else + prefix = name + "." + IndexFileNames.PLAIN_NORMS_EXTENSION; + int prefixLength = prefix.length(); + String[] allFiles = dir.list(); + if (allFiles == null) + throw new IOException("cannot read directory " + dir + ": list() returned null"); + for(int i=0;i prefixLength && Character.isDigit(fileName.charAt(prefixLength)) && fileName.startsWith(prefix)) { + files.add(fileName); + } + } + } + return files; + } + + /* Called whenever any change is made that affects which + * files this segment has. */ + private void clearFiles() { + files = null; + sizeInBytes = -1; + } + + /** Used for debugging */ + public String segString(Directory dir) { + String cfs; + try { + if (getUseCompoundFile()) + cfs = "c"; + else + cfs = "C"; + } catch (IOException ioe) { + cfs = "?"; + } + + String docStore; + + if (docStoreOffset != -1) + docStore = "->" + docStoreSegment; + else + docStore = ""; + + return name + ":" + + cfs + + (this.dir == dir ? "" : "x") + + docCount + docStore; + } + + /** We consider another SegmentInfo instance equal if it + * has the same dir and same name. */ + public boolean equals(Object obj) { + SegmentInfo other; + try { + other = (SegmentInfo) obj; + } catch (ClassCastException cce) { + return false; + } + return other.dir == dir && other.name.equals(name); + } + + public int hashCode() { + return dir.hashCode() + name.hashCode(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentInfos.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentInfos.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentInfos.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,843 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.ChecksumIndexOutput; +import org.apache.lucene.store.ChecksumIndexInput; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Vector; + +final class SegmentInfos extends Vector { + + /** The file format version, a negative number. */ + /* Works since counter, the old 1st entry, is always >= 0 */ + public static final int FORMAT = -1; + + /** This format adds details used for lockless commits. It differs + * slightly from the previous format in that file names + * are never re-used (write once). Instead, each file is + * written to the next generation. For example, + * segments_1, segments_2, etc. This allows us to not use + * a commit lock. See file + * formats for details. + */ + public static final int FORMAT_LOCKLESS = -2; + + /** This format adds a "hasSingleNormFile" flag into each segment info. + * See LUCENE-756 + * for details. + */ + public static final int FORMAT_SINGLE_NORM_FILE = -3; + + /** This format allows multiple segments to share a single + * vectors and stored fields file. */ + public static final int FORMAT_SHARED_DOC_STORE = -4; + + /** This format adds a checksum at the end of the file to + * ensure all bytes were successfully written. */ + public static final int FORMAT_CHECKSUM = -5; + + /** This format adds the deletion count for each segment. + * This way IndexWriter can efficiently report numDocs(). */ + public static final int FORMAT_DEL_COUNT = -6; + + /** This format adds the boolean hasProx to record if any + * fields in the segment store prox information (ie, have + * omitTf==false) */ + public static final int FORMAT_HAS_PROX = -7; + + /* This must always point to the most recent file format. */ + static final int CURRENT_FORMAT = FORMAT_HAS_PROX; + + public int counter = 0; // used to name new segments + /** + * counts how often the index has been changed by adding or deleting docs. + * starting with the current time in milliseconds forces to create unique version numbers. + */ + private long version = System.currentTimeMillis(); + + private long generation = 0; // generation of the "segments_N" for the next commit + private long lastGeneration = 0; // generation of the "segments_N" file we last successfully read + // or wrote; this is normally the same as generation except if + // there was an IOException that had interrupted a commit + + /** + * If non-null, information about loading segments_N files + * will be printed here. @see #setInfoStream. + */ + private static PrintStream infoStream; + + public final SegmentInfo info(int i) { + return (SegmentInfo) get(i); + } + + /** + * Get the generation (N) of the current segments_N file + * from a list of files. + * + * @param files -- array of file names to check + */ + public static long getCurrentSegmentGeneration(String[] files) { + if (files == null) { + return -1; + } + long max = -1; + for (int i = 0; i < files.length; i++) { + String file = files[i]; + if (file.startsWith(IndexFileNames.SEGMENTS) && !file.equals(IndexFileNames.SEGMENTS_GEN)) { + long gen = generationFromSegmentsFileName(file); + if (gen > max) { + max = gen; + } + } + } + return max; + } + + /** + * Get the generation (N) of the current segments_N file + * in the directory. + * + * @param directory -- directory to search for the latest segments_N file + */ + public static long getCurrentSegmentGeneration(Directory directory) throws IOException { + String[] files = directory.list(); + if (files == null) + throw new IOException("cannot read directory " + directory + ": list() returned null"); + return getCurrentSegmentGeneration(files); + } + + /** + * Get the filename of the current segments_N file + * from a list of files. + * + * @param files -- array of file names to check + */ + + public static String getCurrentSegmentFileName(String[] files) throws IOException { + return IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, + "", + getCurrentSegmentGeneration(files)); + } + + /** + * Get the filename of the current segments_N file + * in the directory. + * + * @param directory -- directory to search for the latest segments_N file + */ + public static String getCurrentSegmentFileName(Directory directory) throws IOException { + return IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, + "", + getCurrentSegmentGeneration(directory)); + } + + /** + * Get the segments_N filename in use by this segment infos. + */ + public String getCurrentSegmentFileName() { + return IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, + "", + lastGeneration); + } + + /** + * Parse the generation off the segments file name and + * return it. + */ + public static long generationFromSegmentsFileName(String fileName) { + if (fileName.equals(IndexFileNames.SEGMENTS)) { + return 0; + } else if (fileName.startsWith(IndexFileNames.SEGMENTS)) { + return Long.parseLong(fileName.substring(1+IndexFileNames.SEGMENTS.length()), + Character.MAX_RADIX); + } else { + throw new IllegalArgumentException("fileName \"" + fileName + "\" is not a segments file"); + } + } + + + /** + * Get the next segments_N filename that will be written. + */ + public String getNextSegmentFileName() { + long nextGeneration; + + if (generation == -1) { + nextGeneration = 1; + } else { + nextGeneration = generation+1; + } + return IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, + "", + nextGeneration); + } + + /** + * Read a particular segmentFileName. Note that this may + * throw an IOException if a commit is in process. + * + * @param directory -- directory containing the segments file + * @param segmentFileName -- segment file to load + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public final void read(Directory directory, String segmentFileName) throws CorruptIndexException, IOException { + boolean success = false; + + // Clear any previous segments: + clear(); + + ChecksumIndexInput input = new ChecksumIndexInput(directory.openInput(segmentFileName)); + + generation = generationFromSegmentsFileName(segmentFileName); + + lastGeneration = generation; + + try { + int format = input.readInt(); + if(format < 0){ // file contains explicit format info + // check that it is a format we can understand + if (format < CURRENT_FORMAT) + throw new CorruptIndexException("Unknown format version: " + format); + version = input.readLong(); // read version + counter = input.readInt(); // read counter + } + else{ // file is in old format without explicit format info + counter = format; + } + + for (int i = input.readInt(); i > 0; i--) { // read segmentInfos + add(new SegmentInfo(directory, format, input)); + } + + if(format >= 0){ // in old format the version number may be at the end of the file + if (input.getFilePointer() >= input.length()) + version = System.currentTimeMillis(); // old file format without version number + else + version = input.readLong(); // read version + } + + if (format <= FORMAT_CHECKSUM) { + final long checksumNow = input.getChecksum(); + final long checksumThen = input.readLong(); + if (checksumNow != checksumThen) + throw new CorruptIndexException("checksum mismatch in segments file"); + } + success = true; + } + finally { + input.close(); + if (!success) { + // Clear any segment infos we had loaded so we + // have a clean slate on retry: + clear(); + } + } + } + + /** + * This version of read uses the retry logic (for lock-less + * commits) to find the right segments file to load. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public final void read(Directory directory) throws CorruptIndexException, IOException { + + generation = lastGeneration = -1; + + new FindSegmentsFile(directory) { + + protected Object doBody(String segmentFileName) throws CorruptIndexException, IOException { + read(directory, segmentFileName); + return null; + } + }.run(); + } + + // Only non-null after prepareCommit has been called and + // before finishCommit is called + ChecksumIndexOutput pendingOutput; + + private final void write(Directory directory) throws IOException { + + String segmentFileName = getNextSegmentFileName(); + + // Always advance the generation on write: + if (generation == -1) { + generation = 1; + } else { + generation++; + } + + ChecksumIndexOutput output = new ChecksumIndexOutput(directory.createOutput(segmentFileName)); + + boolean success = false; + + try { + output.writeInt(CURRENT_FORMAT); // write FORMAT + output.writeLong(++version); // every write changes + // the index + output.writeInt(counter); // write counter + output.writeInt(size()); // write infos + for (int i = 0; i < size(); i++) { + info(i).write(output); + } + output.prepareCommit(); + success = true; + pendingOutput = output; + } finally { + if (!success) { + // We hit an exception above; try to close the file + // but suppress any exception: + try { + output.close(); + } catch (Throwable t) { + // Suppress so we keep throwing the original exception + } + try { + // Try not to leave a truncated segments_N file in + // the index: + directory.deleteFile(segmentFileName); + } catch (Throwable t) { + // Suppress so we keep throwing the original exception + } + } + } + } + + /** + * Returns a copy of this instance, also copying each + * SegmentInfo. + */ + + public Object clone() { + SegmentInfos sis = (SegmentInfos) super.clone(); + for(int i=0;i 0) { + buffer.append(' '); + } + final SegmentInfo info = info(i); + buffer.append(info.segString(directory)); + if (info.dir != directory) + buffer.append("**"); + } + return buffer.toString(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentMergeInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentMergeInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentMergeInfo.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,81 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +final class SegmentMergeInfo { + Term term; + int base; + TermEnum termEnum; + IndexReader reader; + private TermPositions postings; // use getPositions() + private int[] docMap; // use getDocMap() + + SegmentMergeInfo(int b, TermEnum te, IndexReader r) + throws IOException { + base = b; + reader = r; + termEnum = te; + term = te.term(); + } + + // maps around deleted docs + int[] getDocMap() { + if (docMap == null) { + // build array which maps document numbers around deletions + if (reader.hasDeletions()) { + int maxDoc = reader.maxDoc(); + docMap = new int[maxDoc]; + int j = 0; + for (int i = 0; i < maxDoc; i++) { + if (reader.isDeleted(i)) + docMap[i] = -1; + else + docMap[i] = j++; + } + } + } + return docMap; + } + + TermPositions getPositions() throws IOException { + if (postings == null) { + postings = reader.termPositions(); + } + return postings; + } + + final boolean next() throws IOException { + if (termEnum.next()) { + term = termEnum.term(); + return true; + } else { + term = null; + return false; + } + } + + final void close() throws IOException { + termEnum.close(); + if (postings != null) { + postings.close(); + } +} +} + Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentMergeQueue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentMergeQueue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentMergeQueue.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,43 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.util.PriorityQueue; + +final class SegmentMergeQueue extends PriorityQueue { + SegmentMergeQueue(int size) { + initialize(size); + } + + protected final boolean lessThan(Object a, Object b) { + SegmentMergeInfo stiA = (SegmentMergeInfo)a; + SegmentMergeInfo stiB = (SegmentMergeInfo)b; + int comparison = stiA.term.compareTo(stiB.term); + if (comparison == 0) + return stiA.base < stiB.base; + else + return comparison < 0; + } + + final void close() throws IOException { + while (top() != null) + ((SegmentMergeInfo)pop()).close(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentMerger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentMerger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentMerger.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,810 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.document.FieldSelectorResult; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; + +/** + * The SegmentMerger class combines two or more Segments, represented by an IndexReader ({@link #add}, + * into a single Segment. After adding the appropriate readers, call the merge method to combine the + * segments. + *

+ * If the compoundFile flag is set, then the segments will be merged into a compound file. + * + * + * @see #merge + * @see #add + */ +final class SegmentMerger { + + /** norms header placeholder */ + static final byte[] NORMS_HEADER = new byte[]{'N','R','M',-1}; + + private Directory directory; + private String segment; + private int termIndexInterval = IndexWriter.DEFAULT_TERM_INDEX_INTERVAL; + + private List readers = new ArrayList(); + private FieldInfos fieldInfos; + + private int mergedDocs; + + private CheckAbort checkAbort; + + // Whether we should merge doc stores (stored fields and + // vectors files). When all segments we are merging + // already share the same doc store files, we don't need + // to merge the doc stores. + private boolean mergeDocStores; + + /** Maximum number of contiguous documents to bulk-copy + when merging stored fields */ + private final static int MAX_RAW_MERGE_DOCS = 4192; + + /** This ctor used only by test code. + * + * @param dir The Directory to merge the other segments into + * @param name The name of the new segment + */ + SegmentMerger(Directory dir, String name) { + directory = dir; + segment = name; + } + + SegmentMerger(IndexWriter writer, String name, MergePolicy.OneMerge merge) { + directory = writer.getDirectory(); + segment = name; + if (merge != null) + checkAbort = new CheckAbort(merge, directory); + termIndexInterval = writer.getTermIndexInterval(); + } + + boolean hasProx() { + return fieldInfos.hasProx(); + } + + /** + * Add an IndexReader to the collection of readers that are to be merged + * @param reader + */ + final void add(IndexReader reader) { + readers.add(reader); + } + + /** + * + * @param i The index of the reader to return + * @return The ith reader to be merged + */ + final IndexReader segmentReader(int i) { + return (IndexReader) readers.get(i); + } + + /** + * Merges the readers specified by the {@link #add} method into the directory passed to the constructor + * @return The number of documents that were merged + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + final int merge() throws CorruptIndexException, IOException { + return merge(true); + } + + /** + * Merges the readers specified by the {@link #add} method + * into the directory passed to the constructor. + * @param mergeDocStores if false, we will not merge the + * stored fields nor vectors files + * @return The number of documents that were merged + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + final int merge(boolean mergeDocStores) throws CorruptIndexException, IOException { + + this.mergeDocStores = mergeDocStores; + + // NOTE: it's important to add calls to + // checkAbort.work(...) if you make any changes to this + // method that will spend alot of time. The frequency + // of this check impacts how long + // IndexWriter.close(false) takes to actually stop the + // threads. + + mergedDocs = mergeFields(); + mergeTerms(); + mergeNorms(); + + if (mergeDocStores && fieldInfos.hasVectors()) + mergeVectors(); + + return mergedDocs; + } + + /** + * close all IndexReaders that have been added. + * Should not be called before merge(). + * @throws IOException + */ + final void closeReaders() throws IOException { + for (int i = 0; i < readers.size(); i++) { // close readers + IndexReader reader = (IndexReader) readers.get(i); + reader.close(); + } + } + + final List createCompoundFile(String fileName) + throws IOException { + CompoundFileWriter cfsWriter = + new CompoundFileWriter(directory, fileName, checkAbort); + + List files = + new ArrayList(IndexFileNames.COMPOUND_EXTENSIONS.length + 1); + + // Basic files + for (int i = 0; i < IndexFileNames.COMPOUND_EXTENSIONS.length; i++) { + String ext = IndexFileNames.COMPOUND_EXTENSIONS[i]; + + if (ext.equals(IndexFileNames.PROX_EXTENSION) && !hasProx()) + continue; + + if (mergeDocStores || (!ext.equals(IndexFileNames.FIELDS_EXTENSION) && + !ext.equals(IndexFileNames.FIELDS_INDEX_EXTENSION))) + files.add(segment + "." + ext); + } + + // Fieldable norm files + for (int i = 0; i < fieldInfos.size(); i++) { + FieldInfo fi = fieldInfos.fieldInfo(i); + if (fi.isIndexed && !fi.omitNorms) { + files.add(segment + "." + IndexFileNames.NORMS_EXTENSION); + break; + } + } + + // Vector files + if (fieldInfos.hasVectors() && mergeDocStores) { + for (int i = 0; i < IndexFileNames.VECTOR_EXTENSIONS.length; i++) { + files.add(segment + "." + IndexFileNames.VECTOR_EXTENSIONS[i]); + } + } + + // Now merge all added files + Iterator it = files.iterator(); + while (it.hasNext()) { + cfsWriter.addFile((String) it.next()); + } + + // Perform the merge + cfsWriter.close(); + + return files; + } + + private void addIndexed(IndexReader reader, FieldInfos fieldInfos, Collection names, boolean storeTermVectors, boolean storePositionWithTermVector, + boolean storeOffsetWithTermVector, boolean storePayloads, boolean omitTf) throws IOException { + Iterator i = names.iterator(); + while (i.hasNext()) { + String field = (String)i.next(); + fieldInfos.add(field, true, storeTermVectors, storePositionWithTermVector, storeOffsetWithTermVector, !reader.hasNorms(field), storePayloads, omitTf); + } + } + + private SegmentReader[] matchingSegmentReaders; + private int[] rawDocLengths; + private int[] rawDocLengths2; + + private void setMatchingSegmentReaders() { + // If the i'th reader is a SegmentReader and has + // identical fieldName -> number mapping, then this + // array will be non-null at position i: + matchingSegmentReaders = new SegmentReader[readers.size()]; + + // If this reader is a SegmentReader, and all of its + // field name -> number mappings match the "merged" + // FieldInfos, then we can do a bulk copy of the + // stored fields: + for (int i = 0; i < readers.size(); i++) { + IndexReader reader = (IndexReader) readers.get(i); + if (reader instanceof SegmentReader) { + SegmentReader segmentReader = (SegmentReader) reader; + boolean same = true; + FieldInfos segmentFieldInfos = segmentReader.getFieldInfos(); + for (int j = 0; same && j < segmentFieldInfos.size(); j++) + same = fieldInfos.fieldName(j).equals(segmentFieldInfos.fieldName(j)); + if (same) + matchingSegmentReaders[i] = segmentReader; + } + } + + // Used for bulk-reading raw bytes for stored fields + rawDocLengths = new int[MAX_RAW_MERGE_DOCS]; + rawDocLengths2 = new int[MAX_RAW_MERGE_DOCS]; + } + + /** + * + * @return The number of documents in all of the readers + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + private final int mergeFields() throws CorruptIndexException, IOException { + + if (!mergeDocStores) { + // When we are not merging by doc stores, that means + // all segments were written as part of a single + // autoCommit=false IndexWriter session, so their field + // name -> number mapping are the same. So, we start + // with the fieldInfos of the last segment in this + // case, to keep that numbering. + final SegmentReader sr = (SegmentReader) readers.get(readers.size()-1); + fieldInfos = (FieldInfos) sr.fieldInfos.clone(); + } else { + fieldInfos = new FieldInfos(); // merge field names + } + + for (int i = 0; i < readers.size(); i++) { + IndexReader reader = (IndexReader) readers.get(i); + if (reader instanceof SegmentReader) { + SegmentReader segmentReader = (SegmentReader) reader; + for (int j = 0; j < segmentReader.getFieldInfos().size(); j++) { + FieldInfo fi = segmentReader.getFieldInfos().fieldInfo(j); + fieldInfos.add(fi.name, fi.isIndexed, fi.storeTermVector, fi.storePositionWithTermVector, fi.storeOffsetWithTermVector, !reader.hasNorms(fi.name), fi.storePayloads, fi.omitTf); + } + } else { + addIndexed(reader, fieldInfos, reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION_OFFSET), true, true, true, false, false); + addIndexed(reader, fieldInfos, reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION), true, true, false, false, false); + addIndexed(reader, fieldInfos, reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_OFFSET), true, false, true, false, false); + addIndexed(reader, fieldInfos, reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR), true, false, false, false, false); + addIndexed(reader, fieldInfos, reader.getFieldNames(IndexReader.FieldOption.OMIT_TF), false, false, false, false, true); + addIndexed(reader, fieldInfos, reader.getFieldNames(IndexReader.FieldOption.STORES_PAYLOADS), false, false, false, true, false); + addIndexed(reader, fieldInfos, reader.getFieldNames(IndexReader.FieldOption.INDEXED), false, false, false, false, false); + fieldInfos.add(reader.getFieldNames(IndexReader.FieldOption.UNINDEXED), false); + } + } + fieldInfos.write(directory, segment + ".fnm"); + + int docCount = 0; + + setMatchingSegmentReaders(); + + if (mergeDocStores) { + + // for merging we don't want to compress/uncompress the data, so to tell the FieldsReader that we're + // in merge mode, we use this FieldSelector + FieldSelector fieldSelectorMerge = new FieldSelector() { + public FieldSelectorResult accept(String fieldName) { + return FieldSelectorResult.LOAD_FOR_MERGE; + } + }; + + // merge field values + final FieldsWriter fieldsWriter = new FieldsWriter(directory, segment, fieldInfos); + + try { + for (int i = 0; i < readers.size(); i++) { + final IndexReader reader = (IndexReader) readers.get(i); + final SegmentReader matchingSegmentReader = matchingSegmentReaders[i]; + final FieldsReader matchingFieldsReader; + final boolean hasMatchingReader; + if (matchingSegmentReader != null) { + final FieldsReader fieldsReader = matchingSegmentReader.getFieldsReader(); + if (fieldsReader != null && !fieldsReader.canReadRawDocs()) { + matchingFieldsReader = null; + hasMatchingReader = false; + } else { + matchingFieldsReader = fieldsReader; + hasMatchingReader = true; + } + } else { + hasMatchingReader = false; + matchingFieldsReader = null; + } + final int maxDoc = reader.maxDoc(); + final boolean hasDeletions = reader.hasDeletions(); + for (int j = 0; j < maxDoc;) { + if (!hasDeletions || !reader.isDeleted(j)) { // skip deleted docs + if (hasMatchingReader) { + // We can optimize this case (doing a bulk + // byte copy) since the field numbers are + // identical + int start = j; + int numDocs = 0; + do { + j++; + numDocs++; + if (j >= maxDoc) + break; + if (hasDeletions && matchingSegmentReader.isDeleted(j)) { + j++; + break; + } + } while(numDocs < MAX_RAW_MERGE_DOCS); + + IndexInput stream = matchingFieldsReader.rawDocs(rawDocLengths, start, numDocs); + fieldsWriter.addRawDocuments(stream, rawDocLengths, numDocs); + docCount += numDocs; + if (checkAbort != null) + checkAbort.work(300*numDocs); + } else { + // NOTE: it's very important to first assign + // to doc then pass it to + // termVectorsWriter.addAllDocVectors; see + // LUCENE-1282 + Document doc = reader.document(j, fieldSelectorMerge); + fieldsWriter.addDocument(doc); + j++; + docCount++; + if (checkAbort != null) + checkAbort.work(300); + } + } else + j++; + } + } + } finally { + fieldsWriter.close(); + } + + final long fdxFileLength = directory.fileLength(segment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); + + if (4+docCount*8 != fdxFileLength) + // This is most likely a bug in Sun JRE 1.6.0_04/_05; + // we detect that the bug has struck, here, and + // throw an exception to prevent the corruption from + // entering the index. See LUCENE-1282 for + // details. + throw new RuntimeException("mergeFields produced an invalid result: docCount is " + docCount + " but fdx file size is " + fdxFileLength + "; now aborting this merge to prevent index corruption"); + + } else + // If we are skipping the doc stores, that means there + // are no deletions in any of these segments, so we + // just sum numDocs() of each segment to get total docCount + for (int i = 0; i < readers.size(); i++) + docCount += ((IndexReader) readers.get(i)).numDocs(); + + return docCount; + } + + /** + * Merge the TermVectors from each of the segments into the new one. + * @throws IOException + */ + private final void mergeVectors() throws IOException { + TermVectorsWriter termVectorsWriter = + new TermVectorsWriter(directory, segment, fieldInfos); + + try { + for (int r = 0; r < readers.size(); r++) { + final SegmentReader matchingSegmentReader = matchingSegmentReaders[r]; + TermVectorsReader matchingVectorsReader; + final boolean hasMatchingReader; + if (matchingSegmentReader != null) { + matchingVectorsReader = matchingSegmentReader.termVectorsReaderOrig; + + // If the TV* files are an older format then they + // cannot read raw docs: + if (matchingVectorsReader != null && !matchingVectorsReader.canReadRawDocs()) { + matchingVectorsReader = null; + hasMatchingReader = false; + } else + hasMatchingReader = matchingVectorsReader != null; + + } else { + hasMatchingReader = false; + matchingVectorsReader = null; + } + IndexReader reader = (IndexReader) readers.get(r); + final boolean hasDeletions = reader.hasDeletions(); + int maxDoc = reader.maxDoc(); + for (int docNum = 0; docNum < maxDoc;) { + // skip deleted docs + if (!hasDeletions || !reader.isDeleted(docNum)) { + if (hasMatchingReader) { + // We can optimize this case (doing a bulk + // byte copy) since the field numbers are + // identical + int start = docNum; + int numDocs = 0; + do { + docNum++; + numDocs++; + if (docNum >= maxDoc) + break; + if (hasDeletions && matchingSegmentReader.isDeleted(docNum)) { + docNum++; + break; + } + } while(numDocs < MAX_RAW_MERGE_DOCS); + + matchingVectorsReader.rawDocs(rawDocLengths, rawDocLengths2, start, numDocs); + termVectorsWriter.addRawDocuments(matchingVectorsReader, rawDocLengths, rawDocLengths2, numDocs); + if (checkAbort != null) + checkAbort.work(300*numDocs); + } else { + // NOTE: it's very important to first assign + // to vectors then pass it to + // termVectorsWriter.addAllDocVectors; see + // LUCENE-1282 + TermFreqVector[] vectors = reader.getTermFreqVectors(docNum); + termVectorsWriter.addAllDocVectors(vectors); + docNum++; + if (checkAbort != null) + checkAbort.work(300); + } + } else + docNum++; + } + } + } finally { + termVectorsWriter.close(); + } + + final long tvxSize = directory.fileLength(segment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); + + if (4+mergedDocs*16 != tvxSize) + // This is most likely a bug in Sun JRE 1.6.0_04/_05; + // we detect that the bug has struck, here, and + // throw an exception to prevent the corruption from + // entering the index. See LUCENE-1282 for + // details. + throw new RuntimeException("mergeVectors produced an invalid result: mergedDocs is " + mergedDocs + " but tvx size is " + tvxSize + "; now aborting this merge to prevent index corruption"); + } + + private IndexOutput freqOutput = null; + private IndexOutput proxOutput = null; + private TermInfosWriter termInfosWriter = null; + private int skipInterval; + private int maxSkipLevels; + private SegmentMergeQueue queue = null; + private DefaultSkipListWriter skipListWriter = null; + + private final void mergeTerms() throws CorruptIndexException, IOException { + try { + freqOutput = directory.createOutput(segment + ".frq"); + if (hasProx()) + proxOutput = directory.createOutput(segment + ".prx"); + termInfosWriter = + new TermInfosWriter(directory, segment, fieldInfos, + termIndexInterval); + skipInterval = termInfosWriter.skipInterval; + maxSkipLevels = termInfosWriter.maxSkipLevels; + skipListWriter = new DefaultSkipListWriter(skipInterval, maxSkipLevels, mergedDocs, freqOutput, proxOutput); + queue = new SegmentMergeQueue(readers.size()); + + mergeTermInfos(); + + } finally { + if (freqOutput != null) freqOutput.close(); + if (proxOutput != null) proxOutput.close(); + if (termInfosWriter != null) termInfosWriter.close(); + if (queue != null) queue.close(); + } + } + + private final void mergeTermInfos() throws CorruptIndexException, IOException { + int base = 0; + final int readerCount = readers.size(); + for (int i = 0; i < readerCount; i++) { + IndexReader reader = (IndexReader) readers.get(i); + TermEnum termEnum = reader.terms(); + SegmentMergeInfo smi = new SegmentMergeInfo(base, termEnum, reader); + int[] docMap = smi.getDocMap(); + if (docMap != null) { + if (docMaps == null) { + docMaps = new int[readerCount][]; + delCounts = new int[readerCount]; + } + docMaps[i] = docMap; + delCounts[i] = smi.reader.maxDoc() - smi.reader.numDocs(); + } + + base += reader.numDocs(); + if (smi.next()) + queue.put(smi); // initialize queue + else + smi.close(); + } + + SegmentMergeInfo[] match = new SegmentMergeInfo[readers.size()]; + + while (queue.size() > 0) { + int matchSize = 0; // pop matching terms + match[matchSize++] = (SegmentMergeInfo) queue.pop(); + Term term = match[0].term; + SegmentMergeInfo top = (SegmentMergeInfo) queue.top(); + + while (top != null && term.compareTo(top.term) == 0) { + match[matchSize++] = (SegmentMergeInfo) queue.pop(); + top = (SegmentMergeInfo) queue.top(); + } + + final int df = mergeTermInfo(match, matchSize); // add new TermInfo + + if (checkAbort != null) + checkAbort.work(df/3.0); + + while (matchSize > 0) { + SegmentMergeInfo smi = match[--matchSize]; + if (smi.next()) + queue.put(smi); // restore queue + else + smi.close(); // done with a segment + } + } + } + + private final TermInfo termInfo = new TermInfo(); // minimize consing + + /** Merge one term found in one or more segments. The array smis + * contains segments that are positioned at the same term. N + * is the number of cells in the array actually occupied. + * + * @param smis array of segments + * @param n number of cells in the array actually occupied + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + private final int mergeTermInfo(SegmentMergeInfo[] smis, int n) + throws CorruptIndexException, IOException { + final long freqPointer = freqOutput.getFilePointer(); + final long proxPointer; + if (proxOutput != null) + proxPointer = proxOutput.getFilePointer(); + else + proxPointer = 0; + + int df; + if (fieldInfos.fieldInfo(smis[0].term.field).omitTf) { // append posting data + df = appendPostingsNoTf(smis, n); + } else{ + df = appendPostings(smis, n); + } + + long skipPointer = skipListWriter.writeSkip(freqOutput); + + if (df > 0) { + // add an entry to the dictionary with pointers to prox and freq files + termInfo.set(df, freqPointer, proxPointer, (int) (skipPointer - freqPointer)); + termInfosWriter.add(smis[0].term, termInfo); + } + + return df; + } + + private byte[] payloadBuffer; + private int[][] docMaps; + int[][] getDocMaps() { + return docMaps; + } + private int[] delCounts; + int[] getDelCounts() { + return delCounts; + } + + /** Process postings from multiple segments all positioned on the + * same term. Writes out merged entries into freqOutput and + * the proxOutput streams. + * + * @param smis array of segments + * @param n number of cells in the array actually occupied + * @return number of documents across all segments where this term was found + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + private final int appendPostings(SegmentMergeInfo[] smis, int n) + throws CorruptIndexException, IOException { + int lastDoc = 0; + int df = 0; // number of docs w/ term + skipListWriter.resetSkip(); + boolean storePayloads = fieldInfos.fieldInfo(smis[0].term.field).storePayloads; + int lastPayloadLength = -1; // ensures that we write the first length + for (int i = 0; i < n; i++) { + SegmentMergeInfo smi = smis[i]; + TermPositions postings = smi.getPositions(); + assert postings != null; + int base = smi.base; + int[] docMap = smi.getDocMap(); + postings.seek(smi.termEnum); + while (postings.next()) { + int doc = postings.doc(); + if (docMap != null) + doc = docMap[doc]; // map around deletions + doc += base; // convert to merged space + + if (doc < 0 || (df > 0 && doc <= lastDoc)) + throw new CorruptIndexException("docs out of order (" + doc + + " <= " + lastDoc + " )"); + + df++; + + if ((df % skipInterval) == 0) { + skipListWriter.setSkipData(lastDoc, storePayloads, lastPayloadLength); + skipListWriter.bufferSkip(df); + } + + int docCode = (doc - lastDoc) << 1; // use low bit to flag freq=1 + lastDoc = doc; + + int freq = postings.freq(); + if (freq == 1) { + freqOutput.writeVInt(docCode | 1); // write doc & freq=1 + } else { + freqOutput.writeVInt(docCode); // write doc + freqOutput.writeVInt(freq); // write frequency in doc + } + + /** See {@link DocumentWriter#writePostings(Posting[], String)} for + * documentation about the encoding of positions and payloads + */ + int lastPosition = 0; // write position deltas + for (int j = 0; j < freq; j++) { + int position = postings.nextPosition(); + int delta = position - lastPosition; + if (storePayloads) { + int payloadLength = postings.getPayloadLength(); + if (payloadLength == lastPayloadLength) { + proxOutput.writeVInt(delta * 2); + } else { + proxOutput.writeVInt(delta * 2 + 1); + proxOutput.writeVInt(payloadLength); + lastPayloadLength = payloadLength; + } + if (payloadLength > 0) { + if (payloadBuffer == null || payloadBuffer.length < payloadLength) { + payloadBuffer = new byte[payloadLength]; + } + postings.getPayload(payloadBuffer, 0); + proxOutput.writeBytes(payloadBuffer, 0, payloadLength); + } + } else { + proxOutput.writeVInt(delta); + } + lastPosition = position; + } + } + } + return df; + } + + /** Process postings from multiple segments without tf, all positioned on the + * same term. Writes out merged entries only into freqOutput, proxOut is not written. + * + * @param smis array of segments + * @param n number of cells in the array actually occupied + * @return number of documents across all segments where this term was found + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + private final int appendPostingsNoTf(SegmentMergeInfo[] smis, int n) + throws CorruptIndexException, IOException { + int lastDoc = 0; + int df = 0; // number of docs w/ term + skipListWriter.resetSkip(); + int lastPayloadLength = -1; // ensures that we write the first length + for (int i = 0; i < n; i++) { + SegmentMergeInfo smi = smis[i]; + TermPositions postings = smi.getPositions(); + assert postings != null; + int base = smi.base; + int[] docMap = smi.getDocMap(); + postings.seek(smi.termEnum); + while (postings.next()) { + int doc = postings.doc(); + if (docMap != null) + doc = docMap[doc]; // map around deletions + doc += base; // convert to merged space + + if (doc < 0 || (df > 0 && doc <= lastDoc)) + throw new CorruptIndexException("docs out of order (" + doc + + " <= " + lastDoc + " )"); + + df++; + + if ((df % skipInterval) == 0) { + skipListWriter.setSkipData(lastDoc, false, lastPayloadLength); + skipListWriter.bufferSkip(df); + } + + int docCode = (doc - lastDoc); + lastDoc = doc; + freqOutput.writeVInt(docCode); // write doc & freq=1 + } + } + return df; + } + + private void mergeNorms() throws IOException { + byte[] normBuffer = null; + IndexOutput output = null; + try { + for (int i = 0; i < fieldInfos.size(); i++) { + FieldInfo fi = fieldInfos.fieldInfo(i); + if (fi.isIndexed && !fi.omitNorms) { + if (output == null) { + output = directory.createOutput(segment + "." + IndexFileNames.NORMS_EXTENSION); + output.writeBytes(NORMS_HEADER,NORMS_HEADER.length); + } + for (int j = 0; j < readers.size(); j++) { + IndexReader reader = (IndexReader) readers.get(j); + int maxDoc = reader.maxDoc(); + if (normBuffer == null || normBuffer.length < maxDoc) { + // the buffer is too small for the current segment + normBuffer = new byte[maxDoc]; + } + reader.norms(fi.name, normBuffer, 0); + if (!reader.hasDeletions()) { + //optimized case for segments without deleted docs + output.writeBytes(normBuffer, maxDoc); + } else { + // this segment has deleted docs, so we have to + // check for every doc if it is deleted or not + for (int k = 0; k < maxDoc; k++) { + if (!reader.isDeleted(k)) { + output.writeByte(normBuffer[k]); + } + } + } + if (checkAbort != null) + checkAbort.work(maxDoc); + } + } + } + } finally { + if (output != null) { + output.close(); + } + } + } + + final static class CheckAbort { + private double workCount; + private MergePolicy.OneMerge merge; + private Directory dir; + public CheckAbort(MergePolicy.OneMerge merge, Directory dir) { + this.merge = merge; + this.dir = dir; + } + + /** + * Records the fact that roughly units amount of work + * have been done since this method was last called. + * When adding time-consuming code into SegmentMerger, + * you should test different values for units to ensure + * that the time in between calls to merge.checkAborted + * is up to ~ 1 second. + */ + public void work(double units) throws MergePolicy.MergeAbortedException { + workCount += units; + if (workCount >= 10000.0) { + merge.checkAborted(dir); + workCount = 0; + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentReader.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,1110 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.search.DefaultSimilarity; +import org.apache.lucene.store.BufferedIndexInput; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.BitVector; +import org.apache.lucene.util.CloseableThreadLocal; + +/** + * @version $Id: SegmentReader.java,v 1.1 2012/08/17 14:55:02 marcin Exp $ + */ +class SegmentReader extends DirectoryIndexReader { + private String segment; + private SegmentInfo si; + private int readBufferSize; + + FieldInfos fieldInfos; + private FieldsReader fieldsReader; + + TermInfosReader tis; + TermVectorsReader termVectorsReaderOrig = null; + CloseableThreadLocal termVectorsLocal = new CloseableThreadLocal(); + + BitVector deletedDocs = null; + private boolean deletedDocsDirty = false; + private boolean normsDirty = false; + private boolean undeleteAll = false; + private int pendingDeleteCount; + + private boolean rollbackDeletedDocsDirty = false; + private boolean rollbackNormsDirty = false; + private boolean rollbackUndeleteAll = false; + private int rollbackPendingDeleteCount; + private boolean readOnly; + + IndexInput freqStream; + IndexInput proxStream; + + // optionally used for the .nrm file shared by multiple norms + private IndexInput singleNormStream; + + // Compound File Reader when based on a compound file segment + CompoundFileReader cfsReader = null; + CompoundFileReader storeCFSReader = null; + + // indicates the SegmentReader with which the resources are being shared, + // in case this is a re-opened reader + private SegmentReader referencedSegmentReader = null; + + private class Norm { + volatile int refCount; + boolean useSingleNormStream; + + public synchronized void incRef() { + assert refCount > 0; + refCount++; + } + + public synchronized void decRef() throws IOException { + assert refCount > 0; + if (refCount == 1) { + close(); + } + refCount--; + + } + + public Norm(IndexInput in, boolean useSingleNormStream, int number, long normSeek) + { + refCount = 1; + this.in = in; + this.number = number; + this.normSeek = normSeek; + this.useSingleNormStream = useSingleNormStream; + } + + private IndexInput in; + private byte[] bytes; + private boolean dirty; + private int number; + private long normSeek; + private boolean rollbackDirty; + + private void reWrite(SegmentInfo si) throws IOException { + // NOTE: norms are re-written in regular directory, not cfs + si.advanceNormGen(this.number); + IndexOutput out = directory().createOutput(si.getNormFileName(this.number)); + try { + out.writeBytes(bytes, maxDoc()); + } finally { + out.close(); + } + this.dirty = false; + } + + /** Closes the underlying IndexInput for this norm. + * It is still valid to access all other norm properties after close is called. + * @throws IOException + */ + private synchronized void close() throws IOException { + if (in != null && !useSingleNormStream) { + in.close(); + } + in = null; + } + } + + /** + * Increments the RC of this reader, as well as + * of all norms this reader is using + */ + public synchronized void incRef() { + super.incRef(); + Iterator it = norms.values().iterator(); + while (it.hasNext()) { + Norm norm = (Norm) it.next(); + norm.incRef(); + } + } + + /** + * only increments the RC of this reader, not tof + * he norms. This is important whenever a reopen() + * creates a new SegmentReader that doesn't share + * the norms with this one + */ + private synchronized void incRefReaderNotNorms() { + super.incRef(); + } + + public synchronized void decRef() throws IOException { + super.decRef(); + Iterator it = norms.values().iterator(); + while (it.hasNext()) { + Norm norm = (Norm) it.next(); + norm.decRef(); + } + } + + private synchronized void decRefReaderNotNorms() throws IOException { + super.decRef(); + } + + Map norms = new HashMap(); + + /** The class which implements SegmentReader. */ + private static Class IMPL; + static { + try { + String name = + System.getProperty("org.apache.lucene.SegmentReader.class", + SegmentReader.class.getName()); + IMPL = Class.forName(name); + } catch (ClassNotFoundException e) { + throw new RuntimeException("cannot load SegmentReader class: " + e, e); + } catch (SecurityException se) { + try { + IMPL = Class.forName(SegmentReader.class.getName()); + } catch (ClassNotFoundException e) { + throw new RuntimeException("cannot load default SegmentReader class: " + e, e); + } + } + } + + private static Class READONLY_IMPL; + static { + try { + String name = + System.getProperty("org.apache.lucene.ReadOnlySegmentReader.class", + ReadOnlySegmentReader.class.getName()); + READONLY_IMPL = Class.forName(name); + } catch (ClassNotFoundException e) { + throw new RuntimeException("cannot load ReadOnlySegmentReader class: " + e, e); + } catch (SecurityException se) { + try { + READONLY_IMPL = Class.forName(ReadOnlySegmentReader.class.getName()); + } catch (ClassNotFoundException e) { + throw new RuntimeException("cannot load default ReadOnlySegmentReader class: " + e, e); + } + } + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static SegmentReader get(SegmentInfo si) throws CorruptIndexException, IOException { + return get(READ_ONLY_DEFAULT, si.dir, si, null, false, false, BufferedIndexInput.BUFFER_SIZE, true); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static SegmentReader get(boolean readOnly, SegmentInfo si) throws CorruptIndexException, IOException { + return get(readOnly, si.dir, si, null, false, false, BufferedIndexInput.BUFFER_SIZE, true); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + static SegmentReader get(SegmentInfo si, boolean doOpenStores) throws CorruptIndexException, IOException { + return get(READ_ONLY_DEFAULT, si.dir, si, null, false, false, BufferedIndexInput.BUFFER_SIZE, doOpenStores); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static SegmentReader get(SegmentInfo si, int readBufferSize) throws CorruptIndexException, IOException { + return get(READ_ONLY_DEFAULT, si.dir, si, null, false, false, readBufferSize, true); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + static SegmentReader get(SegmentInfo si, int readBufferSize, boolean doOpenStores) throws CorruptIndexException, IOException { + return get(READ_ONLY_DEFAULT, si.dir, si, null, false, false, readBufferSize, doOpenStores); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + static SegmentReader get(boolean readOnly, SegmentInfo si, int readBufferSize, boolean doOpenStores) throws CorruptIndexException, IOException { + return get(readOnly, si.dir, si, null, false, false, readBufferSize, doOpenStores); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static SegmentReader get(boolean readOnly, SegmentInfos sis, SegmentInfo si, + boolean closeDir) throws CorruptIndexException, IOException { + return get(readOnly, si.dir, si, sis, closeDir, true, BufferedIndexInput.BUFFER_SIZE, true); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static SegmentReader get(Directory dir, SegmentInfo si, + SegmentInfos sis, + boolean closeDir, boolean ownDir, + int readBufferSize) + throws CorruptIndexException, IOException { + return get(READ_ONLY_DEFAULT, dir, si, sis, closeDir, ownDir, readBufferSize, true); + } + + /** + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public static SegmentReader get(boolean readOnly, + Directory dir, + SegmentInfo si, + SegmentInfos sis, + boolean closeDir, boolean ownDir, + int readBufferSize, + boolean doOpenStores) + throws CorruptIndexException, IOException { + SegmentReader instance; + try { + if (readOnly) + instance = (SegmentReader)READONLY_IMPL.newInstance(); + else + instance = (SegmentReader)IMPL.newInstance(); + } catch (Exception e) { + throw new RuntimeException("cannot load SegmentReader class: " + e, e); + } + instance.init(dir, sis, closeDir, readOnly); + instance.initialize(si, readBufferSize, doOpenStores); + return instance; + } + + private void initialize(SegmentInfo si, int readBufferSize, boolean doOpenStores) throws CorruptIndexException, IOException { + segment = si.name; + this.si = si; + this.readBufferSize = readBufferSize; + + boolean success = false; + + try { + // Use compound file directory for some files, if it exists + Directory cfsDir = directory(); + if (si.getUseCompoundFile()) { + cfsReader = new CompoundFileReader(directory(), segment + "." + IndexFileNames.COMPOUND_FILE_EXTENSION, readBufferSize); + cfsDir = cfsReader; + } + + final Directory storeDir; + + if (doOpenStores) { + if (si.getDocStoreOffset() != -1) { + if (si.getDocStoreIsCompoundFile()) { + storeCFSReader = new CompoundFileReader(directory(), si.getDocStoreSegment() + "." + IndexFileNames.COMPOUND_FILE_STORE_EXTENSION, readBufferSize); + storeDir = storeCFSReader; + } else { + storeDir = directory(); + } + } else { + storeDir = cfsDir; + } + } else + storeDir = null; + + fieldInfos = new FieldInfos(cfsDir, segment + ".fnm"); + + boolean anyProx = false; + final int numFields = fieldInfos.size(); + for(int i=0;!anyProx && i 0) { + return false; + } + } + return true; + } + + // for testing only + boolean normsClosed(String field) { + Norm norm = (Norm) norms.get(field); + return norm.refCount == 0; + } + + /** + * Create a clone from the initial TermVectorsReader and store it in the ThreadLocal. + * @return TermVectorsReader + */ + private TermVectorsReader getTermVectorsReader() { + assert termVectorsReaderOrig != null; + TermVectorsReader tvReader = (TermVectorsReader)termVectorsLocal.get(); + if (tvReader == null) { + try { + tvReader = (TermVectorsReader)termVectorsReaderOrig.clone(); + } catch (CloneNotSupportedException cnse) { + return null; + } + termVectorsLocal.set(tvReader); + } + return tvReader; + } + + /** Return a term frequency vector for the specified document and field. The + * vector returned contains term numbers and frequencies for all terms in + * the specified field of this document, if the field had storeTermVector + * flag set. If the flag was not set, the method returns null. + * @throws IOException + */ + public TermFreqVector getTermFreqVector(int docNumber, String field) throws IOException { + // Check if this field is invalid or has no stored term vector + ensureOpen(); + FieldInfo fi = fieldInfos.fieldInfo(field); + if (fi == null || !fi.storeTermVector || termVectorsReaderOrig == null) + return null; + + TermVectorsReader termVectorsReader = getTermVectorsReader(); + if (termVectorsReader == null) + return null; + + return termVectorsReader.get(docNumber, field); + } + + + public void getTermFreqVector(int docNumber, String field, TermVectorMapper mapper) throws IOException { + ensureOpen(); + FieldInfo fi = fieldInfos.fieldInfo(field); + if (fi == null || !fi.storeTermVector || termVectorsReaderOrig == null) + return; + + TermVectorsReader termVectorsReader = getTermVectorsReader(); + if (termVectorsReader == null) + { + return; + } + + + termVectorsReader.get(docNumber, field, mapper); + } + + + public void getTermFreqVector(int docNumber, TermVectorMapper mapper) throws IOException { + ensureOpen(); + if (termVectorsReaderOrig == null) + return; + + TermVectorsReader termVectorsReader = getTermVectorsReader(); + if (termVectorsReader == null) + return; + + termVectorsReader.get(docNumber, mapper); + } + + /** Return an array of term frequency vectors for the specified document. + * The array contains a vector for each vectorized field in the document. + * Each vector vector contains term numbers and frequencies for all terms + * in a given vectorized field. + * If no such fields existed, the method returns null. + * @throws IOException + */ + public TermFreqVector[] getTermFreqVectors(int docNumber) throws IOException { + ensureOpen(); + if (termVectorsReaderOrig == null) + return null; + + TermVectorsReader termVectorsReader = getTermVectorsReader(); + if (termVectorsReader == null) + return null; + + return termVectorsReader.get(docNumber); + } + + /** Returns the field infos of this segment */ + FieldInfos fieldInfos() { + return fieldInfos; + } + + /** + * Return the name of the segment this reader is reading. + */ + String getSegmentName() { + return segment; + } + + /** + * Return the SegmentInfo of the segment this reader is reading. + */ + SegmentInfo getSegmentInfo() { + return si; + } + + void setSegmentInfo(SegmentInfo info) { + si = info; + } + + void startCommit() { + super.startCommit(); + rollbackDeletedDocsDirty = deletedDocsDirty; + rollbackNormsDirty = normsDirty; + rollbackUndeleteAll = undeleteAll; + rollbackPendingDeleteCount = pendingDeleteCount; + Iterator it = norms.values().iterator(); + while (it.hasNext()) { + Norm norm = (Norm) it.next(); + norm.rollbackDirty = norm.dirty; + } + } + + void rollbackCommit() { + super.rollbackCommit(); + deletedDocsDirty = rollbackDeletedDocsDirty; + normsDirty = rollbackNormsDirty; + undeleteAll = rollbackUndeleteAll; + pendingDeleteCount = rollbackPendingDeleteCount; + Iterator it = norms.values().iterator(); + while (it.hasNext()) { + Norm norm = (Norm) it.next(); + norm.dirty = norm.rollbackDirty; + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermDocs.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermDocs.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermDocs.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,210 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.util.BitVector; +import org.apache.lucene.store.IndexInput; + +class SegmentTermDocs implements TermDocs { + protected SegmentReader parent; + protected IndexInput freqStream; + protected int count; + protected int df; + protected BitVector deletedDocs; + int doc = 0; + int freq; + + private int skipInterval; + private int maxSkipLevels; + private DefaultSkipListReader skipListReader; + + private long freqBasePointer; + private long proxBasePointer; + + private long skipPointer; + private boolean haveSkipped; + + protected boolean currentFieldStoresPayloads; + protected boolean currentFieldOmitTf; + + protected SegmentTermDocs(SegmentReader parent) { + this.parent = parent; + this.freqStream = (IndexInput) parent.freqStream.clone(); + this.deletedDocs = parent.deletedDocs; + this.skipInterval = parent.tis.getSkipInterval(); + this.maxSkipLevels = parent.tis.getMaxSkipLevels(); + } + + public void seek(Term term) throws IOException { + TermInfo ti = parent.tis.get(term); + seek(ti, term); + } + + public void seek(TermEnum termEnum) throws IOException { + TermInfo ti; + Term term; + + // use comparison of fieldinfos to verify that termEnum belongs to the same segment as this SegmentTermDocs + if (termEnum instanceof SegmentTermEnum && ((SegmentTermEnum) termEnum).fieldInfos == parent.fieldInfos) { // optimized case + SegmentTermEnum segmentTermEnum = ((SegmentTermEnum) termEnum); + term = segmentTermEnum.term(); + ti = segmentTermEnum.termInfo(); + } else { // punt case + term = termEnum.term(); + ti = parent.tis.get(term); + } + + seek(ti, term); + } + + void seek(TermInfo ti, Term term) throws IOException { + count = 0; + FieldInfo fi = parent.fieldInfos.fieldInfo(term.field); + currentFieldOmitTf = (fi != null) ? fi.omitTf : false; + currentFieldStoresPayloads = (fi != null) ? fi.storePayloads : false; + if (ti == null) { + df = 0; + } else { + df = ti.docFreq; + doc = 0; + freqBasePointer = ti.freqPointer; + proxBasePointer = ti.proxPointer; + skipPointer = freqBasePointer + ti.skipOffset; + freqStream.seek(freqBasePointer); + haveSkipped = false; + } + } + + public void close() throws IOException { + freqStream.close(); + if (skipListReader != null) + skipListReader.close(); + } + + public final int doc() { return doc; } + public final int freq() { return freq; } + + protected void skippingDoc() throws IOException { + } + + public boolean next() throws IOException { + while (true) { + if (count == df) + return false; + final int docCode = freqStream.readVInt(); + + if (currentFieldOmitTf) { + doc += docCode; + freq = 1; + } else { + doc += docCode >>> 1; // shift off low bit + if ((docCode & 1) != 0) // if low bit is set + freq = 1; // freq is one + else + freq = freqStream.readVInt(); // else read freq + } + + count++; + + if (deletedDocs == null || !deletedDocs.get(doc)) + break; + skippingDoc(); + } + return true; + } + + /** Optimized implementation. */ + public int read(final int[] docs, final int[] freqs) + throws IOException { + final int length = docs.length; + if (currentFieldOmitTf) { + return readNoTf(docs, freqs, length); + } else { + int i = 0; + while (i < length && count < df) { + // manually inlined call to next() for speed + final int docCode = freqStream.readVInt(); + doc += docCode >>> 1; // shift off low bit + if ((docCode & 1) != 0) // if low bit is set + freq = 1; // freq is one + else + freq = freqStream.readVInt(); // else read freq + count++; + + if (deletedDocs == null || !deletedDocs.get(doc)) { + docs[i] = doc; + freqs[i] = freq; + ++i; + } + } + return i; + } + } + + private final int readNoTf(final int[] docs, final int[] freqs, final int length) throws IOException { + int i = 0; + while (i < length && count < df) { + // manually inlined call to next() for speed + doc += freqStream.readVInt(); + count++; + + if (deletedDocs == null || !deletedDocs.get(doc)) { + docs[i] = doc; + // Hardware freq to 1 when term freqs were not + // stored in the index + freqs[i] = 1; + ++i; + } + } + return i; + } + + + /** Overridden by SegmentTermPositions to skip in prox stream. */ + protected void skipProx(long proxPointer, int payloadLength) throws IOException {} + + /** Optimized implementation. */ + public boolean skipTo(int target) throws IOException { + if (df >= skipInterval) { // optimized case + if (skipListReader == null) + skipListReader = new DefaultSkipListReader((IndexInput) freqStream.clone(), maxSkipLevels, skipInterval); // lazily clone + + if (!haveSkipped) { // lazily initialize skip stream + skipListReader.init(skipPointer, freqBasePointer, proxBasePointer, df, currentFieldStoresPayloads); + haveSkipped = true; + } + + int newCount = skipListReader.skipTo(target); + if (newCount > count) { + freqStream.seek(skipListReader.getFreqPointer()); + skipProx(skipListReader.getProxPointer(), skipListReader.getPayloadLength()); + + doc = skipListReader.getDoc(); + count = newCount; + } + } + + // done skipping, now just scan + do { + if (!next()) + return false; + } while (target > doc); + return true; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermEnum.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermEnum.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermEnum.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,209 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.store.IndexInput; + +final class SegmentTermEnum extends TermEnum implements Cloneable { + private IndexInput input; + FieldInfos fieldInfos; + long size; + long position = -1; + + private TermBuffer termBuffer = new TermBuffer(); + private TermBuffer prevBuffer = new TermBuffer(); + private TermBuffer scanBuffer = new TermBuffer(); // used for scanning + + private TermInfo termInfo = new TermInfo(); + + private int format; + private boolean isIndex = false; + long indexPointer = 0; + int indexInterval; + int skipInterval; + int maxSkipLevels; + private int formatM1SkipInterval; + + SegmentTermEnum(IndexInput i, FieldInfos fis, boolean isi) + throws CorruptIndexException, IOException { + input = i; + fieldInfos = fis; + isIndex = isi; + maxSkipLevels = 1; // use single-level skip lists for formats > -3 + + int firstInt = input.readInt(); + if (firstInt >= 0) { + // original-format file, without explicit format version number + format = 0; + size = firstInt; + + // back-compatible settings + indexInterval = 128; + skipInterval = Integer.MAX_VALUE; // switch off skipTo optimization + } else { + // we have a format version number + format = firstInt; + + // check that it is a format we can understand + if (format < TermInfosWriter.FORMAT_CURRENT) + throw new CorruptIndexException("Unknown format version:" + format + " expected " + TermInfosWriter.FORMAT_CURRENT + " or higher"); + + size = input.readLong(); // read the size + + if(format == -1){ + if (!isIndex) { + indexInterval = input.readInt(); + formatM1SkipInterval = input.readInt(); + } + // switch off skipTo optimization for file format prior to 1.4rc2 in order to avoid a bug in + // skipTo implementation of these versions + skipInterval = Integer.MAX_VALUE; + } else { + indexInterval = input.readInt(); + skipInterval = input.readInt(); + if (format <= TermInfosWriter.FORMAT) { + // this new format introduces multi-level skipping + maxSkipLevels = input.readInt(); + } + } + } + if (format > TermInfosWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) { + termBuffer.setPreUTF8Strings(); + scanBuffer.setPreUTF8Strings(); + prevBuffer.setPreUTF8Strings(); + } + } + + protected Object clone() { + SegmentTermEnum clone = null; + try { + clone = (SegmentTermEnum) super.clone(); + } catch (CloneNotSupportedException e) {} + + clone.input = (IndexInput) input.clone(); + clone.termInfo = new TermInfo(termInfo); + + clone.termBuffer = (TermBuffer)termBuffer.clone(); + clone.prevBuffer = (TermBuffer)prevBuffer.clone(); + clone.scanBuffer = new TermBuffer(); + + return clone; + } + + final void seek(long pointer, int p, Term t, TermInfo ti) + throws IOException { + input.seek(pointer); + position = p; + termBuffer.set(t); + prevBuffer.reset(); + termInfo.set(ti); + } + + /** Increments the enumeration to the next element. True if one exists.*/ + public final boolean next() throws IOException { + if (position++ >= size - 1) { + prevBuffer.set(termBuffer); + termBuffer.reset(); + return false; + } + + prevBuffer.set(termBuffer); + termBuffer.read(input, fieldInfos); + + termInfo.docFreq = input.readVInt(); // read doc freq + termInfo.freqPointer += input.readVLong(); // read freq pointer + termInfo.proxPointer += input.readVLong(); // read prox pointer + + if(format == -1){ + // just read skipOffset in order to increment file pointer; + // value is never used since skipTo is switched off + if (!isIndex) { + if (termInfo.docFreq > formatM1SkipInterval) { + termInfo.skipOffset = input.readVInt(); + } + } + } + else{ + if (termInfo.docFreq >= skipInterval) + termInfo.skipOffset = input.readVInt(); + } + + if (isIndex) + indexPointer += input.readVLong(); // read index pointer + + return true; + } + + /** Optimized scan, without allocating new terms. + * Return number of invocations to next(). */ + final int scanTo(Term term) throws IOException { + scanBuffer.set(term); + int count = 0; + while (scanBuffer.compareTo(termBuffer) > 0 && next()) { + count++; + } + return count; + } + + /** Returns the current Term in the enumeration. + Initially invalid, valid after next() called for the first time.*/ + public final Term term() { + return termBuffer.toTerm(); + } + + /** Returns the previous Term enumerated. Initially null.*/ + final Term prev() { + return prevBuffer.toTerm(); + } + + /** Returns the current TermInfo in the enumeration. + Initially invalid, valid after next() called for the first time.*/ + final TermInfo termInfo() { + return new TermInfo(termInfo); + } + + /** Sets the argument to the current TermInfo in the enumeration. + Initially invalid, valid after next() called for the first time.*/ + final void termInfo(TermInfo ti) { + ti.set(termInfo); + } + + /** Returns the docFreq from the current TermInfo in the enumeration. + Initially invalid, valid after next() called for the first time.*/ + public final int docFreq() { + return termInfo.docFreq; + } + + /* Returns the freqPointer from the current TermInfo in the enumeration. + Initially invalid, valid after next() called for the first time.*/ + final long freqPointer() { + return termInfo.freqPointer; + } + + /* Returns the proxPointer from the current TermInfo in the enumeration. + Initially invalid, valid after next() called for the first time.*/ + final long proxPointer() { + return termInfo.proxPointer; + } + + /** Closes the enumeration to further activity, freeing resources. */ + public final void close() throws IOException { + input.close(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermPositionVector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermPositionVector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermPositionVector.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,65 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class SegmentTermPositionVector extends SegmentTermVector implements TermPositionVector { + protected int[][] positions; + protected TermVectorOffsetInfo[][] offsets; + public static final int[] EMPTY_TERM_POS = new int[0]; + + public SegmentTermPositionVector(String field, String terms[], int termFreqs[], int[][] positions, TermVectorOffsetInfo[][] offsets) { + super(field, terms, termFreqs); + this.offsets = offsets; + this.positions = positions; + } + + /** + * Returns an array of TermVectorOffsetInfo in which the term is found. + * + * @param index The position in the array to get the offsets from + * @return An array of TermVectorOffsetInfo objects or the empty list + * @see org.apache.lucene.analysis.Token + */ + public TermVectorOffsetInfo[] getOffsets(int index) { + TermVectorOffsetInfo[] result = TermVectorOffsetInfo.EMPTY_OFFSET_INFO; + if(offsets == null) + return null; + if (index >=0 && index < offsets.length) + { + result = offsets[index]; + } + return result; + } + + /** + * Returns an array of positions in which the term is found. + * Terms are identified by the index at which its number appears in the + * term String array obtained from the indexOf method. + */ + public int[] getTermPositions(int index) { + int[] result = EMPTY_TERM_POS; + if(positions == null) + return null; + if (index >=0 && index < positions.length) + { + result = positions[index]; + } + + return result; + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermPositions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermPositions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermPositions.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,197 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.IndexInput; + +import java.io.IOException; + +final class SegmentTermPositions +extends SegmentTermDocs implements TermPositions { + private IndexInput proxStream; + private int proxCount; + private int position; + + // the current payload length + private int payloadLength; + // indicates whether the payload of the currend position has + // been read from the proxStream yet + private boolean needToLoadPayload; + + // these variables are being used to remember information + // for a lazy skip + private long lazySkipPointer = -1; + private int lazySkipProxCount = 0; + + SegmentTermPositions(SegmentReader p) { + super(p); + this.proxStream = null; // the proxStream will be cloned lazily when nextPosition() is called for the first time + } + + final void seek(TermInfo ti, Term term) throws IOException { + super.seek(ti, term); + if (ti != null) + lazySkipPointer = ti.proxPointer; + + lazySkipProxCount = 0; + proxCount = 0; + payloadLength = 0; + needToLoadPayload = false; + } + + public final void close() throws IOException { + super.close(); + if (proxStream != null) proxStream.close(); + } + + public final int nextPosition() throws IOException { + if (currentFieldOmitTf) + // This field does not store term freq, positions, payloads + return 0; + // perform lazy skips if neccessary + lazySkip(); + proxCount--; + return position += readDeltaPosition(); + } + + private final int readDeltaPosition() throws IOException { + int delta = proxStream.readVInt(); + if (currentFieldStoresPayloads) { + // if the current field stores payloads then + // the position delta is shifted one bit to the left. + // if the LSB is set, then we have to read the current + // payload length + if ((delta & 1) != 0) { + payloadLength = proxStream.readVInt(); + } + delta >>>= 1; + needToLoadPayload = true; + } + return delta; + } + + protected final void skippingDoc() throws IOException { + // we remember to skip a document lazily + lazySkipProxCount += freq; + } + + public final boolean next() throws IOException { + // we remember to skip the remaining positions of the current + // document lazily + lazySkipProxCount += proxCount; + + if (super.next()) { // run super + proxCount = freq; // note frequency + position = 0; // reset position + return true; + } + return false; + } + + public final int read(final int[] docs, final int[] freqs) { + throw new UnsupportedOperationException("TermPositions does not support processing multiple documents in one call. Use TermDocs instead."); + } + + + /** Called by super.skipTo(). */ + protected void skipProx(long proxPointer, int payloadLength) throws IOException { + // we save the pointer, we might have to skip there lazily + lazySkipPointer = proxPointer; + lazySkipProxCount = 0; + proxCount = 0; + this.payloadLength = payloadLength; + needToLoadPayload = false; + } + + private void skipPositions(int n) throws IOException { + assert !currentFieldOmitTf; + for (int f = n; f > 0; f--) { // skip unread positions + readDeltaPosition(); + skipPayload(); + } + } + + private void skipPayload() throws IOException { + if (needToLoadPayload && payloadLength > 0) { + proxStream.seek(proxStream.getFilePointer() + payloadLength); + } + needToLoadPayload = false; + } + + // It is not always neccessary to move the prox pointer + // to a new document after the freq pointer has been moved. + // Consider for example a phrase query with two terms: + // the freq pointer for term 1 has to move to document x + // to answer the question if the term occurs in that document. But + // only if term 2 also matches document x, the positions have to be + // read to figure out if term 1 and term 2 appear next + // to each other in document x and thus satisfy the query. + // So we move the prox pointer lazily to the document + // as soon as positions are requested. + private void lazySkip() throws IOException { + if (proxStream == null) { + // clone lazily + proxStream = (IndexInput)parent.proxStream.clone(); + } + + // we might have to skip the current payload + // if it was not read yet + skipPayload(); + + if (lazySkipPointer != -1) { + proxStream.seek(lazySkipPointer); + lazySkipPointer = -1; + } + + if (lazySkipProxCount != 0) { + skipPositions(lazySkipProxCount); + lazySkipProxCount = 0; + } + } + + public int getPayloadLength() { + return payloadLength; + } + + public byte[] getPayload(byte[] data, int offset) throws IOException { + if (!needToLoadPayload) { + throw new IOException("Payload cannot be loaded more than once for the same term position."); + } + + // read payloads lazily + byte[] retArray; + int retOffset; + if (data == null || data.length - offset < payloadLength) { + // the array is too small to store the payload data, + // so we allocate a new one + retArray = new byte[payloadLength]; + retOffset = 0; + } else { + retArray = data; + retOffset = offset; + } + proxStream.readBytes(retArray, retOffset, payloadLength); + needToLoadPayload = false; + return retArray; + } + + public boolean isPayloadAvailable() { + return needToLoadPayload && payloadLength > 0; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermVector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermVector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SegmentTermVector.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,89 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.*; + + +class SegmentTermVector implements TermFreqVector { + private String field; + private String terms[]; + private int termFreqs[]; + + SegmentTermVector(String field, String terms[], int termFreqs[]) { + this.field = field; + this.terms = terms; + this.termFreqs = termFreqs; + } + + /** + * + * @return The number of the field this vector is associated with + */ + public String getField() { + return field; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append('{'); + sb.append(field).append(": "); + if(terms != null){ + for (int i=0; i0) sb.append(", "); + sb.append(terms[i]).append('/').append(termFreqs[i]); + } + } + sb.append('}'); + + return sb.toString(); + } + + public int size() { + return terms == null ? 0 : terms.length; + } + + public String [] getTerms() { + return terms; + } + + public int[] getTermFrequencies() { + return termFreqs; + } + + public int indexOf(String termText) { + if(terms == null) + return -1; + int res = Arrays.binarySearch(terms, termText); + return res >= 0 ? res : -1; + } + + public int[] indexesOf(String [] termNumbers, int start, int len) { + // TODO: there must be a more efficient way of doing this. + // At least, we could advance the lower bound of the terms array + // as we find valid indexes. Also, it might be possible to leverage + // this even more by starting in the middle of the termNumbers array + // and thus dividing the terms array maybe in half with each found index. + int res[] = new int[len]; + + for (int i=0; i < len; i++) { + res[i] = indexOf(termNumbers[start+ i]); + } + return res; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SerialMergeScheduler.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SerialMergeScheduler.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SerialMergeScheduler.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,41 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** A {@link MergeScheduler} that simply does each merge + * sequentially, using the current thread. */ +public class SerialMergeScheduler extends MergeScheduler { + + /** Just do the merges in sequence. We do this + * "synchronized" so that even if the application is using + * multiple threads, only one merge may run at a time. */ + synchronized public void merge(IndexWriter writer) + throws CorruptIndexException, IOException { + + while(true) { + MergePolicy.OneMerge merge = writer.getNextMerge(); + if (merge == null) + break; + writer.merge(merge); + } + } + + public void close() {} +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/SnapshotDeletionPolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/SnapshotDeletionPolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/SnapshotDeletionPolicy.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,130 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Collection; +import java.util.List; +import java.util.ArrayList; +import java.io.IOException; +import org.apache.lucene.store.Directory; + +/** A {@link IndexDeletionPolicy} that wraps around any other + * {@link IndexDeletionPolicy} and adds the ability to hold and + * later release a single "snapshot" of an index. While + * the snapshot is held, the {@link IndexWriter} will not + * remove any files associated with it even if the index is + * otherwise being actively, arbitrarily changed. Because + * we wrap another arbitrary {@link IndexDeletionPolicy}, this + * gives you the freedom to continue using whatever {@link + * IndexDeletionPolicy} you would normally want to use with your + * index. Note that you can re-use a single instance of + * SnapshotDeletionPolicy across multiple writers as long + * as they are against the same index Directory. Any + * snapshot held when a writer is closed will "survive" + * when the next writer is opened. + * + *

WARNING: This API is a new and experimental and + * may suddenly change.

*/ + +public class SnapshotDeletionPolicy implements IndexDeletionPolicy { + + private IndexCommit lastCommit; + private IndexDeletionPolicy primary; + private String snapshot; + + public SnapshotDeletionPolicy(IndexDeletionPolicy primary) { + this.primary = primary; + } + + public synchronized void onInit(List commits) throws IOException { + primary.onInit(wrapCommits(commits)); + lastCommit = (IndexCommit) commits.get(commits.size()-1); + } + + public synchronized void onCommit(List commits) throws IOException { + primary.onCommit(wrapCommits(commits)); + lastCommit = (IndexCommit) commits.get(commits.size()-1); + } + + /** Take a snapshot of the most recent commit to the + * index. You must call release() to free this snapshot. + * Note that while the snapshot is held, the files it + * references will not be deleted, which will consume + * additional disk space in your index. If you take a + * snapshot at a particularly bad time (say just before + * you call optimize()) then in the worst case this could + * consume an extra 1X of your total index size, until + * you release the snapshot. */ + // TODO 3.0: change this to return IndexCommit instead + public synchronized IndexCommitPoint snapshot() { + if (snapshot == null) + snapshot = lastCommit.getSegmentsFileName(); + else + throw new IllegalStateException("snapshot is already set; please call release() first"); + return lastCommit; + } + + /** Release the currently held snapshot. */ + public synchronized void release() { + if (snapshot != null) + snapshot = null; + else + throw new IllegalStateException("snapshot was not set; please call snapshot() first"); + } + + private class MyCommitPoint extends IndexCommit { + IndexCommit cp; + MyCommitPoint(IndexCommit cp) { + this.cp = cp; + } + public String getSegmentsFileName() { + return cp.getSegmentsFileName(); + } + public Collection getFileNames() throws IOException { + return cp.getFileNames(); + } + public Directory getDirectory() { + return cp.getDirectory(); + } + public void delete() { + synchronized(SnapshotDeletionPolicy.this) { + // Suppress the delete request if this commit point is + // our current snapshot. + if (snapshot == null || !snapshot.equals(getSegmentsFileName())) + cp.delete(); + } + } + public boolean isDeleted() { + return cp.isDeleted(); + } + public long getVersion() { + return cp.getVersion(); + } + public long getGeneration() { + return cp.getGeneration(); + } + } + + private List wrapCommits(List commits) { + final int count = commits.size(); + List myCommits = new ArrayList(count); + for(int i=0;i + * NOTE: This Mapper ignores all Field information for the Document. This means that if you are using offset/positions you will not + * know what Fields they correlate with. + *
+ * This is not thread-safe + */ +public class SortedTermVectorMapper extends TermVectorMapper{ + + + private SortedSet currentSet; + private Map termToTVE = new HashMap(); + private boolean storeOffsets; + private boolean storePositions; + /** + * Stand-in name for the field in {@link TermVectorEntry}. + */ + public static final String ALL = "_ALL_"; + + /** + * + * @param comparator A Comparator for sorting {@link TermVectorEntry}s + */ + public SortedTermVectorMapper(Comparator comparator) { + this(false, false, comparator); + } + + + public SortedTermVectorMapper(boolean ignoringPositions, boolean ignoringOffsets, Comparator comparator) { + super(ignoringPositions, ignoringOffsets); + currentSet = new TreeSet(comparator); + } + + /** + * + * @param term The term to map + * @param frequency The frequency of the term + * @param offsets Offset information, may be null + * @param positions Position information, may be null + */ + //We need to combine any previous mentions of the term + public void map(String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions) { + TermVectorEntry entry = (TermVectorEntry) termToTVE.get(term); + if (entry == null) { + entry = new TermVectorEntry(ALL, term, frequency, + storeOffsets == true ? offsets : null, + storePositions == true ? positions : null); + termToTVE.put(term, entry); + currentSet.add(entry); + } else { + entry.setFrequency(entry.getFrequency() + frequency); + if (storeOffsets) + { + TermVectorOffsetInfo [] existingOffsets = entry.getOffsets(); + //A few diff. cases here: offsets is null, existing offsets is null, both are null, same for positions + if (existingOffsets != null && offsets != null && offsets.length > 0) + { + //copy over the existing offsets + TermVectorOffsetInfo [] newOffsets = new TermVectorOffsetInfo[existingOffsets.length + offsets.length]; + System.arraycopy(existingOffsets, 0, newOffsets, 0, existingOffsets.length); + System.arraycopy(offsets, 0, newOffsets, existingOffsets.length, offsets.length); + entry.setOffsets(newOffsets); + } + else if (existingOffsets == null && offsets != null && offsets.length > 0) + { + entry.setOffsets(offsets); + } + //else leave it alone + } + if (storePositions) + { + int [] existingPositions = entry.getPositions(); + if (existingPositions != null && positions != null && positions.length > 0) + { + int [] newPositions = new int[existingPositions.length + positions.length]; + System.arraycopy(existingPositions, 0, newPositions, 0, existingPositions.length); + System.arraycopy(positions, 0, newPositions, existingPositions.length, positions.length); + entry.setPositions(newPositions); + } + else if (existingPositions == null && positions != null && positions.length > 0) + { + entry.setPositions(positions); + } + } + } + + + } + + public void setExpectations(String field, int numTerms, boolean storeOffsets, boolean storePositions) { + + this.storeOffsets = storeOffsets; + this.storePositions = storePositions; + } + + /** + * The TermVectorEntrySet. A SortedSet of {@link TermVectorEntry} objects. Sort is by the comparator passed into the constructor. + *
+ * This set will be empty until after the mapping process takes place. + * + * @return The SortedSet of {@link TermVectorEntry}. + */ + public SortedSet getTermVectorEntrySet() + { + return currentSet; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/StaleReaderException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/StaleReaderException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/StaleReaderException.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,36 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.index; + +import java.io.IOException; + +/** + * This exception is thrown when an {@link IndexReader} + * tries to make changes to the index (via {@link + * IndexReader#deleteDocument}, {@link + * IndexReader#undeleteAll} or {@link IndexReader#setNorm}) + * but changes have already been committed to the index + * since this reader was instantiated. When this happens + * you must open a new reader on the current index to make + * the changes. + */ +public class StaleReaderException extends IOException { + public StaleReaderException(String message) { + super(message); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/StoredFieldsWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/StoredFieldsWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/StoredFieldsWriter.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,190 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Map; +import java.io.IOException; +import org.apache.lucene.store.RAMOutputStream; +import org.apache.lucene.util.ArrayUtil; + +/** This is a DocFieldConsumer that writes stored fields. */ +final class StoredFieldsWriter extends DocFieldConsumer { + + FieldsWriter fieldsWriter; + final DocumentsWriter docWriter; + int lastDocID; + + PerDoc[] docFreeList = new PerDoc[1]; + int freeCount; + + public StoredFieldsWriter(DocumentsWriter docWriter) { + this.docWriter = docWriter; + } + + public DocFieldConsumerPerThread addThread(DocFieldProcessorPerThread docFieldProcessorPerThread) throws IOException { + return new StoredFieldsWriterPerThread(docFieldProcessorPerThread, this); + } + + synchronized public void flush(Map threadsAndFields, DocumentsWriter.FlushState state) throws IOException { + + if (state.numDocsInStore > 0) { + // It's possible that all documents seen in this segment + // hit non-aborting exceptions, in which case we will + // not have yet init'd the FieldsWriter: + initFieldsWriter(); + + // Fill fdx file to include any final docs that we + // skipped because they hit non-aborting exceptions + fill(state.numDocsInStore - docWriter.getDocStoreOffset()); + } + + if (fieldsWriter != null) + fieldsWriter.flush(); + } + + private void initFieldsWriter() throws IOException { + if (fieldsWriter == null) { + final String docStoreSegment = docWriter.getDocStoreSegment(); + if (docStoreSegment != null) { + assert docStoreSegment != null; + fieldsWriter = new FieldsWriter(docWriter.directory, + docStoreSegment, + fieldInfos); + docWriter.addOpenFile(docStoreSegment + "." + IndexFileNames.FIELDS_EXTENSION); + docWriter.addOpenFile(docStoreSegment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); + lastDocID = 0; + } + } + } + + synchronized public void closeDocStore(DocumentsWriter.FlushState state) throws IOException { + final int inc = state.numDocsInStore - lastDocID; + if (inc > 0) { + initFieldsWriter(); + fill(state.numDocsInStore - docWriter.getDocStoreOffset()); + } + + if (fieldsWriter != null) { + fieldsWriter.close(); + fieldsWriter = null; + lastDocID = 0; + assert state.docStoreSegmentName != null; + state.flushedFiles.add(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_EXTENSION); + state.flushedFiles.add(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); + + state.docWriter.removeOpenFile(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_EXTENSION); + state.docWriter.removeOpenFile(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); + + if (4+state.numDocsInStore*8 != state.directory.fileLength(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION)) + throw new RuntimeException("after flush: fdx size mismatch: " + state.numDocsInStore + " docs vs " + state.directory.fileLength(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION) + " length in bytes of " + state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); + } + } + + int allocCount; + + synchronized PerDoc getPerDoc() { + if (freeCount == 0) { + allocCount++; + if (allocCount > docFreeList.length) { + // Grow our free list up front to make sure we have + // enough space to recycle all outstanding PerDoc + // instances + assert allocCount == 1+docFreeList.length; + docFreeList = new PerDoc[ArrayUtil.getNextSize(allocCount)]; + } + return new PerDoc(); + } else + return docFreeList[--freeCount]; + } + + synchronized void abort() { + if (fieldsWriter != null) { + try { + fieldsWriter.close(); + } catch (Throwable t) { + } + fieldsWriter = null; + lastDocID = 0; + } + } + + /** Fills in any hole in the docIDs */ + void fill(int docID) throws IOException { + final int docStoreOffset = docWriter.getDocStoreOffset(); + + // We must "catch up" for all docs before us + // that had no stored fields: + final int end = docID+docStoreOffset; + while(lastDocID < end) { + fieldsWriter.skipDocument(); + lastDocID++; + } + } + + synchronized void finishDocument(PerDoc perDoc) throws IOException { + assert docWriter.writer.testPoint("StoredFieldsWriter.finishDocument start"); + initFieldsWriter(); + + fill(perDoc.docID); + + // Append stored fields to the real FieldsWriter: + fieldsWriter.flushDocument(perDoc.numStoredFields, perDoc.fdt); + lastDocID++; + perDoc.reset(); + free(perDoc); + assert docWriter.writer.testPoint("StoredFieldsWriter.finishDocument end"); + } + + public boolean freeRAM() { + return false; + } + + synchronized void free(PerDoc perDoc) { + assert freeCount < docFreeList.length; + assert 0 == perDoc.numStoredFields; + assert 0 == perDoc.fdt.length(); + assert 0 == perDoc.fdt.getFilePointer(); + docFreeList[freeCount++] = perDoc; + } + + class PerDoc extends DocumentsWriter.DocWriter { + + // TODO: use something more memory efficient; for small + // docs the 1024 buffer size of RAMOutputStream wastes alot + RAMOutputStream fdt = new RAMOutputStream(); + int numStoredFields; + + void reset() { + fdt.reset(); + numStoredFields = 0; + } + + void abort() { + reset(); + free(this); + } + + public long sizeInBytes() { + return fdt.sizeInBytes(); + } + + public void finish() throws IOException { + finishDocument(this); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/StoredFieldsWriterPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/StoredFieldsWriterPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/StoredFieldsWriterPerField.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,66 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.document.Fieldable; + +final class StoredFieldsWriterPerField extends DocFieldConsumerPerField { + + final StoredFieldsWriterPerThread perThread; + final FieldInfo fieldInfo; + final DocumentsWriter.DocState docState; + + public StoredFieldsWriterPerField(StoredFieldsWriterPerThread perThread, FieldInfo fieldInfo) { + this.perThread = perThread; + this.fieldInfo = fieldInfo; + docState = perThread.docState; + } + + // Process all occurrences of a single field in one doc; + // count is 1 if a given field occurs only once in the + // Document, which is the "typical" case + public void processFields(Fieldable[] fields, int count) throws IOException { + + final StoredFieldsWriter.PerDoc doc; + if (perThread.doc == null) { + doc = perThread.doc = perThread.storedFieldsWriter.getPerDoc(); + doc.docID = docState.docID; + perThread.localFieldsWriter.setFieldsStream(doc.fdt); + assert doc.numStoredFields == 0: "doc.numStoredFields=" + doc.numStoredFields; + assert 0 == doc.fdt.length(); + assert 0 == doc.fdt.getFilePointer(); + } else { + doc = perThread.doc; + assert doc.docID == docState.docID: "doc.docID=" + doc.docID + " docState.docID=" + docState.docID; + } + + for(int i=0;iNote that a null field or null text value results in undefined + * behavior for most Lucene APIs that accept a Term parameter. */ + public Term(String fld, String txt) { + this(fld, txt, true); + } + + /** Constructs a Term with the given field and empty text. + * This serves two purposes: 1) reuse of a Term with the same field. + * 2) pattern for a query. + * + * @param fld + */ + public Term(String fld) { + this(fld, "", true); + } + + Term(String fld, String txt, boolean intern) { + field = intern ? fld.intern() : fld; // field names are interned + text = txt; // unless already known to be + } + + /** Returns the field of this term, an interned string. The field indicates + the part of a document which this term came from. */ + public final String field() { return field; } + + /** Returns the text of this term. In the case of words, this is simply the + text of the word. In the case of dates and other types, this is an + encoding of the object as a string. */ + public final String text() { return text; } + + /** + * Optimized construction of new Terms by reusing same field as this Term + * - avoids field.intern() overhead + * @param text The text of the new term (field is implicitly same as this Term instance) + * @return A new Term + */ + public Term createTerm(String text) + { + return new Term(field,text,false); + } + + /** Compares two terms, returning true iff they have the same + field and text. */ + public final boolean equals(Object o) { + if (o == this) + return true; + if (o == null) + return false; + if (!(o instanceof Term)) + return false; + Term other = (Term)o; + return field == other.field && text.equals(other.text); + } + + /** Combines the hashCode() of the field and the text. */ + public final int hashCode() { + return field.hashCode() + text.hashCode(); + } + + public int compareTo(Object other) { + return compareTo((Term)other); + } + + /** Compares two terms, returning a negative integer if this + term belongs before the argument, zero if this term is equal to the + argument, and a positive integer if this term belongs after the argument. + + The ordering of terms is first by field, then by text.*/ + public final int compareTo(Term other) { + if (field == other.field) // fields are interned + return text.compareTo(other.text); + else + return field.compareTo(other.field); + } + + /** Resets the field and text of a Term. */ + final void set(String fld, String txt) { + field = fld; + text = txt; + } + + public final String toString() { return field + ":" + text; } + + private void readObject(java.io.ObjectInputStream in) + throws java.io.IOException, ClassNotFoundException + { + in.defaultReadObject(); + field = field.intern(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermBuffer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermBuffer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermBuffer.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,139 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.util.UnicodeUtil; + +final class TermBuffer implements Cloneable { + + private String field; + private Term term; // cached + private boolean preUTF8Strings; // true if strings are stored in modified UTF8 encoding (LUCENE-510) + private boolean dirty; // true if text was set externally (ie not read via UTF8 bytes) + + private UnicodeUtil.UTF16Result text = new UnicodeUtil.UTF16Result(); + private UnicodeUtil.UTF8Result bytes = new UnicodeUtil.UTF8Result(); + + public final int compareTo(TermBuffer other) { + if (field == other.field) // fields are interned + return compareChars(text.result, text.length, other.text.result, other.text.length); + else + return field.compareTo(other.field); + } + + private static final int compareChars(char[] chars1, int len1, + char[] chars2, int len2) { + final int end = len1 < len2 ? len1:len2; + for (int k = 0; k < end; k++) { + char c1 = chars1[k]; + char c2 = chars2[k]; + if (c1 != c2) { + return c1 - c2; + } + } + return len1 - len2; + } + + /** Call this if the IndexInput passed to {@link #read} + * stores terms in the "modified UTF8" (pre LUCENE-510) + * format. */ + void setPreUTF8Strings() { + preUTF8Strings = true; + } + + public final void read(IndexInput input, FieldInfos fieldInfos) + throws IOException { + this.term = null; // invalidate cache + int start = input.readVInt(); + int length = input.readVInt(); + int totalLength = start + length; + if (preUTF8Strings) { + text.setLength(totalLength); + input.readChars(text.result, start, length); + } else { + + if (dirty) { + // Fully convert all bytes since bytes is dirty + UnicodeUtil.UTF16toUTF8(text.result, 0, text.length, bytes); + bytes.setLength(totalLength); + input.readBytes(bytes.result, start, length); + UnicodeUtil.UTF8toUTF16(bytes.result, 0, totalLength, text); + dirty = false; + } else { + // Incrementally convert only the UTF8 bytes that are new: + bytes.setLength(totalLength); + input.readBytes(bytes.result, start, length); + UnicodeUtil.UTF8toUTF16(bytes.result, start, length, text); + } + } + this.field = fieldInfos.fieldName(input.readVInt()); + } + + public final void set(Term term) { + if (term == null) { + reset(); + return; + } + final String termText = term.text(); + final int termLen = termText.length(); + text.setLength(termLen); + termText.getChars(0, termLen, text.result, 0); + dirty = true; + field = term.field(); + this.term = term; + } + + public final void set(TermBuffer other) { + text.copyText(other.text); + dirty = true; + field = other.field; + term = other.term; + } + + public void reset() { + field = null; + text.setLength(0); + term = null; + dirty = true; + } + + public Term toTerm() { + if (field == null) // unset + return null; + + if (term == null) + term = new Term(field, new String(text.result, 0, text.length), false); + + return term; + } + + protected Object clone() { + TermBuffer clone = null; + try { + clone = (TermBuffer)super.clone(); + } catch (CloneNotSupportedException e) {} + + clone.dirty = true; + clone.bytes = new UnicodeUtil.UTF8Result(); + clone.text = new UnicodeUtil.UTF16Result(); + clone.text.copyText(text); + return clone; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermDocs.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermDocs.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermDocs.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,82 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** TermDocs provides an interface for enumerating <document, frequency> + pairs for a term.

The document portion names each document containing + the term. Documents are indicated by number. The frequency portion gives + the number of times the term occurred in each document.

The pairs are + ordered by document number. + + @see IndexReader#termDocs() + */ + +public interface TermDocs { + /** Sets this to the data for a term. + * The enumeration is reset to the start of the data for this term. + */ + void seek(Term term) throws IOException; + + /** Sets this to the data for the current term in a {@link TermEnum}. + * This may be optimized in some implementations. + */ + void seek(TermEnum termEnum) throws IOException; + + /** Returns the current document number.

This is invalid until {@link + #next()} is called for the first time.*/ + int doc(); + + /** Returns the frequency of the term within the current document.

This + is invalid until {@link #next()} is called for the first time.*/ + int freq(); + + /** Moves to the next pair in the enumeration.

Returns true iff there is + such a next pair in the enumeration. */ + boolean next() throws IOException; + + /** Attempts to read multiple entries from the enumeration, up to length of + * docs. Document numbers are stored in docs, and term + * frequencies are stored in freqs. The freqs array must be as + * long as the docs array. + * + *

Returns the number of entries read. Zero is only returned when the + * stream has been exhausted. */ + int read(int[] docs, int[] freqs) throws IOException; + + /** Skips entries to the first beyond the current whose document number is + * greater than or equal to target.

Returns true iff there is such + * an entry.

Behaves as if written:

+   *   boolean skipTo(int target) {
+   *     do {
+   *       if (!next())
+   * 	     return false;
+   *     } while (target > doc());
+   *     return true;
+   *   }
+   * 
+ * Some implementations are considerably more efficient than that. + */ + boolean skipTo(int target) throws IOException; + + /** Frees associated resources. */ + void close() throws IOException; +} + + Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermEnum.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermEnum.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermEnum.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,62 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** Abstract class for enumerating terms. + +

Term enumerations are always ordered by Term.compareTo(). Each term in + the enumeration is greater than all that precede it. */ + +public abstract class TermEnum { + /** Increments the enumeration to the next element. True if one exists.*/ + public abstract boolean next() throws IOException; + + /** Returns the current Term in the enumeration.*/ + public abstract Term term(); + + /** Returns the docFreq of the current Term in the enumeration.*/ + public abstract int docFreq(); + + /** Closes the enumeration to further activity, freeing resources. */ + public abstract void close() throws IOException; + +// Term Vector support + + /** Skips terms to the first beyond the current whose value is + * greater or equal to target.

Returns true iff there is such + * an entry.

Behaves as if written:

+   *   public boolean skipTo(Term target) {
+   *     do {
+   *       if (!next())
+   * 	     return false;
+   *     } while (target > term());
+   *     return true;
+   *   }
+   * 
+ * Some implementations are considerably more efficient than that. + */ + public boolean skipTo(Term target) throws IOException { + do { + if (!next()) + return false; + } while (target.compareTo(term()) > 0); + return true; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermFreqVector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermFreqVector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermFreqVector.java 17 Aug 2012 14:55:03 -0000 1.1 @@ -0,0 +1,71 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Provides access to stored term vector of + * a document field. The vector consists of the name of the field, an array of the terms tha occur in the field of the + * {@link org.apache.lucene.document.Document} and a parallel array of frequencies. Thus, getTermFrequencies()[5] corresponds with the + * frequency of getTerms()[5], assuming there are at least 5 terms in the Document. + */ +public interface TermFreqVector { + /** + * The {@link org.apache.lucene.document.Fieldable} name. + * @return The name of the field this vector is associated with. + * + */ + public String getField(); + + /** + * @return The number of terms in the term vector. + */ + public int size(); + + /** + * @return An Array of term texts in ascending order. + */ + public String[] getTerms(); + + + /** Array of term frequencies. Locations of the array correspond one to one + * to the terms in the array obtained from getTerms + * method. Each location in the array contains the number of times this + * term occurs in the document or the document field. + */ + public int[] getTermFrequencies(); + + + /** Return an index in the term numbers array returned from + * getTerms at which the term with the specified + * term appears. If this term does not appear in the array, + * return -1. + */ + public int indexOf(String term); + + + /** Just like indexOf(int) but searches for a number of terms + * at the same time. Returns an array that has the same size as the number + * of terms searched for, each slot containing the result of searching for + * that term number. + * + * @param terms array containing terms to look for + * @param start index in the array where the list of terms starts + * @param len the number of terms in the list + */ + public int[] indexesOf(String[] terms, int start, int len); + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermInfo.java 17 Aug 2012 14:55:00 -0000 1.1 @@ -0,0 +1,59 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** A TermInfo is the record of information stored for a term.*/ + +final class TermInfo { + /** The number of documents which contain the term. */ + int docFreq = 0; + + long freqPointer = 0; + long proxPointer = 0; + int skipOffset; + + TermInfo() {} + + TermInfo(int df, long fp, long pp) { + docFreq = df; + freqPointer = fp; + proxPointer = pp; + } + + TermInfo(TermInfo ti) { + docFreq = ti.docFreq; + freqPointer = ti.freqPointer; + proxPointer = ti.proxPointer; + skipOffset = ti.skipOffset; + } + + final void set(int docFreq, + long freqPointer, long proxPointer, int skipOffset) { + this.docFreq = docFreq; + this.freqPointer = freqPointer; + this.proxPointer = proxPointer; + this.skipOffset = skipOffset; + } + + final void set(TermInfo ti) { + docFreq = ti.docFreq; + freqPointer = ti.freqPointer; + proxPointer = ti.proxPointer; + skipOffset = ti.skipOffset; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermInfosReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermInfosReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermInfosReader.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,335 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.BufferedIndexInput; +import org.apache.lucene.util.cache.Cache; +import org.apache.lucene.util.cache.SimpleLRUCache; +import org.apache.lucene.util.CloseableThreadLocal; + +/** This stores a monotonically increasing set of pairs in a + * Directory. Pairs are accessed either by Term or by ordinal position the + * set. */ + +final class TermInfosReader { + private Directory directory; + private String segment; + private FieldInfos fieldInfos; + + private CloseableThreadLocal threadResources = new CloseableThreadLocal(); + private SegmentTermEnum origEnum; + private long size; + + private Term[] indexTerms = null; + private TermInfo[] indexInfos; + private long[] indexPointers; + + private SegmentTermEnum indexEnum; + + private int indexDivisor = 1; + private int totalIndexInterval; + + private final static int DEFAULT_CACHE_SIZE = 1024; + + /** + * Per-thread resources managed by ThreadLocal + */ + private static final class ThreadResources { + SegmentTermEnum termEnum; + + // Used for caching the least recently looked-up Terms + Cache termInfoCache; + } + + TermInfosReader(Directory dir, String seg, FieldInfos fis) + throws CorruptIndexException, IOException { + this(dir, seg, fis, BufferedIndexInput.BUFFER_SIZE); + } + + TermInfosReader(Directory dir, String seg, FieldInfos fis, int readBufferSize) + throws CorruptIndexException, IOException { + boolean success = false; + + try { + directory = dir; + segment = seg; + fieldInfos = fis; + + origEnum = new SegmentTermEnum(directory.openInput(segment + "." + IndexFileNames.TERMS_EXTENSION, + readBufferSize), fieldInfos, false); + size = origEnum.size; + totalIndexInterval = origEnum.indexInterval; + + indexEnum = new SegmentTermEnum(directory.openInput(segment + "." + IndexFileNames.TERMS_INDEX_EXTENSION, + readBufferSize), fieldInfos, true); + + success = true; + } finally { + // With lock-less commits, it's entirely possible (and + // fine) to hit a FileNotFound exception above. In + // this case, we want to explicitly close any subset + // of things that were opened so that we don't have to + // wait for a GC to do so. + if (!success) { + close(); + } + } + } + + public int getSkipInterval() { + return origEnum.skipInterval; + } + + public int getMaxSkipLevels() { + return origEnum.maxSkipLevels; + } + + /** + *

Sets the indexDivisor, which subsamples the number + * of indexed terms loaded into memory. This has a + * similar effect as {@link + * IndexWriter#setTermIndexInterval} except that setting + * must be done at indexing time while this setting can be + * set per reader. When set to N, then one in every + * N*termIndexInterval terms in the index is loaded into + * memory. By setting this to a value > 1 you can reduce + * memory usage, at the expense of higher latency when + * loading a TermInfo. The default value is 1.

+ * + * NOTE: you must call this before the term + * index is loaded. If the index is already loaded, + * an IllegalStateException is thrown. + * + + @throws IllegalStateException if the term index has + * already been loaded into memory. + */ + public void setIndexDivisor(int indexDivisor) throws IllegalStateException { + if (indexDivisor < 1) + throw new IllegalArgumentException("indexDivisor must be > 0: got " + indexDivisor); + + if (indexTerms != null) + throw new IllegalStateException("index terms are already loaded"); + + this.indexDivisor = indexDivisor; + totalIndexInterval = origEnum.indexInterval * indexDivisor; + } + + /** Returns the indexDivisor. + * @see #setIndexDivisor + */ + public int getIndexDivisor() { + return indexDivisor; + } + + final void close() throws IOException { + if (origEnum != null) + origEnum.close(); + if (indexEnum != null) + indexEnum.close(); + threadResources.close(); + } + + /** Returns the number of term/value pairs in the set. */ + final long size() { + return size; + } + + private ThreadResources getThreadResources() { + ThreadResources resources = (ThreadResources)threadResources.get(); + if (resources == null) { + resources = new ThreadResources(); + resources.termEnum = terms(); + // Cache does not have to be thread-safe, it is only used by one thread at the same time + resources.termInfoCache = new SimpleLRUCache(DEFAULT_CACHE_SIZE); + threadResources.set(resources); + } + return resources; + } + + private synchronized void ensureIndexIsRead() throws IOException { + if (indexTerms != null) // index already read + return; // do nothing + try { + int indexSize = 1+((int)indexEnum.size-1)/indexDivisor; // otherwise read index + + indexTerms = new Term[indexSize]; + indexInfos = new TermInfo[indexSize]; + indexPointers = new long[indexSize]; + + for (int i = 0; indexEnum.next(); i++) { + indexTerms[i] = indexEnum.term(); + indexInfos[i] = indexEnum.termInfo(); + indexPointers[i] = indexEnum.indexPointer; + + for (int j = 1; j < indexDivisor; j++) + if (!indexEnum.next()) + break; + } + } finally { + indexEnum.close(); + indexEnum = null; + } + } + + /** Returns the offset of the greatest index entry which is less than or equal to term.*/ + private final int getIndexOffset(Term term) { + int lo = 0; // binary search indexTerms[] + int hi = indexTerms.length - 1; + + while (hi >= lo) { + int mid = (lo + hi) >> 1; + int delta = term.compareTo(indexTerms[mid]); + if (delta < 0) + hi = mid - 1; + else if (delta > 0) + lo = mid + 1; + else + return mid; + } + return hi; + } + + private final void seekEnum(SegmentTermEnum enumerator, int indexOffset) throws IOException { + enumerator.seek(indexPointers[indexOffset], + (indexOffset * totalIndexInterval) - 1, + indexTerms[indexOffset], indexInfos[indexOffset]); + } + + /** Returns the TermInfo for a Term in the set, or null. */ + TermInfo get(Term term) throws IOException { + return get(term, true); + } + + /** Returns the TermInfo for a Term in the set, or null. */ + private TermInfo get(Term term, boolean useCache) throws IOException { + if (size == 0) return null; + + ensureIndexIsRead(); + + TermInfo ti; + ThreadResources resources = getThreadResources(); + Cache cache = null; + + if (useCache) { + cache = resources.termInfoCache; + // check the cache first if the term was recently looked up + ti = (TermInfo) cache.get(term); + if (ti != null) { + return ti; + } + } + + // optimize sequential access: first try scanning cached enum w/o seeking + SegmentTermEnum enumerator = resources.termEnum; + if (enumerator.term() != null // term is at or past current + && ((enumerator.prev() != null && term.compareTo(enumerator.prev())> 0) + || term.compareTo(enumerator.term()) >= 0)) { + int enumOffset = (int)(enumerator.position/totalIndexInterval)+1; + if (indexTerms.length == enumOffset // but before end of block + || term.compareTo(indexTerms[enumOffset]) < 0) { + // no need to seek + + int numScans = enumerator.scanTo(term); + if (enumerator.term() != null && term.compareTo(enumerator.term()) == 0) { + ti = enumerator.termInfo(); + if (cache != null && numScans > 1) { + // we only want to put this TermInfo into the cache if + // scanEnum skipped more than one dictionary entry. + // This prevents RangeQueries or WildcardQueries to + // wipe out the cache when they iterate over a large numbers + // of terms in order + cache.put(term, ti); + } + } else { + ti = null; + } + + return ti; + } + } + + // random-access: must seek + seekEnum(enumerator, getIndexOffset(term)); + enumerator.scanTo(term); + if (enumerator.term() != null && term.compareTo(enumerator.term()) == 0) { + ti = enumerator.termInfo(); + if (cache != null) { + cache.put(term, ti); + } + } else { + ti = null; + } + return ti; + } + + /** Returns the nth term in the set. */ + final Term get(int position) throws IOException { + if (size == 0) return null; + + SegmentTermEnum enumerator = getThreadResources().termEnum; + if (enumerator != null && enumerator.term() != null && + position >= enumerator.position && + position < (enumerator.position + totalIndexInterval)) + return scanEnum(enumerator, position); // can avoid seek + + seekEnum(enumerator, position/totalIndexInterval); // must seek + return scanEnum(enumerator, position); + } + + private final Term scanEnum(SegmentTermEnum enumerator, int position) throws IOException { + while(enumerator.position < position) + if (!enumerator.next()) + return null; + + return enumerator.term(); + } + + /** Returns the position of a Term in the set or -1. */ + final long getPosition(Term term) throws IOException { + if (size == 0) return -1; + + ensureIndexIsRead(); + int indexOffset = getIndexOffset(term); + + SegmentTermEnum enumerator = getThreadResources().termEnum; + seekEnum(enumerator, indexOffset); + + while(term.compareTo(enumerator.term()) > 0 && enumerator.next()) {} + + if (term.compareTo(enumerator.term()) == 0) + return enumerator.position; + else + return -1; + } + + /** Returns an enumeration of all the Terms and TermInfos in the set. */ + public SegmentTermEnum terms() { + return (SegmentTermEnum)origEnum.clone(); + } + + /** Returns an enumeration of terms starting at or after the named term. */ + public SegmentTermEnum terms(Term term) throws IOException { + // don't use the cache in this call because we want to reposition the + // enumeration + get(term, false); + return (SegmentTermEnum)getThreadResources().termEnum.clone(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermInfosWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermInfosWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermInfosWriter.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,228 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import java.io.IOException; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.Directory; +import org.apache.lucene.util.UnicodeUtil; + +/** This stores a monotonically increasing set of pairs in a + Directory. A TermInfos can be written once, in order. */ + +final class TermInfosWriter { + /** The file format version, a negative number. */ + public static final int FORMAT = -3; + + // Changed strings to true utf8 with length-in-bytes not + // length-in-chars + public static final int FORMAT_VERSION_UTF8_LENGTH_IN_BYTES = -4; + + // NOTE: always change this if you switch to a new format! + public static final int FORMAT_CURRENT = FORMAT_VERSION_UTF8_LENGTH_IN_BYTES; + + private FieldInfos fieldInfos; + private IndexOutput output; + private TermInfo lastTi = new TermInfo(); + private long size; + + // TODO: the default values for these two parameters should be settable from + // IndexWriter. However, once that's done, folks will start setting them to + // ridiculous values and complaining that things don't work well, as with + // mergeFactor. So, let's wait until a number of folks find that alternate + // values work better. Note that both of these values are stored in the + // segment, so that it's safe to change these w/o rebuilding all indexes. + + /** Expert: The fraction of terms in the "dictionary" which should be stored + * in RAM. Smaller values use more memory, but make searching slightly + * faster, while larger values use less memory and make searching slightly + * slower. Searching is typically not dominated by dictionary lookup, so + * tweaking this is rarely useful.*/ + int indexInterval = 128; + + /** Expert: The fraction of {@link TermDocs} entries stored in skip tables, + * used to accellerate {@link TermDocs#skipTo(int)}. Larger values result in + * smaller indexes, greater acceleration, but fewer accelerable cases, while + * smaller values result in bigger indexes, less acceleration and more + * accelerable cases. More detailed experiments would be useful here. */ + int skipInterval = 16; + + /** Expert: The maximum number of skip levels. Smaller values result in + * slightly smaller indexes, but slower skipping in big posting lists. + */ + int maxSkipLevels = 10; + + private long lastIndexPointer; + private boolean isIndex; + private byte[] lastTermBytes = new byte[10]; + private int lastTermBytesLength = 0; + private int lastFieldNumber = -1; + + private TermInfosWriter other; + private UnicodeUtil.UTF8Result utf8Result = new UnicodeUtil.UTF8Result(); + + TermInfosWriter(Directory directory, String segment, FieldInfos fis, + int interval) + throws IOException { + initialize(directory, segment, fis, interval, false); + other = new TermInfosWriter(directory, segment, fis, interval, true); + other.other = this; + } + + private TermInfosWriter(Directory directory, String segment, FieldInfos fis, + int interval, boolean isIndex) throws IOException { + initialize(directory, segment, fis, interval, isIndex); + } + + private void initialize(Directory directory, String segment, FieldInfos fis, + int interval, boolean isi) throws IOException { + indexInterval = interval; + fieldInfos = fis; + isIndex = isi; + output = directory.createOutput(segment + (isIndex ? ".tii" : ".tis")); + output.writeInt(FORMAT_CURRENT); // write format + output.writeLong(0); // leave space for size + output.writeInt(indexInterval); // write indexInterval + output.writeInt(skipInterval); // write skipInterval + output.writeInt(maxSkipLevels); // write maxSkipLevels + assert initUTF16Results(); + } + + void add(Term term, TermInfo ti) throws IOException { + UnicodeUtil.UTF16toUTF8(term.text, 0, term.text.length(), utf8Result); + add(fieldInfos.fieldNumber(term.field), utf8Result.result, utf8Result.length, ti); + } + + // Currently used only by assert statements + UnicodeUtil.UTF16Result utf16Result1; + UnicodeUtil.UTF16Result utf16Result2; + + // Currently used only by assert statements + private boolean initUTF16Results() { + utf16Result1 = new UnicodeUtil.UTF16Result(); + utf16Result2 = new UnicodeUtil.UTF16Result(); + return true; + } + + // Currently used only by assert statement + private int compareToLastTerm(int fieldNumber, byte[] termBytes, int termBytesLength) { + + if (lastFieldNumber != fieldNumber) { + final int cmp = fieldInfos.fieldName(lastFieldNumber).compareTo(fieldInfos.fieldName(fieldNumber)); + // If there is a field named "" (empty string) then we + // will get 0 on this comparison, yet, it's "OK". But + // it's not OK if two different field numbers map to + // the same name. + if (cmp != 0 || lastFieldNumber != -1) + return cmp; + } + + UnicodeUtil.UTF8toUTF16(lastTermBytes, 0, lastTermBytesLength, utf16Result1); + UnicodeUtil.UTF8toUTF16(termBytes, 0, termBytesLength, utf16Result2); + final int len; + if (utf16Result1.length < utf16Result2.length) + len = utf16Result1.length; + else + len = utf16Result2.length; + + for(int i=0;i, TermInfo> pair to the set. + Term must be lexicographically greater than all previous Terms added. + TermInfo pointers must be positive and greater than all previous.*/ + void add(int fieldNumber, byte[] termBytes, int termBytesLength, TermInfo ti) + throws IOException { + + assert compareToLastTerm(fieldNumber, termBytes, termBytesLength) < 0 || + (isIndex && termBytesLength == 0 && lastTermBytesLength == 0) : + "Terms are out of order: field=" + fieldInfos.fieldName(fieldNumber) + " (number " + fieldNumber + ")" + + " lastField=" + fieldInfos.fieldName(lastFieldNumber) + " (number " + lastFieldNumber + ")" + + " text=" + new String(termBytes, 0, termBytesLength, "UTF-8") + " lastText=" + new String(lastTermBytes, 0, lastTermBytesLength, "UTF-8"); + + assert ti.freqPointer >= lastTi.freqPointer: "freqPointer out of order (" + ti.freqPointer + " < " + lastTi.freqPointer + ")"; + assert ti.proxPointer >= lastTi.proxPointer: "proxPointer out of order (" + ti.proxPointer + " < " + lastTi.proxPointer + ")"; + + if (!isIndex && size % indexInterval == 0) + other.add(lastFieldNumber, lastTermBytes, lastTermBytesLength, lastTi); // add an index term + + writeTerm(fieldNumber, termBytes, termBytesLength); // write term + + output.writeVInt(ti.docFreq); // write doc freq + output.writeVLong(ti.freqPointer - lastTi.freqPointer); // write pointers + output.writeVLong(ti.proxPointer - lastTi.proxPointer); + + if (ti.docFreq >= skipInterval) { + output.writeVInt(ti.skipOffset); + } + + if (isIndex) { + output.writeVLong(other.output.getFilePointer() - lastIndexPointer); + lastIndexPointer = other.output.getFilePointer(); // write pointer + } + + lastFieldNumber = fieldNumber; + lastTi.set(ti); + size++; + } + + private void writeTerm(int fieldNumber, byte[] termBytes, int termBytesLength) + throws IOException { + + // TODO: UTF16toUTF8 could tell us this prefix + // Compute prefix in common with last term: + int start = 0; + final int limit = termBytesLength < lastTermBytesLength ? termBytesLength : lastTermBytesLength; + while(start < limit) { + if (termBytes[start] != lastTermBytes[start]) + break; + start++; + } + + final int length = termBytesLength - start; + output.writeVInt(start); // write shared prefix length + output.writeVInt(length); // write delta length + output.writeBytes(termBytes, start, length); // write delta bytes + output.writeVInt(fieldNumber); // write field num + if (lastTermBytes.length < termBytesLength) { + byte[] newArray = new byte[(int) (termBytesLength*1.5)]; + System.arraycopy(lastTermBytes, 0, newArray, 0, start); + lastTermBytes = newArray; + } + System.arraycopy(termBytes, start, lastTermBytes, start, length); + lastTermBytesLength = termBytesLength; + } + + /** Called to complete TermInfos creation. */ + void close() throws IOException { + output.seek(4); // write size after format + output.writeLong(size); + output.close(); + + if (!isIndex) + other.close(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermPositionVector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermPositionVector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermPositionVector.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,43 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Extends TermFreqVector to provide additional information about + * positions in which each of the terms is found. A TermPositionVector not necessarily + * contains both positions and offsets, but at least one of these arrays exists. + */ +public interface TermPositionVector extends TermFreqVector { + + /** Returns an array of positions in which the term is found. + * Terms are identified by the index at which its number appears in the + * term String array obtained from the indexOf method. + * May return null if positions have not been stored. + */ + public int[] getTermPositions(int index); + + /** + * Returns an array of TermVectorOffsetInfo in which the term is found. + * May return null if offsets have not been stored. + * + * @see org.apache.lucene.analysis.Token + * + * @param index The position in the array to get the offsets from + * @return An array of TermVectorOffsetInfo objects or the empty list + */ + public TermVectorOffsetInfo [] getOffsets(int index); +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermPositions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermPositions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermPositions.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,79 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + * TermPositions provides an interface for enumerating the <document, + * frequency, <position>* > tuples for a term.

The document and + * frequency are the same as for a TermDocs. The positions portion lists the ordinal + * positions of each occurrence of a term in a document. + * + * @see IndexReader#termPositions() + */ + +public interface TermPositions + extends TermDocs +{ + /** Returns next position in the current document. It is an error to call + this more than {@link #freq()} times + without calling {@link #next()}

This is + invalid until {@link #next()} is called for + the first time. + */ + int nextPosition() throws IOException; + + /** + * Returns the length of the payload at the current term position. + * This is invalid until {@link #nextPosition()} is called for + * the first time.
+ * @return length of the current payload in number of bytes + */ + int getPayloadLength(); + + /** + * Returns the payload data at the current term position. + * This is invalid until {@link #nextPosition()} is called for + * the first time. + * This method must not be called more than once after each call + * of {@link #nextPosition()}. However, payloads are loaded lazily, + * so if the payload data for the current position is not needed, + * this method may not be called at all for performance reasons.
+ * + * @param data the array into which the data of this payload is to be + * stored, if it is big enough; otherwise, a new byte[] array + * is allocated for this purpose. + * @param offset the offset in the array into which the data of this payload + * is to be stored. + * @return a byte[] array containing the data of this payload + * @throws IOException + */ + byte[] getPayload(byte[] data, int offset) throws IOException; + + /** + * Checks if a payload can be loaded at this position. + *

+ * Payloads can only be loaded once per call to + * {@link #nextPosition()}. + * + * @return true if there is a payload available at this position that can be loaded + */ + public boolean isPayloadAvailable(); + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorEntry.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,98 @@ +package org.apache.lucene.index; + +/** + * Copyright 2007 The Apache Software Foundation + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Convenience class for holding TermVector information. + */ +public class TermVectorEntry { + private String field; + private String term; + private int frequency; + private TermVectorOffsetInfo [] offsets; + int [] positions; + + + public TermVectorEntry() { + } + + public TermVectorEntry(String field, String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions) { + this.field = field; + this.term = term; + this.frequency = frequency; + this.offsets = offsets; + this.positions = positions; + } + + + public String getField() { + return field; + } + + public int getFrequency() { + return frequency; + } + + public TermVectorOffsetInfo[] getOffsets() { + return offsets; + } + + public int[] getPositions() { + return positions; + } + + public String getTerm() { + return term; + } + + //Keep package local + void setFrequency(int frequency) { + this.frequency = frequency; + } + + void setOffsets(TermVectorOffsetInfo[] offsets) { + this.offsets = offsets; + } + + void setPositions(int[] positions) { + this.positions = positions; + } + + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + TermVectorEntry that = (TermVectorEntry) o; + + if (term != null ? !term.equals(that.term) : that.term != null) return false; + + return true; + } + + public int hashCode() { + return (term != null ? term.hashCode() : 0); + } + + public String toString() { + return "TermVectorEntry{" + + "field='" + field + '\'' + + ", term='" + term + '\'' + + ", frequency=" + frequency + + '}'; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorEntryFreqSortedComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorEntryFreqSortedComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorEntryFreqSortedComparator.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,42 @@ +package org.apache.lucene.index; +/** + * Copyright 2007 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import java.util.Comparator; + +/** + * Compares {@link org.apache.lucene.index.TermVectorEntry}s first by frequency and then by + * the term (case-sensitive) + * + **/ +public class TermVectorEntryFreqSortedComparator implements Comparator { + public int compare(Object object, Object object1) { + int result = 0; + TermVectorEntry entry = (TermVectorEntry) object; + TermVectorEntry entry1 = (TermVectorEntry) object1; + result = entry1.getFrequency() - entry.getFrequency(); + if (result == 0) + { + result = entry.getTerm().compareTo(entry1.getTerm()); + if (result == 0) + { + result = entry.getField().compareTo(entry1.getField()); + } + } + return result; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorMapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorMapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorMapper.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,101 @@ +package org.apache.lucene.index; +/** + * Copyright 2007 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * The TermVectorMapper can be used to map Term Vectors into your own + * structure instead of the parallel array structure used by + * {@link org.apache.lucene.index.IndexReader#getTermFreqVector(int,String)}. + *

+ * It is up to the implementation to make sure it is thread-safe. + * + * + **/ +public abstract class TermVectorMapper { + + private boolean ignoringPositions; + private boolean ignoringOffsets; + + + protected TermVectorMapper() { + } + + /** + * + * @param ignoringPositions true if this mapper should tell Lucene to ignore positions even if they are stored + * @param ignoringOffsets similar to ignoringPositions + */ + protected TermVectorMapper(boolean ignoringPositions, boolean ignoringOffsets) { + this.ignoringPositions = ignoringPositions; + this.ignoringOffsets = ignoringOffsets; + } + + /** + * Tell the mapper what to expect in regards to field, number of terms, offset and position storage. + * This method will be called once before retrieving the vector for a field. + * + * This method will be called before {@link #map(String,int,TermVectorOffsetInfo[],int[])}. + * @param field The field the vector is for + * @param numTerms The number of terms that need to be mapped + * @param storeOffsets true if the mapper should expect offset information + * @param storePositions true if the mapper should expect positions info + */ + public abstract void setExpectations(String field, int numTerms, boolean storeOffsets, boolean storePositions); + /** + * Map the Term Vector information into your own structure + * @param term The term to add to the vector + * @param frequency The frequency of the term in the document + * @param offsets null if the offset is not specified, otherwise the offset into the field of the term + * @param positions null if the position is not specified, otherwise the position in the field of the term + */ + public abstract void map(String term, int frequency, TermVectorOffsetInfo [] offsets, int [] positions); + + /** + * Indicate to Lucene that even if there are positions stored, this mapper is not interested in them and they + * can be skipped over. Derived classes should set this to true if they want to ignore positions. The default + * is false, meaning positions will be loaded if they are stored. + * @return false + */ + public boolean isIgnoringPositions() + { + return ignoringPositions; + } + + /** + * + * @see #isIgnoringPositions() Same principal as {@link #isIgnoringPositions()}, but applied to offsets. false by default. + * @return false + */ + public boolean isIgnoringOffsets() + { + return ignoringOffsets; + } + + /** + * Passes down the index of the document whose term vector is currently being mapped, + * once for each top level call to a term vector reader. + *

+ * Default implementation IGNORES the document number. Override if your implementation needs the document number. + *

+ * NOTE: Document numbers are internal to Lucene and subject to change depending on indexing operations. + * + * @param documentNumber index of document currently being mapped + */ + public void setDocumentNumber(int documentNumber) { + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorOffsetInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorOffsetInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorOffsetInfo.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,89 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The TermVectorOffsetInfo class holds information pertaining to a Term in a {@link org.apache.lucene.index.TermPositionVector}'s + * offset information. This offset information is the character offset as set during the Analysis phase (and thus may not be the actual offset in the + * original content). + */ +public class TermVectorOffsetInfo { + /** + * Convenience declaration when creating a {@link org.apache.lucene.index.TermPositionVector} that stores only position information. + */ + public static final TermVectorOffsetInfo[] EMPTY_OFFSET_INFO = new TermVectorOffsetInfo[0]; + private int startOffset; + private int endOffset; + + public TermVectorOffsetInfo() { + } + + public TermVectorOffsetInfo(int startOffset, int endOffset) { + this.endOffset = endOffset; + this.startOffset = startOffset; + } + + /** + * The accessor for the ending offset for the term + * @return The offset + */ + public int getEndOffset() { + return endOffset; + } + + public void setEndOffset(int endOffset) { + this.endOffset = endOffset; + } + + /** + * The accessor for the starting offset of the term. + * + * @return The offset + */ + public int getStartOffset() { + return startOffset; + } + + public void setStartOffset(int startOffset) { + this.startOffset = startOffset; + } + + /** + * Two TermVectorOffsetInfos are equals if both the start and end offsets are the same + * @param o The comparison Object + * @return true if both {@link #getStartOffset()} and {@link #getEndOffset()} are the same for both objects. + */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof TermVectorOffsetInfo)) return false; + + final TermVectorOffsetInfo termVectorOffsetInfo = (TermVectorOffsetInfo) o; + + if (endOffset != termVectorOffsetInfo.endOffset) return false; + if (startOffset != termVectorOffsetInfo.startOffset) return false; + + return true; + } + + public int hashCode() { + int result; + result = startOffset; + result = 29 * result + endOffset; + return result; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsReader.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,599 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.BufferedIndexInput; +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; + +import java.io.IOException; +import java.util.Arrays; + +/** + * @version $Id: TermVectorsReader.java,v 1.1 2012/08/17 14:54:59 marcin Exp $ + */ +class TermVectorsReader implements Cloneable { + + // NOTE: if you make a new format, it must be larger than + // the current format + static final int FORMAT_VERSION = 2; + + // Changes to speed up bulk merging of term vectors: + static final int FORMAT_VERSION2 = 3; + + // Changed strings to UTF8 with length-in-bytes not length-in-chars + static final int FORMAT_UTF8_LENGTH_IN_BYTES = 4; + + // NOTE: always change this if you switch to a new format! + static final int FORMAT_CURRENT = FORMAT_UTF8_LENGTH_IN_BYTES; + + //The size in bytes that the FORMAT_VERSION will take up at the beginning of each file + static final int FORMAT_SIZE = 4; + + static final byte STORE_POSITIONS_WITH_TERMVECTOR = 0x1; + static final byte STORE_OFFSET_WITH_TERMVECTOR = 0x2; + + private FieldInfos fieldInfos; + + private IndexInput tvx; + private IndexInput tvd; + private IndexInput tvf; + private int size; + private int numTotalDocs; + + // The docID offset where our docs begin in the index + // file. This will be 0 if we have our own private file. + private int docStoreOffset; + + private final int format; + + TermVectorsReader(Directory d, String segment, FieldInfos fieldInfos) + throws CorruptIndexException, IOException { + this(d, segment, fieldInfos, BufferedIndexInput.BUFFER_SIZE); + } + + TermVectorsReader(Directory d, String segment, FieldInfos fieldInfos, int readBufferSize) + throws CorruptIndexException, IOException { + this(d, segment, fieldInfos, readBufferSize, -1, 0); + } + + TermVectorsReader(Directory d, String segment, FieldInfos fieldInfos, int readBufferSize, int docStoreOffset, int size) + throws CorruptIndexException, IOException { + boolean success = false; + + try { + if (d.fileExists(segment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION)) { + tvx = d.openInput(segment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION, readBufferSize); + format = checkValidFormat(tvx); + tvd = d.openInput(segment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION, readBufferSize); + final int tvdFormat = checkValidFormat(tvd); + tvf = d.openInput(segment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION, readBufferSize); + final int tvfFormat = checkValidFormat(tvf); + + assert format == tvdFormat; + assert format == tvfFormat; + + if (format >= FORMAT_VERSION2) { + assert (tvx.length()-FORMAT_SIZE) % 16 == 0; + numTotalDocs = (int) (tvx.length() >> 4); + } else { + assert (tvx.length()-FORMAT_SIZE) % 8 == 0; + numTotalDocs = (int) (tvx.length() >> 3); + } + + if (-1 == docStoreOffset) { + this.docStoreOffset = 0; + this.size = numTotalDocs; + assert size == 0 || numTotalDocs == size; + } else { + this.docStoreOffset = docStoreOffset; + this.size = size; + // Verify the file is long enough to hold all of our + // docs + assert numTotalDocs >= size + docStoreOffset: "numTotalDocs=" + numTotalDocs + " size=" + size + " docStoreOffset=" + docStoreOffset; + } + } else + format = 0; + + this.fieldInfos = fieldInfos; + success = true; + } finally { + // With lock-less commits, it's entirely possible (and + // fine) to hit a FileNotFound exception above. In + // this case, we want to explicitly close any subset + // of things that were opened so that we don't have to + // wait for a GC to do so. + if (!success) { + close(); + } + } + } + + // Used for bulk copy when merging + IndexInput getTvdStream() { + return tvd; + } + + // Used for bulk copy when merging + IndexInput getTvfStream() { + return tvf; + } + + final private void seekTvx(final int docNum) throws IOException { + if (format < FORMAT_VERSION2) + tvx.seek((docNum + docStoreOffset) * 8L + FORMAT_SIZE); + else + tvx.seek((docNum + docStoreOffset) * 16L + FORMAT_SIZE); + } + + boolean canReadRawDocs() { + return format >= FORMAT_UTF8_LENGTH_IN_BYTES; + } + + /** Retrieve the length (in bytes) of the tvd and tvf + * entries for the next numDocs starting with + * startDocID. This is used for bulk copying when + * merging segments, if the field numbers are + * congruent. Once this returns, the tvf & tvd streams + * are seeked to the startDocID. */ + final void rawDocs(int[] tvdLengths, int[] tvfLengths, int startDocID, int numDocs) throws IOException { + + if (tvx == null) { + Arrays.fill(tvdLengths, 0); + Arrays.fill(tvfLengths, 0); + return; + } + + // SegmentMerger calls canReadRawDocs() first and should + // not call us if that returns false. + if (format < FORMAT_VERSION2) + throw new IllegalStateException("cannot read raw docs with older term vector formats"); + + seekTvx(startDocID); + + long tvdPosition = tvx.readLong(); + tvd.seek(tvdPosition); + + long tvfPosition = tvx.readLong(); + tvf.seek(tvfPosition); + + long lastTvdPosition = tvdPosition; + long lastTvfPosition = tvfPosition; + + int count = 0; + while (count < numDocs) { + final int docID = docStoreOffset + startDocID + count + 1; + assert docID <= numTotalDocs; + if (docID < numTotalDocs) { + tvdPosition = tvx.readLong(); + tvfPosition = tvx.readLong(); + } else { + tvdPosition = tvd.length(); + tvfPosition = tvf.length(); + assert count == numDocs-1; + } + tvdLengths[count] = (int) (tvdPosition-lastTvdPosition); + tvfLengths[count] = (int) (tvfPosition-lastTvfPosition); + count++; + lastTvdPosition = tvdPosition; + lastTvfPosition = tvfPosition; + } + } + + private int checkValidFormat(IndexInput in) throws CorruptIndexException, IOException + { + int format = in.readInt(); + if (format > FORMAT_CURRENT) { + throw new CorruptIndexException("Incompatible format version: " + format + " expected " + + FORMAT_CURRENT + " or less"); + } + return format; + } + + void close() throws IOException { + // make all effort to close up. Keep the first exception + // and throw it as a new one. + IOException keep = null; + if (tvx != null) try { tvx.close(); } catch (IOException e) { if (keep == null) keep = e; } + if (tvd != null) try { tvd.close(); } catch (IOException e) { if (keep == null) keep = e; } + if (tvf != null) try { tvf.close(); } catch (IOException e) { if (keep == null) keep = e; } + if (keep != null) throw (IOException) keep.fillInStackTrace(); + } + + /** + * + * @return The number of documents in the reader + */ + int size() { + return size; + } + + public void get(int docNum, String field, TermVectorMapper mapper) throws IOException { + if (tvx != null) { + int fieldNumber = fieldInfos.fieldNumber(field); + //We need to account for the FORMAT_SIZE at when seeking in the tvx + //We don't need to do this in other seeks because we already have the + // file pointer + //that was written in another file + seekTvx(docNum); + //System.out.println("TVX Pointer: " + tvx.getFilePointer()); + long tvdPosition = tvx.readLong(); + + tvd.seek(tvdPosition); + int fieldCount = tvd.readVInt(); + //System.out.println("Num Fields: " + fieldCount); + // There are only a few fields per document. We opt for a full scan + // rather then requiring that they be ordered. We need to read through + // all of the fields anyway to get to the tvf pointers. + int number = 0; + int found = -1; + for (int i = 0; i < fieldCount; i++) { + if (format >= FORMAT_VERSION) + number = tvd.readVInt(); + else + number += tvd.readVInt(); + + if (number == fieldNumber) + found = i; + } + + // This field, although valid in the segment, was not found in this + // document + if (found != -1) { + // Compute position in the tvf file + long position; + if (format >= FORMAT_VERSION2) + position = tvx.readLong(); + else + position = tvd.readVLong(); + for (int i = 1; i <= found; i++) + position += tvd.readVLong(); + + mapper.setDocumentNumber(docNum); + readTermVector(field, position, mapper); + } else { + //System.out.println("Fieldable not found"); + } + } else { + //System.out.println("No tvx file"); + } + } + + + + /** + * Retrieve the term vector for the given document and field + * @param docNum The document number to retrieve the vector for + * @param field The field within the document to retrieve + * @return The TermFreqVector for the document and field or null if there is no termVector for this field. + * @throws IOException if there is an error reading the term vector files + */ + TermFreqVector get(int docNum, String field) throws IOException { + // Check if no term vectors are available for this segment at all + ParallelArrayTermVectorMapper mapper = new ParallelArrayTermVectorMapper(); + get(docNum, field, mapper); + + return mapper.materializeVector(); + } + + // Reads the String[] fields; you have to pre-seek tvd to + // the right point + final private String[] readFields(int fieldCount) throws IOException { + int number = 0; + String[] fields = new String[fieldCount]; + + for (int i = 0; i < fieldCount; i++) { + if (format >= FORMAT_VERSION) + number = tvd.readVInt(); + else + number += tvd.readVInt(); + + fields[i] = fieldInfos.fieldName(number); + } + + return fields; + } + + // Reads the long[] offsets into TVF; you have to pre-seek + // tvx/tvd to the right point + final private long[] readTvfPointers(int fieldCount) throws IOException { + // Compute position in the tvf file + long position; + if (format >= FORMAT_VERSION2) + position = tvx.readLong(); + else + position = tvd.readVLong(); + + long[] tvfPointers = new long[fieldCount]; + tvfPointers[0] = position; + + for (int i = 1; i < fieldCount; i++) { + position += tvd.readVLong(); + tvfPointers[i] = position; + } + + return tvfPointers; + } + + /** + * Return all term vectors stored for this document or null if the could not be read in. + * + * @param docNum The document number to retrieve the vector for + * @return All term frequency vectors + * @throws IOException if there is an error reading the term vector files + */ + TermFreqVector[] get(int docNum) throws IOException { + TermFreqVector[] result = null; + if (tvx != null) { + //We need to offset by + seekTvx(docNum); + long tvdPosition = tvx.readLong(); + + tvd.seek(tvdPosition); + int fieldCount = tvd.readVInt(); + + // No fields are vectorized for this document + if (fieldCount != 0) { + final String[] fields = readFields(fieldCount); + final long[] tvfPointers = readTvfPointers(fieldCount); + result = readTermVectors(docNum, fields, tvfPointers); + } + } else { + //System.out.println("No tvx file"); + } + return result; + } + + public void get(int docNumber, TermVectorMapper mapper) throws IOException { + // Check if no term vectors are available for this segment at all + if (tvx != null) { + //We need to offset by + + seekTvx(docNumber); + long tvdPosition = tvx.readLong(); + + tvd.seek(tvdPosition); + int fieldCount = tvd.readVInt(); + + // No fields are vectorized for this document + if (fieldCount != 0) { + final String[] fields = readFields(fieldCount); + final long[] tvfPointers = readTvfPointers(fieldCount); + mapper.setDocumentNumber(docNumber); + readTermVectors(fields, tvfPointers, mapper); + } + } else { + //System.out.println("No tvx file"); + } + } + + + private SegmentTermVector[] readTermVectors(int docNum, String fields[], long tvfPointers[]) + throws IOException { + SegmentTermVector res[] = new SegmentTermVector[fields.length]; + for (int i = 0; i < fields.length; i++) { + ParallelArrayTermVectorMapper mapper = new ParallelArrayTermVectorMapper(); + mapper.setDocumentNumber(docNum); + readTermVector(fields[i], tvfPointers[i], mapper); + res[i] = (SegmentTermVector) mapper.materializeVector(); + } + return res; + } + + private void readTermVectors(String fields[], long tvfPointers[], TermVectorMapper mapper) + throws IOException { + for (int i = 0; i < fields.length; i++) { + readTermVector(fields[i], tvfPointers[i], mapper); + } + } + + + /** + * + * @param field The field to read in + * @param tvfPointer The pointer within the tvf file where we should start reading + * @param mapper The mapper used to map the TermVector + * @throws IOException + */ + private void readTermVector(String field, long tvfPointer, TermVectorMapper mapper) + throws IOException { + + // Now read the data from specified position + //We don't need to offset by the FORMAT here since the pointer already includes the offset + tvf.seek(tvfPointer); + + int numTerms = tvf.readVInt(); + //System.out.println("Num Terms: " + numTerms); + // If no terms - return a constant empty termvector. However, this should never occur! + if (numTerms == 0) + return; + + boolean storePositions; + boolean storeOffsets; + + if (format >= FORMAT_VERSION){ + byte bits = tvf.readByte(); + storePositions = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; + storeOffsets = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; + } + else{ + tvf.readVInt(); + storePositions = false; + storeOffsets = false; + } + mapper.setExpectations(field, numTerms, storeOffsets, storePositions); + int start = 0; + int deltaLength = 0; + int totalLength = 0; + byte[] byteBuffer; + char[] charBuffer; + final boolean preUTF8 = format < FORMAT_UTF8_LENGTH_IN_BYTES; + + // init the buffers + if (preUTF8) { + charBuffer = new char[10]; + byteBuffer = null; + } else { + charBuffer = null; + byteBuffer = new byte[20]; + } + + for (int i = 0; i < numTerms; i++) { + start = tvf.readVInt(); + deltaLength = tvf.readVInt(); + totalLength = start + deltaLength; + + final String term; + + if (preUTF8) { + // Term stored as java chars + if (charBuffer.length < totalLength) { + char[] newCharBuffer = new char[(int) (1.5*totalLength)]; + System.arraycopy(charBuffer, 0, newCharBuffer, 0, start); + charBuffer = newCharBuffer; + } + tvf.readChars(charBuffer, start, deltaLength); + term = new String(charBuffer, 0, totalLength); + } else { + // Term stored as utf8 bytes + if (byteBuffer.length < totalLength) { + byte[] newByteBuffer = new byte[(int) (1.5*totalLength)]; + System.arraycopy(byteBuffer, 0, newByteBuffer, 0, start); + byteBuffer = newByteBuffer; + } + tvf.readBytes(byteBuffer, start, deltaLength); + term = new String(byteBuffer, 0, totalLength, "UTF-8"); + } + int freq = tvf.readVInt(); + int [] positions = null; + if (storePositions) { //read in the positions + //does the mapper even care about positions? + if (mapper.isIgnoringPositions() == false) { + positions = new int[freq]; + int prevPosition = 0; + for (int j = 0; j < freq; j++) + { + positions[j] = prevPosition + tvf.readVInt(); + prevPosition = positions[j]; + } + } else { + //we need to skip over the positions. Since these are VInts, I don't believe there is anyway to know for sure how far to skip + // + for (int j = 0; j < freq; j++) + { + tvf.readVInt(); + } + } + } + TermVectorOffsetInfo[] offsets = null; + if (storeOffsets) { + //does the mapper even care about offsets? + if (mapper.isIgnoringOffsets() == false) { + offsets = new TermVectorOffsetInfo[freq]; + int prevOffset = 0; + for (int j = 0; j < freq; j++) { + int startOffset = prevOffset + tvf.readVInt(); + int endOffset = startOffset + tvf.readVInt(); + offsets[j] = new TermVectorOffsetInfo(startOffset, endOffset); + prevOffset = endOffset; + } + } else { + for (int j = 0; j < freq; j++){ + tvf.readVInt(); + tvf.readVInt(); + } + } + } + mapper.map(term, freq, offsets, positions); + } + } + + protected Object clone() throws CloneNotSupportedException { + + final TermVectorsReader clone = (TermVectorsReader) super.clone(); + + // These are null when a TermVectorsReader was created + // on a segment that did not have term vectors saved + if (tvx != null && tvd != null && tvf != null) { + clone.tvx = (IndexInput) tvx.clone(); + clone.tvd = (IndexInput) tvd.clone(); + clone.tvf = (IndexInput) tvf.clone(); + } + + return clone; + } +} + + +/** + * Models the existing parallel array structure + */ +class ParallelArrayTermVectorMapper extends TermVectorMapper +{ + + private String[] terms; + private int[] termFreqs; + private int positions[][]; + private TermVectorOffsetInfo offsets[][]; + private int currentPosition; + private boolean storingOffsets; + private boolean storingPositions; + private String field; + + public void setExpectations(String field, int numTerms, boolean storeOffsets, boolean storePositions) { + this.field = field; + terms = new String[numTerms]; + termFreqs = new int[numTerms]; + this.storingOffsets = storeOffsets; + this.storingPositions = storePositions; + if(storePositions) + this.positions = new int[numTerms][]; + if(storeOffsets) + this.offsets = new TermVectorOffsetInfo[numTerms][]; + } + + public void map(String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions) { + terms[currentPosition] = term; + termFreqs[currentPosition] = frequency; + if (storingOffsets) + { + this.offsets[currentPosition] = offsets; + } + if (storingPositions) + { + this.positions[currentPosition] = positions; + } + currentPosition++; + } + + /** + * Construct the vector + * @return The {@link TermFreqVector} based on the mappings. + */ + public TermFreqVector materializeVector() { + SegmentTermVector tv = null; + if (field != null && terms != null) { + if (storingPositions || storingOffsets) { + tv = new SegmentTermPositionVector(field, terms, termFreqs, positions, offsets); + } else { + tv = new SegmentTermVector(field, terms, termFreqs); + } + } + return tv; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsTermsWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsTermsWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsTermsWriter.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,290 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.store.RAMOutputStream; +import org.apache.lucene.util.ArrayUtil; + +import java.io.IOException; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; + +final class TermVectorsTermsWriter extends TermsHashConsumer { + + final DocumentsWriter docWriter; + TermVectorsWriter termVectorsWriter; + PerDoc[] docFreeList = new PerDoc[1]; + int freeCount; + IndexOutput tvx; + IndexOutput tvd; + IndexOutput tvf; + int lastDocID; + + public TermVectorsTermsWriter(DocumentsWriter docWriter) { + this.docWriter = docWriter; + } + + public TermsHashConsumerPerThread addThread(TermsHashPerThread termsHashPerThread) { + return new TermVectorsTermsWriterPerThread(termsHashPerThread, this); + } + + void createPostings(RawPostingList[] postings, int start, int count) { + final int end = start + count; + for(int i=start;i 0) + // In case there are some final documents that we + // didn't see (because they hit a non-aborting exception): + fill(state.numDocsInStore - docWriter.getDocStoreOffset()); + + tvx.flush(); + tvd.flush(); + tvf.flush(); + } + + Iterator it = threadsAndFields.entrySet().iterator(); + while(it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + Iterator it2 = ((Collection) entry.getValue()).iterator(); + while(it2.hasNext()) { + TermVectorsTermsWriterPerField perField = (TermVectorsTermsWriterPerField) it2.next(); + perField.termsHashPerField.reset(); + perField.shrinkHash(); + } + + TermVectorsTermsWriterPerThread perThread = (TermVectorsTermsWriterPerThread) entry.getKey(); + perThread.termsHashPerThread.reset(true); + } + } + + synchronized void closeDocStore(final DocumentsWriter.FlushState state) throws IOException { + if (tvx != null) { + // At least one doc in this run had term vectors + // enabled + fill(state.numDocsInStore - docWriter.getDocStoreOffset()); + tvx.close(); + tvf.close(); + tvd.close(); + tvx = null; + assert state.docStoreSegmentName != null; + if (4+state.numDocsInStore*16 != state.directory.fileLength(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION)) + throw new RuntimeException("after flush: tvx size mismatch: " + state.numDocsInStore + " docs vs " + state.directory.fileLength(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION) + " length in bytes of " + state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); + + state.flushedFiles.add(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); + state.flushedFiles.add(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION); + state.flushedFiles.add(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION); + + docWriter.removeOpenFile(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); + docWriter.removeOpenFile(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION); + docWriter.removeOpenFile(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION); + + lastDocID = 0; + } + } + + int allocCount; + + synchronized PerDoc getPerDoc() { + if (freeCount == 0) { + allocCount++; + if (allocCount > docFreeList.length) { + // Grow our free list up front to make sure we have + // enough space to recycle all outstanding PerDoc + // instances + assert allocCount == 1+docFreeList.length; + docFreeList = new PerDoc[ArrayUtil.getNextSize(allocCount)]; + } + return new PerDoc(); + } else + return docFreeList[--freeCount]; + } + + /** Fills in no-term-vectors for all docs we haven't seen + * since the last doc that had term vectors. */ + void fill(int docID) throws IOException { + final int docStoreOffset = docWriter.getDocStoreOffset(); + final int end = docID+docStoreOffset; + if (lastDocID < end) { + final long tvfPosition = tvf.getFilePointer(); + while(lastDocID < end) { + tvx.writeLong(tvd.getFilePointer()); + tvd.writeVInt(0); + tvx.writeLong(tvfPosition); + lastDocID++; + } + } + } + + synchronized void initTermVectorsWriter() throws IOException { + if (tvx == null) { + + final String docStoreSegment = docWriter.getDocStoreSegment(); + + if (docStoreSegment == null) + return; + + assert docStoreSegment != null; + + // If we hit an exception while init'ing the term + // vector output files, we must abort this segment + // because those files will be in an unknown + // state: + tvx = docWriter.directory.createOutput(docStoreSegment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); + tvd = docWriter.directory.createOutput(docStoreSegment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION); + tvf = docWriter.directory.createOutput(docStoreSegment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION); + + tvx.writeInt(TermVectorsReader.FORMAT_CURRENT); + tvd.writeInt(TermVectorsReader.FORMAT_CURRENT); + tvf.writeInt(TermVectorsReader.FORMAT_CURRENT); + + docWriter.addOpenFile(docStoreSegment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); + docWriter.addOpenFile(docStoreSegment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION); + docWriter.addOpenFile(docStoreSegment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION); + + lastDocID = 0; + } + } + + synchronized void finishDocument(PerDoc perDoc) throws IOException { + + assert docWriter.writer.testPoint("TermVectorsTermsWriter.finishDocument start"); + + initTermVectorsWriter(); + + fill(perDoc.docID); + + // Append term vectors to the real outputs: + tvx.writeLong(tvd.getFilePointer()); + tvx.writeLong(tvf.getFilePointer()); + tvd.writeVInt(perDoc.numVectorFields); + if (perDoc.numVectorFields > 0) { + for(int i=0;i= 0; + + if (!doVectors || numPostings == 0) + return; + + if (numPostings > maxNumPostings) + maxNumPostings = numPostings; + + final IndexOutput tvf = perThread.doc.tvf; + + // This is called once, after inverting all occurences + // of a given field in the doc. At this point we flush + // our hash into the DocWriter. + + assert fieldInfo.storeTermVector; + assert perThread.vectorFieldsInOrder(fieldInfo); + + perThread.doc.addField(termsHashPerField.fieldInfo.number); + + final RawPostingList[] postings = termsHashPerField.sortPostings(); + + tvf.writeVInt(numPostings); + byte bits = 0x0; + if (doVectorPositions) + bits |= TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR; + if (doVectorOffsets) + bits |= TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR; + tvf.writeByte(bits); + + int encoderUpto = 0; + int lastTermBytesCount = 0; + + final ByteSliceReader reader = perThread.vectorSliceReader; + final char[][] charBuffers = perThread.termsHashPerThread.charPool.buffers; + for(int j=0;j> DocumentsWriter.CHAR_BLOCK_SHIFT]; + final int start2 = posting.textStart & DocumentsWriter.CHAR_BLOCK_MASK; + + // We swap between two encoders to save copying + // last Term's byte array + final UnicodeUtil.UTF8Result utf8Result = perThread.utf8Results[encoderUpto]; + + // TODO: we could do this incrementally + UnicodeUtil.UTF16toUTF8(text2, start2, utf8Result); + final int termBytesCount = utf8Result.length; + + // TODO: UTF16toUTF8 could tell us this prefix + // Compute common prefix between last term and + // this term + int prefix = 0; + if (j > 0) { + final byte[] lastTermBytes = perThread.utf8Results[1-encoderUpto].result; + final byte[] termBytes = perThread.utf8Results[encoderUpto].result; + while(prefix < lastTermBytesCount && prefix < termBytesCount) { + if (lastTermBytes[prefix] != termBytes[prefix]) + break; + prefix++; + } + } + encoderUpto = 1-encoderUpto; + lastTermBytesCount = termBytesCount; + + final int suffix = termBytesCount - prefix; + tvf.writeVInt(prefix); + tvf.writeVInt(suffix); + tvf.writeBytes(utf8Result.result, prefix, suffix); + tvf.writeVInt(freq); + + if (doVectorPositions) { + termsHashPerField.initReader(reader, posting, 0); + reader.writeTo(tvf); + } + + if (doVectorOffsets) { + termsHashPerField.initReader(reader, posting, 1); + reader.writeTo(tvf); + } + } + + termsHashPerField.reset(); + perThread.termsHashPerThread.reset(false); + } + + void shrinkHash() { + termsHashPerField.shrinkHash(maxNumPostings); + maxNumPostings = 0; + } + + void newTerm(Token t, RawPostingList p0) { + + assert docState.testPoint("TermVectorsTermsWriterPerField.newTerm start"); + + TermVectorsTermsWriter.PostingList p = (TermVectorsTermsWriter.PostingList) p0; + + p.freq = 1; + + if (doVectorOffsets) { + final int startOffset = fieldState.offset + t.startOffset(); + final int endOffset = fieldState.offset + t.endOffset(); + termsHashPerField.writeVInt(1, startOffset); + termsHashPerField.writeVInt(1, endOffset - startOffset); + p.lastOffset = endOffset; + } + + if (doVectorPositions) { + termsHashPerField.writeVInt(0, fieldState.position); + p.lastPosition = fieldState.position; + } + } + + void addTerm(Token t, RawPostingList p0) { + + assert docState.testPoint("TermVectorsTermsWriterPerField.addTerm start"); + + TermVectorsTermsWriter.PostingList p = (TermVectorsTermsWriter.PostingList) p0; + p.freq++; + + if (doVectorOffsets) { + final int startOffset = fieldState.offset + t.startOffset(); + final int endOffset = fieldState.offset + t.endOffset(); + termsHashPerField.writeVInt(1, startOffset - p.lastOffset); + termsHashPerField.writeVInt(1, endOffset - startOffset); + p.lastOffset = endOffset; + } + + if (doVectorPositions) { + termsHashPerField.writeVInt(0, fieldState.position - p.lastPosition); + p.lastPosition = fieldState.position; + } + } + + void skippingLongTerm(Token t) {} +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsTermsWriterPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsTermsWriterPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsTermsWriterPerThread.java 17 Aug 2012 14:55:02 -0000 1.1 @@ -0,0 +1,87 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.util.UnicodeUtil; + +final class TermVectorsTermsWriterPerThread extends TermsHashConsumerPerThread { + + final TermVectorsTermsWriter termsWriter; + final TermsHashPerThread termsHashPerThread; + final DocumentsWriter.DocState docState; + + TermVectorsTermsWriter.PerDoc doc; + + public TermVectorsTermsWriterPerThread(TermsHashPerThread termsHashPerThread, TermVectorsTermsWriter termsWriter) { + this.termsWriter = termsWriter; + this.termsHashPerThread = termsHashPerThread; + docState = termsHashPerThread.docState; + } + + // Used by perField when serializing the term vectors + final ByteSliceReader vectorSliceReader = new ByteSliceReader(); + + final UnicodeUtil.UTF8Result utf8Results[] = {new UnicodeUtil.UTF8Result(), + new UnicodeUtil.UTF8Result()}; + + public void startDocument() { + assert clearLastVectorFieldName(); + if (doc != null) { + doc.reset(); + doc.docID = docState.docID; + } + } + + public DocumentsWriter.DocWriter finishDocument() { + try { + return doc; + } finally { + doc = null; + } + } + + public TermsHashConsumerPerField addField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo) { + return new TermVectorsTermsWriterPerField(termsHashPerField, this, fieldInfo); + } + + public void abort() { + if (doc != null) { + doc.abort(); + doc = null; + } + } + + // Called only by assert + final boolean clearLastVectorFieldName() { + lastVectorFieldName = null; + return true; + } + + // Called only by assert + String lastVectorFieldName; + final boolean vectorFieldsInOrder(FieldInfo fi) { + try { + if (lastVectorFieldName != null) + return lastVectorFieldName.compareTo(fi.name) < 0; + else + return true; + } finally { + lastVectorFieldName = fi.name; + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermVectorsWriter.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,216 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexOutput; +import org.apache.lucene.util.StringHelper; +import org.apache.lucene.util.UnicodeUtil; + +import java.io.IOException; + +final class TermVectorsWriter { + + private IndexOutput tvx = null, tvd = null, tvf = null; + private FieldInfos fieldInfos; + final UnicodeUtil.UTF8Result[] utf8Results = new UnicodeUtil.UTF8Result[] {new UnicodeUtil.UTF8Result(), + new UnicodeUtil.UTF8Result()}; + + public TermVectorsWriter(Directory directory, String segment, + FieldInfos fieldInfos) + throws IOException { + // Open files for TermVector storage + tvx = directory.createOutput(segment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); + tvx.writeInt(TermVectorsReader.FORMAT_CURRENT); + tvd = directory.createOutput(segment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION); + tvd.writeInt(TermVectorsReader.FORMAT_CURRENT); + tvf = directory.createOutput(segment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION); + tvf.writeInt(TermVectorsReader.FORMAT_CURRENT); + + this.fieldInfos = fieldInfos; + } + + /** + * Add a complete document specified by all its term vectors. If document has no + * term vectors, add value for tvx. + * + * @param vectors + * @throws IOException + */ + public final void addAllDocVectors(TermFreqVector[] vectors) + throws IOException { + + tvx.writeLong(tvd.getFilePointer()); + tvx.writeLong(tvf.getFilePointer()); + + if (vectors != null) { + final int numFields = vectors.length; + tvd.writeVInt(numFields); + + long[] fieldPointers = new long[numFields]; + + for (int i=0; i 0 && tpVector.getTermPositions(0) != null; + storeOffsets = tpVector.size() > 0 && tpVector.getOffsets(0) != null; + bits = (byte) ((storePositions ? TermVectorsReader.STORE_POSITIONS_WITH_TERMVECTOR : 0) + + (storeOffsets ? TermVectorsReader.STORE_OFFSET_WITH_TERMVECTOR : 0)); + } else { + tpVector = null; + bits = 0; + storePositions = false; + storeOffsets = false; + } + + tvf.writeVInt(bits); + + final String[] terms = vectors[i].getTerms(); + final int[] freqs = vectors[i].getTermFrequencies(); + + int utf8Upto = 0; + utf8Results[1].length = 0; + + for (int j=0; j postingsFreeList.length) + // Pre-allocate the postingsFreeList so it's large + // enough to hold all postings we've given out + postingsFreeList = new RawPostingList[ArrayUtil.getNextSize(newPostingsAllocCount)]; + } + + postingsFreeCount -= numToCopy; + + if (trackAllocations) + docWriter.bytesUsed(postings.length * bytesPerPosting); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumer.java 17 Aug 2012 14:54:59 -0000 1.1 @@ -0,0 +1,36 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Map; + +abstract class TermsHashConsumer { + abstract int bytesPerPosting(); + abstract void createPostings(RawPostingList[] postings, int start, int count); + abstract TermsHashConsumerPerThread addThread(TermsHashPerThread perThread); + abstract void flush(Map threadsAndFields, final DocumentsWriter.FlushState state) throws IOException; + abstract void abort(); + abstract void closeDocStore(DocumentsWriter.FlushState state) throws IOException; + + FieldInfos fieldInfos; + + void setFieldInfos(FieldInfos fieldInfos) { + this.fieldInfos = fieldInfos; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumerPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumerPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumerPerField.java 17 Aug 2012 14:55:01 -0000 1.1 @@ -0,0 +1,36 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Implement this class to plug into the TermsHash + * processor, which inverts & stores Tokens into a hash + * table and provides an API for writing bytes into + * multiple streams for each unique Token. */ + +import java.io.IOException; +import org.apache.lucene.document.Fieldable; +import org.apache.lucene.analysis.Token; + +abstract class TermsHashConsumerPerField { + abstract boolean start(Fieldable[] fields, int count) throws IOException; + abstract void finish() throws IOException; + abstract void skippingLongTerm(Token t) throws IOException; + abstract void newTerm(Token t, RawPostingList p) throws IOException; + abstract void addTerm(Token t, RawPostingList p) throws IOException; + abstract int getStreamCount(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumerPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumerPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashConsumerPerThread.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,27 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +abstract class TermsHashConsumerPerThread { + abstract void startDocument() throws IOException; + abstract DocumentsWriter.DocWriter finishDocument() throws IOException; + abstract public TermsHashConsumerPerField addField(TermsHashPerField termsHashPerField, FieldInfo fieldInfo); + abstract public void abort(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashPerField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermsHashPerField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashPerField.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,546 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Arrays; + +import org.apache.lucene.document.Fieldable; +import org.apache.lucene.analysis.Token; +import org.apache.lucene.util.UnicodeUtil; + +final class TermsHashPerField extends InvertedDocConsumerPerField { + + final TermsHashConsumerPerField consumer; + final TermsHashPerField nextPerField; + final TermsHashPerThread perThread; + final DocumentsWriter.DocState docState; + final DocInverter.FieldInvertState fieldState; + + // Copied from our perThread + final CharBlockPool charPool; + final IntBlockPool intPool; + final ByteBlockPool bytePool; + + final int streamCount; + final int numPostingInt; + + final FieldInfo fieldInfo; + + boolean postingsCompacted; + int numPostings; + private int postingsHashSize = 4; + private int postingsHashHalfSize = postingsHashSize/2; + private int postingsHashMask = postingsHashSize-1; + private RawPostingList[] postingsHash = new RawPostingList[postingsHashSize]; + private RawPostingList p; + + public TermsHashPerField(DocInverterPerField docInverterPerField, final TermsHashPerThread perThread, final TermsHashPerThread nextPerThread, final FieldInfo fieldInfo) { + this.perThread = perThread; + intPool = perThread.intPool; + charPool = perThread.charPool; + bytePool = perThread.bytePool; + docState = perThread.docState; + fieldState = docInverterPerField.fieldState; + this.consumer = perThread.consumer.addField(this, fieldInfo); + streamCount = consumer.getStreamCount(); + numPostingInt = 2*streamCount; + this.fieldInfo = fieldInfo; + if (nextPerThread != null) + nextPerField = (TermsHashPerField) nextPerThread.addField(docInverterPerField, fieldInfo); + else + nextPerField = null; + } + + void shrinkHash(int targetSize) { + assert postingsCompacted || numPostings == 0; + + // Cannot use ArrayUtil.shrink because we require power + // of 2: + int newSize = postingsHash.length; + while(newSize >= 8 && newSize/4 > targetSize) { + newSize /= 2; + } + + if (newSize != postingsHash.length) { + postingsHash = new RawPostingList[newSize]; + postingsHashSize = newSize; + postingsHashHalfSize = newSize/2; + postingsHashMask = newSize-1; + } + } + + public void reset() { + if (!postingsCompacted) + compactPostings(); + assert numPostings <= postingsHash.length; + if (numPostings > 0) { + perThread.termsHash.recyclePostings(postingsHash, numPostings); + Arrays.fill(postingsHash, 0, numPostings, null); + numPostings = 0; + } + postingsCompacted = false; + if (nextPerField != null) + nextPerField.reset(); + } + + synchronized public void abort() { + reset(); + if (nextPerField != null) + nextPerField.abort(); + } + + public void initReader(ByteSliceReader reader, RawPostingList p, int stream) { + assert stream < streamCount; + final int[] ints = intPool.buffers[p.intStart >> DocumentsWriter.INT_BLOCK_SHIFT]; + final int upto = p.intStart & DocumentsWriter.INT_BLOCK_MASK; + reader.init(bytePool, + p.byteStart+stream*ByteBlockPool.FIRST_LEVEL_SIZE, + ints[upto+stream]); + } + + private synchronized void compactPostings() { + int upto = 0; + for(int i=0;i= hi) + return; + else if (hi == 1+lo) { + if (comparePostings(postings[lo], postings[hi]) > 0) { + final RawPostingList tmp = postings[lo]; + postings[lo] = postings[hi]; + postings[hi] = tmp; + } + return; + } + + int mid = (lo + hi) >>> 1; + + if (comparePostings(postings[lo], postings[mid]) > 0) { + RawPostingList tmp = postings[lo]; + postings[lo] = postings[mid]; + postings[mid] = tmp; + } + + if (comparePostings(postings[mid], postings[hi]) > 0) { + RawPostingList tmp = postings[mid]; + postings[mid] = postings[hi]; + postings[hi] = tmp; + + if (comparePostings(postings[lo], postings[mid]) > 0) { + RawPostingList tmp2 = postings[lo]; + postings[lo] = postings[mid]; + postings[mid] = tmp2; + } + } + + int left = lo + 1; + int right = hi - 1; + + if (left >= right) + return; + + RawPostingList partition = postings[mid]; + + for (; ;) { + while (comparePostings(postings[right], partition) > 0) + --right; + + while (left < right && comparePostings(postings[left], partition) <= 0) + ++left; + + if (left < right) { + RawPostingList tmp = postings[left]; + postings[left] = postings[right]; + postings[right] = tmp; + --right; + } else { + break; + } + } + + quickSort(postings, lo, left); + quickSort(postings, left + 1, hi); + } + + /** Compares term text for two Posting instance and + * returns -1 if p1 < p2; 1 if p1 > p2; else 0. */ + int comparePostings(RawPostingList p1, RawPostingList p2) { + + if (p1 == p2) + return 0; + + final char[] text1 = charPool.buffers[p1.textStart >> DocumentsWriter.CHAR_BLOCK_SHIFT]; + int pos1 = p1.textStart & DocumentsWriter.CHAR_BLOCK_MASK; + final char[] text2 = charPool.buffers[p2.textStart >> DocumentsWriter.CHAR_BLOCK_SHIFT]; + int pos2 = p2.textStart & DocumentsWriter.CHAR_BLOCK_MASK; + + assert text1 != text2 || pos1 != pos2; + + while(true) { + final char c1 = text1[pos1++]; + final char c2 = text2[pos2++]; + if (c1 != c2) { + if (0xffff == c2) + return 1; + else if (0xffff == c1) + return -1; + else + return c1-c2; + } else + // This method should never compare equal postings + // unless p1==p2 + assert c1 != 0xffff; + } + } + + /** Test whether the text for current RawPostingList p equals + * current tokenText. */ + private boolean postingEquals(final char[] tokenText, final int tokenTextLen) { + + final char[] text = perThread.charPool.buffers[p.textStart >> DocumentsWriter.CHAR_BLOCK_SHIFT]; + assert text != null; + int pos = p.textStart & DocumentsWriter.CHAR_BLOCK_MASK; + + int tokenPos = 0; + for(;tokenPos>8)+code)|1; + do { + code += inc; + hashPos = code & postingsHashMask; + p = postingsHash[hashPos]; + } while (p != null && p.textStart != textStart); + } + + if (p == null) { + + // First time we are seeing this token since we last + // flushed the hash. + + // Refill? + if (0 == perThread.freePostingsCount) + perThread.morePostings(); + + // Pull next free RawPostingList from free list + p = perThread.freePostings[--perThread.freePostingsCount]; + assert p != null; + + p.textStart = textStart; + + assert postingsHash[hashPos] == null; + postingsHash[hashPos] = p; + numPostings++; + + if (numPostings == postingsHashHalfSize) + rehashPostings(2*postingsHashSize); + + // Init stream slices + if (numPostingInt + intPool.intUpto > DocumentsWriter.INT_BLOCK_SIZE) + intPool.nextBuffer(); + + if (DocumentsWriter.BYTE_BLOCK_SIZE - bytePool.byteUpto < numPostingInt*ByteBlockPool.FIRST_LEVEL_SIZE) + bytePool.nextBuffer(); + + intUptos = intPool.buffer; + intUptoStart = intPool.intUpto; + intPool.intUpto += streamCount; + + p.intStart = intUptoStart + intPool.intOffset; + + for(int i=0;i> DocumentsWriter.INT_BLOCK_SHIFT]; + intUptoStart = p.intStart & DocumentsWriter.INT_BLOCK_MASK; + consumer.addTerm(token, p); + } + } + + // Primary entry point (for first TermsHash) + void add(Token token) throws IOException { + + assert !postingsCompacted; + + // We are first in the chain so we must "intern" the + // term text into textStart address + + // Get the text of this term. + final char[] tokenText = token.termBuffer(); + final int tokenTextLen = token.termLength(); + + // Compute hashcode & replace any invalid UTF16 sequences + int downto = tokenTextLen; + int code = 0; + while (downto > 0) { + char ch = tokenText[--downto]; + + if (ch >= UnicodeUtil.UNI_SUR_LOW_START && ch <= UnicodeUtil.UNI_SUR_LOW_END) { + if (0 == downto) { + // Unpaired + ch = tokenText[downto] = UnicodeUtil.UNI_REPLACEMENT_CHAR; + } else { + final char ch2 = tokenText[downto-1]; + if (ch2 >= UnicodeUtil.UNI_SUR_HIGH_START && ch2 <= UnicodeUtil.UNI_SUR_HIGH_END) { + // OK: high followed by low. This is a valid + // surrogate pair. + code = ((code*31) + ch)*31+ch2; + downto--; + continue; + } else { + // Unpaired + ch = tokenText[downto] = UnicodeUtil.UNI_REPLACEMENT_CHAR; + } + } + } else if (ch >= UnicodeUtil.UNI_SUR_HIGH_START && ch <= UnicodeUtil.UNI_SUR_HIGH_END) + // Unpaired + ch = tokenText[downto] = UnicodeUtil.UNI_REPLACEMENT_CHAR; + + code = (code*31) + ch; + } + + int hashPos = code & postingsHashMask; + + // Locate RawPostingList in hash + p = postingsHash[hashPos]; + + if (p != null && !postingEquals(tokenText, tokenTextLen)) { + // Conflict: keep searching different locations in + // the hash table. + final int inc = ((code>>8)+code)|1; + do { + code += inc; + hashPos = code & postingsHashMask; + p = postingsHash[hashPos]; + } while (p != null && !postingEquals(tokenText, tokenTextLen)); + } + + if (p == null) { + + // First time we are seeing this token since we last + // flushed the hash. + final int textLen1 = 1+tokenTextLen; + if (textLen1 + charPool.charUpto > DocumentsWriter.CHAR_BLOCK_SIZE) { + if (textLen1 > DocumentsWriter.CHAR_BLOCK_SIZE) { + // Just skip this term, to remain as robust as + // possible during indexing. A TokenFilter + // can be inserted into the analyzer chain if + // other behavior is wanted (pruning the term + // to a prefix, throwing an exception, etc). + + if (docState.maxTermPrefix == null) + docState.maxTermPrefix = new String(tokenText, 0, 30); + + consumer.skippingLongTerm(token); + return; + } + charPool.nextBuffer(); + } + + // Refill? + if (0 == perThread.freePostingsCount) + perThread.morePostings(); + + // Pull next free RawPostingList from free list + p = perThread.freePostings[--perThread.freePostingsCount]; + assert p != null; + + final char[] text = charPool.buffer; + final int textUpto = charPool.charUpto; + p.textStart = textUpto + charPool.charOffset; + charPool.charUpto += textLen1; + System.arraycopy(tokenText, 0, text, textUpto, tokenTextLen); + text[textUpto+tokenTextLen] = 0xffff; + + assert postingsHash[hashPos] == null; + postingsHash[hashPos] = p; + numPostings++; + + if (numPostings == postingsHashHalfSize) + rehashPostings(2*postingsHashSize); + + // Init stream slices + if (numPostingInt + intPool.intUpto > DocumentsWriter.INT_BLOCK_SIZE) + intPool.nextBuffer(); + + if (DocumentsWriter.BYTE_BLOCK_SIZE - bytePool.byteUpto < numPostingInt*ByteBlockPool.FIRST_LEVEL_SIZE) + bytePool.nextBuffer(); + + intUptos = intPool.buffer; + intUptoStart = intPool.intUpto; + intPool.intUpto += streamCount; + + p.intStart = intUptoStart + intPool.intOffset; + + for(int i=0;i> DocumentsWriter.INT_BLOCK_SHIFT]; + intUptoStart = p.intStart & DocumentsWriter.INT_BLOCK_MASK; + consumer.addTerm(token, p); + } + + if (doNextCall) + nextPerField.add(token, p.textStart); + } + + int[] intUptos; + int intUptoStart; + + void writeByte(int stream, byte b) { + int upto = intUptos[intUptoStart+stream]; + byte[] bytes = bytePool.buffers[upto >> DocumentsWriter.BYTE_BLOCK_SHIFT]; + assert bytes != null; + int offset = upto & DocumentsWriter.BYTE_BLOCK_MASK; + if (bytes[offset] != 0) { + // End of slice; allocate a new one + offset = bytePool.allocSlice(bytes, offset); + bytes = bytePool.buffer; + intUptos[intUptoStart+stream] = offset + bytePool.byteOffset; + } + bytes[offset] = b; + (intUptos[intUptoStart+stream])++; + } + + public void writeBytes(int stream, byte[] b, int offset, int len) { + // TODO: optimize + final int end = offset + len; + for(int i=offset;i>>= 7; + } + writeByte(stream, (byte) i); + } + + void finish() throws IOException { + consumer.finish(); + if (nextPerField != null) + nextPerField.finish(); + } + + /** Called when postings hash is too small (> 50% + * occupied) or too large (< 20% occupied). */ + void rehashPostings(final int newSize) { + + final int newMask = newSize-1; + + RawPostingList[] newHash = new RawPostingList[newSize]; + for(int i=0;i> DocumentsWriter.CHAR_BLOCK_SHIFT]; + int pos = start; + while(text[pos] != 0xffff) + pos++; + code = 0; + while (pos > start) + code = (code*31) + text[--pos]; + } else + code = p0.textStart; + + int hashPos = code & newMask; + assert hashPos >= 0; + if (newHash[hashPos] != null) { + final int inc = ((code>>8)+code)|1; + do { + code += inc; + hashPos = code & newMask; + } while (newHash[hashPos] != null); + } + newHash[hashPos] = p0; + } + } + + postingsHashMask = newMask; + postingsHash = newHash; + postingsHashSize = newSize; + postingsHashHalfSize = newSize >> 1; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashPerThread.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/index/TermsHashPerThread.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/index/TermsHashPerThread.java 17 Aug 2012 14:54:58 -0000 1.1 @@ -0,0 +1,121 @@ +package org.apache.lucene.index; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +final class TermsHashPerThread extends InvertedDocConsumerPerThread { + + final TermsHash termsHash; + final TermsHashConsumerPerThread consumer; + final TermsHashPerThread nextPerThread; + + final CharBlockPool charPool; + final IntBlockPool intPool; + final ByteBlockPool bytePool; + final boolean primary; + final DocumentsWriter.DocState docState; + + final RawPostingList freePostings[] = new RawPostingList[256]; + int freePostingsCount; + + public TermsHashPerThread(DocInverterPerThread docInverterPerThread, final TermsHash termsHash, final TermsHash nextTermsHash, final TermsHashPerThread primaryPerThread) { + docState = docInverterPerThread.docState; + + this.termsHash = termsHash; + this.consumer = termsHash.consumer.addThread(this); + + if (nextTermsHash != null) { + // We are primary + charPool = new CharBlockPool(termsHash.docWriter); + primary = true; + } else { + charPool = primaryPerThread.charPool; + primary = false; + } + + intPool = new IntBlockPool(termsHash.docWriter, termsHash.trackAllocations); + bytePool = new ByteBlockPool(termsHash.docWriter.byteBlockAllocator, termsHash.trackAllocations); + + if (nextTermsHash != null) + nextPerThread = nextTermsHash.addThread(docInverterPerThread, this); + else + nextPerThread = null; + } + + InvertedDocConsumerPerField addField(DocInverterPerField docInverterPerField, final FieldInfo fieldInfo) { + return new TermsHashPerField(docInverterPerField, this, nextPerThread, fieldInfo); + } + + synchronized public void abort() { + reset(true); + consumer.abort(); + if (nextPerThread != null) + nextPerThread.abort(); + } + + // perField calls this when it needs more postings: + void morePostings() throws IOException { + assert freePostingsCount == 0; + termsHash.getPostings(freePostings); + freePostingsCount = freePostings.length; + assert noNullPostings(freePostings, freePostingsCount, "consumer=" + consumer); + } + + private static boolean noNullPostings(RawPostingList[] postings, int count, String details) { + for(int i=0;i + + + + + + + +Code to maintain and access indices. + + Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/CharStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/CharStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/CharStream.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,112 @@ +/* Generated By:JavaCC: Do not edit this line. CharStream.java Version 4.1 */ +/* JavaCCOptions:STATIC=false */ +package org.apache.lucene.queryParser; + +/** + * This interface describes a character stream that maintains line and + * column number positions of the characters. It also has the capability + * to backup the stream to some extent. An implementation of this + * interface is used in the TokenManager implementation generated by + * JavaCCParser. + * + * All the methods except backup can be implemented in any fashion. backup + * needs to be implemented correctly for the correct operation of the lexer. + * Rest of the methods are all used to get information like line number, + * column number and the String that constitutes a token and are not used + * by the lexer. Hence their implementation won't affect the generated lexer's + * operation. + */ + +public interface CharStream { + + /** + * Returns the next character from the selected input. The method + * of selecting the input is the responsibility of the class + * implementing this interface. Can throw any java.io.IOException. + */ + char readChar() throws java.io.IOException; + + /** + * Returns the column position of the character last read. + * @deprecated + * @see #getEndColumn + */ + int getColumn(); + + /** + * Returns the line number of the character last read. + * @deprecated + * @see #getEndLine + */ + int getLine(); + + /** + * Returns the column number of the last character for current token (being + * matched after the last call to BeginTOken). + */ + int getEndColumn(); + + /** + * Returns the line number of the last character for current token (being + * matched after the last call to BeginTOken). + */ + int getEndLine(); + + /** + * Returns the column number of the first character for current token (being + * matched after the last call to BeginTOken). + */ + int getBeginColumn(); + + /** + * Returns the line number of the first character for current token (being + * matched after the last call to BeginTOken). + */ + int getBeginLine(); + + /** + * Backs up the input stream by amount steps. Lexer calls this method if it + * had already read some characters, but could not use them to match a + * (longer) token. So, they will be used again as the prefix of the next + * token and it is the implemetation's responsibility to do this right. + */ + void backup(int amount); + + /** + * Returns the next character that marks the beginning of the next token. + * All characters must remain in the buffer between two successive calls + * to this method to implement backup correctly. + */ + char BeginToken() throws java.io.IOException; + + /** + * Returns a string made up of characters from the marked token beginning + * to the current buffer position. Implementations have the choice of returning + * anything that they want to. For example, for efficiency, one might decide + * to just return null, which is a valid implementation. + */ + String GetImage(); + + /** + * Returns an array of characters that make up the suffix of length 'len' for + * the currently matched token. This is used to build up the matched string + * for use in actions in the case of MORE. A simple and inefficient + * implementation of this is as follows : + * + * { + * String t = GetImage(); + * return t.substring(t.length() - len, t.length()).toCharArray(); + * } + */ + char[] GetSuffix(int len); + + /** + * The lexer calls this function to indicate that it is done with the stream + * and hence implementations can free any resources held by this class. + * Again, the body of this function can be just empty and it will not + * affect the lexer's operation. + */ + void Done(); + +} +/* JavaCC - OriginalChecksum=32a89423891f765dde472f7ef0e3ef7b (do not edit this line) */ Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/FastCharStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/FastCharStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/FastCharStream.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,122 @@ +// FastCharStream.java +package org.apache.lucene.queryParser; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.*; + +/** An efficient implementation of JavaCC's CharStream interface.

Note that + * this does not do line-number counting, but instead keeps track of the + * character position of the token in the input, as required by Lucene's {@link + * org.apache.lucene.analysis.Token} API. */ +public final class FastCharStream implements CharStream { + char[] buffer = null; + + int bufferLength = 0; // end of valid chars + int bufferPosition = 0; // next char to read + + int tokenStart = 0; // offset in buffer + int bufferStart = 0; // position in file of buffer + + Reader input; // source of chars + + /** Constructs from a Reader. */ + public FastCharStream(Reader r) { + input = r; + } + + public final char readChar() throws IOException { + if (bufferPosition >= bufferLength) + refill(); + return buffer[bufferPosition++]; + } + + private final void refill() throws IOException { + int newPosition = bufferLength - tokenStart; + + if (tokenStart == 0) { // token won't fit in buffer + if (buffer == null) { // first time: alloc buffer + buffer = new char[2048]; + } else if (bufferLength == buffer.length) { // grow buffer + char[] newBuffer = new char[buffer.length*2]; + System.arraycopy(buffer, 0, newBuffer, 0, bufferLength); + buffer = newBuffer; + } + } else { // shift token to front + System.arraycopy(buffer, tokenStart, buffer, 0, newPosition); + } + + bufferLength = newPosition; // update state + bufferPosition = newPosition; + bufferStart += tokenStart; + tokenStart = 0; + + int charsRead = // fill space in buffer + input.read(buffer, newPosition, buffer.length-newPosition); + if (charsRead == -1) + throw new IOException("read past eof"); + else + bufferLength += charsRead; + } + + public final char BeginToken() throws IOException { + tokenStart = bufferPosition; + return readChar(); + } + + public final void backup(int amount) { + bufferPosition -= amount; + } + + public final String GetImage() { + return new String(buffer, tokenStart, bufferPosition - tokenStart); + } + + public final char[] GetSuffix(int len) { + char[] value = new char[len]; + System.arraycopy(buffer, bufferPosition - len, value, 0, len); + return value; + } + + public final void Done() { + try { + input.close(); + } catch (IOException e) { + System.err.println("Caught: " + e + "; ignoring."); + } + } + + public final int getColumn() { + return bufferStart + bufferPosition; + } + public final int getLine() { + return 1; + } + public final int getEndColumn() { + return bufferStart + bufferPosition; + } + public final int getEndLine() { + return 1; + } + public final int getBeginColumn() { + return bufferStart + tokenStart; + } + public final int getBeginLine() { + return 1; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/MultiFieldQueryParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/MultiFieldQueryParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/MultiFieldQueryParser.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,321 @@ +package org.apache.lucene.queryParser; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.MultiPhraseQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.Query; + +/** + * A QueryParser which constructs queries to search multiple fields. + * + * + * @version $Revision: 1.1 $ + */ +public class MultiFieldQueryParser extends QueryParser +{ + protected String[] fields; + protected Map boosts; + + /** + * Creates a MultiFieldQueryParser. + * Allows passing of a map with term to Boost, and the boost to apply to each term. + * + *

It will, when parse(String query) + * is called, construct a query like this (assuming the query consists of + * two terms and you specify the two fields title and body):

+ * + * + * (title:term1 body:term1) (title:term2 body:term2) + * + * + *

When setDefaultOperator(AND_OPERATOR) is set, the result will be:

+ * + * + * +(title:term1 body:term1) +(title:term2 body:term2) + * + * + *

When you pass a boost (title=>5 body=>10) you can get

+ * + * + * +(title:term1^5.0 body:term1^10.0) +(title:term2^5.0 body:term2^10.0) + * + * + *

In other words, all the query's terms must appear, but it doesn't matter in + * what fields they appear.

+ */ + public MultiFieldQueryParser(String[] fields, Analyzer analyzer, Map boosts) { + this(fields,analyzer); + this.boosts = boosts; + } + + /** + * Creates a MultiFieldQueryParser. + * + *

It will, when parse(String query) + * is called, construct a query like this (assuming the query consists of + * two terms and you specify the two fields title and body):

+ * + * + * (title:term1 body:term1) (title:term2 body:term2) + * + * + *

When setDefaultOperator(AND_OPERATOR) is set, the result will be:

+ * + * + * +(title:term1 body:term1) +(title:term2 body:term2) + * + * + *

In other words, all the query's terms must appear, but it doesn't matter in + * what fields they appear.

+ */ + public MultiFieldQueryParser(String[] fields, Analyzer analyzer) { + super(null, analyzer); + this.fields = fields; + } + + protected Query getFieldQuery(String field, String queryText, int slop) throws ParseException { + if (field == null) { + List clauses = new ArrayList(); + for (int i = 0; i < fields.length; i++) { + Query q = super.getFieldQuery(fields[i], queryText); + if (q != null) { + //If the user passes a map of boosts + if (boosts != null) { + //Get the boost from the map and apply them + Float boost = (Float)boosts.get(fields[i]); + if (boost != null) { + q.setBoost(boost.floatValue()); + } + } + applySlop(q,slop); + clauses.add(new BooleanClause(q, BooleanClause.Occur.SHOULD)); + } + } + if (clauses.size() == 0) // happens for stopwords + return null; + return getBooleanQuery(clauses, true); + } + Query q = super.getFieldQuery(field, queryText); + applySlop(q,slop); + return q; + } + + private void applySlop(Query q, int slop) { + if (q instanceof PhraseQuery) { + ((PhraseQuery) q).setSlop(slop); + } else if (q instanceof MultiPhraseQuery) { + ((MultiPhraseQuery) q).setSlop(slop); + } + } + + + protected Query getFieldQuery(String field, String queryText) throws ParseException { + return getFieldQuery(field, queryText, 0); + } + + + protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException + { + if (field == null) { + List clauses = new ArrayList(); + for (int i = 0; i < fields.length; i++) { + clauses.add(new BooleanClause(getFuzzyQuery(fields[i], termStr, minSimilarity), + BooleanClause.Occur.SHOULD)); + } + return getBooleanQuery(clauses, true); + } + return super.getFuzzyQuery(field, termStr, minSimilarity); + } + + protected Query getPrefixQuery(String field, String termStr) throws ParseException + { + if (field == null) { + List clauses = new ArrayList(); + for (int i = 0; i < fields.length; i++) { + clauses.add(new BooleanClause(getPrefixQuery(fields[i], termStr), + BooleanClause.Occur.SHOULD)); + } + return getBooleanQuery(clauses, true); + } + return super.getPrefixQuery(field, termStr); + } + + protected Query getWildcardQuery(String field, String termStr) throws ParseException { + if (field == null) { + List clauses = new ArrayList(); + for (int i = 0; i < fields.length; i++) { + clauses.add(new BooleanClause(getWildcardQuery(fields[i], termStr), + BooleanClause.Occur.SHOULD)); + } + return getBooleanQuery(clauses, true); + } + return super.getWildcardQuery(field, termStr); + } + + + protected Query getRangeQuery(String field, String part1, String part2, boolean inclusive) throws ParseException { + if (field == null) { + List clauses = new ArrayList(); + for (int i = 0; i < fields.length; i++) { + clauses.add(new BooleanClause(getRangeQuery(fields[i], part1, part2, inclusive), + BooleanClause.Occur.SHOULD)); + } + return getBooleanQuery(clauses, true); + } + return super.getRangeQuery(field, part1, part2, inclusive); + } + + /** + * Parses a query which searches on the fields specified. + *

+ * If x fields are specified, this effectively constructs: + *

+   * 
+   * (field1:query1) (field2:query2) (field3:query3)...(fieldx:queryx)
+   * 
+   * 
+ * @param queries Queries strings to parse + * @param fields Fields to search on + * @param analyzer Analyzer to use + * @throws ParseException if query parsing fails + * @throws IllegalArgumentException if the length of the queries array differs + * from the length of the fields array + */ + public static Query parse(String[] queries, String[] fields, + Analyzer analyzer) throws ParseException + { + if (queries.length != fields.length) + throw new IllegalArgumentException("queries.length != fields.length"); + BooleanQuery bQuery = new BooleanQuery(); + for (int i = 0; i < fields.length; i++) + { + QueryParser qp = new QueryParser(fields[i], analyzer); + Query q = qp.parse(queries[i]); + if (q!=null && // q never null, just being defensive + (!(q instanceof BooleanQuery) || ((BooleanQuery)q).getClauses().length>0)) { + bQuery.add(q, BooleanClause.Occur.SHOULD); + } + } + return bQuery; + } + + /** + * Parses a query, searching on the fields specified. + * Use this if you need to specify certain fields as required, + * and others as prohibited. + *

+   * Usage:
+   * 
+   * String[] fields = {"filename", "contents", "description"};
+   * BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
+   *                BooleanClause.Occur.MUST,
+   *                BooleanClause.Occur.MUST_NOT};
+   * MultiFieldQueryParser.parse("query", fields, flags, analyzer);
+   * 
+   * 
+ *

+ * The code above would construct a query: + *

+   * 
+   * (filename:query) +(contents:query) -(description:query)
+   * 
+   * 
+ * + * @param query Query string to parse + * @param fields Fields to search on + * @param flags Flags describing the fields + * @param analyzer Analyzer to use + * @throws ParseException if query parsing fails + * @throws IllegalArgumentException if the length of the fields array differs + * from the length of the flags array + */ + public static Query parse(String query, String[] fields, + BooleanClause.Occur[] flags, Analyzer analyzer) throws ParseException { + if (fields.length != flags.length) + throw new IllegalArgumentException("fields.length != flags.length"); + BooleanQuery bQuery = new BooleanQuery(); + for (int i = 0; i < fields.length; i++) { + QueryParser qp = new QueryParser(fields[i], analyzer); + Query q = qp.parse(query); + if (q!=null && // q never null, just being defensive + (!(q instanceof BooleanQuery) || ((BooleanQuery)q).getClauses().length>0)) { + bQuery.add(q, flags[i]); + } + } + return bQuery; + } + + /** + * Parses a query, searching on the fields specified. + * Use this if you need to specify certain fields as required, + * and others as prohibited. + *

+   * Usage:
+   * 
+   * String[] query = {"query1", "query2", "query3"};
+   * String[] fields = {"filename", "contents", "description"};
+   * BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
+   *                BooleanClause.Occur.MUST,
+   *                BooleanClause.Occur.MUST_NOT};
+   * MultiFieldQueryParser.parse(query, fields, flags, analyzer);
+   * 
+   * 
+ *

+ * The code above would construct a query: + *

+   * 
+   * (filename:query1) +(contents:query2) -(description:query3)
+   * 
+   * 
+ * + * @param queries Queries string to parse + * @param fields Fields to search on + * @param flags Flags describing the fields + * @param analyzer Analyzer to use + * @throws ParseException if query parsing fails + * @throws IllegalArgumentException if the length of the queries, fields, + * and flags array differ + */ + public static Query parse(String[] queries, String[] fields, BooleanClause.Occur[] flags, + Analyzer analyzer) throws ParseException + { + if (!(queries.length == fields.length && queries.length == flags.length)) + throw new IllegalArgumentException("queries, fields, and flags array have have different length"); + BooleanQuery bQuery = new BooleanQuery(); + for (int i = 0; i < fields.length; i++) + { + QueryParser qp = new QueryParser(fields[i], analyzer); + Query q = qp.parse(queries[i]); + if (q!=null && // q never null, just being defensive + (!(q instanceof BooleanQuery) || ((BooleanQuery)q).getClauses().length>0)) { + bQuery.add(q, flags[i]); + } + } + return bQuery; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/ParseException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/ParseException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/ParseException.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,198 @@ +/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 4.1 */ +/* JavaCCOptions:KEEP_LINE_COL=null */ +package org.apache.lucene.queryParser; + +/** + * This exception is thrown when parse errors are encountered. + * You can explicitly create objects of this exception type by + * calling the method generateParseException in the generated + * parser. + * + * You can modify this class to customize your error reporting + * mechanisms so long as you retain the public fields. + */ +public class ParseException extends Exception { + + /** + * This constructor is used by the method "generateParseException" + * in the generated parser. Calling this constructor generates + * a new object of this type with the fields "currentToken", + * "expectedTokenSequences", and "tokenImage" set. The boolean + * flag "specialConstructor" is also set to true to indicate that + * this constructor was used to create this object. + * This constructor calls its super class with the empty string + * to force the "toString" method of parent class "Throwable" to + * print the error message in the form: + * ParseException: + */ + public ParseException(Token currentTokenVal, + int[][] expectedTokenSequencesVal, + String[] tokenImageVal + ) + { + super(""); + specialConstructor = true; + currentToken = currentTokenVal; + expectedTokenSequences = expectedTokenSequencesVal; + tokenImage = tokenImageVal; + } + + /** + * The following constructors are for use by you for whatever + * purpose you can think of. Constructing the exception in this + * manner makes the exception behave in the normal way - i.e., as + * documented in the class "Throwable". The fields "errorToken", + * "expectedTokenSequences", and "tokenImage" do not contain + * relevant information. The JavaCC generated code does not use + * these constructors. + */ + + public ParseException() { + super(); + specialConstructor = false; + } + + /** Constructor with message. */ + public ParseException(String message) { + super(message); + specialConstructor = false; + } + + /** + * This variable determines which constructor was used to create + * this object and thereby affects the semantics of the + * "getMessage" method (see below). + */ + protected boolean specialConstructor; + + /** + * This is the last token that has been consumed successfully. If + * this object has been created due to a parse error, the token + * followng this token will (therefore) be the first error token. + */ + public Token currentToken; + + /** + * Each entry in this array is an array of integers. Each array + * of integers represents a sequence of tokens (by their ordinal + * values) that is expected at this point of the parse. + */ + public int[][] expectedTokenSequences; + + /** + * This is a reference to the "tokenImage" array of the generated + * parser within which the parse error occurred. This array is + * defined in the generated ...Constants interface. + */ + public String[] tokenImage; + + /** + * This method has the standard behavior when this object has been + * created using the standard constructors. Otherwise, it uses + * "currentToken" and "expectedTokenSequences" to generate a parse + * error message and returns it. If this object has been created + * due to a parse error, and you do not catch it (it gets thrown + * from the parser), then this method is called during the printing + * of the final stack trace, and hence the correct error message + * gets displayed. + */ + public String getMessage() { + if (!specialConstructor) { + return super.getMessage(); + } + StringBuffer expected = new StringBuffer(); + int maxSize = 0; + for (int i = 0; i < expectedTokenSequences.length; i++) { + if (maxSize < expectedTokenSequences[i].length) { + maxSize = expectedTokenSequences[i].length; + } + for (int j = 0; j < expectedTokenSequences[i].length; j++) { + expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); + } + if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { + expected.append("..."); + } + expected.append(eol).append(" "); + } + String retval = "Encountered \""; + Token tok = currentToken.next; + for (int i = 0; i < maxSize; i++) { + if (i != 0) retval += " "; + if (tok.kind == 0) { + retval += tokenImage[0]; + break; + } + retval += " " + tokenImage[tok.kind]; + retval += " \""; + retval += add_escapes(tok.image); + retval += " \""; + tok = tok.next; + } + retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; + retval += "." + eol; + if (expectedTokenSequences.length == 1) { + retval += "Was expecting:" + eol + " "; + } else { + retval += "Was expecting one of:" + eol + " "; + } + retval += expected.toString(); + return retval; + } + + /** + * The end of line string for this machine. + */ + protected String eol = System.getProperty("line.separator", "\n"); + + /** + * Used to convert raw characters to their escaped version + * when these raw version cannot be used as part of an ASCII + * string literal. + */ + protected String add_escapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + +} +/* JavaCC - OriginalChecksum=c7631a240f7446940695eac31d9483ca (do not edit this line) */ Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParser.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParser.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParser.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,1767 @@ +/* Generated By:JavaCC: Do not edit this line. QueryParser.java */ +package org.apache.lucene.queryParser; + +import java.io.IOException; +import java.io.StringReader; +import java.text.DateFormat; +import java.text.Collator; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.document.DateField; +import org.apache.lucene.document.DateTools; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.ConstantScoreRangeQuery; +import org.apache.lucene.search.FuzzyQuery; +import org.apache.lucene.search.MatchAllDocsQuery; +import org.apache.lucene.search.MultiPhraseQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.RangeQuery; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.WildcardQuery; +import org.apache.lucene.util.Parameter; + +/** + * This class is generated by JavaCC. The most important method is + * {@link #parse(String)}. + * + * The syntax for query strings is as follows: + * A Query is a series of clauses. + * A clause may be prefixed by: + *
    + *
  • a plus (+) or a minus (-) sign, indicating + * that the clause is required or prohibited respectively; or + *
  • a term followed by a colon, indicating the field to be searched. + * This enables one to construct queries which search multiple fields. + *
+ * + * A clause may be either: + *
    + *
  • a term, indicating all the documents that contain this term; or + *
  • a nested query, enclosed in parentheses. Note that this may be used + * with a +/- prefix to require any of a set of + * terms. + *
+ * + * Thus, in BNF, the query grammar is: + *
+ *   Query  ::= ( Clause )*
+ *   Clause ::= ["+", "-"] [<TERM> ":"] ( <TERM> | "(" Query ")" )
+ * 
+ * + *

+ * Examples of appropriately formatted queries can be found in the query syntax + * documentation. + *

+ * + *

+ * In {@link RangeQuery}s, QueryParser tries to detect date values, e.g. + * date:[6/1/2005 TO 6/4/2005] produces a range query that searches + * for "date" fields between 2005-06-01 and 2005-06-04. Note that the format + * of the accepted input depends on {@link #setLocale(Locale) the locale}. + * By default a date is converted into a search term using the deprecated + * {@link DateField} for compatibility reasons. + * To use the new {@link DateTools} to convert dates, a + * {@link org.apache.lucene.document.DateTools.Resolution} has to be set. + *

+ *

+ * The date resolution that shall be used for RangeQueries can be set + * using {@link #setDateResolution(DateTools.Resolution)} + * or {@link #setDateResolution(String, DateTools.Resolution)}. The former + * sets the default date resolution for all fields, whereas the latter can + * be used to set field specific date resolutions. Field specific date + * resolutions take, if set, precedence over the default date resolution. + *

+ *

+ * If you use neither {@link DateField} nor {@link DateTools} in your + * index, you can create your own + * query parser that inherits QueryParser and overwrites + * {@link #getRangeQuery(String, String, String, boolean)} to + * use a different method for date conversion. + *

+ * + *

Note that QueryParser is not thread-safe.

+ * + */ +public class QueryParser implements QueryParserConstants { + + private static final int CONJ_NONE = 0; + private static final int CONJ_AND = 1; + private static final int CONJ_OR = 2; + + private static final int MOD_NONE = 0; + private static final int MOD_NOT = 10; + private static final int MOD_REQ = 11; + + // make it possible to call setDefaultOperator() without accessing + // the nested class: + /** Alternative form of QueryParser.Operator.AND */ + public static final Operator AND_OPERATOR = Operator.AND; + /** Alternative form of QueryParser.Operator.OR */ + public static final Operator OR_OPERATOR = Operator.OR; + + /** The actual operator that parser uses to combine query terms */ + private Operator operator = OR_OPERATOR; + + boolean lowercaseExpandedTerms = true; + boolean useOldRangeQuery= false; + boolean allowLeadingWildcard = false; + boolean enablePositionIncrements = false; + + Analyzer analyzer; + String field; + int phraseSlop = 0; + float fuzzyMinSim = FuzzyQuery.defaultMinSimilarity; + int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength; + Locale locale = Locale.getDefault(); + + // the default date resolution + DateTools.Resolution dateResolution = null; + // maps field names to date resolutions + Map fieldToDateResolution = null; + + // The collator to use when determining range inclusion, + // for use when constructing RangeQuerys and ConstantScoreRangeQuerys. + Collator rangeCollator = null; + + /** The default operator for parsing queries. + * Use {@link QueryParser#setDefaultOperator} to change it. + */ + static public final class Operator extends Parameter { + private Operator(String name) { + super(name); + } + static public final Operator OR = new Operator("OR"); + static public final Operator AND = new Operator("AND"); + } + + + /** Constructs a query parser. + * @param f the default field for query terms. + * @param a used to find terms in the query text. + */ + public QueryParser(String f, Analyzer a) { + this(new FastCharStream(new StringReader(""))); + analyzer = a; + field = f; + } + + /** Parses a query string, returning a {@link org.apache.lucene.search.Query}. + * @param query the query string to be parsed. + * @throws ParseException if the parsing fails + */ + public Query parse(String query) throws ParseException { + ReInit(new FastCharStream(new StringReader(query))); + try { + // TopLevelQuery is a Query followed by the end-of-input (EOF) + Query res = TopLevelQuery(field); + return res!=null ? res : newBooleanQuery(false); + } + catch (ParseException tme) { + // rethrow to include the original query: + throw new ParseException("Cannot parse '" +query+ "': " + tme.getMessage()); + } + catch (TokenMgrError tme) { + throw new ParseException("Cannot parse '" +query+ "': " + tme.getMessage()); + } + catch (BooleanQuery.TooManyClauses tmc) { + throw new ParseException("Cannot parse '" +query+ "': too many boolean clauses"); + } + } + + /** + * @return Returns the analyzer. + */ + public Analyzer getAnalyzer() { + return analyzer; + } + + /** + * @return Returns the field. + */ + public String getField() { + return field; + } + + /** + * Get the minimal similarity for fuzzy queries. + */ + public float getFuzzyMinSim() { + return fuzzyMinSim; + } + + /** + * Set the minimum similarity for fuzzy queries. + * Default is 0.5f. + */ + public void setFuzzyMinSim(float fuzzyMinSim) { + this.fuzzyMinSim = fuzzyMinSim; + } + + /** + * Get the prefix length for fuzzy queries. + * @return Returns the fuzzyPrefixLength. + */ + public int getFuzzyPrefixLength() { + return fuzzyPrefixLength; + } + + /** + * Set the prefix length for fuzzy queries. Default is 0. + * @param fuzzyPrefixLength The fuzzyPrefixLength to set. + */ + public void setFuzzyPrefixLength(int fuzzyPrefixLength) { + this.fuzzyPrefixLength = fuzzyPrefixLength; + } + + /** + * Sets the default slop for phrases. If zero, then exact phrase matches + * are required. Default value is zero. + */ + public void setPhraseSlop(int phraseSlop) { + this.phraseSlop = phraseSlop; + } + + /** + * Gets the default slop for phrases. + */ + public int getPhraseSlop() { + return phraseSlop; + } + + + /** + * Set to true to allow leading wildcard characters. + *

+ * When set, * or ? are allowed as + * the first character of a PrefixQuery and WildcardQuery. + * Note that this can produce very slow + * queries on big indexes. + *

+ * Default: false. + */ + public void setAllowLeadingWildcard(boolean allowLeadingWildcard) { + this.allowLeadingWildcard = allowLeadingWildcard; + } + + /** + * @see #setAllowLeadingWildcard(boolean) + */ + public boolean getAllowLeadingWildcard() { + return allowLeadingWildcard; + } + + /** + * Set to true to enable position increments in result query. + *

+ * When set, result phrase and multi-phrase queries will + * be aware of position increments. + * Useful when e.g. a StopFilter increases the position increment of + * the token that follows an omitted token. + *

+ * Default: false. + */ + public void setEnablePositionIncrements(boolean enable) { + this.enablePositionIncrements = enable; + } + + /** + * @see #setEnablePositionIncrements(boolean) + */ + public boolean getEnablePositionIncrements() { + return enablePositionIncrements; + } + + /** + * Sets the boolean operator of the QueryParser. + * In default mode (OR_OPERATOR) terms without any modifiers + * are considered optional: for example capital of Hungary is equal to + * capital OR of OR Hungary.
+ * In AND_OPERATOR mode terms are considered to be in conjunction: the + * above mentioned query is parsed as capital AND of AND Hungary + */ + public void setDefaultOperator(Operator op) { + this.operator = op; + } + + + /** + * Gets implicit operator setting, which will be either AND_OPERATOR + * or OR_OPERATOR. + */ + public Operator getDefaultOperator() { + return operator; + } + + + /** + * Whether terms of wildcard, prefix, fuzzy and range queries are to be automatically + * lower-cased or not. Default is true. + */ + public void setLowercaseExpandedTerms(boolean lowercaseExpandedTerms) { + this.lowercaseExpandedTerms = lowercaseExpandedTerms; + } + + + /** + * @see #setLowercaseExpandedTerms(boolean) + */ + public boolean getLowercaseExpandedTerms() { + return lowercaseExpandedTerms; + } + + /** + * By default QueryParser uses new ConstantScoreRangeQuery in preference to RangeQuery + * for range queries. This implementation is generally preferable because it + * a) Runs faster b) Does not have the scarcity of range terms unduly influence score + * c) avoids any "TooManyBooleanClauses" exception. + * However, if your application really needs to use the old-fashioned RangeQuery and the above + * points are not required then set this option to true + * Default is false. + */ + public void setUseOldRangeQuery(boolean useOldRangeQuery) { + this.useOldRangeQuery = useOldRangeQuery; + } + + + /** + * @see #setUseOldRangeQuery(boolean) + */ + public boolean getUseOldRangeQuery() { + return useOldRangeQuery; + } + + /** + * Set locale used by date range parsing. + */ + public void setLocale(Locale locale) { + this.locale = locale; + } + + /** + * Returns current locale, allowing access by subclasses. + */ + public Locale getLocale() { + return locale; + } + + /** + * Sets the default date resolution used by RangeQueries for fields for which no + * specific date resolutions has been set. Field specific resolutions can be set + * with {@link #setDateResolution(String, DateTools.Resolution)}. + * + * @param dateResolution the default date resolution to set + */ + public void setDateResolution(DateTools.Resolution dateResolution) { + this.dateResolution = dateResolution; + } + + /** + * Sets the date resolution used by RangeQueries for a specific field. + * + * @param fieldName field for which the date resolution is to be set + * @param dateResolution date resolution to set + */ + public void setDateResolution(String fieldName, DateTools.Resolution dateResolution) { + if (fieldName == null) { + throw new IllegalArgumentException("Field cannot be null."); + } + + if (fieldToDateResolution == null) { + // lazily initialize HashMap + fieldToDateResolution = new HashMap(); + } + + fieldToDateResolution.put(fieldName, dateResolution); + } + + /** + * Returns the date resolution that is used by RangeQueries for the given field. + * Returns null, if no default or field specific date resolution has been set + * for the given field. + * + */ + public DateTools.Resolution getDateResolution(String fieldName) { + if (fieldName == null) { + throw new IllegalArgumentException("Field cannot be null."); + } + + if (fieldToDateResolution == null) { + // no field specific date resolutions set; return default date resolution instead + return this.dateResolution; + } + + DateTools.Resolution resolution = (DateTools.Resolution) fieldToDateResolution.get(fieldName); + if (resolution == null) { + // no date resolutions set for the given field; return default date resolution instead + resolution = this.dateResolution; + } + + return resolution; + } + + /** + * Sets the collator used to determine index term inclusion in ranges + * specified either for ConstantScoreRangeQuerys or RangeQuerys (if + * {@link #setUseOldRangeQuery(boolean)} is called with a true + * value.) + *

+ * WARNING: Setting the rangeCollator to a non-null + * collator using this method will cause every single index Term in the + * Field referenced by lowerTerm and/or upperTerm to be examined. + * Depending on the number of index Terms in this Field, the operation could + * be very slow. + * + * @param rc the collator to use when constructing RangeQuerys + * and ConstantScoreRangeQuerys + */ + public void setRangeCollator(Collator rc) { + rangeCollator = rc; + } + + /** + * @return the collator used to determine index term inclusion in ranges + * specified either for ConstantScoreRangeQuerys or RangeQuerys (if + * {@link #setUseOldRangeQuery(boolean)} is called with a true + * value.) + */ + public Collator getRangeCollator() { + return rangeCollator; + } + + /** + * @deprecated use {@link #addClause(List, int, int, Query)} instead. + */ + protected void addClause(Vector clauses, int conj, int mods, Query q) { + addClause((List) clauses, conj, mods, q); + } + + protected void addClause(List clauses, int conj, int mods, Query q) { + boolean required, prohibited; + + // If this term is introduced by AND, make the preceding term required, + // unless it's already prohibited + if (clauses.size() > 0 && conj == CONJ_AND) { + BooleanClause c = (BooleanClause) clauses.get(clauses.size()-1); + if (!c.isProhibited()) + c.setOccur(BooleanClause.Occur.MUST); + } + + if (clauses.size() > 0 && operator == AND_OPERATOR && conj == CONJ_OR) { + // If this term is introduced by OR, make the preceding term optional, + // unless it's prohibited (that means we leave -a OR b but +a OR b-->a OR b) + // notice if the input is a OR b, first term is parsed as required; without + // this modification a OR b would parsed as +a OR b + BooleanClause c = (BooleanClause) clauses.get(clauses.size()-1); + if (!c.isProhibited()) + c.setOccur(BooleanClause.Occur.SHOULD); + } + + // We might have been passed a null query; the term might have been + // filtered away by the analyzer. + if (q == null) + return; + + if (operator == OR_OPERATOR) { + // We set REQUIRED if we're introduced by AND or +; PROHIBITED if + // introduced by NOT or -; make sure not to set both. + prohibited = (mods == MOD_NOT); + required = (mods == MOD_REQ); + if (conj == CONJ_AND && !prohibited) { + required = true; + } + } else { + // We set PROHIBITED if we're introduced by NOT or -; We set REQUIRED + // if not PROHIBITED and not introduced by OR + prohibited = (mods == MOD_NOT); + required = (!prohibited && conj != CONJ_OR); + } + if (required && !prohibited) + clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST)); + else if (!required && !prohibited) + clauses.add(newBooleanClause(q, BooleanClause.Occur.SHOULD)); + else if (!required && prohibited) + clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST_NOT)); + else + throw new RuntimeException("Clause cannot be both required and prohibited"); + } + + + /** + * @exception ParseException throw in overridden method to disallow + */ + protected Query getFieldQuery(String field, String queryText) throws ParseException { + // Use the analyzer to get all the tokens, and then build a TermQuery, + // PhraseQuery, or nothing based on the term count + + TokenStream source = analyzer.tokenStream(field, new StringReader(queryText)); + List list = new ArrayList(); + final org.apache.lucene.analysis.Token reusableToken = new org.apache.lucene.analysis.Token(); + org.apache.lucene.analysis.Token nextToken; + int positionCount = 0; + boolean severalTokensAtSamePosition = false; + + while (true) { + try { + nextToken = source.next(reusableToken); + } + catch (IOException e) { + nextToken = null; + } + if (nextToken == null) + break; + list.add(nextToken.clone()); + if (nextToken.getPositionIncrement() != 0) + positionCount += nextToken.getPositionIncrement(); + else + severalTokensAtSamePosition = true; + } + try { + source.close(); + } + catch (IOException e) { + // ignore + } + + if (list.size() == 0) + return null; + else if (list.size() == 1) { + nextToken = (org.apache.lucene.analysis.Token) list.get(0); + return newTermQuery(new Term(field, nextToken.term())); + } else { + if (severalTokensAtSamePosition) { + if (positionCount == 1) { + // no phrase query: + BooleanQuery q = newBooleanQuery(true); + for (int i = 0; i < list.size(); i++) { + nextToken = (org.apache.lucene.analysis.Token) list.get(i); + Query currentQuery = newTermQuery( + new Term(field, nextToken.term())); + q.add(currentQuery, BooleanClause.Occur.SHOULD); + } + return q; + } + else { + // phrase query: + MultiPhraseQuery mpq = newMultiPhraseQuery(); + mpq.setSlop(phraseSlop); + List multiTerms = new ArrayList(); + int position = -1; + for (int i = 0; i < list.size(); i++) { + nextToken = (org.apache.lucene.analysis.Token) list.get(i); + if (nextToken.getPositionIncrement() > 0 && multiTerms.size() > 0) { + if (enablePositionIncrements) { + mpq.add((Term[])multiTerms.toArray(new Term[0]),position); + } else { + mpq.add((Term[])multiTerms.toArray(new Term[0])); + } + multiTerms.clear(); + } + position += nextToken.getPositionIncrement(); + multiTerms.add(new Term(field, nextToken.term())); + } + if (enablePositionIncrements) { + mpq.add((Term[])multiTerms.toArray(new Term[0]),position); + } else { + mpq.add((Term[])multiTerms.toArray(new Term[0])); + } + return mpq; + } + } + else { + PhraseQuery pq = newPhraseQuery(); + pq.setSlop(phraseSlop); + int position = -1; + for (int i = 0; i < list.size(); i++) { + nextToken = (org.apache.lucene.analysis.Token) list.get(i); + if (enablePositionIncrements) { + position += nextToken.getPositionIncrement(); + pq.add(new Term(field, nextToken.term()),position); + } else { + pq.add(new Term(field, nextToken.term())); + } + } + return pq; + } + } + } + + + /** + * Base implementation delegates to {@link #getFieldQuery(String,String)}. + * This method may be overridden, for example, to return + * a SpanNearQuery instead of a PhraseQuery. + * + * @exception ParseException throw in overridden method to disallow + */ + protected Query getFieldQuery(String field, String queryText, int slop) + throws ParseException { + Query query = getFieldQuery(field, queryText); + + if (query instanceof PhraseQuery) { + ((PhraseQuery) query).setSlop(slop); + } + if (query instanceof MultiPhraseQuery) { + ((MultiPhraseQuery) query).setSlop(slop); + } + + return query; + } + + + /** + * @exception ParseException throw in overridden method to disallow + */ + protected Query getRangeQuery(String field, + String part1, + String part2, + boolean inclusive) throws ParseException + { + if (lowercaseExpandedTerms) { + part1 = part1.toLowerCase(); + part2 = part2.toLowerCase(); + } + try { + DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale); + df.setLenient(true); + Date d1 = df.parse(part1); + Date d2 = df.parse(part2); + if (inclusive) { + // The user can only specify the date, not the time, so make sure + // the time is set to the latest possible time of that date to really + // include all documents: + Calendar cal = Calendar.getInstance(locale); + cal.setTime(d2); + cal.set(Calendar.HOUR_OF_DAY, 23); + cal.set(Calendar.MINUTE, 59); + cal.set(Calendar.SECOND, 59); + cal.set(Calendar.MILLISECOND, 999); + d2 = cal.getTime(); + } + DateTools.Resolution resolution = getDateResolution(field); + if (resolution == null) { + // no default or field specific date resolution has been set, + // use deprecated DateField to maintain compatibilty with + // pre-1.9 Lucene versions. + part1 = DateField.dateToString(d1); + part2 = DateField.dateToString(d2); + } else { + part1 = DateTools.dateToString(d1, resolution); + part2 = DateTools.dateToString(d2, resolution); + } + } + catch (Exception e) { } + + return newRangeQuery(field, part1, part2, inclusive); + } + + /** + * Builds a new BooleanQuery instance + * @param disableCoord disable coord + * @return new BooleanQuery instance + */ + protected BooleanQuery newBooleanQuery(boolean disableCoord) { + return new BooleanQuery(disableCoord); + } + + /** + * Builds a new BooleanClause instance + * @param q sub query + * @param occur how this clause should occur when matching documents + * @return new BooleanClause instance + */ + protected BooleanClause newBooleanClause(Query q, BooleanClause.Occur occur) { + return new BooleanClause(q, occur); + } + + /** + * Builds a new TermQuery instance + * @param term term + * @return new TermQuery instance + */ + protected Query newTermQuery(Term term){ + return new TermQuery(term); + } + + /** + * Builds a new PhraseQuery instance + * @return new PhraseQuery instance + */ + protected PhraseQuery newPhraseQuery(){ + return new PhraseQuery(); + } + + /** + * Builds a new MultiPhraseQuery instance + * @return new MultiPhraseQuery instance + */ + protected MultiPhraseQuery newMultiPhraseQuery(){ + return new MultiPhraseQuery(); + } + + /** + * Builds a new PrefixQuery instance + * @param prefix Prefix term + * @return new PrefixQuery instance + */ + protected Query newPrefixQuery(Term prefix){ + return new PrefixQuery(prefix); + } + + /** + * Builds a new FuzzyQuery instance + * @param term Term + * @param minimumSimilarity minimum similarity + * @param prefixLength prefix length + * @return new FuzzyQuery Instance + */ + protected Query newFuzzyQuery(Term term, float minimumSimilarity, int prefixLength) { + return new FuzzyQuery(term,minimumSimilarity,prefixLength); + } + + /** + * Builds a new RangeQuery instance + * @param field Field + * @param part1 min + * @param part2 max + * @param inclusive true if range is inclusive + * @return new RangeQuery instance + */ + protected Query newRangeQuery(String field, String part1, String part2, boolean inclusive) { + if(useOldRangeQuery) + { + return new RangeQuery(new Term(field, part1), + new Term(field, part2), + inclusive, rangeCollator); + } + else + { + return new ConstantScoreRangeQuery + (field, part1, part2, inclusive, inclusive, rangeCollator); + } + } + + /** + * Builds a new MatchAllDocsQuery instance + * @return new MatchAllDocsQuery instance + */ + protected Query newMatchAllDocsQuery() { + return new MatchAllDocsQuery(); + } + + /** + * Builds a new WildcardQuery instance + * @param t wildcard term + * @return new WildcardQuery instance + */ + protected Query newWildcardQuery(Term t) { + return new WildcardQuery(t); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + * @deprecated use {@link #getBooleanQuery(List)} instead + */ + protected Query getBooleanQuery(Vector clauses) throws ParseException { + return getBooleanQuery((List) clauses, false); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + */ + protected Query getBooleanQuery(List clauses) throws ParseException { + return getBooleanQuery(clauses, false); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * @param disableCoord true if coord scoring should be disabled. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + * @deprecated use {@link #getBooleanQuery(List, boolean)} instead + */ + protected Query getBooleanQuery(Vector clauses, boolean disableCoord) + throws ParseException + { + return getBooleanQuery((List) clauses, disableCoord); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * @param disableCoord true if coord scoring should be disabled. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + */ + protected Query getBooleanQuery(List clauses, boolean disableCoord) + throws ParseException + { + if (clauses.size()==0) { + return null; // all clause words were filtered away by the analyzer. + } + BooleanQuery query = newBooleanQuery(disableCoord); + for (int i = 0; i < clauses.size(); i++) { + query.add((BooleanClause)clauses.get(i)); + } + return query; + } + + /** + * Factory method for generating a query. Called when parser + * parses an input term token that contains one or more wildcard + * characters (? and *), but is not a prefix term token (one + * that has just a single * character at the end) + *

+ * Depending on settings, prefix term may be lower-cased + * automatically. It will not go through the default Analyzer, + * however, since normal Analyzers are unlikely to work properly + * with wildcard templates. + *

+ * Can be overridden by extending classes, to provide custom handling for + * wildcard queries, which may be necessary due to missing analyzer calls. + * + * @param field Name of the field query will use. + * @param termStr Term token that contains one or more wild card + * characters (? or *), but is not simple prefix term + * + * @return Resulting {@link Query} built for the term + * @exception ParseException throw in overridden method to disallow + */ + protected Query getWildcardQuery(String field, String termStr) throws ParseException + { + if ("*".equals(field)) { + if ("*".equals(termStr)) return newMatchAllDocsQuery(); + } + if (!allowLeadingWildcard && (termStr.startsWith("*") || termStr.startsWith("?"))) + throw new ParseException("'*' or '?' not allowed as first character in WildcardQuery"); + if (lowercaseExpandedTerms) { + termStr = termStr.toLowerCase(); + } + Term t = new Term(field, termStr); + return newWildcardQuery(t); + } + + /** + * Factory method for generating a query (similar to + * {@link #getWildcardQuery}). Called when parser parses an input term + * token that uses prefix notation; that is, contains a single '*' wildcard + * character as its last character. Since this is a special case + * of generic wildcard term, and such a query can be optimized easily, + * this usually results in a different query object. + *

+ * Depending on settings, a prefix term may be lower-cased + * automatically. It will not go through the default Analyzer, + * however, since normal Analyzers are unlikely to work properly + * with wildcard templates. + *

+ * Can be overridden by extending classes, to provide custom handling for + * wild card queries, which may be necessary due to missing analyzer calls. + * + * @param field Name of the field query will use. + * @param termStr Term token to use for building term for the query + * (without trailing '*' character!) + * + * @return Resulting {@link Query} built for the term + * @exception ParseException throw in overridden method to disallow + */ + protected Query getPrefixQuery(String field, String termStr) throws ParseException + { + if (!allowLeadingWildcard && termStr.startsWith("*")) + throw new ParseException("'*' not allowed as first character in PrefixQuery"); + if (lowercaseExpandedTerms) { + termStr = termStr.toLowerCase(); + } + Term t = new Term(field, termStr); + return newPrefixQuery(t); + } + + /** + * Factory method for generating a query (similar to + * {@link #getWildcardQuery}). Called when parser parses + * an input term token that has the fuzzy suffix (~) appended. + * + * @param field Name of the field query will use. + * @param termStr Term token to use for building term for the query + * + * @return Resulting {@link Query} built for the term + * @exception ParseException throw in overridden method to disallow + */ + protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException + { + if (lowercaseExpandedTerms) { + termStr = termStr.toLowerCase(); + } + Term t = new Term(field, termStr); + return newFuzzyQuery(t, minSimilarity, fuzzyPrefixLength); + } + + /** + * Returns a String where the escape char has been + * removed, or kept only once if there was a double escape. + * + * Supports escaped unicode characters, e. g. translates + * \\u0041 to A. + * + */ + private String discardEscapeChar(String input) throws ParseException { + // Create char array to hold unescaped char sequence + char[] output = new char[input.length()]; + + // The length of the output can be less than the input + // due to discarded escape chars. This variable holds + // the actual length of the output + int length = 0; + + // We remember whether the last processed character was + // an escape character + boolean lastCharWasEscapeChar = false; + + // The multiplier the current unicode digit must be multiplied with. + // E. g. the first digit must be multiplied with 16^3, the second with 16^2... + int codePointMultiplier = 0; + + // Used to calculate the codepoint of the escaped unicode character + int codePoint = 0; + + for (int i = 0; i < input.length(); i++) { + char curChar = input.charAt(i); + if (codePointMultiplier > 0) { + codePoint += hexToInt(curChar) * codePointMultiplier; + codePointMultiplier >>>= 4; + if (codePointMultiplier == 0) { + output[length++] = (char)codePoint; + codePoint = 0; + } + } else if (lastCharWasEscapeChar) { + if (curChar == 'u') { + // found an escaped unicode character + codePointMultiplier = 16 * 16 * 16; + } else { + // this character was escaped + output[length] = curChar; + length++; + } + lastCharWasEscapeChar = false; + } else { + if (curChar == '\\') { + lastCharWasEscapeChar = true; + } else { + output[length] = curChar; + length++; + } + } + } + + if (codePointMultiplier > 0) { + throw new ParseException("Truncated unicode escape sequence."); + } + + if (lastCharWasEscapeChar) { + throw new ParseException("Term can not end with escape character."); + } + + return new String(output, 0, length); + } + + /** Returns the numeric value of the hexadecimal character */ + private static final int hexToInt(char c) throws ParseException { + if ('0' <= c && c <= '9') { + return c - '0'; + } else if ('a' <= c && c <= 'f'){ + return c - 'a' + 10; + } else if ('A' <= c && c <= 'F') { + return c - 'A' + 10; + } else { + throw new ParseException("None-hex character in unicode escape sequence: " + c); + } + } + + /** + * Returns a String where those characters that QueryParser + * expects to be escaped are escaped by a preceding \. + */ + public static String escape(String s) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + // These characters are part of the query syntax and must be escaped + if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':' + || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~' + || c == '*' || c == '?' || c == '|' || c == '&') { + sb.append('\\'); + } + sb.append(c); + } + return sb.toString(); + } + + /** + * Command line tool to test QueryParser, using {@link org.apache.lucene.analysis.SimpleAnalyzer}. + * Usage:
+ * java org.apache.lucene.queryParser.QueryParser <input> + */ + public static void main(String[] args) throws Exception { + if (args.length == 0) { + System.out.println("Usage: java org.apache.lucene.queryParser.QueryParser "); + System.exit(0); + } + QueryParser qp = new QueryParser("field", + new org.apache.lucene.analysis.SimpleAnalyzer()); + Query q = qp.parse(args[0]); + System.out.println(q.toString("field")); + } + +// * Query ::= ( Clause )* +// * Clause ::= ["+", "-"] [ ":"] ( | "(" Query ")" ) + final public int Conjunction() throws ParseException { + int ret = CONJ_NONE; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case AND: + case OR: + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case AND: + jj_consume_token(AND); + ret = CONJ_AND; + break; + case OR: + jj_consume_token(OR); + ret = CONJ_OR; + break; + default: + jj_la1[0] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + break; + default: + jj_la1[1] = jj_gen; + ; + } + {if (true) return ret;} + throw new Error("Missing return statement in function"); + } + + final public int Modifiers() throws ParseException { + int ret = MOD_NONE; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case NOT: + case PLUS: + case MINUS: + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case PLUS: + jj_consume_token(PLUS); + ret = MOD_REQ; + break; + case MINUS: + jj_consume_token(MINUS); + ret = MOD_NOT; + break; + case NOT: + jj_consume_token(NOT); + ret = MOD_NOT; + break; + default: + jj_la1[2] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + break; + default: + jj_la1[3] = jj_gen; + ; + } + {if (true) return ret;} + throw new Error("Missing return statement in function"); + } + +// This makes sure that there is no garbage after the query string + final public Query TopLevelQuery(String field) throws ParseException { + Query q; + q = Query(field); + jj_consume_token(0); + {if (true) return q;} + throw new Error("Missing return statement in function"); + } + + final public Query Query(String field) throws ParseException { + List clauses = new ArrayList(); + Query q, firstQuery=null; + int conj, mods; + mods = Modifiers(); + q = Clause(field); + addClause(clauses, CONJ_NONE, mods, q); + if (mods == MOD_NONE) + firstQuery=q; + label_1: + while (true) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case AND: + case OR: + case NOT: + case PLUS: + case MINUS: + case LPAREN: + case STAR: + case QUOTED: + case TERM: + case PREFIXTERM: + case WILDTERM: + case RANGEIN_START: + case RANGEEX_START: + case NUMBER: + ; + break; + default: + jj_la1[4] = jj_gen; + break label_1; + } + conj = Conjunction(); + mods = Modifiers(); + q = Clause(field); + addClause(clauses, conj, mods, q); + } + if (clauses.size() == 1 && firstQuery != null) + {if (true) return firstQuery;} + else { + {if (true) return getBooleanQuery(clauses);} + } + throw new Error("Missing return statement in function"); + } + + final public Query Clause(String field) throws ParseException { + Query q; + Token fieldToken=null, boost=null; + if (jj_2_1(2)) { + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case TERM: + fieldToken = jj_consume_token(TERM); + jj_consume_token(COLON); + field=discardEscapeChar(fieldToken.image); + break; + case STAR: + jj_consume_token(STAR); + jj_consume_token(COLON); + field="*"; + break; + default: + jj_la1[5] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } else { + ; + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case STAR: + case QUOTED: + case TERM: + case PREFIXTERM: + case WILDTERM: + case RANGEIN_START: + case RANGEEX_START: + case NUMBER: + q = Term(field); + break; + case LPAREN: + jj_consume_token(LPAREN); + q = Query(field); + jj_consume_token(RPAREN); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case CARAT: + jj_consume_token(CARAT); + boost = jj_consume_token(NUMBER); + break; + default: + jj_la1[6] = jj_gen; + ; + } + break; + default: + jj_la1[7] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + if (boost != null) { + float f = (float)1.0; + try { + f = Float.valueOf(boost.image).floatValue(); + q.setBoost(f); + } catch (Exception ignored) { } + } + {if (true) return q;} + throw new Error("Missing return statement in function"); + } + + final public Query Term(String field) throws ParseException { + Token term, boost=null, fuzzySlop=null, goop1, goop2; + boolean prefix = false; + boolean wildcard = false; + boolean fuzzy = false; + boolean rangein = false; + Query q; + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case STAR: + case TERM: + case PREFIXTERM: + case WILDTERM: + case NUMBER: + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case TERM: + term = jj_consume_token(TERM); + break; + case STAR: + term = jj_consume_token(STAR); + wildcard=true; + break; + case PREFIXTERM: + term = jj_consume_token(PREFIXTERM); + prefix=true; + break; + case WILDTERM: + term = jj_consume_token(WILDTERM); + wildcard=true; + break; + case NUMBER: + term = jj_consume_token(NUMBER); + break; + default: + jj_la1[8] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case FUZZY_SLOP: + fuzzySlop = jj_consume_token(FUZZY_SLOP); + fuzzy=true; + break; + default: + jj_la1[9] = jj_gen; + ; + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case CARAT: + jj_consume_token(CARAT); + boost = jj_consume_token(NUMBER); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case FUZZY_SLOP: + fuzzySlop = jj_consume_token(FUZZY_SLOP); + fuzzy=true; + break; + default: + jj_la1[10] = jj_gen; + ; + } + break; + default: + jj_la1[11] = jj_gen; + ; + } + String termImage=discardEscapeChar(term.image); + if (wildcard) { + q = getWildcardQuery(field, termImage); + } else if (prefix) { + q = getPrefixQuery(field, + discardEscapeChar(term.image.substring + (0, term.image.length()-1))); + } else if (fuzzy) { + float fms = fuzzyMinSim; + try { + fms = Float.valueOf(fuzzySlop.image.substring(1)).floatValue(); + } catch (Exception ignored) { } + if(fms < 0.0f || fms > 1.0f){ + {if (true) throw new ParseException("Minimum similarity for a FuzzyQuery has to be between 0.0f and 1.0f !");} + } + q = getFuzzyQuery(field, termImage,fms); + } else { + q = getFieldQuery(field, termImage); + } + break; + case RANGEIN_START: + jj_consume_token(RANGEIN_START); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case RANGEIN_GOOP: + goop1 = jj_consume_token(RANGEIN_GOOP); + break; + case RANGEIN_QUOTED: + goop1 = jj_consume_token(RANGEIN_QUOTED); + break; + default: + jj_la1[12] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case RANGEIN_TO: + jj_consume_token(RANGEIN_TO); + break; + default: + jj_la1[13] = jj_gen; + ; + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case RANGEIN_GOOP: + goop2 = jj_consume_token(RANGEIN_GOOP); + break; + case RANGEIN_QUOTED: + goop2 = jj_consume_token(RANGEIN_QUOTED); + break; + default: + jj_la1[14] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + jj_consume_token(RANGEIN_END); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case CARAT: + jj_consume_token(CARAT); + boost = jj_consume_token(NUMBER); + break; + default: + jj_la1[15] = jj_gen; + ; + } + if (goop1.kind == RANGEIN_QUOTED) { + goop1.image = goop1.image.substring(1, goop1.image.length()-1); + } + if (goop2.kind == RANGEIN_QUOTED) { + goop2.image = goop2.image.substring(1, goop2.image.length()-1); + } + q = getRangeQuery(field, discardEscapeChar(goop1.image), discardEscapeChar(goop2.image), true); + break; + case RANGEEX_START: + jj_consume_token(RANGEEX_START); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case RANGEEX_GOOP: + goop1 = jj_consume_token(RANGEEX_GOOP); + break; + case RANGEEX_QUOTED: + goop1 = jj_consume_token(RANGEEX_QUOTED); + break; + default: + jj_la1[16] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case RANGEEX_TO: + jj_consume_token(RANGEEX_TO); + break; + default: + jj_la1[17] = jj_gen; + ; + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case RANGEEX_GOOP: + goop2 = jj_consume_token(RANGEEX_GOOP); + break; + case RANGEEX_QUOTED: + goop2 = jj_consume_token(RANGEEX_QUOTED); + break; + default: + jj_la1[18] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + jj_consume_token(RANGEEX_END); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case CARAT: + jj_consume_token(CARAT); + boost = jj_consume_token(NUMBER); + break; + default: + jj_la1[19] = jj_gen; + ; + } + if (goop1.kind == RANGEEX_QUOTED) { + goop1.image = goop1.image.substring(1, goop1.image.length()-1); + } + if (goop2.kind == RANGEEX_QUOTED) { + goop2.image = goop2.image.substring(1, goop2.image.length()-1); + } + + q = getRangeQuery(field, discardEscapeChar(goop1.image), discardEscapeChar(goop2.image), false); + break; + case QUOTED: + term = jj_consume_token(QUOTED); + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case FUZZY_SLOP: + fuzzySlop = jj_consume_token(FUZZY_SLOP); + break; + default: + jj_la1[20] = jj_gen; + ; + } + switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + case CARAT: + jj_consume_token(CARAT); + boost = jj_consume_token(NUMBER); + break; + default: + jj_la1[21] = jj_gen; + ; + } + int s = phraseSlop; + + if (fuzzySlop != null) { + try { + s = Float.valueOf(fuzzySlop.image.substring(1)).intValue(); + } + catch (Exception ignored) { } + } + q = getFieldQuery(field, discardEscapeChar(term.image.substring(1, term.image.length()-1)), s); + break; + default: + jj_la1[22] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + if (boost != null) { + float f = (float) 1.0; + try { + f = Float.valueOf(boost.image).floatValue(); + } + catch (Exception ignored) { + /* Should this be handled somehow? (defaults to "no boost", if + * boost number is invalid) + */ + } + + // avoid boosting null queries, such as those caused by stop words + if (q != null) { + q.setBoost(f); + } + } + {if (true) return q;} + throw new Error("Missing return statement in function"); + } + + private boolean jj_2_1(int xla) { + jj_la = xla; jj_lastpos = jj_scanpos = token; + try { return !jj_3_1(); } + catch(LookaheadSuccess ls) { return true; } + finally { jj_save(0, xla); } + } + + private boolean jj_3R_3() { + if (jj_scan_token(STAR)) return true; + if (jj_scan_token(COLON)) return true; + return false; + } + + private boolean jj_3R_2() { + if (jj_scan_token(TERM)) return true; + if (jj_scan_token(COLON)) return true; + return false; + } + + private boolean jj_3_1() { + Token xsp; + xsp = jj_scanpos; + if (jj_3R_2()) { + jj_scanpos = xsp; + if (jj_3R_3()) return true; + } + return false; + } + + /** Generated Token Manager. */ + public QueryParserTokenManager token_source; + /** Current token. */ + public Token token; + /** Next token. */ + public Token jj_nt; + private int jj_ntk; + private Token jj_scanpos, jj_lastpos; + private int jj_la; + private int jj_gen; + final private int[] jj_la1 = new int[23]; + static private int[] jj_la1_0; + static private int[] jj_la1_1; + static { + jj_la1_init_0(); + jj_la1_init_1(); + } + private static void jj_la1_init_0() { + jj_la1_0 = new int[] {0x300,0x300,0x1c00,0x1c00,0x3ed3f00,0x90000,0x20000,0x3ed2000,0x2690000,0x100000,0x100000,0x20000,0x30000000,0x4000000,0x30000000,0x20000,0x0,0x40000000,0x0,0x20000,0x100000,0x20000,0x3ed0000,}; + } + private static void jj_la1_init_1() { + jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0x0,0x3,0x0,0x0,0x0,0x0,}; + } + final private JJCalls[] jj_2_rtns = new JJCalls[1]; + private boolean jj_rescan = false; + private int jj_gc = 0; + + /** Constructor with user supplied CharStream. */ + public QueryParser(CharStream stream) { + token_source = new QueryParserTokenManager(stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 23; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Reinitialise. */ + public void ReInit(CharStream stream) { + token_source.ReInit(stream); + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 23; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Constructor with generated Token Manager. */ + public QueryParser(QueryParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 23; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + /** Reinitialise. */ + public void ReInit(QueryParserTokenManager tm) { + token_source = tm; + token = new Token(); + jj_ntk = -1; + jj_gen = 0; + for (int i = 0; i < 23; i++) jj_la1[i] = -1; + for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + } + + private Token jj_consume_token(int kind) throws ParseException { + Token oldToken; + if ((oldToken = token).next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + if (token.kind == kind) { + jj_gen++; + if (++jj_gc > 100) { + jj_gc = 0; + for (int i = 0; i < jj_2_rtns.length; i++) { + JJCalls c = jj_2_rtns[i]; + while (c != null) { + if (c.gen < jj_gen) c.first = null; + c = c.next; + } + } + } + return token; + } + token = oldToken; + jj_kind = kind; + throw generateParseException(); + } + + static private final class LookaheadSuccess extends java.lang.Error { } + final private LookaheadSuccess jj_ls = new LookaheadSuccess(); + private boolean jj_scan_token(int kind) { + if (jj_scanpos == jj_lastpos) { + jj_la--; + if (jj_scanpos.next == null) { + jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); + } else { + jj_lastpos = jj_scanpos = jj_scanpos.next; + } + } else { + jj_scanpos = jj_scanpos.next; + } + if (jj_rescan) { + int i = 0; Token tok = token; + while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } + if (tok != null) jj_add_error_token(kind, i); + } + if (jj_scanpos.kind != kind) return true; + if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; + return false; + } + + +/** Get the next Token. */ + final public Token getNextToken() { + if (token.next != null) token = token.next; + else token = token.next = token_source.getNextToken(); + jj_ntk = -1; + jj_gen++; + return token; + } + +/** Get the specific Token. */ + final public Token getToken(int index) { + Token t = token; + for (int i = 0; i < index; i++) { + if (t.next != null) t = t.next; + else t = t.next = token_source.getNextToken(); + } + return t; + } + + private int jj_ntk() { + if ((jj_nt=token.next) == null) + return (jj_ntk = (token.next=token_source.getNextToken()).kind); + else + return (jj_ntk = jj_nt.kind); + } + + private java.util.List jj_expentries = new java.util.ArrayList(); + private int[] jj_expentry; + private int jj_kind = -1; + private int[] jj_lasttokens = new int[100]; + private int jj_endpos; + + private void jj_add_error_token(int kind, int pos) { + if (pos >= 100) return; + if (pos == jj_endpos + 1) { + jj_lasttokens[jj_endpos++] = kind; + } else if (jj_endpos != 0) { + jj_expentry = new int[jj_endpos]; + for (int i = 0; i < jj_endpos; i++) { + jj_expentry[i] = jj_lasttokens[i]; + } + jj_entries_loop: for (java.util.Iterator it = jj_expentries.iterator(); it.hasNext();) { + int[] oldentry = (int[])(it.next()); + if (oldentry.length == jj_expentry.length) { + for (int i = 0; i < jj_expentry.length; i++) { + if (oldentry[i] != jj_expentry[i]) { + continue jj_entries_loop; + } + } + jj_expentries.add(jj_expentry); + break jj_entries_loop; + } + } + if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; + } + } + + /** Generate ParseException. */ + public ParseException generateParseException() { + jj_expentries.clear(); + boolean[] la1tokens = new boolean[34]; + if (jj_kind >= 0) { + la1tokens[jj_kind] = true; + jj_kind = -1; + } + for (int i = 0; i < 23; i++) { + if (jj_la1[i] == jj_gen) { + for (int j = 0; j < 32; j++) { + if ((jj_la1_0[i] & (1< jj_gen) { + jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; + switch (i) { + case 0: jj_3_1(); break; + } + } + p = p.next; + } while (p != null); + } catch(LookaheadSuccess ls) { } + } + jj_rescan = false; + } + + private void jj_save(int index, int xla) { + JJCalls p = jj_2_rtns[index]; + while (p.gen > jj_gen) { + if (p.next == null) { p = p.next = new JJCalls(); break; } + p = p.next; + } + p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; + } + + static final class JJCalls { + int gen; + Token first; + int arg; + JJCalls next; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParser.jj =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParser.jj,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParser.jj 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,1346 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +options { + STATIC=false; + JAVA_UNICODE_ESCAPE=true; + USER_CHAR_STREAM=true; +} + +PARSER_BEGIN(QueryParser) + +package org.apache.lucene.queryParser; + +import java.io.IOException; +import java.io.StringReader; +import java.text.DateFormat; +import java.text.Collator; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.document.DateField; +import org.apache.lucene.document.DateTools; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.ConstantScoreRangeQuery; +import org.apache.lucene.search.FuzzyQuery; +import org.apache.lucene.search.MatchAllDocsQuery; +import org.apache.lucene.search.MultiPhraseQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.RangeQuery; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.WildcardQuery; +import org.apache.lucene.util.Parameter; + +/** + * This class is generated by JavaCC. The most important method is + * {@link #parse(String)}. + * + * The syntax for query strings is as follows: + * A Query is a series of clauses. + * A clause may be prefixed by: + *

    + *
  • a plus (+) or a minus (-) sign, indicating + * that the clause is required or prohibited respectively; or + *
  • a term followed by a colon, indicating the field to be searched. + * This enables one to construct queries which search multiple fields. + *
+ * + * A clause may be either: + *
    + *
  • a term, indicating all the documents that contain this term; or + *
  • a nested query, enclosed in parentheses. Note that this may be used + * with a +/- prefix to require any of a set of + * terms. + *
+ * + * Thus, in BNF, the query grammar is: + *
+ *   Query  ::= ( Clause )*
+ *   Clause ::= ["+", "-"] [<TERM> ":"] ( <TERM> | "(" Query ")" )
+ * 
+ * + *

+ * Examples of appropriately formatted queries can be found in the query syntax + * documentation. + *

+ * + *

+ * In {@link RangeQuery}s, QueryParser tries to detect date values, e.g. + * date:[6/1/2005 TO 6/4/2005] produces a range query that searches + * for "date" fields between 2005-06-01 and 2005-06-04. Note that the format + * of the accepted input depends on {@link #setLocale(Locale) the locale}. + * By default a date is converted into a search term using the deprecated + * {@link DateField} for compatibility reasons. + * To use the new {@link DateTools} to convert dates, a + * {@link org.apache.lucene.document.DateTools.Resolution} has to be set. + *

+ *

+ * The date resolution that shall be used for RangeQueries can be set + * using {@link #setDateResolution(DateTools.Resolution)} + * or {@link #setDateResolution(String, DateTools.Resolution)}. The former + * sets the default date resolution for all fields, whereas the latter can + * be used to set field specific date resolutions. Field specific date + * resolutions take, if set, precedence over the default date resolution. + *

+ *

+ * If you use neither {@link DateField} nor {@link DateTools} in your + * index, you can create your own + * query parser that inherits QueryParser and overwrites + * {@link #getRangeQuery(String, String, String, boolean)} to + * use a different method for date conversion. + *

+ * + *

Note that QueryParser is not thread-safe.

+ * + * @author Brian Goetz + * @author Peter Halacsy + * @author Tatu Saloranta + */ +public class QueryParser { + + private static final int CONJ_NONE = 0; + private static final int CONJ_AND = 1; + private static final int CONJ_OR = 2; + + private static final int MOD_NONE = 0; + private static final int MOD_NOT = 10; + private static final int MOD_REQ = 11; + + // make it possible to call setDefaultOperator() without accessing + // the nested class: + /** Alternative form of QueryParser.Operator.AND */ + public static final Operator AND_OPERATOR = Operator.AND; + /** Alternative form of QueryParser.Operator.OR */ + public static final Operator OR_OPERATOR = Operator.OR; + + /** The actual operator that parser uses to combine query terms */ + private Operator operator = OR_OPERATOR; + + boolean lowercaseExpandedTerms = true; + boolean useOldRangeQuery= false; + boolean allowLeadingWildcard = false; + boolean enablePositionIncrements = false; + + Analyzer analyzer; + String field; + int phraseSlop = 0; + float fuzzyMinSim = FuzzyQuery.defaultMinSimilarity; + int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength; + Locale locale = Locale.getDefault(); + + // the default date resolution + DateTools.Resolution dateResolution = null; + // maps field names to date resolutions + Map fieldToDateResolution = null; + + // The collator to use when determining range inclusion, + // for use when constructing RangeQuerys and ConstantScoreRangeQuerys. + Collator rangeCollator = null; + + /** The default operator for parsing queries. + * Use {@link QueryParser#setDefaultOperator} to change it. + */ + static public final class Operator extends Parameter { + private Operator(String name) { + super(name); + } + static public final Operator OR = new Operator("OR"); + static public final Operator AND = new Operator("AND"); + } + + + /** Constructs a query parser. + * @param f the default field for query terms. + * @param a used to find terms in the query text. + */ + public QueryParser(String f, Analyzer a) { + this(new FastCharStream(new StringReader(""))); + analyzer = a; + field = f; + } + + /** Parses a query string, returning a {@link org.apache.lucene.search.Query}. + * @param query the query string to be parsed. + * @throws ParseException if the parsing fails + */ + public Query parse(String query) throws ParseException { + ReInit(new FastCharStream(new StringReader(query))); + try { + // TopLevelQuery is a Query followed by the end-of-input (EOF) + Query res = TopLevelQuery(field); + return res!=null ? res : newBooleanQuery(false); + } + catch (ParseException tme) { + // rethrow to include the original query: + throw new ParseException("Cannot parse '" +query+ "': " + tme.getMessage()); + } + catch (TokenMgrError tme) { + throw new ParseException("Cannot parse '" +query+ "': " + tme.getMessage()); + } + catch (BooleanQuery.TooManyClauses tmc) { + throw new ParseException("Cannot parse '" +query+ "': too many boolean clauses"); + } + } + + /** + * @return Returns the analyzer. + */ + public Analyzer getAnalyzer() { + return analyzer; + } + + /** + * @return Returns the field. + */ + public String getField() { + return field; + } + + /** + * Get the minimal similarity for fuzzy queries. + */ + public float getFuzzyMinSim() { + return fuzzyMinSim; + } + + /** + * Set the minimum similarity for fuzzy queries. + * Default is 0.5f. + */ + public void setFuzzyMinSim(float fuzzyMinSim) { + this.fuzzyMinSim = fuzzyMinSim; + } + + /** + * Get the prefix length for fuzzy queries. + * @return Returns the fuzzyPrefixLength. + */ + public int getFuzzyPrefixLength() { + return fuzzyPrefixLength; + } + + /** + * Set the prefix length for fuzzy queries. Default is 0. + * @param fuzzyPrefixLength The fuzzyPrefixLength to set. + */ + public void setFuzzyPrefixLength(int fuzzyPrefixLength) { + this.fuzzyPrefixLength = fuzzyPrefixLength; + } + + /** + * Sets the default slop for phrases. If zero, then exact phrase matches + * are required. Default value is zero. + */ + public void setPhraseSlop(int phraseSlop) { + this.phraseSlop = phraseSlop; + } + + /** + * Gets the default slop for phrases. + */ + public int getPhraseSlop() { + return phraseSlop; + } + + + /** + * Set to true to allow leading wildcard characters. + *

+ * When set, * or ? are allowed as + * the first character of a PrefixQuery and WildcardQuery. + * Note that this can produce very slow + * queries on big indexes. + *

+ * Default: false. + */ + public void setAllowLeadingWildcard(boolean allowLeadingWildcard) { + this.allowLeadingWildcard = allowLeadingWildcard; + } + + /** + * @see #setAllowLeadingWildcard(boolean) + */ + public boolean getAllowLeadingWildcard() { + return allowLeadingWildcard; + } + + /** + * Set to true to enable position increments in result query. + *

+ * When set, result phrase and multi-phrase queries will + * be aware of position increments. + * Useful when e.g. a StopFilter increases the position increment of + * the token that follows an omitted token. + *

+ * Default: false. + */ + public void setEnablePositionIncrements(boolean enable) { + this.enablePositionIncrements = enable; + } + + /** + * @see #setEnablePositionIncrements(boolean) + */ + public boolean getEnablePositionIncrements() { + return enablePositionIncrements; + } + + /** + * Sets the boolean operator of the QueryParser. + * In default mode (OR_OPERATOR) terms without any modifiers + * are considered optional: for example capital of Hungary is equal to + * capital OR of OR Hungary.
+ * In AND_OPERATOR mode terms are considered to be in conjunction: the + * above mentioned query is parsed as capital AND of AND Hungary + */ + public void setDefaultOperator(Operator op) { + this.operator = op; + } + + + /** + * Gets implicit operator setting, which will be either AND_OPERATOR + * or OR_OPERATOR. + */ + public Operator getDefaultOperator() { + return operator; + } + + + /** + * Whether terms of wildcard, prefix, fuzzy and range queries are to be automatically + * lower-cased or not. Default is true. + */ + public void setLowercaseExpandedTerms(boolean lowercaseExpandedTerms) { + this.lowercaseExpandedTerms = lowercaseExpandedTerms; + } + + + /** + * @see #setLowercaseExpandedTerms(boolean) + */ + public boolean getLowercaseExpandedTerms() { + return lowercaseExpandedTerms; + } + + /** + * By default QueryParser uses new ConstantScoreRangeQuery in preference to RangeQuery + * for range queries. This implementation is generally preferable because it + * a) Runs faster b) Does not have the scarcity of range terms unduly influence score + * c) avoids any "TooManyBooleanClauses" exception. + * However, if your application really needs to use the old-fashioned RangeQuery and the above + * points are not required then set this option to true + * Default is false. + */ + public void setUseOldRangeQuery(boolean useOldRangeQuery) { + this.useOldRangeQuery = useOldRangeQuery; + } + + + /** + * @see #setUseOldRangeQuery(boolean) + */ + public boolean getUseOldRangeQuery() { + return useOldRangeQuery; + } + + /** + * Set locale used by date range parsing. + */ + public void setLocale(Locale locale) { + this.locale = locale; + } + + /** + * Returns current locale, allowing access by subclasses. + */ + public Locale getLocale() { + return locale; + } + + /** + * Sets the default date resolution used by RangeQueries for fields for which no + * specific date resolutions has been set. Field specific resolutions can be set + * with {@link #setDateResolution(String, DateTools.Resolution)}. + * + * @param dateResolution the default date resolution to set + */ + public void setDateResolution(DateTools.Resolution dateResolution) { + this.dateResolution = dateResolution; + } + + /** + * Sets the date resolution used by RangeQueries for a specific field. + * + * @param fieldName field for which the date resolution is to be set + * @param dateResolution date resolution to set + */ + public void setDateResolution(String fieldName, DateTools.Resolution dateResolution) { + if (fieldName == null) { + throw new IllegalArgumentException("Field cannot be null."); + } + + if (fieldToDateResolution == null) { + // lazily initialize HashMap + fieldToDateResolution = new HashMap(); + } + + fieldToDateResolution.put(fieldName, dateResolution); + } + + /** + * Returns the date resolution that is used by RangeQueries for the given field. + * Returns null, if no default or field specific date resolution has been set + * for the given field. + * + */ + public DateTools.Resolution getDateResolution(String fieldName) { + if (fieldName == null) { + throw new IllegalArgumentException("Field cannot be null."); + } + + if (fieldToDateResolution == null) { + // no field specific date resolutions set; return default date resolution instead + return this.dateResolution; + } + + DateTools.Resolution resolution = (DateTools.Resolution) fieldToDateResolution.get(fieldName); + if (resolution == null) { + // no date resolutions set for the given field; return default date resolution instead + resolution = this.dateResolution; + } + + return resolution; + } + + /** + * Sets the collator used to determine index term inclusion in ranges + * specified either for ConstantScoreRangeQuerys or RangeQuerys (if + * {@link #setUseOldRangeQuery(boolean)} is called with a true + * value.) + *

+ * WARNING: Setting the rangeCollator to a non-null + * collator using this method will cause every single index Term in the + * Field referenced by lowerTerm and/or upperTerm to be examined. + * Depending on the number of index Terms in this Field, the operation could + * be very slow. + * + * @param rc the collator to use when constructing RangeQuerys + * and ConstantScoreRangeQuerys + */ + public void setRangeCollator(Collator rc) { + rangeCollator = rc; + } + + /** + * @return the collator used to determine index term inclusion in ranges + * specified either for ConstantScoreRangeQuerys or RangeQuerys (if + * {@link #setUseOldRangeQuery(boolean)} is called with a true + * value.) + */ + public Collator getRangeCollator() { + return rangeCollator; + } + + /** + * @deprecated use {@link #addClause(List, int, int, Query)} instead. + */ + protected void addClause(Vector clauses, int conj, int mods, Query q) { + addClause((List) clauses, conj, mods, q); + } + + protected void addClause(List clauses, int conj, int mods, Query q) { + boolean required, prohibited; + + // If this term is introduced by AND, make the preceding term required, + // unless it's already prohibited + if (clauses.size() > 0 && conj == CONJ_AND) { + BooleanClause c = (BooleanClause) clauses.get(clauses.size()-1); + if (!c.isProhibited()) + c.setOccur(BooleanClause.Occur.MUST); + } + + if (clauses.size() > 0 && operator == AND_OPERATOR && conj == CONJ_OR) { + // If this term is introduced by OR, make the preceding term optional, + // unless it's prohibited (that means we leave -a OR b but +a OR b-->a OR b) + // notice if the input is a OR b, first term is parsed as required; without + // this modification a OR b would parsed as +a OR b + BooleanClause c = (BooleanClause) clauses.get(clauses.size()-1); + if (!c.isProhibited()) + c.setOccur(BooleanClause.Occur.SHOULD); + } + + // We might have been passed a null query; the term might have been + // filtered away by the analyzer. + if (q == null) + return; + + if (operator == OR_OPERATOR) { + // We set REQUIRED if we're introduced by AND or +; PROHIBITED if + // introduced by NOT or -; make sure not to set both. + prohibited = (mods == MOD_NOT); + required = (mods == MOD_REQ); + if (conj == CONJ_AND && !prohibited) { + required = true; + } + } else { + // We set PROHIBITED if we're introduced by NOT or -; We set REQUIRED + // if not PROHIBITED and not introduced by OR + prohibited = (mods == MOD_NOT); + required = (!prohibited && conj != CONJ_OR); + } + if (required && !prohibited) + clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST)); + else if (!required && !prohibited) + clauses.add(newBooleanClause(q, BooleanClause.Occur.SHOULD)); + else if (!required && prohibited) + clauses.add(newBooleanClause(q, BooleanClause.Occur.MUST_NOT)); + else + throw new RuntimeException("Clause cannot be both required and prohibited"); + } + + + /** + * @exception ParseException throw in overridden method to disallow + */ + protected Query getFieldQuery(String field, String queryText) throws ParseException { + // Use the analyzer to get all the tokens, and then build a TermQuery, + // PhraseQuery, or nothing based on the term count + + TokenStream source = analyzer.tokenStream(field, new StringReader(queryText)); + List list = new ArrayList(); + final org.apache.lucene.analysis.Token reusableToken = new org.apache.lucene.analysis.Token(); + org.apache.lucene.analysis.Token nextToken; + int positionCount = 0; + boolean severalTokensAtSamePosition = false; + + while (true) { + try { + nextToken = source.next(reusableToken); + } + catch (IOException e) { + nextToken = null; + } + if (nextToken == null) + break; + list.add(nextToken.clone()); + if (nextToken.getPositionIncrement() != 0) + positionCount += nextToken.getPositionIncrement(); + else + severalTokensAtSamePosition = true; + } + try { + source.close(); + } + catch (IOException e) { + // ignore + } + + if (list.size() == 0) + return null; + else if (list.size() == 1) { + nextToken = (org.apache.lucene.analysis.Token) list.get(0); + return newTermQuery(new Term(field, nextToken.term())); + } else { + if (severalTokensAtSamePosition) { + if (positionCount == 1) { + // no phrase query: + BooleanQuery q = newBooleanQuery(true); + for (int i = 0; i < list.size(); i++) { + nextToken = (org.apache.lucene.analysis.Token) list.get(i); + Query currentQuery = newTermQuery( + new Term(field, nextToken.term())); + q.add(currentQuery, BooleanClause.Occur.SHOULD); + } + return q; + } + else { + // phrase query: + MultiPhraseQuery mpq = newMultiPhraseQuery(); + mpq.setSlop(phraseSlop); + List multiTerms = new ArrayList(); + int position = -1; + for (int i = 0; i < list.size(); i++) { + nextToken = (org.apache.lucene.analysis.Token) list.get(i); + if (nextToken.getPositionIncrement() > 0 && multiTerms.size() > 0) { + if (enablePositionIncrements) { + mpq.add((Term[])multiTerms.toArray(new Term[0]),position); + } else { + mpq.add((Term[])multiTerms.toArray(new Term[0])); + } + multiTerms.clear(); + } + position += nextToken.getPositionIncrement(); + multiTerms.add(new Term(field, nextToken.term())); + } + if (enablePositionIncrements) { + mpq.add((Term[])multiTerms.toArray(new Term[0]),position); + } else { + mpq.add((Term[])multiTerms.toArray(new Term[0])); + } + return mpq; + } + } + else { + PhraseQuery pq = newPhraseQuery(); + pq.setSlop(phraseSlop); + int position = -1; + for (int i = 0; i < list.size(); i++) { + nextToken = (org.apache.lucene.analysis.Token) list.get(i); + if (enablePositionIncrements) { + position += nextToken.getPositionIncrement(); + pq.add(new Term(field, nextToken.term()),position); + } else { + pq.add(new Term(field, nextToken.term())); + } + } + return pq; + } + } + } + + + /** + * Base implementation delegates to {@link #getFieldQuery(String,String)}. + * This method may be overridden, for example, to return + * a SpanNearQuery instead of a PhraseQuery. + * + * @exception ParseException throw in overridden method to disallow + */ + protected Query getFieldQuery(String field, String queryText, int slop) + throws ParseException { + Query query = getFieldQuery(field, queryText); + + if (query instanceof PhraseQuery) { + ((PhraseQuery) query).setSlop(slop); + } + if (query instanceof MultiPhraseQuery) { + ((MultiPhraseQuery) query).setSlop(slop); + } + + return query; + } + + + /** + * @exception ParseException throw in overridden method to disallow + */ + protected Query getRangeQuery(String field, + String part1, + String part2, + boolean inclusive) throws ParseException + { + if (lowercaseExpandedTerms) { + part1 = part1.toLowerCase(); + part2 = part2.toLowerCase(); + } + try { + DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale); + df.setLenient(true); + Date d1 = df.parse(part1); + Date d2 = df.parse(part2); + if (inclusive) { + // The user can only specify the date, not the time, so make sure + // the time is set to the latest possible time of that date to really + // include all documents: + Calendar cal = Calendar.getInstance(locale); + cal.setTime(d2); + cal.set(Calendar.HOUR_OF_DAY, 23); + cal.set(Calendar.MINUTE, 59); + cal.set(Calendar.SECOND, 59); + cal.set(Calendar.MILLISECOND, 999); + d2 = cal.getTime(); + } + DateTools.Resolution resolution = getDateResolution(field); + if (resolution == null) { + // no default or field specific date resolution has been set, + // use deprecated DateField to maintain compatibilty with + // pre-1.9 Lucene versions. + part1 = DateField.dateToString(d1); + part2 = DateField.dateToString(d2); + } else { + part1 = DateTools.dateToString(d1, resolution); + part2 = DateTools.dateToString(d2, resolution); + } + } + catch (Exception e) { } + + return newRangeQuery(field, part1, part2, inclusive); + } + + /** + * Builds a new BooleanQuery instance + * @param disableCoord disable coord + * @return new BooleanQuery instance + */ + protected BooleanQuery newBooleanQuery(boolean disableCoord) { + return new BooleanQuery(disableCoord); + } + + /** + * Builds a new BooleanClause instance + * @param q sub query + * @param occur how this clause should occur when matching documents + * @return new BooleanClause instance + */ + protected BooleanClause newBooleanClause(Query q, BooleanClause.Occur occur) { + return new BooleanClause(q, occur); + } + + /** + * Builds a new TermQuery instance + * @param term term + * @return new TermQuery instance + */ + protected Query newTermQuery(Term term){ + return new TermQuery(term); + } + + /** + * Builds a new PhraseQuery instance + * @return new PhraseQuery instance + */ + protected PhraseQuery newPhraseQuery(){ + return new PhraseQuery(); + } + + /** + * Builds a new MultiPhraseQuery instance + * @return new MultiPhraseQuery instance + */ + protected MultiPhraseQuery newMultiPhraseQuery(){ + return new MultiPhraseQuery(); + } + + /** + * Builds a new PrefixQuery instance + * @param prefix Prefix term + * @return new PrefixQuery instance + */ + protected Query newPrefixQuery(Term prefix){ + return new PrefixQuery(prefix); + } + + /** + * Builds a new FuzzyQuery instance + * @param term Term + * @param minimumSimilarity minimum similarity + * @param prefixLength prefix length + * @return new FuzzyQuery Instance + */ + protected Query newFuzzyQuery(Term term, float minimumSimilarity, int prefixLength) { + return new FuzzyQuery(term,minimumSimilarity,prefixLength); + } + + /** + * Builds a new RangeQuery instance + * @param field Field + * @param part1 min + * @param part2 max + * @param inclusive true if range is inclusive + * @return new RangeQuery instance + */ + protected Query newRangeQuery(String field, String part1, String part2, boolean inclusive) { + if(useOldRangeQuery) + { + return new RangeQuery(new Term(field, part1), + new Term(field, part2), + inclusive, rangeCollator); + } + else + { + return new ConstantScoreRangeQuery + (field, part1, part2, inclusive, inclusive, rangeCollator); + } + } + + /** + * Builds a new MatchAllDocsQuery instance + * @return new MatchAllDocsQuery instance + */ + protected Query newMatchAllDocsQuery() { + return new MatchAllDocsQuery(); + } + + /** + * Builds a new WildcardQuery instance + * @param t wildcard term + * @return new WildcardQuery instance + */ + protected Query newWildcardQuery(Term t) { + return new WildcardQuery(t); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + * @deprecated use {@link #getBooleanQuery(List)} instead + */ + protected Query getBooleanQuery(Vector clauses) throws ParseException { + return getBooleanQuery((List) clauses, false); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + */ + protected Query getBooleanQuery(List clauses) throws ParseException { + return getBooleanQuery(clauses, false); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * @param disableCoord true if coord scoring should be disabled. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + * @deprecated use {@link #getBooleanQuery(List, boolean)} instead + */ + protected Query getBooleanQuery(Vector clauses, boolean disableCoord) + throws ParseException + { + return getBooleanQuery((List) clauses, disableCoord); + } + + /** + * Factory method for generating query, given a set of clauses. + * By default creates a boolean query composed of clauses passed in. + * + * Can be overridden by extending classes, to modify query being + * returned. + * + * @param clauses List that contains {@link BooleanClause} instances + * to join. + * @param disableCoord true if coord scoring should be disabled. + * + * @return Resulting {@link Query} object. + * @exception ParseException throw in overridden method to disallow + */ + protected Query getBooleanQuery(List clauses, boolean disableCoord) + throws ParseException + { + if (clauses.size()==0) { + return null; // all clause words were filtered away by the analyzer. + } + BooleanQuery query = newBooleanQuery(disableCoord); + for (int i = 0; i < clauses.size(); i++) { + query.add((BooleanClause)clauses.get(i)); + } + return query; + } + + /** + * Factory method for generating a query. Called when parser + * parses an input term token that contains one or more wildcard + * characters (? and *), but is not a prefix term token (one + * that has just a single * character at the end) + *

+ * Depending on settings, prefix term may be lower-cased + * automatically. It will not go through the default Analyzer, + * however, since normal Analyzers are unlikely to work properly + * with wildcard templates. + *

+ * Can be overridden by extending classes, to provide custom handling for + * wildcard queries, which may be necessary due to missing analyzer calls. + * + * @param field Name of the field query will use. + * @param termStr Term token that contains one or more wild card + * characters (? or *), but is not simple prefix term + * + * @return Resulting {@link Query} built for the term + * @exception ParseException throw in overridden method to disallow + */ + protected Query getWildcardQuery(String field, String termStr) throws ParseException + { + if ("*".equals(field)) { + if ("*".equals(termStr)) return newMatchAllDocsQuery(); + } + if (!allowLeadingWildcard && (termStr.startsWith("*") || termStr.startsWith("?"))) + throw new ParseException("'*' or '?' not allowed as first character in WildcardQuery"); + if (lowercaseExpandedTerms) { + termStr = termStr.toLowerCase(); + } + Term t = new Term(field, termStr); + return newWildcardQuery(t); + } + + /** + * Factory method for generating a query (similar to + * {@link #getWildcardQuery}). Called when parser parses an input term + * token that uses prefix notation; that is, contains a single '*' wildcard + * character as its last character. Since this is a special case + * of generic wildcard term, and such a query can be optimized easily, + * this usually results in a different query object. + *

+ * Depending on settings, a prefix term may be lower-cased + * automatically. It will not go through the default Analyzer, + * however, since normal Analyzers are unlikely to work properly + * with wildcard templates. + *

+ * Can be overridden by extending classes, to provide custom handling for + * wild card queries, which may be necessary due to missing analyzer calls. + * + * @param field Name of the field query will use. + * @param termStr Term token to use for building term for the query + * (without trailing '*' character!) + * + * @return Resulting {@link Query} built for the term + * @exception ParseException throw in overridden method to disallow + */ + protected Query getPrefixQuery(String field, String termStr) throws ParseException + { + if (!allowLeadingWildcard && termStr.startsWith("*")) + throw new ParseException("'*' not allowed as first character in PrefixQuery"); + if (lowercaseExpandedTerms) { + termStr = termStr.toLowerCase(); + } + Term t = new Term(field, termStr); + return newPrefixQuery(t); + } + + /** + * Factory method for generating a query (similar to + * {@link #getWildcardQuery}). Called when parser parses + * an input term token that has the fuzzy suffix (~) appended. + * + * @param field Name of the field query will use. + * @param termStr Term token to use for building term for the query + * + * @return Resulting {@link Query} built for the term + * @exception ParseException throw in overridden method to disallow + */ + protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException + { + if (lowercaseExpandedTerms) { + termStr = termStr.toLowerCase(); + } + Term t = new Term(field, termStr); + return newFuzzyQuery(t, minSimilarity, fuzzyPrefixLength); + } + + /** + * Returns a String where the escape char has been + * removed, or kept only once if there was a double escape. + * + * Supports escaped unicode characters, e. g. translates + * \\u0041 to A. + * + */ + private String discardEscapeChar(String input) throws ParseException { + // Create char array to hold unescaped char sequence + char[] output = new char[input.length()]; + + // The length of the output can be less than the input + // due to discarded escape chars. This variable holds + // the actual length of the output + int length = 0; + + // We remember whether the last processed character was + // an escape character + boolean lastCharWasEscapeChar = false; + + // The multiplier the current unicode digit must be multiplied with. + // E. g. the first digit must be multiplied with 16^3, the second with 16^2... + int codePointMultiplier = 0; + + // Used to calculate the codepoint of the escaped unicode character + int codePoint = 0; + + for (int i = 0; i < input.length(); i++) { + char curChar = input.charAt(i); + if (codePointMultiplier > 0) { + codePoint += hexToInt(curChar) * codePointMultiplier; + codePointMultiplier >>>= 4; + if (codePointMultiplier == 0) { + output[length++] = (char)codePoint; + codePoint = 0; + } + } else if (lastCharWasEscapeChar) { + if (curChar == 'u') { + // found an escaped unicode character + codePointMultiplier = 16 * 16 * 16; + } else { + // this character was escaped + output[length] = curChar; + length++; + } + lastCharWasEscapeChar = false; + } else { + if (curChar == '\\') { + lastCharWasEscapeChar = true; + } else { + output[length] = curChar; + length++; + } + } + } + + if (codePointMultiplier > 0) { + throw new ParseException("Truncated unicode escape sequence."); + } + + if (lastCharWasEscapeChar) { + throw new ParseException("Term can not end with escape character."); + } + + return new String(output, 0, length); + } + + /** Returns the numeric value of the hexadecimal character */ + private static final int hexToInt(char c) throws ParseException { + if ('0' <= c && c <= '9') { + return c - '0'; + } else if ('a' <= c && c <= 'f'){ + return c - 'a' + 10; + } else if ('A' <= c && c <= 'F') { + return c - 'A' + 10; + } else { + throw new ParseException("None-hex character in unicode escape sequence: " + c); + } + } + + /** + * Returns a String where those characters that QueryParser + * expects to be escaped are escaped by a preceding \. + */ + public static String escape(String s) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + // These characters are part of the query syntax and must be escaped + if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':' + || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~' + || c == '*' || c == '?' || c == '|' || c == '&') { + sb.append('\\'); + } + sb.append(c); + } + return sb.toString(); + } + + /** + * Command line tool to test QueryParser, using {@link org.apache.lucene.analysis.SimpleAnalyzer}. + * Usage:
+ * java org.apache.lucene.queryParser.QueryParser <input> + */ + public static void main(String[] args) throws Exception { + if (args.length == 0) { + System.out.println("Usage: java org.apache.lucene.queryParser.QueryParser "); + System.exit(0); + } + QueryParser qp = new QueryParser("field", + new org.apache.lucene.analysis.SimpleAnalyzer()); + Query q = qp.parse(args[0]); + System.out.println(q.toString("field")); + } +} + +PARSER_END(QueryParser) + +/* ***************** */ +/* Token Definitions */ +/* ***************** */ + +<*> TOKEN : { + <#_NUM_CHAR: ["0"-"9"] > +// every character that follows a backslash is considered as an escaped character +| <#_ESCAPED_CHAR: "\\" ~[] > +| <#_TERM_START_CHAR: ( ~[ " ", "\t", "\n", "\r", "+", "-", "!", "(", ")", ":", "^", + "[", "]", "\"", "{", "}", "~", "*", "?", "\\" ] + | <_ESCAPED_CHAR> ) > +| <#_TERM_CHAR: ( <_TERM_START_CHAR> | <_ESCAPED_CHAR> | "-" | "+" ) > +| <#_WHITESPACE: ( " " | "\t" | "\n" | "\r") > +| <#_QUOTED_CHAR: ( ~[ "\"", "\\" ] | <_ESCAPED_CHAR> ) > +} + + SKIP : { + < <_WHITESPACE>> +} + + TOKEN : { + +| +| +| +| +| +| +| +| +| : Boost +| )* "\""> +| (<_TERM_CHAR>)* > +| )+ ( "." (<_NUM_CHAR>)+ )? )? > +| (<_TERM_CHAR>)* "*" ) > +| | [ "*", "?" ]) (<_TERM_CHAR> | ( [ "*", "?" ] ))* > +| : RangeIn +| : RangeEx +} + + TOKEN : { +)+ ( "." (<_NUM_CHAR>)+ )? > : DEFAULT +} + + TOKEN : { + +| : DEFAULT +| +| +} + + TOKEN : { + +| : DEFAULT +| +| +} + +// * Query ::= ( Clause )* +// * Clause ::= ["+", "-"] [ ":"] ( | "(" Query ")" ) + +int Conjunction() : { + int ret = CONJ_NONE; +} +{ + [ + { ret = CONJ_AND; } + | { ret = CONJ_OR; } + ] + { return ret; } +} + +int Modifiers() : { + int ret = MOD_NONE; +} +{ + [ + { ret = MOD_REQ; } + | { ret = MOD_NOT; } + | { ret = MOD_NOT; } + ] + { return ret; } +} + +// This makes sure that there is no garbage after the query string +Query TopLevelQuery(String field) : +{ + Query q; +} +{ + q=Query(field) + { + return q; + } +} + +Query Query(String field) : +{ + List clauses = new ArrayList(); + Query q, firstQuery=null; + int conj, mods; +} +{ + mods=Modifiers() q=Clause(field) + { + addClause(clauses, CONJ_NONE, mods, q); + if (mods == MOD_NONE) + firstQuery=q; + } + ( + conj=Conjunction() mods=Modifiers() q=Clause(field) + { addClause(clauses, conj, mods, q); } + )* + { + if (clauses.size() == 1 && firstQuery != null) + return firstQuery; + else { + return getBooleanQuery(clauses); + } + } +} + +Query Clause(String field) : { + Query q; + Token fieldToken=null, boost=null; +} +{ + [ + LOOKAHEAD(2) + ( + fieldToken= {field=discardEscapeChar(fieldToken.image);} + | {field="*";} + ) + ] + + ( + q=Term(field) + | q=Query(field) ( boost=)? + + ) + { + if (boost != null) { + float f = (float)1.0; + try { + f = Float.valueOf(boost.image).floatValue(); + q.setBoost(f); + } catch (Exception ignored) { } + } + return q; + } +} + + +Query Term(String field) : { + Token term, boost=null, fuzzySlop=null, goop1, goop2; + boolean prefix = false; + boolean wildcard = false; + boolean fuzzy = false; + boolean rangein = false; + Query q; +} +{ + ( + ( + term= + | term= { wildcard=true; } + | term= { prefix=true; } + | term= { wildcard=true; } + | term= + ) + [ fuzzySlop= { fuzzy=true; } ] + [ boost= [ fuzzySlop= { fuzzy=true; } ] ] + { + String termImage=discardEscapeChar(term.image); + if (wildcard) { + q = getWildcardQuery(field, termImage); + } else if (prefix) { + q = getPrefixQuery(field, + discardEscapeChar(term.image.substring + (0, term.image.length()-1))); + } else if (fuzzy) { + float fms = fuzzyMinSim; + try { + fms = Float.valueOf(fuzzySlop.image.substring(1)).floatValue(); + } catch (Exception ignored) { } + if(fms < 0.0f || fms > 1.0f){ + throw new ParseException("Minimum similarity for a FuzzyQuery has to be between 0.0f and 1.0f !"); + } + q = getFuzzyQuery(field, termImage,fms); + } else { + q = getFieldQuery(field, termImage); + } + } + | ( ( goop1=|goop1= ) + [ ] ( goop2=|goop2= ) + ) + [ boost= ] + { + if (goop1.kind == RANGEIN_QUOTED) { + goop1.image = goop1.image.substring(1, goop1.image.length()-1); + } + if (goop2.kind == RANGEIN_QUOTED) { + goop2.image = goop2.image.substring(1, goop2.image.length()-1); + } + q = getRangeQuery(field, discardEscapeChar(goop1.image), discardEscapeChar(goop2.image), true); + } + | ( ( goop1=|goop1= ) + [ ] ( goop2=|goop2= ) + ) + [ boost= ] + { + if (goop1.kind == RANGEEX_QUOTED) { + goop1.image = goop1.image.substring(1, goop1.image.length()-1); + } + if (goop2.kind == RANGEEX_QUOTED) { + goop2.image = goop2.image.substring(1, goop2.image.length()-1); + } + + q = getRangeQuery(field, discardEscapeChar(goop1.image), discardEscapeChar(goop2.image), false); + } + | term= + [ fuzzySlop= ] + [ boost= ] + { + int s = phraseSlop; + + if (fuzzySlop != null) { + try { + s = Float.valueOf(fuzzySlop.image.substring(1)).intValue(); + } + catch (Exception ignored) { } + } + q = getFieldQuery(field, discardEscapeChar(term.image.substring(1, term.image.length()-1)), s); + } + ) + { + if (boost != null) { + float f = (float) 1.0; + try { + f = Float.valueOf(boost.image).floatValue(); + } + catch (Exception ignored) { + /* Should this be handled somehow? (defaults to "no boost", if + * boost number is invalid) + */ + } + + // avoid boosting null queries, such as those caused by stop words + if (q != null) { + q.setBoost(f); + } + } + return q; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParserConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParserConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParserConstants.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,125 @@ +/* Generated By:JavaCC: Do not edit this line. QueryParserConstants.java */ +package org.apache.lucene.queryParser; + + +/** + * Token literal values and constants. + * Generated by org.javacc.parser.OtherFilesGen#start() + */ +public interface QueryParserConstants { + + /** End of File. */ + int EOF = 0; + /** RegularExpression Id. */ + int _NUM_CHAR = 1; + /** RegularExpression Id. */ + int _ESCAPED_CHAR = 2; + /** RegularExpression Id. */ + int _TERM_START_CHAR = 3; + /** RegularExpression Id. */ + int _TERM_CHAR = 4; + /** RegularExpression Id. */ + int _WHITESPACE = 5; + /** RegularExpression Id. */ + int _QUOTED_CHAR = 6; + /** RegularExpression Id. */ + int AND = 8; + /** RegularExpression Id. */ + int OR = 9; + /** RegularExpression Id. */ + int NOT = 10; + /** RegularExpression Id. */ + int PLUS = 11; + /** RegularExpression Id. */ + int MINUS = 12; + /** RegularExpression Id. */ + int LPAREN = 13; + /** RegularExpression Id. */ + int RPAREN = 14; + /** RegularExpression Id. */ + int COLON = 15; + /** RegularExpression Id. */ + int STAR = 16; + /** RegularExpression Id. */ + int CARAT = 17; + /** RegularExpression Id. */ + int QUOTED = 18; + /** RegularExpression Id. */ + int TERM = 19; + /** RegularExpression Id. */ + int FUZZY_SLOP = 20; + /** RegularExpression Id. */ + int PREFIXTERM = 21; + /** RegularExpression Id. */ + int WILDTERM = 22; + /** RegularExpression Id. */ + int RANGEIN_START = 23; + /** RegularExpression Id. */ + int RANGEEX_START = 24; + /** RegularExpression Id. */ + int NUMBER = 25; + /** RegularExpression Id. */ + int RANGEIN_TO = 26; + /** RegularExpression Id. */ + int RANGEIN_END = 27; + /** RegularExpression Id. */ + int RANGEIN_QUOTED = 28; + /** RegularExpression Id. */ + int RANGEIN_GOOP = 29; + /** RegularExpression Id. */ + int RANGEEX_TO = 30; + /** RegularExpression Id. */ + int RANGEEX_END = 31; + /** RegularExpression Id. */ + int RANGEEX_QUOTED = 32; + /** RegularExpression Id. */ + int RANGEEX_GOOP = 33; + + /** Lexical state. */ + int Boost = 0; + /** Lexical state. */ + int RangeEx = 1; + /** Lexical state. */ + int RangeIn = 2; + /** Lexical state. */ + int DEFAULT = 3; + + /** Literal token values. */ + String[] tokenImage = { + "", + "<_NUM_CHAR>", + "<_ESCAPED_CHAR>", + "<_TERM_START_CHAR>", + "<_TERM_CHAR>", + "<_WHITESPACE>", + "<_QUOTED_CHAR>", + "", + "", + "", + "", + "\"+\"", + "\"-\"", + "\"(\"", + "\")\"", + "\":\"", + "\"*\"", + "\"^\"", + "", + "", + "", + "", + "", + "\"[\"", + "\"{\"", + "", + "\"TO\"", + "\"]\"", + "", + "", + "\"TO\"", + "\"}\"", + "", + "", + }; + +} Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParserTokenManager.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParserTokenManager.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/QueryParserTokenManager.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,1183 @@ +/* Generated By:JavaCC: Do not edit this line. QueryParserTokenManager.java */ +package org.apache.lucene.queryParser; +import java.io.IOException; +import java.io.StringReader; +import java.text.DateFormat; +import java.text.Collator; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.document.DateField; +import org.apache.lucene.document.DateTools; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.ConstantScoreRangeQuery; +import org.apache.lucene.search.FuzzyQuery; +import org.apache.lucene.search.MatchAllDocsQuery; +import org.apache.lucene.search.MultiPhraseQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.RangeQuery; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.WildcardQuery; +import org.apache.lucene.util.Parameter; + +/** Token Manager. */ +public class QueryParserTokenManager implements QueryParserConstants +{ + + /** Debug output. */ + public java.io.PrintStream debugStream = System.out; + /** Set debug output. */ + public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } +private final int jjStopStringLiteralDfa_3(int pos, long active0) +{ + switch (pos) + { + default : + return -1; + } +} +private final int jjStartNfa_3(int pos, long active0) +{ + return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0), pos + 1); +} +private int jjStopAtPos(int pos, int kind) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + return pos + 1; +} +private int jjMoveStringLiteralDfa0_3() +{ + switch(curChar) + { + case 40: + return jjStopAtPos(0, 13); + case 41: + return jjStopAtPos(0, 14); + case 42: + return jjStartNfaWithStates_3(0, 16, 36); + case 43: + return jjStopAtPos(0, 11); + case 45: + return jjStopAtPos(0, 12); + case 58: + return jjStopAtPos(0, 15); + case 91: + return jjStopAtPos(0, 23); + case 94: + return jjStopAtPos(0, 17); + case 123: + return jjStopAtPos(0, 24); + default : + return jjMoveNfa_3(0, 0); + } +} +private int jjStartNfaWithStates_3(int pos, int kind, int state) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return pos + 1; } + return jjMoveNfa_3(state, pos + 1); +} +static final long[] jjbitVec0 = { + 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +static final long[] jjbitVec2 = { + 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL +}; +private int jjMoveNfa_3(int startState, int curPos) +{ + int startsAt = 0; + jjnewStateCnt = 36; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + do + { + switch(jjstateSet[--i]) + { + case 36: + case 25: + if ((0xfbfffcf8ffffd9ffL & l) == 0L) + break; + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 0: + if ((0xfbffd4f8ffffd9ffL & l) != 0L) + { + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + } + else if ((0x100002600L & l) != 0L) + { + if (kind > 7) + kind = 7; + } + else if (curChar == 34) + jjCheckNAddStates(0, 2); + else if (curChar == 33) + { + if (kind > 10) + kind = 10; + } + if ((0x7bffd0f8ffffd9ffL & l) != 0L) + { + if (kind > 19) + kind = 19; + jjCheckNAddStates(3, 7); + } + else if (curChar == 42) + { + if (kind > 21) + kind = 21; + } + if (curChar == 38) + jjstateSet[jjnewStateCnt++] = 4; + break; + case 4: + if (curChar == 38 && kind > 8) + kind = 8; + break; + case 5: + if (curChar == 38) + jjstateSet[jjnewStateCnt++] = 4; + break; + case 13: + if (curChar == 33 && kind > 10) + kind = 10; + break; + case 14: + if (curChar == 34) + jjCheckNAddStates(0, 2); + break; + case 15: + if ((0xfffffffbffffffffL & l) != 0L) + jjCheckNAddStates(0, 2); + break; + case 17: + jjCheckNAddStates(0, 2); + break; + case 18: + if (curChar == 34 && kind > 18) + kind = 18; + break; + case 20: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 20) + kind = 20; + jjAddStates(8, 9); + break; + case 21: + if (curChar == 46) + jjCheckNAdd(22); + break; + case 22: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 20) + kind = 20; + jjCheckNAdd(22); + break; + case 23: + if (curChar == 42 && kind > 21) + kind = 21; + break; + case 24: + if ((0xfbffd4f8ffffd9ffL & l) == 0L) + break; + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 27: + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 28: + if ((0x7bffd0f8ffffd9ffL & l) == 0L) + break; + if (kind > 19) + kind = 19; + jjCheckNAddStates(3, 7); + break; + case 29: + if ((0x7bfff8f8ffffd9ffL & l) == 0L) + break; + if (kind > 19) + kind = 19; + jjCheckNAddTwoStates(29, 30); + break; + case 31: + if (kind > 19) + kind = 19; + jjCheckNAddTwoStates(29, 30); + break; + case 32: + if ((0x7bfff8f8ffffd9ffL & l) != 0L) + jjCheckNAddStates(10, 12); + break; + case 34: + jjCheckNAddStates(10, 12); + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 36: + if ((0x97ffffff87ffffffL & l) != 0L) + { + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + } + else if (curChar == 92) + jjCheckNAddTwoStates(27, 27); + break; + case 0: + if ((0x97ffffff87ffffffL & l) != 0L) + { + if (kind > 19) + kind = 19; + jjCheckNAddStates(3, 7); + } + else if (curChar == 92) + jjCheckNAddStates(13, 15); + else if (curChar == 126) + { + if (kind > 20) + kind = 20; + jjstateSet[jjnewStateCnt++] = 20; + } + if ((0x97ffffff87ffffffL & l) != 0L) + { + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + } + if (curChar == 78) + jjstateSet[jjnewStateCnt++] = 11; + else if (curChar == 124) + jjstateSet[jjnewStateCnt++] = 8; + else if (curChar == 79) + jjstateSet[jjnewStateCnt++] = 6; + else if (curChar == 65) + jjstateSet[jjnewStateCnt++] = 2; + break; + case 1: + if (curChar == 68 && kind > 8) + kind = 8; + break; + case 2: + if (curChar == 78) + jjstateSet[jjnewStateCnt++] = 1; + break; + case 3: + if (curChar == 65) + jjstateSet[jjnewStateCnt++] = 2; + break; + case 6: + if (curChar == 82 && kind > 9) + kind = 9; + break; + case 7: + if (curChar == 79) + jjstateSet[jjnewStateCnt++] = 6; + break; + case 8: + if (curChar == 124 && kind > 9) + kind = 9; + break; + case 9: + if (curChar == 124) + jjstateSet[jjnewStateCnt++] = 8; + break; + case 10: + if (curChar == 84 && kind > 10) + kind = 10; + break; + case 11: + if (curChar == 79) + jjstateSet[jjnewStateCnt++] = 10; + break; + case 12: + if (curChar == 78) + jjstateSet[jjnewStateCnt++] = 11; + break; + case 15: + if ((0xffffffffefffffffL & l) != 0L) + jjCheckNAddStates(0, 2); + break; + case 16: + if (curChar == 92) + jjstateSet[jjnewStateCnt++] = 17; + break; + case 17: + jjCheckNAddStates(0, 2); + break; + case 19: + if (curChar != 126) + break; + if (kind > 20) + kind = 20; + jjstateSet[jjnewStateCnt++] = 20; + break; + case 24: + if ((0x97ffffff87ffffffL & l) == 0L) + break; + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 25: + if ((0x97ffffff87ffffffL & l) == 0L) + break; + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 26: + if (curChar == 92) + jjCheckNAddTwoStates(27, 27); + break; + case 27: + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 28: + if ((0x97ffffff87ffffffL & l) == 0L) + break; + if (kind > 19) + kind = 19; + jjCheckNAddStates(3, 7); + break; + case 29: + if ((0x97ffffff87ffffffL & l) == 0L) + break; + if (kind > 19) + kind = 19; + jjCheckNAddTwoStates(29, 30); + break; + case 30: + if (curChar == 92) + jjCheckNAddTwoStates(31, 31); + break; + case 31: + if (kind > 19) + kind = 19; + jjCheckNAddTwoStates(29, 30); + break; + case 32: + if ((0x97ffffff87ffffffL & l) != 0L) + jjCheckNAddStates(10, 12); + break; + case 33: + if (curChar == 92) + jjCheckNAddTwoStates(34, 34); + break; + case 34: + jjCheckNAddStates(10, 12); + break; + case 35: + if (curChar == 92) + jjCheckNAddStates(13, 15); + break; + default : break; + } + } while(i != startsAt); + } + else + { + int hiByte = (int)(curChar >> 8); + int i1 = hiByte >> 6; + long l1 = 1L << (hiByte & 077); + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 36: + case 25: + case 27: + if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) + break; + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 0: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + { + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + } + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + { + if (kind > 19) + kind = 19; + jjCheckNAddStates(3, 7); + } + break; + case 15: + case 17: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjCheckNAddStates(0, 2); + break; + case 24: + if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) + break; + if (kind > 22) + kind = 22; + jjCheckNAddTwoStates(25, 26); + break; + case 28: + if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) + break; + if (kind > 19) + kind = 19; + jjCheckNAddStates(3, 7); + break; + case 29: + case 31: + if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) + break; + if (kind > 19) + kind = 19; + jjCheckNAddTwoStates(29, 30); + break; + case 32: + case 34: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjCheckNAddStates(10, 12); + break; + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 36 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +private final int jjStopStringLiteralDfa_1(int pos, long active0) +{ + switch (pos) + { + case 0: + if ((active0 & 0x40000000L) != 0L) + { + jjmatchedKind = 33; + return 6; + } + return -1; + default : + return -1; + } +} +private final int jjStartNfa_1(int pos, long active0) +{ + return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0), pos + 1); +} +private int jjMoveStringLiteralDfa0_1() +{ + switch(curChar) + { + case 84: + return jjMoveStringLiteralDfa1_1(0x40000000L); + case 125: + return jjStopAtPos(0, 31); + default : + return jjMoveNfa_1(0, 0); + } +} +private int jjMoveStringLiteralDfa1_1(long active0) +{ + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_1(0, active0); + return 1; + } + switch(curChar) + { + case 79: + if ((active0 & 0x40000000L) != 0L) + return jjStartNfaWithStates_1(1, 30, 6); + break; + default : + break; + } + return jjStartNfa_1(0, active0); +} +private int jjStartNfaWithStates_1(int pos, int kind, int state) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return pos + 1; } + return jjMoveNfa_1(state, pos + 1); +} +private int jjMoveNfa_1(int startState, int curPos) +{ + int startsAt = 0; + jjnewStateCnt = 7; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + do + { + switch(jjstateSet[--i]) + { + case 0: + if ((0xfffffffeffffffffL & l) != 0L) + { + if (kind > 33) + kind = 33; + jjCheckNAdd(6); + } + if ((0x100002600L & l) != 0L) + { + if (kind > 7) + kind = 7; + } + else if (curChar == 34) + jjCheckNAddTwoStates(2, 4); + break; + case 1: + if (curChar == 34) + jjCheckNAddTwoStates(2, 4); + break; + case 2: + if ((0xfffffffbffffffffL & l) != 0L) + jjCheckNAddStates(16, 18); + break; + case 3: + if (curChar == 34) + jjCheckNAddStates(16, 18); + break; + case 5: + if (curChar == 34 && kind > 32) + kind = 32; + break; + case 6: + if ((0xfffffffeffffffffL & l) == 0L) + break; + if (kind > 33) + kind = 33; + jjCheckNAdd(6); + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 0: + case 6: + if ((0xdfffffffffffffffL & l) == 0L) + break; + if (kind > 33) + kind = 33; + jjCheckNAdd(6); + break; + case 2: + jjAddStates(16, 18); + break; + case 4: + if (curChar == 92) + jjstateSet[jjnewStateCnt++] = 3; + break; + default : break; + } + } while(i != startsAt); + } + else + { + int hiByte = (int)(curChar >> 8); + int i1 = hiByte >> 6; + long l1 = 1L << (hiByte & 077); + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 0: + case 6: + if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) + break; + if (kind > 33) + kind = 33; + jjCheckNAdd(6); + break; + case 2: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjAddStates(16, 18); + break; + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 7 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +private int jjMoveStringLiteralDfa0_0() +{ + return jjMoveNfa_0(0, 0); +} +private int jjMoveNfa_0(int startState, int curPos) +{ + int startsAt = 0; + jjnewStateCnt = 3; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + do + { + switch(jjstateSet[--i]) + { + case 0: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 25) + kind = 25; + jjAddStates(19, 20); + break; + case 1: + if (curChar == 46) + jjCheckNAdd(2); + break; + case 2: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 25) + kind = 25; + jjCheckNAdd(2); + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + default : break; + } + } while(i != startsAt); + } + else + { + int hiByte = (int)(curChar >> 8); + int i1 = hiByte >> 6; + long l1 = 1L << (hiByte & 077); + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +private final int jjStopStringLiteralDfa_2(int pos, long active0) +{ + switch (pos) + { + case 0: + if ((active0 & 0x4000000L) != 0L) + { + jjmatchedKind = 29; + return 6; + } + return -1; + default : + return -1; + } +} +private final int jjStartNfa_2(int pos, long active0) +{ + return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0), pos + 1); +} +private int jjMoveStringLiteralDfa0_2() +{ + switch(curChar) + { + case 84: + return jjMoveStringLiteralDfa1_2(0x4000000L); + case 93: + return jjStopAtPos(0, 27); + default : + return jjMoveNfa_2(0, 0); + } +} +private int jjMoveStringLiteralDfa1_2(long active0) +{ + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { + jjStopStringLiteralDfa_2(0, active0); + return 1; + } + switch(curChar) + { + case 79: + if ((active0 & 0x4000000L) != 0L) + return jjStartNfaWithStates_2(1, 26, 6); + break; + default : + break; + } + return jjStartNfa_2(0, active0); +} +private int jjStartNfaWithStates_2(int pos, int kind, int state) +{ + jjmatchedKind = kind; + jjmatchedPos = pos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return pos + 1; } + return jjMoveNfa_2(state, pos + 1); +} +private int jjMoveNfa_2(int startState, int curPos) +{ + int startsAt = 0; + jjnewStateCnt = 7; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for (;;) + { + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64) + { + long l = 1L << curChar; + do + { + switch(jjstateSet[--i]) + { + case 0: + if ((0xfffffffeffffffffL & l) != 0L) + { + if (kind > 29) + kind = 29; + jjCheckNAdd(6); + } + if ((0x100002600L & l) != 0L) + { + if (kind > 7) + kind = 7; + } + else if (curChar == 34) + jjCheckNAddTwoStates(2, 4); + break; + case 1: + if (curChar == 34) + jjCheckNAddTwoStates(2, 4); + break; + case 2: + if ((0xfffffffbffffffffL & l) != 0L) + jjCheckNAddStates(16, 18); + break; + case 3: + if (curChar == 34) + jjCheckNAddStates(16, 18); + break; + case 5: + if (curChar == 34 && kind > 28) + kind = 28; + break; + case 6: + if ((0xfffffffeffffffffL & l) == 0L) + break; + if (kind > 29) + kind = 29; + jjCheckNAdd(6); + break; + default : break; + } + } while(i != startsAt); + } + else if (curChar < 128) + { + long l = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 0: + case 6: + if ((0xffffffffdfffffffL & l) == 0L) + break; + if (kind > 29) + kind = 29; + jjCheckNAdd(6); + break; + case 2: + jjAddStates(16, 18); + break; + case 4: + if (curChar == 92) + jjstateSet[jjnewStateCnt++] = 3; + break; + default : break; + } + } while(i != startsAt); + } + else + { + int hiByte = (int)(curChar >> 8); + int i1 = hiByte >> 6; + long l1 = 1L << (hiByte & 077); + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do + { + switch(jjstateSet[--i]) + { + case 0: + case 6: + if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) + break; + if (kind > 29) + kind = 29; + jjCheckNAdd(6); + break; + case 2: + if (jjCanMove_0(hiByte, i1, i2, l1, l2)) + jjAddStates(16, 18); + break; + default : break; + } + } while(i != startsAt); + } + if (kind != 0x7fffffff) + { + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 7 - (jjnewStateCnt = startsAt))) + return curPos; + try { curChar = input_stream.readChar(); } + catch(java.io.IOException e) { return curPos; } + } +} +static final int[] jjnextStates = { + 15, 16, 18, 29, 32, 23, 33, 30, 20, 21, 32, 23, 33, 31, 34, 27, + 2, 4, 5, 0, 1, +}; +private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) +{ + switch(hiByte) + { + case 0: + return ((jjbitVec2[i2] & l2) != 0L); + default : + if ((jjbitVec0[i1] & l1) != 0L) + return true; + return false; + } +} + +/** Token literal values. */ +public static final String[] jjstrLiteralImages = { +"", null, null, null, null, null, null, null, null, null, null, "\53", "\55", +"\50", "\51", "\72", "\52", "\136", null, null, null, null, null, "\133", "\173", +null, "\124\117", "\135", null, null, "\124\117", "\175", null, null, }; + +/** Lexer state names. */ +public static final String[] lexStateNames = { + "Boost", + "RangeEx", + "RangeIn", + "DEFAULT", +}; + +/** Lex State array. */ +public static final int[] jjnewLexState = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, 2, 1, + 3, -1, 3, -1, -1, -1, 3, -1, -1, +}; +static final long[] jjtoToken = { + 0x3ffffff01L, +}; +static final long[] jjtoSkip = { + 0x80L, +}; +protected CharStream input_stream; +private final int[] jjrounds = new int[36]; +private final int[] jjstateSet = new int[72]; +protected char curChar; +/** Constructor. */ +public QueryParserTokenManager(CharStream stream){ + input_stream = stream; +} + +/** Constructor. */ +public QueryParserTokenManager(CharStream stream, int lexState){ + this(stream); + SwitchTo(lexState); +} + +/** Reinitialise parser. */ +public void ReInit(CharStream stream) +{ + jjmatchedPos = jjnewStateCnt = 0; + curLexState = defaultLexState; + input_stream = stream; + ReInitRounds(); +} +private void ReInitRounds() +{ + int i; + jjround = 0x80000001; + for (i = 36; i-- > 0;) + jjrounds[i] = 0x80000000; +} + +/** Reinitialise parser. */ +public void ReInit(CharStream stream, int lexState) +{ + ReInit(stream); + SwitchTo(lexState); +} + +/** Switch to specified lex state. */ +public void SwitchTo(int lexState) +{ + if (lexState >= 4 || lexState < 0) + throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); + else + curLexState = lexState; +} + +protected Token jjFillToken() +{ + final Token t; + final String curTokenImage; + final int beginLine; + final int endLine; + final int beginColumn; + final int endColumn; + String im = jjstrLiteralImages[jjmatchedKind]; + curTokenImage = (im == null) ? input_stream.GetImage() : im; + beginLine = input_stream.getBeginLine(); + beginColumn = input_stream.getBeginColumn(); + endLine = input_stream.getEndLine(); + endColumn = input_stream.getEndColumn(); + t = Token.newToken(jjmatchedKind, curTokenImage); + + t.beginLine = beginLine; + t.endLine = endLine; + t.beginColumn = beginColumn; + t.endColumn = endColumn; + + return t; +} + +int curLexState = 3; +int defaultLexState = 3; +int jjnewStateCnt; +int jjround; +int jjmatchedPos; +int jjmatchedKind; + +/** Get the next Token. */ +public Token getNextToken() +{ + Token matchedToken; + int curPos = 0; + + EOFLoop : + for (;;) + { + try + { + curChar = input_stream.BeginToken(); + } + catch(java.io.IOException e) + { + jjmatchedKind = 0; + matchedToken = jjFillToken(); + return matchedToken; + } + + switch(curLexState) + { + case 0: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_0(); + break; + case 1: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_1(); + break; + case 2: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_2(); + break; + case 3: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_3(); + break; + } + if (jjmatchedKind != 0x7fffffff) + { + if (jjmatchedPos + 1 < curPos) + input_stream.backup(curPos - jjmatchedPos - 1); + if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) + { + matchedToken = jjFillToken(); + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + return matchedToken; + } + else + { + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + continue EOFLoop; + } + } + int error_line = input_stream.getEndLine(); + int error_column = input_stream.getEndColumn(); + String error_after = null; + boolean EOFSeen = false; + try { input_stream.readChar(); input_stream.backup(1); } + catch (java.io.IOException e1) { + EOFSeen = true; + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + if (curChar == '\n' || curChar == '\r') { + error_line++; + error_column = 0; + } + else + error_column++; + } + if (!EOFSeen) { + input_stream.backup(1); + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + } + throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); + } +} + +private void jjCheckNAdd(int state) +{ + if (jjrounds[state] != jjround) + { + jjstateSet[jjnewStateCnt++] = state; + jjrounds[state] = jjround; + } +} +private void jjAddStates(int start, int end) +{ + do { + jjstateSet[jjnewStateCnt++] = jjnextStates[start]; + } while (start++ != end); +} +private void jjCheckNAddTwoStates(int state1, int state2) +{ + jjCheckNAdd(state1); + jjCheckNAdd(state2); +} + +private void jjCheckNAddStates(int start, int end) +{ + do { + jjCheckNAdd(jjnextStates[start]); + } while (start++ != end); +} + +} Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/Token.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/Token.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/Token.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,124 @@ +/* Generated By:JavaCC: Do not edit this line. Token.java Version 4.1 */ +/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null */ +package org.apache.lucene.queryParser; + +/** + * Describes the input token stream. + */ + +public class Token { + + /** + * An integer that describes the kind of this token. This numbering + * system is determined by JavaCCParser, and a table of these numbers is + * stored in the file ...Constants.java. + */ + public int kind; + + /** The line number of the first character of this Token. */ + public int beginLine; + /** The column number of the first character of this Token. */ + public int beginColumn; + /** The line number of the last character of this Token. */ + public int endLine; + /** The column number of the last character of this Token. */ + public int endColumn; + + /** + * The string image of the token. + */ + public String image; + + /** + * A reference to the next regular (non-special) token from the input + * stream. If this is the last token from the input stream, or if the + * token manager has not read tokens beyond this one, this field is + * set to null. This is true only if this token is also a regular + * token. Otherwise, see below for a description of the contents of + * this field. + */ + public Token next; + + /** + * This field is used to access special tokens that occur prior to this + * token, but after the immediately preceding regular (non-special) token. + * If there are no such special tokens, this field is set to null. + * When there are more than one such special token, this field refers + * to the last of these special tokens, which in turn refers to the next + * previous special token through its specialToken field, and so on + * until the first special token (whose specialToken field is null). + * The next fields of special tokens refer to other special tokens that + * immediately follow it (without an intervening regular token). If there + * is no such token, this field is null. + */ + public Token specialToken; + + /** + * An optional attribute value of the Token. + * Tokens which are not used as syntactic sugar will often contain + * meaningful values that will be used later on by the compiler or + * interpreter. This attribute value is often different from the image. + * Any subclass of Token that actually wants to return a non-null value can + * override this method as appropriate. + */ + public Object getValue() { + return null; + } + + /** + * No-argument constructor + */ + public Token() {} + + /** + * Constructs a new token for the specified Image. + */ + public Token(int kind) + { + this(kind, null); + } + + /** + * Constructs a new token for the specified Image and Kind. + */ + public Token(int kind, String image) + { + this.kind = kind; + this.image = image; + } + + /** + * Returns the image. + */ + public String toString() + { + return image; + } + + /** + * Returns a new Token object, by default. However, if you want, you + * can create and return subclass objects based on the value of ofKind. + * Simply add the cases to the switch for all those special cases. + * For example, if you have a subclass of Token called IDToken that + * you want to create if ofKind is ID, simply add something like : + * + * case MyParserConstants.ID : return new IDToken(ofKind, image); + * + * to the following switch statement. Then you can cast matchedToken + * variable to the appropriate type and use sit in your lexical actions. + */ + public static Token newToken(int ofKind, String image) + { + switch(ofKind) + { + default : return new Token(ofKind, image); + } + } + + public static Token newToken(int ofKind) + { + return newToken(ofKind, null); + } + +} +/* JavaCC - OriginalChecksum=c147cc166a7cf8812c7c39bc8c5eb868 (do not edit this line) */ Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/TokenMgrError.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/TokenMgrError.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/TokenMgrError.java 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,140 @@ +/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 4.1 */ +/* JavaCCOptions: */ +package org.apache.lucene.queryParser; + +/** Token Manager Error. */ +public class TokenMgrError extends Error +{ + + /* + * Ordinals for various reasons why an Error of this type can be thrown. + */ + + /** + * Lexical error occurred. + */ + static final int LEXICAL_ERROR = 0; + + /** + * An attempt was made to create a second instance of a static token manager. + */ + static final int STATIC_LEXER_ERROR = 1; + + /** + * Tried to change to an invalid lexical state. + */ + static final int INVALID_LEXICAL_STATE = 2; + + /** + * Detected (and bailed out of) an infinite loop in the token manager. + */ + static final int LOOP_DETECTED = 3; + + /** + * Indicates the reason why the exception is thrown. It will have + * one of the above 4 values. + */ + int errorCode; + + /** + * Replaces unprintable characters by their escaped (or unicode escaped) + * equivalents in the given string + */ + protected static final String addEscapes(String str) { + StringBuffer retval = new StringBuffer(); + char ch; + for (int i = 0; i < str.length(); i++) { + switch (str.charAt(i)) + { + case 0 : + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + } else { + retval.append(ch); + } + continue; + } + } + return retval.toString(); + } + + /** + * Returns a detailed message for the Error when it is thrown by the + * token manager to indicate a lexical error. + * Parameters : + * EOFSeen : indicates if EOF caused the lexical error + * curLexState : lexical state in which this error occurred + * errorLine : line number when the error occurred + * errorColumn : column number when the error occurred + * errorAfter : prefix that was seen before this error occurred + * curchar : the offending character + * Note: You can customize the lexical error message by modifying this method. + */ + protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { + return("Lexical error at line " + + errorLine + ", column " + + errorColumn + ". Encountered: " + + (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + + "after : \"" + addEscapes(errorAfter) + "\""); + } + + /** + * You can also modify the body of this method to customize your error messages. + * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not + * of end-users concern, so you can return something like : + * + * "Internal Error : Please file a bug report .... " + * + * from this method for such cases in the release version of your parser. + */ + public String getMessage() { + return super.getMessage(); + } + + /* + * Constructors of various flavors follow. + */ + + /** No arg constructor. */ + public TokenMgrError() { + } + + /** Constructor with message and reason. */ + public TokenMgrError(String message, int reason) { + super(message); + errorCode = reason; + } + + /** Full Constructor. */ + public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { + this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); + } +} +/* JavaCC - OriginalChecksum=186d5bcc64733844c7daab5ad5a6e349 (do not edit this line) */ Index: 3rdParty_sources/lucene/org/apache/lucene/queryParser/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/queryParser/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/queryParser/package.html 17 Aug 2012 14:55:12 -0000 1.1 @@ -0,0 +1,31 @@ + + + + + + + + +A simple query parser implemented with JavaCC. +

Note that JavaCC defines lots of public classes, methods and fields +that do not need to be public.  These clutter the documentation.  +Sorry. +

Note that because JavaCC defines a class named Token, org.apache.lucene.analysis.Token +must always be fully qualified in source code in this package. + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/BooleanClause.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/BooleanClause.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/BooleanClause.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,115 @@ +package org.apache.lucene.search; + +import org.apache.lucene.util.Parameter; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** A clause in a BooleanQuery. */ +public class BooleanClause implements java.io.Serializable { + + /** Specifies how clauses are to occur in matching documents. */ + public static final class Occur extends Parameter implements java.io.Serializable { + + private Occur(String name) { + // typesafe enum pattern, no public constructor + super(name); + } + + public String toString() { + if (this == MUST) return "+"; + if (this == MUST_NOT) return "-"; + return ""; + } + + /** Use this operator for clauses that must appear in the matching documents. */ + public static final Occur MUST = new Occur("MUST"); + /** Use this operator for clauses that should appear in the + * matching documents. For a BooleanQuery with no MUST + * clauses one or more SHOULD clauses must match a document + * for the BooleanQuery to match. + * @see BooleanQuery#setMinimumNumberShouldMatch + */ + public static final Occur SHOULD = new Occur("SHOULD"); + /** Use this operator for clauses that must not appear in the matching documents. + * Note that it is not possible to search for queries that only consist + * of a MUST_NOT clause. */ + public static final Occur MUST_NOT = new Occur("MUST_NOT"); + + } + + /** The query whose matching documents are combined by the boolean query. + */ + private Query query; + + private Occur occur; + + + /** Constructs a BooleanClause. + */ + public BooleanClause(Query query, Occur occur) { + this.query = query; + this.occur = occur; + + } + + public Occur getOccur() { + return occur; + } + + public void setOccur(Occur occur) { + this.occur = occur; + + } + + public Query getQuery() { + return query; + } + + public void setQuery(Query query) { + this.query = query; + } + + public boolean isProhibited() { + return Occur.MUST_NOT.equals(occur); + } + + public boolean isRequired() { + return Occur.MUST.equals(occur); + } + + + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (!(o instanceof BooleanClause)) + return false; + BooleanClause other = (BooleanClause)o; + return this.query.equals(other.query) + && this.occur.equals(other.occur); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + return query.hashCode() ^ (Occur.MUST.equals(occur)?1:0) ^ (Occur.MUST_NOT.equals(occur)?2:0); + } + + + public String toString() { + return occur.toString() + query.toString(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/BooleanQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/BooleanQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/BooleanQuery.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,470 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.ToStringUtils; +import org.apache.lucene.search.BooleanClause.Occur; + +import java.io.IOException; +import java.util.*; + +/** A Query that matches documents matching boolean combinations of other + * queries, e.g. {@link TermQuery}s, {@link PhraseQuery}s or other + * BooleanQuerys. + */ +public class BooleanQuery extends Query { + + + private static int maxClauseCount = 1024; + + /** Thrown when an attempt is made to add more than {@link + * #getMaxClauseCount()} clauses. This typically happens if + * a PrefixQuery, FuzzyQuery, WildcardQuery, or RangeQuery + * is expanded to many terms during search. + */ + public static class TooManyClauses extends RuntimeException { + public TooManyClauses() {} + public String getMessage() { + return "maxClauseCount is set to " + maxClauseCount; + } + } + + /** Return the maximum number of clauses permitted, 1024 by default. + * Attempts to add more than the permitted number of clauses cause {@link + * TooManyClauses} to be thrown. + * @see #setMaxClauseCount(int) + */ + public static int getMaxClauseCount() { return maxClauseCount; } + + /** Set the maximum number of clauses permitted per BooleanQuery. + * Default value is 1024. + *

TermQuery clauses are generated from for example prefix queries and + * fuzzy queries. Each TermQuery needs some buffer space during search, + * so this parameter indirectly controls the maximum buffer requirements for + * query search. + *

When this parameter becomes a bottleneck for a Query one can use a + * Filter. For example instead of a {@link RangeQuery} one can use a + * {@link RangeFilter}. + *

Normally the buffers are allocated by the JVM. When using for example + * {@link org.apache.lucene.store.MMapDirectory} the buffering is left to + * the operating system. + */ + public static void setMaxClauseCount(int maxClauseCount) { + if (maxClauseCount < 1) + throw new IllegalArgumentException("maxClauseCount must be >= 1"); + BooleanQuery.maxClauseCount = maxClauseCount; + } + + private ArrayList clauses = new ArrayList(); + private boolean disableCoord; + + /** Constructs an empty boolean query. */ + public BooleanQuery() {} + + /** Constructs an empty boolean query. + * + * {@link Similarity#coord(int,int)} may be disabled in scoring, as + * appropriate. For example, this score factor does not make sense for most + * automatically generated queries, like {@link WildcardQuery} and {@link + * FuzzyQuery}. + * + * @param disableCoord disables {@link Similarity#coord(int,int)} in scoring. + */ + public BooleanQuery(boolean disableCoord) { + this.disableCoord = disableCoord; + } + + /** Returns true iff {@link Similarity#coord(int,int)} is disabled in + * scoring for this query instance. + * @see #BooleanQuery(boolean) + */ + public boolean isCoordDisabled() { return disableCoord; } + + // Implement coord disabling. + // Inherit javadoc. + public Similarity getSimilarity(Searcher searcher) { + Similarity result = super.getSimilarity(searcher); + if (disableCoord) { // disable coord as requested + result = new SimilarityDelegator(result) { + public float coord(int overlap, int maxOverlap) { + return 1.0f; + } + }; + } + return result; + } + + /** + * Specifies a minimum number of the optional BooleanClauses + * which must be satisfied. + * + *

+ * By default no optional clauses are necessary for a match + * (unless there are no required clauses). If this method is used, + * then the specified number of clauses is required. + *

+ *

+ * Use of this method is totally independent of specifying that + * any specific clauses are required (or prohibited). This number will + * only be compared against the number of matching optional clauses. + *

+ *

+ * EXPERT NOTE: Using this method may force collecting docs in order, + * regardless of whether setAllowDocsOutOfOrder(true) has been called. + *

+ * + * @param min the number of optional clauses that must match + * @see #setAllowDocsOutOfOrder + */ + public void setMinimumNumberShouldMatch(int min) { + this.minNrShouldMatch = min; + } + protected int minNrShouldMatch = 0; + + /** + * Gets the minimum number of the optional BooleanClauses + * which must be satisifed. + */ + public int getMinimumNumberShouldMatch() { + return minNrShouldMatch; + } + + /** Adds a clause to a boolean query. + * + * @throws TooManyClauses if the new number of clauses exceeds the maximum clause number + * @see #getMaxClauseCount() + */ + public void add(Query query, BooleanClause.Occur occur) { + add(new BooleanClause(query, occur)); + } + + /** Adds a clause to a boolean query. + * @throws TooManyClauses if the new number of clauses exceeds the maximum clause number + * @see #getMaxClauseCount() + */ + public void add(BooleanClause clause) { + if (clauses.size() >= maxClauseCount) + throw new TooManyClauses(); + + clauses.add(clause); + } + + /** Returns the set of clauses in this query. */ + public BooleanClause[] getClauses() { + return (BooleanClause[])clauses.toArray(new BooleanClause[clauses.size()]); + } + + /** Returns the list of clauses in this query. */ + public List clauses() { return clauses; } + + private class BooleanWeight implements Weight { + protected Similarity similarity; + protected ArrayList weights = new ArrayList(); + + public BooleanWeight(Searcher searcher) + throws IOException { + this.similarity = getSimilarity(searcher); + for (int i = 0 ; i < clauses.size(); i++) { + BooleanClause c = (BooleanClause)clauses.get(i); + weights.add(c.getQuery().createWeight(searcher)); + } + } + + public Query getQuery() { return BooleanQuery.this; } + public float getValue() { return getBoost(); } + + public float sumOfSquaredWeights() throws IOException { + float sum = 0.0f; + for (int i = 0 ; i < weights.size(); i++) { + BooleanClause c = (BooleanClause)clauses.get(i); + Weight w = (Weight)weights.get(i); + // call sumOfSquaredWeights for all clauses in case of side effects + float s = w.sumOfSquaredWeights(); // sum sub weights + if (!c.isProhibited()) + // only add to sum for non-prohibited clauses + sum += s; + } + + sum *= getBoost() * getBoost(); // boost each sub-weight + + return sum ; + } + + + public void normalize(float norm) { + norm *= getBoost(); // incorporate boost + for (int i = 0 ; i < weights.size(); i++) { + Weight w = (Weight)weights.get(i); + // normalize all clauses, (even if prohibited in case of side affects) + w.normalize(norm); + } + } + + /** @return Returns BooleanScorer2 that uses and provides skipTo(), + * and scores documents in document number order. + */ + public Scorer scorer(IndexReader reader) throws IOException { + BooleanScorer2 result = new BooleanScorer2(similarity, + minNrShouldMatch, + allowDocsOutOfOrder); + + for (int i = 0 ; i < weights.size(); i++) { + BooleanClause c = (BooleanClause)clauses.get(i); + Weight w = (Weight)weights.get(i); + Scorer subScorer = w.scorer(reader); + if (subScorer != null) + result.add(subScorer, c.isRequired(), c.isProhibited()); + else if (c.isRequired()) + return null; + } + + return result; + } + + public Explanation explain(IndexReader reader, int doc) + throws IOException { + final int minShouldMatch = + BooleanQuery.this.getMinimumNumberShouldMatch(); + ComplexExplanation sumExpl = new ComplexExplanation(); + sumExpl.setDescription("sum of:"); + int coord = 0; + int maxCoord = 0; + float sum = 0.0f; + boolean fail = false; + int shouldMatchCount = 0; + for (int i = 0 ; i < weights.size(); i++) { + BooleanClause c = (BooleanClause)clauses.get(i); + Weight w = (Weight)weights.get(i); + Explanation e = w.explain(reader, doc); + if (!c.isProhibited()) maxCoord++; + if (e.isMatch()) { + if (!c.isProhibited()) { + sumExpl.addDetail(e); + sum += e.getValue(); + coord++; + } else { + Explanation r = + new Explanation(0.0f, "match on prohibited clause (" + c.getQuery().toString() + ")"); + r.addDetail(e); + sumExpl.addDetail(r); + fail = true; + } + if (c.getOccur().equals(Occur.SHOULD)) + shouldMatchCount++; + } else if (c.isRequired()) { + Explanation r = new Explanation(0.0f, "no match on required clause (" + c.getQuery().toString() + ")"); + r.addDetail(e); + sumExpl.addDetail(r); + fail = true; + } + } + if (fail) { + sumExpl.setMatch(Boolean.FALSE); + sumExpl.setValue(0.0f); + sumExpl.setDescription + ("Failure to meet condition(s) of required/prohibited clause(s)"); + return sumExpl; + } else if (shouldMatchCount < minShouldMatch) { + sumExpl.setMatch(Boolean.FALSE); + sumExpl.setValue(0.0f); + sumExpl.setDescription("Failure to match minimum number "+ + "of optional clauses: " + minShouldMatch); + return sumExpl; + } + + sumExpl.setMatch(0 < coord ? Boolean.TRUE : Boolean.FALSE); + sumExpl.setValue(sum); + + float coordFactor = similarity.coord(coord, maxCoord); + if (coordFactor == 1.0f) // coord is no-op + return sumExpl; // eliminate wrapper + else { + ComplexExplanation result = new ComplexExplanation(sumExpl.isMatch(), + sum*coordFactor, + "product of:"); + result.addDetail(sumExpl); + result.addDetail(new Explanation(coordFactor, + "coord("+coord+"/"+maxCoord+")")); + return result; + } + } + } + + /** Whether hit docs may be collected out of docid order. */ + private static boolean allowDocsOutOfOrder = false; + + /** + * Expert: Indicates whether hit docs may be collected out of docid + * order. + * + *

+ * Background: although the contract of the Scorer class requires that + * documents be iterated in order of doc id, this was not true in early + * versions of Lucene. Many pieces of functionality in the current + * Lucene code base have undefined behavior if this contract is not + * upheld, but in some specific simple cases may be faster. (For + * example: disjunction queries with less than 32 prohibited clauses; + * This setting has no effect for other queries.) + *

+ * + *

+ * Specifics: By setting this option to true, calls to + * {@link HitCollector#collect(int,float)} might be + * invoked first for docid N and only later for docid N-1. + * Being static, this setting is system wide. + *

+ */ + public static void setAllowDocsOutOfOrder(boolean allow) { + allowDocsOutOfOrder = allow; + } + + /** + * Whether hit docs may be collected out of docid order. + * @see #setAllowDocsOutOfOrder(boolean) + */ + public static boolean getAllowDocsOutOfOrder() { + return allowDocsOutOfOrder; + } + + /** + * @deprecated Use {@link #setAllowDocsOutOfOrder(boolean)} instead. + */ + public static void setUseScorer14(boolean use14) { + setAllowDocsOutOfOrder(use14); + } + + /** + * @deprecated Use {@link #getAllowDocsOutOfOrder()} instead. + */ + public static boolean getUseScorer14() { + return getAllowDocsOutOfOrder(); + } + + protected Weight createWeight(Searcher searcher) throws IOException { + return new BooleanWeight(searcher); + } + + public Query rewrite(IndexReader reader) throws IOException { + if (minNrShouldMatch == 0 && clauses.size() == 1) { // optimize 1-clause queries + BooleanClause c = (BooleanClause)clauses.get(0); + if (!c.isProhibited()) { // just return clause + + Query query = c.getQuery().rewrite(reader); // rewrite first + + if (getBoost() != 1.0f) { // incorporate boost + if (query == c.getQuery()) // if rewrite was no-op + query = (Query)query.clone(); // then clone before boost + query.setBoost(getBoost() * query.getBoost()); + } + + return query; + } + } + + BooleanQuery clone = null; // recursively rewrite + for (int i = 0 ; i < clauses.size(); i++) { + BooleanClause c = (BooleanClause)clauses.get(i); + Query query = c.getQuery().rewrite(reader); + if (query != c.getQuery()) { // clause rewrote: must clone + if (clone == null) + clone = (BooleanQuery)this.clone(); + clone.clauses.set(i, new BooleanClause(query, c.getOccur())); + } + } + if (clone != null) { + return clone; // some clauses rewrote + } else + return this; // no clauses rewrote + } + + // inherit javadoc + public void extractTerms(Set terms) { + for (Iterator i = clauses.iterator(); i.hasNext();) { + BooleanClause clause = (BooleanClause) i.next(); + clause.getQuery().extractTerms(terms); + } + } + + public Object clone() { + BooleanQuery clone = (BooleanQuery)super.clone(); + clone.clauses = (ArrayList)this.clauses.clone(); + return clone; + } + + /** Prints a user-readable version of this query. */ + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + boolean needParens=(getBoost() != 1.0) || (getMinimumNumberShouldMatch()>0) ; + if (needParens) { + buffer.append("("); + } + + for (int i = 0 ; i < clauses.size(); i++) { + BooleanClause c = (BooleanClause)clauses.get(i); + if (c.isProhibited()) + buffer.append("-"); + else if (c.isRequired()) + buffer.append("+"); + + Query subQuery = c.getQuery(); + if (subQuery instanceof BooleanQuery) { // wrap sub-bools in parens + buffer.append("("); + buffer.append(c.getQuery().toString(field)); + buffer.append(")"); + } else + buffer.append(c.getQuery().toString(field)); + + if (i != clauses.size()-1) + buffer.append(" "); + } + + if (needParens) { + buffer.append(")"); + } + + if (getMinimumNumberShouldMatch()>0) { + buffer.append('~'); + buffer.append(getMinimumNumberShouldMatch()); + } + + if (getBoost() != 1.0f) + { + buffer.append(ToStringUtils.boost(getBoost())); + } + + return buffer.toString(); + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (!(o instanceof BooleanQuery)) + return false; + BooleanQuery other = (BooleanQuery)o; + return (this.getBoost() == other.getBoost()) + && this.clauses.equals(other.clauses) + && this.getMinimumNumberShouldMatch() == other.getMinimumNumberShouldMatch(); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + return Float.floatToIntBits(getBoost()) ^ clauses.hashCode() + + getMinimumNumberShouldMatch(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/BooleanScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/BooleanScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/BooleanScorer.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,272 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +final class BooleanScorer extends Scorer { + private SubScorer scorers = null; + private BucketTable bucketTable = new BucketTable(); + + private int maxCoord = 1; + private float[] coordFactors = null; + + private int requiredMask = 0; + private int prohibitedMask = 0; + private int nextMask = 1; + + private final int minNrShouldMatch; + + BooleanScorer(Similarity similarity) { + this(similarity, 1); + } + + BooleanScorer(Similarity similarity, int minNrShouldMatch) { + super(similarity); + this.minNrShouldMatch = minNrShouldMatch; + } + + static final class SubScorer { + public Scorer scorer; + public boolean done; + public boolean required = false; + public boolean prohibited = false; + public HitCollector collector; + public SubScorer next; + + public SubScorer(Scorer scorer, boolean required, boolean prohibited, + HitCollector collector, SubScorer next) + throws IOException { + this.scorer = scorer; + this.done = !scorer.next(); + this.required = required; + this.prohibited = prohibited; + this.collector = collector; + this.next = next; + } + } + + final void add(Scorer scorer, boolean required, boolean prohibited) + throws IOException { + int mask = 0; + if (required || prohibited) { + if (nextMask == 0) + throw new IndexOutOfBoundsException + ("More than 32 required/prohibited clauses in query."); + mask = nextMask; + nextMask = nextMask << 1; + } else + mask = 0; + + if (!prohibited) + maxCoord++; + + if (prohibited) + prohibitedMask |= mask; // update prohibited mask + else if (required) + requiredMask |= mask; // update required mask + + scorers = new SubScorer(scorer, required, prohibited, + bucketTable.newCollector(mask), scorers); + } + + private final void computeCoordFactors() { + coordFactors = new float[maxCoord]; + for (int i = 0; i < maxCoord; i++) + coordFactors[i] = getSimilarity().coord(i, maxCoord-1); + } + + private int end; + private Bucket current; + + public void score(HitCollector hc) throws IOException { + next(); + score(hc, Integer.MAX_VALUE); + } + + protected boolean score(HitCollector hc, int max) throws IOException { + if (coordFactors == null) + computeCoordFactors(); + + boolean more; + Bucket tmp; + + do { + bucketTable.first = null; + + while (current != null) { // more queued + + // check prohibited & required + if ((current.bits & prohibitedMask) == 0 && + (current.bits & requiredMask) == requiredMask) { + + if (current.doc >= max){ + tmp = current; + current = current.next; + tmp.next = bucketTable.first; + bucketTable.first = tmp; + continue; + } + + if (current.coord >= minNrShouldMatch) { + hc.collect(current.doc, current.score * coordFactors[current.coord]); + } + } + + current = current.next; // pop the queue + } + + if (bucketTable.first != null){ + current = bucketTable.first; + bucketTable.first = current.next; + return true; + } + + // refill the queue + more = false; + end += BucketTable.SIZE; + for (SubScorer sub = scorers; sub != null; sub = sub.next) { + if (!sub.done) { + sub.done = !sub.scorer.score(sub.collector, end); + if (!sub.done) + more = true; + } + } + current = bucketTable.first; + + } while (current != null || more); + + return false; + } + + public int doc() { return current.doc; } + + public boolean next() throws IOException { + boolean more; + do { + while (bucketTable.first != null) { // more queued + current = bucketTable.first; + bucketTable.first = current.next; // pop the queue + + // check prohibited & required, and minNrShouldMatch + if ((current.bits & prohibitedMask) == 0 && + (current.bits & requiredMask) == requiredMask && + current.coord >= minNrShouldMatch) { + return true; + } + } + + // refill the queue + more = false; + end += BucketTable.SIZE; + for (SubScorer sub = scorers; sub != null; sub = sub.next) { + Scorer scorer = sub.scorer; + while (!sub.done && scorer.doc() < end) { + sub.collector.collect(scorer.doc(), scorer.score()); + sub.done = !scorer.next(); + } + if (!sub.done) { + more = true; + } + } + } while (bucketTable.first != null || more); + + return false; + } + + public float score() { + if (coordFactors == null) + computeCoordFactors(); + return current.score * coordFactors[current.coord]; + } + + static final class Bucket { + int doc = -1; // tells if bucket is valid + float score; // incremental score + int bits; // used for bool constraints + int coord; // count of terms in score + Bucket next; // next valid bucket + } + + /** A simple hash table of document scores within a range. */ + static final class BucketTable { + public static final int SIZE = 1 << 11; + public static final int MASK = SIZE - 1; + + final Bucket[] buckets = new Bucket[SIZE]; + Bucket first = null; // head of valid list + + public BucketTable() {} + + public final int size() { return SIZE; } + + public HitCollector newCollector(int mask) { + return new Collector(mask, this); + } + } + + static final class Collector extends HitCollector { + private BucketTable bucketTable; + private int mask; + public Collector(int mask, BucketTable bucketTable) { + this.mask = mask; + this.bucketTable = bucketTable; + } + public final void collect(final int doc, final float score) { + final BucketTable table = bucketTable; + final int i = doc & BucketTable.MASK; + Bucket bucket = table.buckets[i]; + if (bucket == null) + table.buckets[i] = bucket = new Bucket(); + + if (bucket.doc != doc) { // invalid bucket + bucket.doc = doc; // set doc + bucket.score = score; // initialize score + bucket.bits = mask; // initialize mask + bucket.coord = 1; // initialize coord + + bucket.next = table.first; // push onto valid list + table.first = bucket; + } else { // valid bucket + bucket.score += score; // increment score + bucket.bits |= mask; // add bits in mask + bucket.coord++; // increment coord + } + } + } + + public boolean skipTo(int target) { + throw new UnsupportedOperationException(); + } + + public Explanation explain(int doc) { + throw new UnsupportedOperationException(); + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("boolean("); + for (SubScorer sub = scorers; sub != null; sub = sub.next) { + buffer.append(sub.scorer.toString()); + buffer.append(" "); + } + buffer.append(")"); + return buffer.toString(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/BooleanScorer2.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/BooleanScorer2.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/BooleanScorer2.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,390 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Iterator; + +/** An alternative to BooleanScorer that also allows a minimum number + * of optional scorers that should match. + *
Implements skipTo(), and has no limitations on the numbers of added scorers. + *
Uses ConjunctionScorer, DisjunctionScorer, ReqOptScorer and ReqExclScorer. + */ +class BooleanScorer2 extends Scorer { + private ArrayList requiredScorers = new ArrayList(); + private ArrayList optionalScorers = new ArrayList(); + private ArrayList prohibitedScorers = new ArrayList(); + + private class Coordinator { + int maxCoord = 0; // to be increased for each non prohibited scorer + + private float[] coordFactors = null; + + void init() { // use after all scorers have been added. + coordFactors = new float[maxCoord + 1]; + Similarity sim = getSimilarity(); + for (int i = 0; i <= maxCoord; i++) { + coordFactors[i] = sim.coord(i, maxCoord); + } + } + + int nrMatchers; // to be increased by score() of match counting scorers. + + void initDoc() { + nrMatchers = 0; + } + + float coordFactor() { + return coordFactors[nrMatchers]; + } + } + + private final Coordinator coordinator; + + /** The scorer to which all scoring will be delegated, + * except for computing and using the coordination factor. + */ + private Scorer countingSumScorer = null; + + /** The number of optionalScorers that need to match (if there are any) */ + private final int minNrShouldMatch; + + /** Whether it is allowed to return documents out of order. + * This can accelerate the scoring of disjunction queries. + */ + private boolean allowDocsOutOfOrder; + + + /** Create a BooleanScorer2. + * @param similarity The similarity to be used. + * @param minNrShouldMatch The minimum number of optional added scorers + * that should match during the search. + * In case no required scorers are added, + * at least one of the optional scorers will have to + * match during the search. + * @param allowDocsOutOfOrder Whether it is allowed to return documents out of order. + * This can accelerate the scoring of disjunction queries. + */ + public BooleanScorer2(Similarity similarity, int minNrShouldMatch, boolean allowDocsOutOfOrder) { + super(similarity); + if (minNrShouldMatch < 0) { + throw new IllegalArgumentException("Minimum number of optional scorers should not be negative"); + } + coordinator = new Coordinator(); + this.minNrShouldMatch = minNrShouldMatch; + this.allowDocsOutOfOrder = allowDocsOutOfOrder; + } + + /** Create a BooleanScorer2. + * In no required scorers are added, + * at least one of the optional scorers will have to match during the search. + * @param similarity The similarity to be used. + * @param minNrShouldMatch The minimum number of optional added scorers + * that should match during the search. + * In case no required scorers are added, + * at least one of the optional scorers will have to + * match during the search. + */ + public BooleanScorer2(Similarity similarity, int minNrShouldMatch) { + this(similarity, minNrShouldMatch, false); + } + + /** Create a BooleanScorer2. + * In no required scorers are added, + * at least one of the optional scorers will have to match during the search. + * @param similarity The similarity to be used. + */ + public BooleanScorer2(Similarity similarity) { + this(similarity, 0, false); + } + + public void add(final Scorer scorer, boolean required, boolean prohibited) { + if (!prohibited) { + coordinator.maxCoord++; + } + + if (required) { + if (prohibited) { + throw new IllegalArgumentException("scorer cannot be required and prohibited"); + } + requiredScorers.add(scorer); + } else if (prohibited) { + prohibitedScorers.add(scorer); + } else { + optionalScorers.add(scorer); + } + } + + /** Initialize the match counting scorer that sums all the + * scores.

+ * When "counting" is used in a name it means counting the number + * of matching scorers.
+ * When "sum" is used in a name it means score value summing + * over the matching scorers + */ + private void initCountingSumScorer() throws IOException { + coordinator.init(); + countingSumScorer = makeCountingSumScorer(); + } + + /** Count a scorer as a single match. */ + private class SingleMatchScorer extends Scorer { + private Scorer scorer; + private int lastScoredDoc = -1; + + SingleMatchScorer(Scorer scorer) { + super(scorer.getSimilarity()); + this.scorer = scorer; + } + public float score() throws IOException { + if (this.doc() >= lastScoredDoc) { + lastScoredDoc = this.doc(); + coordinator.nrMatchers++; + } + return scorer.score(); + } + public int doc() { + return scorer.doc(); + } + public boolean next() throws IOException { + return scorer.next(); + } + public boolean skipTo(int docNr) throws IOException { + return scorer.skipTo(docNr); + } + public Explanation explain(int docNr) throws IOException { + return scorer.explain(docNr); + } + } + + private Scorer countingDisjunctionSumScorer(final List scorers, + int minNrShouldMatch) + // each scorer from the list counted as a single matcher + { + return new DisjunctionSumScorer(scorers, minNrShouldMatch) { + private int lastScoredDoc = -1; + public float score() throws IOException { + if (this.doc() >= lastScoredDoc) { + lastScoredDoc = this.doc(); + coordinator.nrMatchers += super.nrMatchers; + } + return super.score(); + } + }; + } + + private static Similarity defaultSimilarity = new DefaultSimilarity(); + + private Scorer countingConjunctionSumScorer(List requiredScorers) throws IOException { + // each scorer from the list counted as a single matcher + final int requiredNrMatchers = requiredScorers.size(); + return new ConjunctionScorer(defaultSimilarity, requiredScorers) { + private int lastScoredDoc = -1; + + public float score() throws IOException { + if (this.doc() >= lastScoredDoc) { + lastScoredDoc = this.doc(); + coordinator.nrMatchers += requiredNrMatchers; + } + // All scorers match, so defaultSimilarity super.score() always has 1 as + // the coordination factor. + // Therefore the sum of the scores of the requiredScorers + // is used as score. + return super.score(); + } + }; + } + + private Scorer dualConjunctionSumScorer(Scorer req1, Scorer req2) throws IOException { // non counting. + return new ConjunctionScorer(defaultSimilarity, new Scorer[]{req1, req2}); + // All scorers match, so defaultSimilarity always has 1 as + // the coordination factor. + // Therefore the sum of the scores of two scorers + // is used as score. + } + + /** Returns the scorer to be used for match counting and score summing. + * Uses requiredScorers, optionalScorers and prohibitedScorers. + */ + private Scorer makeCountingSumScorer() throws IOException { // each scorer counted as a single matcher + return (requiredScorers.size() == 0) + ? makeCountingSumScorerNoReq() + : makeCountingSumScorerSomeReq(); + } + + private Scorer makeCountingSumScorerNoReq() throws IOException { // No required scorers + if (optionalScorers.size() == 0) { + return new NonMatchingScorer(); // no clauses or only prohibited clauses + } else { // No required scorers. At least one optional scorer. + // minNrShouldMatch optional scorers are required, but at least 1 + int nrOptRequired = (minNrShouldMatch < 1) ? 1 : minNrShouldMatch; + if (optionalScorers.size() < nrOptRequired) { + return new NonMatchingScorer(); // fewer optional clauses than minimum (at least 1) that should match + } else { // optionalScorers.size() >= nrOptRequired, no required scorers + Scorer requiredCountingSumScorer = + (optionalScorers.size() > nrOptRequired) + ? countingDisjunctionSumScorer(optionalScorers, nrOptRequired) + : // optionalScorers.size() == nrOptRequired (all optional scorers are required), no required scorers + (optionalScorers.size() == 1) + ? new SingleMatchScorer((Scorer) optionalScorers.get(0)) + : countingConjunctionSumScorer(optionalScorers); + return addProhibitedScorers(requiredCountingSumScorer); + } + } + } + + private Scorer makeCountingSumScorerSomeReq() throws IOException { // At least one required scorer. + if (optionalScorers.size() < minNrShouldMatch) { + return new NonMatchingScorer(); // fewer optional clauses than minimum that should match + } else if (optionalScorers.size() == minNrShouldMatch) { // all optional scorers also required. + ArrayList allReq = new ArrayList(requiredScorers); + allReq.addAll(optionalScorers); + return addProhibitedScorers(countingConjunctionSumScorer(allReq)); + } else { // optionalScorers.size() > minNrShouldMatch, and at least one required scorer + Scorer requiredCountingSumScorer = + (requiredScorers.size() == 1) + ? new SingleMatchScorer((Scorer) requiredScorers.get(0)) + : countingConjunctionSumScorer(requiredScorers); + if (minNrShouldMatch > 0) { // use a required disjunction scorer over the optional scorers + return addProhibitedScorers( + dualConjunctionSumScorer( // non counting + requiredCountingSumScorer, + countingDisjunctionSumScorer( + optionalScorers, + minNrShouldMatch))); + } else { // minNrShouldMatch == 0 + return new ReqOptSumScorer( + addProhibitedScorers(requiredCountingSumScorer), + ((optionalScorers.size() == 1) + ? new SingleMatchScorer((Scorer) optionalScorers.get(0)) + : countingDisjunctionSumScorer(optionalScorers, 1))); // require 1 in combined, optional scorer. + } + } + } + + /** Returns the scorer to be used for match counting and score summing. + * Uses the given required scorer and the prohibitedScorers. + * @param requiredCountingSumScorer A required scorer already built. + */ + private Scorer addProhibitedScorers(Scorer requiredCountingSumScorer) + { + return (prohibitedScorers.size() == 0) + ? requiredCountingSumScorer // no prohibited + : new ReqExclScorer(requiredCountingSumScorer, + ((prohibitedScorers.size() == 1) + ? (Scorer) prohibitedScorers.get(0) + : new DisjunctionSumScorer(prohibitedScorers))); + } + + /** Scores and collects all matching documents. + * @param hc The collector to which all matching documents are passed through + * {@link HitCollector#collect(int, float)}. + *
When this method is used the {@link #explain(int)} method should not be used. + */ + public void score(HitCollector hc) throws IOException { + if (allowDocsOutOfOrder && requiredScorers.size() == 0 + && prohibitedScorers.size() < 32) { + // fall back to BooleanScorer, scores documents somewhat out of order + BooleanScorer bs = new BooleanScorer(getSimilarity(), minNrShouldMatch); + Iterator si = optionalScorers.iterator(); + while (si.hasNext()) { + bs.add((Scorer) si.next(), false /* required */, false /* prohibited */); + } + si = prohibitedScorers.iterator(); + while (si.hasNext()) { + bs.add((Scorer) si.next(), false /* required */, true /* prohibited */); + } + bs.score(hc); + } else { + if (countingSumScorer == null) { + initCountingSumScorer(); + } + while (countingSumScorer.next()) { + hc.collect(countingSumScorer.doc(), score()); + } + } + } + + /** Expert: Collects matching documents in a range. + *
Note that {@link #next()} must be called once before this method is + * called for the first time. + * @param hc The collector to which all matching documents are passed through + * {@link HitCollector#collect(int, float)}. + * @param max Do not score documents past this. + * @return true if more matching documents may remain. + */ + protected boolean score(HitCollector hc, int max) throws IOException { + // null pointer exception when next() was not called before: + int docNr = countingSumScorer.doc(); + while (docNr < max) { + hc.collect(docNr, score()); + if (! countingSumScorer.next()) { + return false; + } + docNr = countingSumScorer.doc(); + } + return true; + } + + public int doc() { return countingSumScorer.doc(); } + + public boolean next() throws IOException { + if (countingSumScorer == null) { + initCountingSumScorer(); + } + return countingSumScorer.next(); + } + + public float score() throws IOException { + coordinator.initDoc(); + float sum = countingSumScorer.score(); + return sum * coordinator.coordFactor(); + } + + /** Skips to the first match beyond the current whose document number is + * greater than or equal to a given target. + * + *

When this method is used the {@link #explain(int)} method should not be used. + * + * @param target The target document number. + * @return true iff there is such a match. + */ + public boolean skipTo(int target) throws IOException { + if (countingSumScorer == null) { + initCountingSumScorer(); + } + return countingSumScorer.skipTo(target); + } + + /** Throws an UnsupportedOperationException. + * TODO: Implement an explanation of the coordination factor. + * @param doc The document number for the explanation. + * @throws UnsupportedOperationException + */ + public Explanation explain(int doc) { + throw new UnsupportedOperationException(); + /* How to explain the coordination factor? + initCountingSumScorer(); + return countingSumScorer.explain(doc); // misses coord factor. + */ + } +} + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/CachingSpanFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/CachingSpanFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/CachingSpanFilter.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,92 @@ +package org.apache.lucene.search; +/** + * Copyright 2005 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; +import java.util.BitSet; +import java.util.Map; +import java.util.WeakHashMap; + +/** + * Wraps another SpanFilter's result and caches it. The purpose is to allow + * filters to simply filter, and then wrap with this class to add caching. + */ +public class CachingSpanFilter extends SpanFilter { + protected SpanFilter filter; + + /** + * A transient Filter cache. To cache Filters even when using {@link org.apache.lucene.search.RemoteSearchable} use + * {@link org.apache.lucene.search.RemoteCachingWrapperFilter} instead. + */ + protected transient Map cache; + + /** + * @param filter Filter to cache results of + */ + public CachingSpanFilter(SpanFilter filter) { + this.filter = filter; + } + + /** + * @deprecated Use {@link #getDocIdSet(IndexReader)} instead. + */ + public BitSet bits(IndexReader reader) throws IOException { + SpanFilterResult result = getCachedResult(reader); + return result != null ? result.getBits() : null; + } + + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + SpanFilterResult result = getCachedResult(reader); + return result != null ? result.getDocIdSet() : null; + } + + private SpanFilterResult getCachedResult(IndexReader reader) throws IOException { + SpanFilterResult result = null; + if (cache == null) { + cache = new WeakHashMap(); + } + + synchronized (cache) { // check cache + result = (SpanFilterResult) cache.get(reader); + if (result == null) { + result = filter.bitSpans(reader); + cache.put(reader, result); + } + } + return result; + } + + + public SpanFilterResult bitSpans(IndexReader reader) throws IOException { + return getCachedResult(reader); + } + + public String toString() { + return "CachingSpanFilter("+filter+")"; + } + + public boolean equals(Object o) { + if (!(o instanceof CachingSpanFilter)) return false; + return this.filter.equals(((CachingSpanFilter)o).filter); + } + + public int hashCode() { + return filter.hashCode() ^ 0x1117BF25; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/CachingWrapperFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/CachingWrapperFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/CachingWrapperFilter.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,104 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import java.util.BitSet; +import java.util.WeakHashMap; +import java.util.Map; +import java.io.IOException; + +/** + * Wraps another filter's result and caches it. The purpose is to allow + * filters to simply filter, and then wrap with this class to add caching. + */ +public class CachingWrapperFilter extends Filter { + protected Filter filter; + + /** + * A transient Filter cache. To cache Filters even when using {@link RemoteSearchable} use + * {@link RemoteCachingWrapperFilter} instead. + */ + protected transient Map cache; + + /** + * @param filter Filter to cache results of + */ + public CachingWrapperFilter(Filter filter) { + this.filter = filter; + } + + /** + * @deprecated Use {@link #getDocIdSet(IndexReader)} instead. + */ + public BitSet bits(IndexReader reader) throws IOException { + if (cache == null) { + cache = new WeakHashMap(); + } + + synchronized (cache) { // check cache + BitSet cached = (BitSet) cache.get(reader); + if (cached != null) { + return cached; + } + } + + final BitSet bits = filter.bits(reader); + + synchronized (cache) { // update cache + cache.put(reader, bits); + } + + return bits; + } + + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + if (cache == null) { + cache = new WeakHashMap(); + } + + synchronized (cache) { // check cache + DocIdSet cached = (DocIdSet) cache.get(reader); + if (cached != null) { + return cached; + } + } + + final DocIdSet docIdSet = filter.getDocIdSet(reader); + + synchronized (cache) { // update cache + cache.put(reader, docIdSet); + } + + return docIdSet; + + } + + public String toString() { + return "CachingWrapperFilter("+filter+")"; + } + + public boolean equals(Object o) { + if (!(o instanceof CachingWrapperFilter)) return false; + return this.filter.equals(((CachingWrapperFilter)o).filter); + } + + public int hashCode() { + return filter.hashCode() ^ 0x1117BF25; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ComplexExplanation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ComplexExplanation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ComplexExplanation.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,69 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Expert: Describes the score computation for document and query, and + * can distinguish a match independent of a positive value. */ +public class ComplexExplanation extends Explanation { + private Boolean match; + + public ComplexExplanation() { + super(); + } + + public ComplexExplanation(boolean match, float value, String description) { + // NOTE: use of "boolean" instead of "Boolean" in params is concious + // choice to encourage clients to be specific. + super(value, description); + this.match = Boolean.valueOf(match); + } + + /** + * The match status of this explanation node. + * @return May be null if match status is unknown + */ + public Boolean getMatch() { return match; } + /** + * Sets the match status assigned to this explanation node. + * @param match May be null if match status is unknown + */ + public void setMatch(Boolean match) { this.match = match; } + /** + * Indicates whether or not this Explanation models a good match. + * + *

+ * If the match status is explicitly set (i.e.: not null) this method + * uses it; otherwise it defers to the superclass. + *

+ * @see #getMatch + */ + public boolean isMatch() { + Boolean m = getMatch(); + return (null != m ? m.booleanValue() : super.isMatch()); + } + + protected String getSummary() { + if (null == getMatch()) + return super.getSummary(); + + return getValue() + " = " + + (isMatch() ? "(MATCH) " : "(NON-MATCH) ") + + getDescription(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ConjunctionScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ConjunctionScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ConjunctionScorer.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,126 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Collection; +import java.util.Arrays; +import java.util.Comparator; + +/** Scorer for conjunctions, sets of queries, all of which are required. */ +class ConjunctionScorer extends Scorer { + private final Scorer[] scorers; + + private boolean firstTime=true; + private boolean more; + private final float coord; + private int lastDoc=-1; + + public ConjunctionScorer(Similarity similarity, Collection scorers) throws IOException { + this(similarity, (Scorer[])scorers.toArray(new Scorer[scorers.size()])); + } + + public ConjunctionScorer(Similarity similarity, Scorer[] scorers) throws IOException { + super(similarity); + this.scorers = scorers; + coord = getSimilarity().coord(this.scorers.length, this.scorers.length); + } + + public int doc() { return lastDoc; } + + public boolean next() throws IOException { + if (firstTime) + return init(0); + else if (more) + more = scorers[(scorers.length-1)].next(); + return doNext(); + } + + private boolean doNext() throws IOException { + int first=0; + Scorer lastScorer = scorers[scorers.length-1]; + Scorer firstScorer; + while (more && (firstScorer=scorers[first]).doc() < (lastDoc=lastScorer.doc())) { + more = firstScorer.skipTo(lastDoc); + lastScorer = firstScorer; + first = (first == (scorers.length-1)) ? 0 : first+1; + } + return more; + } + + public boolean skipTo(int target) throws IOException { + if (firstTime) + return init(target); + else if (more) + more = scorers[(scorers.length-1)].skipTo(target); + return doNext(); + } + + // Note... most of this could be done in the constructor + // thus skipping a check for firstTime per call to next() and skipTo() + private boolean init(int target) throws IOException { + firstTime=false; + more = scorers.length>1; + for (int i=0; i>1); i++) { + Scorer tmp = scorers[i]; + scorers[i] = scorers[end-i-1]; + scorers[end-i-1] = tmp; + } + + return more; + } + + public float score() throws IOException { + float sum = 0.0f; + for (int i = 0; i < scorers.length; i++) { + sum += scorers[i].score(); + } + return sum * coord; + } + + public Explanation explain(int doc) { + throw new UnsupportedOperationException(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ConstantScoreQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ConstantScoreQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ConstantScoreQuery.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,170 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; +import java.util.Set; + +/** + * A query that wraps a filter and simply returns a constant score equal to the + * query boost for every document in the filter. + * + * + * @version $Id: ConstantScoreQuery.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +public class ConstantScoreQuery extends Query { + protected final Filter filter; + + public ConstantScoreQuery(Filter filter) { + this.filter=filter; + } + + /** Returns the encapsulated filter */ + public Filter getFilter() { + return filter; + } + + public Query rewrite(IndexReader reader) throws IOException { + return this; + } + + public void extractTerms(Set terms) { + // OK to not add any terms when used for MultiSearcher, + // but may not be OK for highlighting + } + + protected class ConstantWeight implements Weight { + private Similarity similarity; + private float queryNorm; + private float queryWeight; + + public ConstantWeight(Searcher searcher) { + this.similarity = getSimilarity(searcher); + } + + public Query getQuery() { + return ConstantScoreQuery.this; + } + + public float getValue() { + return queryWeight; + } + + public float sumOfSquaredWeights() throws IOException { + queryWeight = getBoost(); + return queryWeight * queryWeight; + } + + public void normalize(float norm) { + this.queryNorm = norm; + queryWeight *= this.queryNorm; + } + + public Scorer scorer(IndexReader reader) throws IOException { + return new ConstantScorer(similarity, reader, this); + } + + public Explanation explain(IndexReader reader, int doc) throws IOException { + + ConstantScorer cs = (ConstantScorer)scorer(reader); + boolean exists = cs.docIdSetIterator.skipTo(doc) && (cs.docIdSetIterator.doc() == doc); + + ComplexExplanation result = new ComplexExplanation(); + + if (exists) { + result.setDescription("ConstantScoreQuery(" + filter + + "), product of:"); + result.setValue(queryWeight); + result.setMatch(Boolean.TRUE); + result.addDetail(new Explanation(getBoost(), "boost")); + result.addDetail(new Explanation(queryNorm,"queryNorm")); + } else { + result.setDescription("ConstantScoreQuery(" + filter + + ") doesn't match id " + doc); + result.setValue(0); + result.setMatch(Boolean.FALSE); + } + return result; + } + } + + protected class ConstantScorer extends Scorer { + final DocIdSetIterator docIdSetIterator; + final float theScore; + int doc=-1; + + public ConstantScorer(Similarity similarity, IndexReader reader, Weight w) throws IOException { + super(similarity); + theScore = w.getValue(); + docIdSetIterator = filter.getDocIdSet(reader).iterator(); + } + + public boolean next() throws IOException { + return docIdSetIterator.next(); + } + + public int doc() { + return docIdSetIterator.doc(); + } + + public float score() throws IOException { + return theScore; + } + + public boolean skipTo(int target) throws IOException { + return docIdSetIterator.skipTo(target); + } + + public Explanation explain(int doc) throws IOException { + throw new UnsupportedOperationException(); + } + } + + + protected Weight createWeight(Searcher searcher) { + return new ConstantScoreQuery.ConstantWeight(searcher); + } + + + /** Prints a user-readable version of this query. */ + public String toString(String field) + { + return "ConstantScore(" + filter.toString() + + (getBoost()==1.0 ? ")" : "^" + getBoost()); + } + + /** Returns true if o is equal to this. */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ConstantScoreQuery)) return false; + ConstantScoreQuery other = (ConstantScoreQuery)o; + return this.getBoost()==other.getBoost() && filter.equals(other.filter); + } + + /** Returns a hash code value for this object. */ + public int hashCode() { + // Simple add is OK since no existing filter hashcode has a float component. + return filter.hashCode() + Float.floatToIntBits(getBoost()); + } + +} + + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/ConstantScoreRangeQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ConstantScoreRangeQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ConstantScoreRangeQuery.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,152 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; +import java.text.Collator; + +/** + * A range query that returns a constant score equal to its boost for + * all documents in the range. + *

+ * It does not have an upper bound on the number of clauses covered in the range. + *

+ * If an endpoint is null, it is said to be "open". + * Either or both endpoints may be open. Open endpoints may not be exclusive + * (you can't select all but the first or last term without explicitly specifying the term to exclude.) + * + * + * @version $Id: ConstantScoreRangeQuery.java,v 1.1 2012/08/17 14:54:56 marcin Exp $ + */ + +public class ConstantScoreRangeQuery extends Query +{ + private final String fieldName; + private final String lowerVal; + private final String upperVal; + private final boolean includeLower; + private final boolean includeUpper; + private Collator collator; + + + public ConstantScoreRangeQuery(String fieldName, String lowerVal, String upperVal, boolean includeLower, boolean includeUpper) + { + // do a little bit of normalization... + // open ended range queries should always be inclusive. + if (lowerVal==null) { + includeLower=true; + } else if (includeLower && lowerVal.equals("")) { + lowerVal=null; + } + if (upperVal==null) { + includeUpper=true; + } + + + this.fieldName = fieldName.intern(); // intern it, just like terms... + this.lowerVal = lowerVal; + this.upperVal = upperVal; + this.includeLower = includeLower; + this.includeUpper = includeUpper; + } + + public ConstantScoreRangeQuery(String fieldName, String lowerVal, + String upperVal, boolean includeLower, + boolean includeUpper, Collator collator) + { + this(fieldName, lowerVal, upperVal, includeLower, includeUpper); + this.collator = collator; + } + + /** Returns the field name for this query */ + public String getField() { return fieldName; } + /** Returns the value of the lower endpoint of this range query, null if open ended */ + public String getLowerVal() { return lowerVal; } + /** Returns the value of the upper endpoint of this range query, null if open ended */ + public String getUpperVal() { return upperVal; } + /** Returns true if the lower endpoint is inclusive */ + public boolean includesLower() { return includeLower; } + /** Returns true if the upper endpoint is inclusive */ + public boolean includesUpper() { return includeUpper; } + + public Query rewrite(IndexReader reader) throws IOException { + // Map to RangeFilter semantics which are slightly different... + RangeFilter rangeFilt = new RangeFilter + (fieldName, lowerVal != null?lowerVal:"", upperVal, + lowerVal==""?false:includeLower, upperVal==null?false:includeUpper, + collator); + Query q = new ConstantScoreQuery(rangeFilt); + q.setBoost(getBoost()); + return q; + } + + /** Prints a user-readable version of this query. */ + public String toString(String field) + { + StringBuffer buffer = new StringBuffer(); + if (!getField().equals(field)) + { + buffer.append(getField()); + buffer.append(":"); + } + buffer.append(includeLower ? '[' : '{'); + buffer.append(lowerVal != null ? lowerVal : "*"); + buffer.append(" TO "); + buffer.append(upperVal != null ? upperVal : "*"); + buffer.append(includeUpper ? ']' : '}'); + if (getBoost() != 1.0f) + { + buffer.append("^"); + buffer.append(Float.toString(getBoost())); + } + return buffer.toString(); + } + + /** Returns true if o is equal to this. */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ConstantScoreRangeQuery)) return false; + ConstantScoreRangeQuery other = (ConstantScoreRangeQuery) o; + + if (this.fieldName != other.fieldName // interned comparison + || this.includeLower != other.includeLower + || this.includeUpper != other.includeUpper + || (this.collator != null && ! this.collator.equals(other.collator)) + ) { return false; } + if (this.lowerVal != null ? !this.lowerVal.equals(other.lowerVal) : other.lowerVal != null) return false; + if (this.upperVal != null ? !this.upperVal.equals(other.upperVal) : other.upperVal != null) return false; + return this.getBoost() == other.getBoost(); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + int h = Float.floatToIntBits(getBoost()) ^ fieldName.hashCode(); + // hashCode of "" is 0, so don't use that for null... + h ^= lowerVal != null ? lowerVal.hashCode() : 0x965a965a; + // don't just XOR upperVal with out mixing either it or h, as it will cancel + // out lowerVal if they are equal. + h ^= (h << 17) | (h >>> 16); // a reversible (one to one) 32 bit mapping mix + h ^= (upperVal != null ? (upperVal.hashCode()) : 0x5a695a69); + h ^= (includeLower ? 0x665599aa : 0) + ^ (includeUpper ? 0x99aa5566 : 0); + h ^= collator != null ? collator.hashCode() : 0; + return h; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/DefaultSimilarity.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/DefaultSimilarity.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/DefaultSimilarity.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,51 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Expert: Default scoring implementation. */ +public class DefaultSimilarity extends Similarity { + /** Implemented as 1/sqrt(numTerms). */ + public float lengthNorm(String fieldName, int numTerms) { + return (float)(1.0 / Math.sqrt(numTerms)); + } + + /** Implemented as 1/sqrt(sumOfSquaredWeights). */ + public float queryNorm(float sumOfSquaredWeights) { + return (float)(1.0 / Math.sqrt(sumOfSquaredWeights)); + } + + /** Implemented as sqrt(freq). */ + public float tf(float freq) { + return (float)Math.sqrt(freq); + } + + /** Implemented as 1 / (distance + 1). */ + public float sloppyFreq(int distance) { + return 1.0f / (distance + 1); + } + + /** Implemented as log(numDocs/(docFreq+1)) + 1. */ + public float idf(int docFreq, int numDocs) { + return (float)(Math.log(numDocs/(double)(docFreq+1)) + 1.0); + } + + /** Implemented as overlap / maxOverlap. */ + public float coord(int overlap, int maxOverlap) { + return overlap / (float)maxOverlap; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/DisjunctionMaxQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/DisjunctionMaxQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/DisjunctionMaxQuery.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,256 @@ +package org.apache.lucene.search; + +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Collection; +import java.util.Set; + +/** + * A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum + * score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries. + * This is useful when searching for a word in multiple fields with different boost factors (so that the fields cannot be + * combined equivalently into a single search field). We want the primary score to be the one associated with the highest boost, + * not the sum of the field scores (as BooleanQuery would give). + * If the query is "albino elephant" this ensures that "albino" matching one field and "elephant" matching + * another gets a higher score than "albino" matching both fields. + * To get this result, use both BooleanQuery and DisjunctionMaxQuery: for each term a DisjunctionMaxQuery searches for it in + * each field, while the set of these DisjunctionMaxQuery's is combined into a BooleanQuery. + * The tie breaker capability allows results that include the same term in multiple fields to be judged better than results that + * include this term in only the best of those multiple fields, without confusing this with the better case of two different terms + * in the multiple fields. + */ +public class DisjunctionMaxQuery extends Query { + + /* The subqueries */ + private ArrayList disjuncts = new ArrayList(); + + /* Multiple of the non-max disjunct scores added into our final score. Non-zero values support tie-breaking. */ + private float tieBreakerMultiplier = 0.0f; + + /** Creates a new empty DisjunctionMaxQuery. Use add() to add the subqueries. + * @param tieBreakerMultiplier the score of each non-maximum disjunct for a document is multiplied by this weight + * and added into the final score. If non-zero, the value should be small, on the order of 0.1, which says that + * 10 occurrences of word in a lower-scored field that is also in a higher scored field is just as good as a unique + * word in the lower scored field (i.e., one that is not in any higher scored field. + */ + public DisjunctionMaxQuery(float tieBreakerMultiplier) { + this.tieBreakerMultiplier = tieBreakerMultiplier; + } + + /** + * Creates a new DisjunctionMaxQuery + * @param disjuncts a Collection of all the disjuncts to add + * @param tieBreakerMultiplier the weight to give to each matching non-maximum disjunct + */ + public DisjunctionMaxQuery(Collection disjuncts, float tieBreakerMultiplier) { + this.tieBreakerMultiplier = tieBreakerMultiplier; + add(disjuncts); + } + + /** Add a subquery to this disjunction + * @param query the disjunct added + */ + public void add(Query query) { + disjuncts.add(query); + } + + /** Add a collection of disjuncts to this disjunction + * via Iterable + */ + public void add(Collection disjuncts) { + this.disjuncts.addAll(disjuncts); + } + + /** An Iterator over the disjuncts */ + public Iterator iterator() { + return disjuncts.iterator(); + } + + /* The Weight for DisjunctionMaxQuery's, used to normalize, score and explain these queries */ + private class DisjunctionMaxWeight implements Weight { + + private Similarity similarity; // The similarity which we are associated. + private ArrayList weights = new ArrayList(); // The Weight's for our subqueries, in 1-1 correspondence with disjuncts + + /* Construct the Weight for this Query searched by searcher. Recursively construct subquery weights. */ + public DisjunctionMaxWeight(Searcher searcher) throws IOException { + this.similarity = searcher.getSimilarity(); + for (int i = 0; i < disjuncts.size(); i++) + weights.add(((Query) disjuncts.get(i)).createWeight(searcher)); + } + + /* Return our associated DisjunctionMaxQuery */ + public Query getQuery() { return DisjunctionMaxQuery.this; } + + /* Return our boost */ + public float getValue() { return getBoost(); } + + /* Compute the sub of squared weights of us applied to our subqueries. Used for normalization. */ + public float sumOfSquaredWeights() throws IOException { + float max = 0.0f, sum = 0.0f; + for (int i = 0; i < weights.size(); i++) { + float sub = ((Weight) weights.get(i)).sumOfSquaredWeights(); + sum += sub; + max = Math.max(max, sub); + } + return (((sum - max) * tieBreakerMultiplier * tieBreakerMultiplier) + max) * getBoost() * getBoost(); + } + + /* Apply the computed normalization factor to our subqueries */ + public void normalize(float norm) { + norm *= getBoost(); // Incorporate our boost + for (int i = 0 ; i < weights.size(); i++) + ((Weight) weights.get(i)).normalize(norm); + } + + /* Create the scorer used to score our associated DisjunctionMaxQuery */ + public Scorer scorer(IndexReader reader) throws IOException { + DisjunctionMaxScorer result = new DisjunctionMaxScorer(tieBreakerMultiplier, similarity); + for (int i = 0 ; i < weights.size(); i++) { + Weight w = (Weight) weights.get(i); + Scorer subScorer = w.scorer(reader); + if (subScorer == null) return null; + result.add(subScorer); + } + return result; + } + + /* Explain the score we computed for doc */ + public Explanation explain(IndexReader reader, int doc) throws IOException { + if ( disjuncts.size() == 1) return ((Weight) weights.get(0)).explain(reader,doc); + ComplexExplanation result = new ComplexExplanation(); + float max = 0.0f, sum = 0.0f; + result.setDescription(tieBreakerMultiplier == 0.0f ? "max of:" : "max plus " + tieBreakerMultiplier + " times others of:"); + for (int i = 0 ; i < weights.size(); i++) { + Explanation e = ((Weight) weights.get(i)).explain(reader, doc); + if (e.isMatch()) { + result.setMatch(Boolean.TRUE); + result.addDetail(e); + sum += e.getValue(); + max = Math.max(max, e.getValue()); + } + } + result.setValue(max + (sum - max)*tieBreakerMultiplier); + return result; + } + + } // end of DisjunctionMaxWeight inner class + + /* Create the Weight used to score us */ + protected Weight createWeight(Searcher searcher) throws IOException { + return new DisjunctionMaxWeight(searcher); + } + + /** Optimize our representation and our subqueries representations + * @param reader the IndexReader we query + * @return an optimized copy of us (which may not be a copy if there is nothing to optimize) */ + public Query rewrite(IndexReader reader) throws IOException { + if (disjuncts.size() == 1) { + Query singleton = (Query) disjuncts.get(0); + Query result = singleton.rewrite(reader); + if (getBoost() != 1.0f) { + if (result == singleton) result = (Query)result.clone(); + result.setBoost(getBoost() * result.getBoost()); + } + return result; + } + DisjunctionMaxQuery clone = null; + for (int i = 0 ; i < disjuncts.size(); i++) { + Query clause = (Query) disjuncts.get(i); + Query rewrite = clause.rewrite(reader); + if (rewrite != clause) { + if (clone == null) clone = (DisjunctionMaxQuery)this.clone(); + clone.disjuncts.set(i, rewrite); + } + } + if (clone != null) return clone; + else return this; + } + + /** Create a shallow copy of us -- used in rewriting if necessary + * @return a copy of us (but reuse, don't copy, our subqueries) */ + public Object clone() { + DisjunctionMaxQuery clone = (DisjunctionMaxQuery)super.clone(); + clone.disjuncts = (ArrayList)this.disjuncts.clone(); + return clone; + } + + + // inherit javadoc + public void extractTerms(Set terms) { + for (int i = 0; i < disjuncts.size(); i++) { + ((Query)disjuncts.get(i)).extractTerms(terms); + } + } + + + /** Prettyprint us. + * @param field the field to which we are applied + * @return a string that shows what we do, of the form "(disjunct1 | disjunct2 | ... | disjunctn)^boost" + */ + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + buffer.append("("); + for (int i = 0 ; i < disjuncts.size(); i++) { + Query subquery = (Query) disjuncts.get(i); + if (subquery instanceof BooleanQuery) { // wrap sub-bools in parens + buffer.append("("); + buffer.append(subquery.toString(field)); + buffer.append(")"); + } + else buffer.append(subquery.toString(field)); + if (i != disjuncts.size()-1) buffer.append(" | "); + } + buffer.append(")"); + if (tieBreakerMultiplier != 0.0f) { + buffer.append("~"); + buffer.append(tieBreakerMultiplier); + } + if (getBoost() != 1.0) { + buffer.append("^"); + buffer.append(getBoost()); + } + return buffer.toString(); + } + + /** Return true iff we represent the same query as o + * @param o another object + * @return true iff o is a DisjunctionMaxQuery with the same boost and the same subqueries, in the same order, as us + */ + public boolean equals(Object o) { + if (! (o instanceof DisjunctionMaxQuery) ) return false; + DisjunctionMaxQuery other = (DisjunctionMaxQuery)o; + return this.getBoost() == other.getBoost() + && this.tieBreakerMultiplier == other.tieBreakerMultiplier + && this.disjuncts.equals(other.disjuncts); + } + + /** Compute a hash code for hashing us + * @return the hash code + */ + public int hashCode() { + return Float.floatToIntBits(getBoost()) + + Float.floatToIntBits(tieBreakerMultiplier) + + disjuncts.hashCode(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/DisjunctionMaxScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/DisjunctionMaxScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/DisjunctionMaxScorer.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,194 @@ +package org.apache.lucene.search; + +/** + * Copyright 2004 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.ArrayList; + +/** + * The Scorer for DisjunctionMaxQuery's. The union of all documents generated by the the subquery scorers + * is generated in document number order. The score for each document is the maximum of the scores computed + * by the subquery scorers that generate that document, plus tieBreakerMultiplier times the sum of the scores + * for the other subqueries that generate the document. + */ +class DisjunctionMaxScorer extends Scorer { + + /* The scorers for subqueries that have remaining docs, kept as a min heap by number of next doc. */ + private ArrayList subScorers = new ArrayList(); + + /* Multiplier applied to non-maximum-scoring subqueries for a document as they are summed into the result. */ + private float tieBreakerMultiplier; + + private boolean more = false; // True iff there is a next document + private boolean firstTime = true; // True iff next() has not yet been called + + /** Creates a new instance of DisjunctionMaxScorer + * @param tieBreakerMultiplier Multiplier applied to non-maximum-scoring subqueries for a document as they are summed into the result. + * @param similarity -- not used since our definition involves neither coord nor terms directly */ + public DisjunctionMaxScorer(float tieBreakerMultiplier, Similarity similarity) { + super(similarity); + this.tieBreakerMultiplier = tieBreakerMultiplier; + } + + /** Add the scorer for a subquery + * @param scorer the scorer of a subquery of our associated DisjunctionMaxQuery + */ + public void add(Scorer scorer) throws IOException { + if (scorer.next()) { // Initialize and retain only if it produces docs + subScorers.add(scorer); + more = true; + } + } + + /** Generate the next document matching our associated DisjunctionMaxQuery. + * @return true iff there is a next document + */ + public boolean next() throws IOException { + if (!more) return false; + if (firstTime) { + heapify(); + firstTime = false; + return true; // more would have been false if no subScorers had any docs + } + // Increment all generators that generated the last doc and adjust the heap. + int lastdoc = ((Scorer) subScorers.get(0)).doc(); + do { + if (((Scorer) subScorers.get(0)).next()) + heapAdjust(0); + else { + heapRemoveRoot(); + if (subScorers.isEmpty()) return (more = false); + } + } while ( ((Scorer) subScorers.get(0)).doc()==lastdoc ); + return true; + } + + /** Determine the current document number. Initially invalid, until {@link #next()} is called the first time. + * @return the document number of the currently generated document + */ + public int doc() { + return ((Scorer) subScorers.get(0)).doc(); + } + + /** Determine the current document score. Initially invalid, until {@link #next()} is called the first time. + * @return the score of the current generated document + */ + public float score() throws IOException { + int doc = ((Scorer) subScorers.get(0)).doc(); + float[] sum = {((Scorer) subScorers.get(0)).score()}, max = {sum[0]}; + int size = subScorers.size(); + scoreAll(1, size, doc, sum, max); + scoreAll(2, size, doc, sum, max); + return max[0] + (sum[0] - max[0])*tieBreakerMultiplier; + } + + // Recursively iterate all subScorers that generated last doc computing sum and max + private void scoreAll(int root, int size, int doc, float[] sum, float[] max) throws IOException { + if (root0 && ((Scorer)subScorers.get(0)).doc()>1)-1; i>=0; i--) + heapAdjust(i); + } + + /* The subtree of subScorers at root is a min heap except possibly for its root element. + * Bubble the root down as required to make the subtree a heap. + */ + private void heapAdjust(int root) { + Scorer scorer=(Scorer)subScorers.get(root); + int doc=scorer.doc(); + int i=root, size=subScorers.size(); + while (i<=(size>>1)-1) { + int lchild=(i<<1)+1; + Scorer lscorer=(Scorer)subScorers.get(lchild); + int ldoc=lscorer.doc(); + int rdoc=Integer.MAX_VALUE, rchild=(i<<1)+2; + Scorer rscorer=null; + if (rchildConjunctionScorer. + * This Scorer implements {@link Scorer#skipTo(int)} and uses skipTo() on the given Scorers. + * @todo Implement score(HitCollector, int). + */ +class DisjunctionSumScorer extends Scorer { + /** The number of subscorers. */ + private final int nrScorers; + + /** The subscorers. */ + protected final List subScorers; + + /** The minimum number of scorers that should match. */ + private final int minimumNrMatchers; + + /** The scorerDocQueue contains all subscorers ordered by their current doc(), + * with the minimum at the top. + *
The scorerDocQueue is initialized the first time next() or skipTo() is called. + *
An exhausted scorer is immediately removed from the scorerDocQueue. + *
If less than the minimumNrMatchers scorers + * remain in the scorerDocQueue next() and skipTo() return false. + *

+ * After each to call to next() or skipTo() + * currentSumScore is the total score of the current matching doc, + * nrMatchers is the number of matching scorers, + * and all scorers are after the matching doc, or are exhausted. + */ + private ScorerDocQueue scorerDocQueue = null; + private int queueSize = -1; // used to avoid size() method calls on scorerDocQueue + + /** The document number of the current match. */ + private int currentDoc = -1; + + /** The number of subscorers that provide the current match. */ + protected int nrMatchers = -1; + + private float currentScore = Float.NaN; + + /** Construct a DisjunctionScorer. + * @param subScorers A collection of at least two subscorers. + * @param minimumNrMatchers The positive minimum number of subscorers that should + * match to match this query. + *
When minimumNrMatchers is bigger than + * the number of subScorers, + * no matches will be produced. + *
When minimumNrMatchers equals the number of subScorers, + * it more efficient to use ConjunctionScorer. + */ + public DisjunctionSumScorer( List subScorers, int minimumNrMatchers) { + super(null); + + nrScorers = subScorers.size(); + + if (minimumNrMatchers <= 0) { + throw new IllegalArgumentException("Minimum nr of matchers must be positive"); + } + if (nrScorers <= 1) { + throw new IllegalArgumentException("There must be at least 2 subScorers"); + } + + this.minimumNrMatchers = minimumNrMatchers; + this.subScorers = subScorers; + } + + /** Construct a DisjunctionScorer, using one as the minimum number + * of matching subscorers. + */ + public DisjunctionSumScorer(List subScorers) { + this(subScorers, 1); + } + + /** Called the first time next() or skipTo() is called to + * initialize scorerDocQueue. + */ + private void initScorerDocQueue() throws IOException { + Iterator si = subScorers.iterator(); + scorerDocQueue = new ScorerDocQueue(nrScorers); + queueSize = 0; + while (si.hasNext()) { + Scorer se = (Scorer) si.next(); + if (se.next()) { // doc() method will be used in scorerDocQueue. + if (scorerDocQueue.insert(se)) { + queueSize++; + } + } + } + } + + /** Scores and collects all matching documents. + * @param hc The collector to which all matching documents are passed through + * {@link HitCollector#collect(int, float)}. + *
When this method is used the {@link #explain(int)} method should not be used. + */ + public void score(HitCollector hc) throws IOException { + while (next()) { + hc.collect(currentDoc, currentScore); + } + } + + /** Expert: Collects matching documents in a range. Hook for optimization. + * Note that {@link #next()} must be called once before this method is called + * for the first time. + * @param hc The collector to which all matching documents are passed through + * {@link HitCollector#collect(int, float)}. + * @param max Do not score documents past this. + * @return true if more matching documents may remain. + */ + protected boolean score(HitCollector hc, int max) throws IOException { + while (currentDoc < max) { + hc.collect(currentDoc, currentScore); + if (!next()) { + return false; + } + } + return true; + } + + public boolean next() throws IOException { + if (scorerDocQueue == null) { + initScorerDocQueue(); + } + return (scorerDocQueue.size() >= minimumNrMatchers) + && advanceAfterCurrent(); + } + + + /** Advance all subscorers after the current document determined by the + * top of the scorerDocQueue. + * Repeat until at least the minimum number of subscorers match on the same + * document and all subscorers are after that document or are exhausted. + *
On entry the scorerDocQueue has at least minimumNrMatchers + * available. At least the scorer with the minimum document number will be advanced. + * @return true iff there is a match. + *
In case there is a match, currentDoc, currentSumScore, + * and nrMatchers describe the match. + * + * @todo Investigate whether it is possible to use skipTo() when + * the minimum number of matchers is bigger than one, ie. try and use the + * character of ConjunctionScorer for the minimum number of matchers. + * Also delay calling score() on the sub scorers until the minimum number of + * matchers is reached. + *
For this, a Scorer array with minimumNrMatchers elements might + * hold Scorers at currentDoc that are temporarily popped from scorerQueue. + */ + protected boolean advanceAfterCurrent() throws IOException { + do { // repeat until minimum nr of matchers + currentDoc = scorerDocQueue.topDoc(); + currentScore = scorerDocQueue.topScore(); + nrMatchers = 1; + do { // Until all subscorers are after currentDoc + if (! scorerDocQueue.topNextAndAdjustElsePop()) { + if (--queueSize == 0) { + break; // nothing more to advance, check for last match. + } + } + if (scorerDocQueue.topDoc() != currentDoc) { + break; // All remaining subscorers are after currentDoc. + } + currentScore += scorerDocQueue.topScore(); + nrMatchers++; + } while (true); + + if (nrMatchers >= minimumNrMatchers) { + return true; + } else if (queueSize < minimumNrMatchers) { + return false; + } + } while (true); + } + + /** Returns the score of the current document matching the query. + * Initially invalid, until {@link #next()} is called the first time. + */ + public float score() throws IOException { return currentScore; } + + public int doc() { return currentDoc; } + + /** Returns the number of subscorers matching the current document. + * Initially invalid, until {@link #next()} is called the first time. + */ + public int nrMatchers() { + return nrMatchers; + } + + /** Skips to the first match beyond the current whose document number is + * greater than or equal to a given target. + *
When this method is used the {@link #explain(int)} method should not be used. + *
The implementation uses the skipTo() method on the subscorers. + * @param target The target document number. + * @return true iff there is such a match. + */ + public boolean skipTo(int target) throws IOException { + if (scorerDocQueue == null) { + initScorerDocQueue(); + } + if (queueSize < minimumNrMatchers) { + return false; + } + if (target <= currentDoc) { + return true; + } + do { + if (scorerDocQueue.topDoc() >= target) { + return advanceAfterCurrent(); + } else if (! scorerDocQueue.topSkipToAndAdjustElsePop(target)) { + if (--queueSize < minimumNrMatchers) { + return false; + } + } + } while (true); + } + + /** @return An explanation for the score of a given document. */ + public Explanation explain(int doc) throws IOException { + Explanation res = new Explanation(); + Iterator ssi = subScorers.iterator(); + float sumScore = 0.0f; + int nrMatches = 0; + while (ssi.hasNext()) { + Explanation es = ((Scorer) ssi.next()).explain(doc); + if (es.getValue() > 0.0f) { // indicates match + sumScore += es.getValue(); + nrMatches++; + } + res.addDetail(es); + } + if (nrMatchers >= minimumNrMatchers) { + res.setValue(sumScore); + res.setDescription("sum over at least " + minimumNrMatchers + + " of " + subScorers.size() + ":"); + } else { + res.setValue(0.0f); + res.setDescription(nrMatches + " match(es) but at least " + + minimumNrMatchers + " of " + + subScorers.size() + " needed"); + } + return res; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/DocIdSet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/DocIdSet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/DocIdSet.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,27 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * A DocIdSet contains a set of doc ids. Implementing classes must provide + * a {@link DocIdSetIterator} to access the set. + */ +public abstract class DocIdSet { + public abstract DocIdSetIterator iterator(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/DocIdSetIterator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/DocIdSetIterator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/DocIdSetIterator.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,49 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + * This abstract class defines methods to iterate over a set of + * non-decreasing doc ids. + */ +public abstract class DocIdSetIterator { + /** Returns the current document number.

This is invalid until {@link + #next()} is called for the first time.*/ + public abstract int doc(); + + /** Moves to the next docId in the set. Returns true, iff + * there is such a docId. */ + public abstract boolean next() throws IOException; + + /** Skips entries to the first beyond the current whose document number is + * greater than or equal to target.

Returns true iff there is such + * an entry.

Behaves as if written:

+     *   boolean skipTo(int target) {
+     *     do {
+     *       if (!next())
+     *         return false;
+     *     } while (target > doc());
+     *     return true;
+     *   }
+     * 
+ * Some implementations are considerably more efficient than that. + */ + public abstract boolean skipTo(int target) throws IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ExactPhraseScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ExactPhraseScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ExactPhraseScorer.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,55 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.index.*; + +final class ExactPhraseScorer extends PhraseScorer { + + ExactPhraseScorer(Weight weight, TermPositions[] tps, int[] offsets, Similarity similarity, + byte[] norms) { + super(weight, tps, offsets, similarity, norms); + } + + protected final float phraseFreq() throws IOException { + // sort list with pq + pq.clear(); + for (PhrasePositions pp = first; pp != null; pp = pp.next) { + pp.firstPosition(); + pq.put(pp); // build pq from list + } + pqToList(); // rebuild list from pq + + // for counting how many times the exact phrase is found in current document, + // just count how many times all PhrasePosition's have exactly the same position. + int freq = 0; + do { // find position w/ all terms + while (first.position < last.position) { // scan forward in first + do { + if (!first.nextPosition()) + return (float)freq; + } while (first.position < last.position); + firstToLast(); + } + freq++; // all equal: a match + } while (last.nextPosition()); + + return (float)freq; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Explanation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Explanation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Explanation.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,127 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; + +/** Expert: Describes the score computation for document and query. */ +public class Explanation implements java.io.Serializable { + private float value; // the value of this node + private String description; // what it represents + private ArrayList details; // sub-explanations + + public Explanation() {} + + public Explanation(float value, String description) { + this.value = value; + this.description = description; + } + + /** + * Indicates whether or not this Explanation models a good match. + * + *

+ * By default, an Explanation represents a "match" if the value is positive. + *

+ * @see #getValue + */ + public boolean isMatch() { + return (0.0f < getValue()); + } + + + + /** The value assigned to this explanation node. */ + public float getValue() { return value; } + /** Sets the value assigned to this explanation node. */ + public void setValue(float value) { this.value = value; } + + /** A description of this explanation node. */ + public String getDescription() { return description; } + /** Sets the description of this explanation node. */ + public void setDescription(String description) { + this.description = description; + } + + /** + * A short one line summary which should contain all high level + * information about this Explanation, without the "Details" + */ + protected String getSummary() { + return getValue() + " = " + getDescription(); + } + + /** The sub-nodes of this explanation node. */ + public Explanation[] getDetails() { + if (details == null) + return null; + return (Explanation[])details.toArray(new Explanation[0]); + } + + /** Adds a sub-node to this explanation node. */ + public void addDetail(Explanation detail) { + if (details == null) + details = new ArrayList(); + details.add(detail); + } + + /** Render an explanation as text. */ + public String toString() { + return toString(0); + } + protected String toString(int depth) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < depth; i++) { + buffer.append(" "); + } + buffer.append(getSummary()); + buffer.append("\n"); + + Explanation[] details = getDetails(); + if (details != null) { + for (int i = 0 ; i < details.length; i++) { + buffer.append(details[i].toString(depth+1)); + } + } + + return buffer.toString(); + } + + + /** Render an explanation as HTML. */ + public String toHtml() { + StringBuffer buffer = new StringBuffer(); + buffer.append("
    \n"); + + buffer.append("
  • "); + buffer.append(getSummary()); + buffer.append("
    \n"); + + Explanation[] details = getDetails(); + if (details != null) { + for (int i = 0 ; i < details.length; i++) { + buffer.append(details[i].toHtml()); + } + } + + buffer.append("
  • \n"); + buffer.append("
\n"); + + return buffer.toString(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ExtendedFieldCache.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ExtendedFieldCache.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ExtendedFieldCache.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,104 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; + + +/** + * + * + **/ +public interface ExtendedFieldCache extends FieldCache { + public interface LongParser { + /** + * Return an long representation of this field's value. + */ + public long parseLong(String string); + } + + public interface DoubleParser { + /** + * Return an long representation of this field's value. + */ + public double parseDouble(String string); + } + + public static ExtendedFieldCache EXT_DEFAULT = new ExtendedFieldCacheImpl(); + + /** + * Checks the internal cache for an appropriate entry, and if none is + * found, reads the terms in field as longs and returns an array + * of size reader.maxDoc() of the value each document + * has in the given field. + * + * @param reader Used to get field values. + * @param field Which field contains the longs. + * @return The values in the given field for each document. + * @throws java.io.IOException If any error occurs. + */ + public long[] getLongs(IndexReader reader, String field) + throws IOException; + + /** + * Checks the internal cache for an appropriate entry, and if none is found, + * reads the terms in field as longs and returns an array of + * size reader.maxDoc() of the value each document has in the + * given field. + * + * @param reader Used to get field values. + * @param field Which field contains the longs. + * @param parser Computes integer for string values. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public long[] getLongs(IndexReader reader, String field, LongParser parser) + throws IOException; + + + /** + * Checks the internal cache for an appropriate entry, and if none is + * found, reads the terms in field as integers and returns an array + * of size reader.maxDoc() of the value each document + * has in the given field. + * + * @param reader Used to get field values. + * @param field Which field contains the doubles. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public double[] getDoubles(IndexReader reader, String field) + throws IOException; + + /** + * Checks the internal cache for an appropriate entry, and if none is found, + * reads the terms in field as doubles and returns an array of + * size reader.maxDoc() of the value each document has in the + * given field. + * + * @param reader Used to get field values. + * @param field Which field contains the doubles. + * @param parser Computes integer for string values. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public double[] getDoubles(IndexReader reader, String field, DoubleParser parser) + throws IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ExtendedFieldCacheImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ExtendedFieldCacheImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ExtendedFieldCacheImpl.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,182 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermDocs; +import org.apache.lucene.index.TermEnum; + +import java.io.IOException; + + +/** + * + * + **/ +class ExtendedFieldCacheImpl extends FieldCacheImpl implements ExtendedFieldCache { + private static final LongParser LONG_PARSER = new LongParser() { + public long parseLong(String value) { + return Long.parseLong(value); + } + }; + + private static final DoubleParser DOUBLE_PARSER = new DoubleParser() { + public double parseDouble(String value) { + return Double.parseDouble(value); + } + }; + + + public long[] getLongs(IndexReader reader, String field) throws IOException { + return getLongs(reader, field, LONG_PARSER); + } + + // inherit javadocs + public long[] getLongs(IndexReader reader, String field, LongParser parser) + throws IOException { + return (long[]) longsCache.get(reader, new Entry(field, parser)); + } + + Cache longsCache = new Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + Entry entry = (Entry) entryKey; + String field = entry.field; + LongParser parser = (LongParser) entry.custom; + final long[] retArray = new long[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term(field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + long termval = parser.parseLong(term.text()); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + + // inherit javadocs + public double[] getDoubles(IndexReader reader, String field) + throws IOException { + return getDoubles(reader, field, DOUBLE_PARSER); + } + + // inherit javadocs + public double[] getDoubles(IndexReader reader, String field, DoubleParser parser) + throws IOException { + return (double[]) doublesCache.get(reader, new Entry(field, parser)); + } + + Cache doublesCache = new Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + Entry entry = (Entry) entryKey; + String field = entry.field; + DoubleParser parser = (DoubleParser) entry.custom; + final double[] retArray = new double[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + double termval = parser.parseDouble(term.text()); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + + + // inherit javadocs + public Object getAuto(IndexReader reader, String field) throws IOException { + return autoCache.get(reader, field); + } + + Cache autoCache = new Cache() { + + protected Object createValue(IndexReader reader, Object fieldKey) + throws IOException { + String field = ((String)fieldKey).intern(); + TermEnum enumerator = reader.terms (new Term (field)); + try { + Term term = enumerator.term(); + if (term == null) { + throw new RuntimeException ("no terms in field " + field + " - cannot determine sort type"); + } + Object ret = null; + if (term.field() == field) { + String termtext = term.text().trim(); + + /** + * Java 1.4 level code: + + if (pIntegers.matcher(termtext).matches()) + return IntegerSortedHitQueue.comparator (reader, enumerator, field); + + else if (pFloats.matcher(termtext).matches()) + return FloatSortedHitQueue.comparator (reader, enumerator, field); + */ + + // Java 1.3 level code: + try { + Integer.parseInt (termtext); + ret = getInts (reader, field); + } catch (NumberFormatException nfe1) { + try { + Long.parseLong(termtext); + ret = getLongs (reader, field); + } catch (NumberFormatException nfe2) { + try { + Float.parseFloat (termtext); + ret = getFloats (reader, field); + } catch (NumberFormatException nfe3) { + ret = getStringIndex (reader, field); + } + } + } + } else { + throw new RuntimeException ("field \"" + field + "\" does not appear to be indexed"); + } + return ret; + } finally { + enumerator.close(); + } + } + }; + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FieldCache.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FieldCache.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FieldCache.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,242 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import java.io.IOException; + +/** + * Expert: Maintains caches of term values. + * + *

Created: May 19, 2004 11:13:14 AM + * + * @since lucene 1.4 + * @version $Id: FieldCache.java,v 1.1 2012/08/17 14:54:55 marcin Exp $ + */ +public interface FieldCache { + + /** Indicator for StringIndex values in the cache. */ + // NOTE: the value assigned to this constant must not be + // the same as any of those in SortField!! + public static final int STRING_INDEX = -1; + + + /** Expert: Stores term text values and document ordering data. */ + public static class StringIndex { + + /** All the term values, in natural order. */ + public final String[] lookup; + + /** For each document, an index into the lookup array. */ + public final int[] order; + + /** Creates one of these objects */ + public StringIndex (int[] values, String[] lookup) { + this.order = values; + this.lookup = lookup; + } + } + + /** Interface to parse bytes from document fields. + * @see FieldCache#getBytes(IndexReader, String, FieldCache.ByteParser) + */ + public interface ByteParser { + /** Return a single Byte representation of this field's value. */ + public byte parseByte(String string); + } + + /** Interface to parse shorts from document fields. + * @see FieldCache#getShorts(IndexReader, String, FieldCache.ShortParser) + */ + public interface ShortParser { + /** Return a short representation of this field's value. */ + public short parseShort(String string); + } + + /** Interface to parse ints from document fields. + * @see FieldCache#getInts(IndexReader, String, FieldCache.IntParser) + */ + public interface IntParser { + /** Return an integer representation of this field's value. */ + public int parseInt(String string); + } + + /** Interface to parse floats from document fields. + * @see FieldCache#getFloats(IndexReader, String, FieldCache.FloatParser) + */ + public interface FloatParser { + /** Return an float representation of this field's value. */ + public float parseFloat(String string); + } + + /** Expert: The cache used internally by sorting and range query classes. */ + public static FieldCache DEFAULT = new FieldCacheImpl(); + + /** Checks the internal cache for an appropriate entry, and if none is + * found, reads the terms in field as a single byte and returns an array + * of size reader.maxDoc() of the value each document + * has in the given field. + * @param reader Used to get field values. + * @param field Which field contains the single byte values. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public byte[] getBytes (IndexReader reader, String field) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none is found, + * reads the terms in field as bytes and returns an array of + * size reader.maxDoc() of the value each document has in the + * given field. + * @param reader Used to get field values. + * @param field Which field contains the bytes. + * @param parser Computes byte for string values. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public byte[] getBytes (IndexReader reader, String field, ByteParser parser) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none is + * found, reads the terms in field as shorts and returns an array + * of size reader.maxDoc() of the value each document + * has in the given field. + * @param reader Used to get field values. + * @param field Which field contains the shorts. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public short[] getShorts (IndexReader reader, String field) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none is found, + * reads the terms in field as shorts and returns an array of + * size reader.maxDoc() of the value each document has in the + * given field. + * @param reader Used to get field values. + * @param field Which field contains the shorts. + * @param parser Computes short for string values. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public short[] getShorts (IndexReader reader, String field, ShortParser parser) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none is + * found, reads the terms in field as integers and returns an array + * of size reader.maxDoc() of the value each document + * has in the given field. + * @param reader Used to get field values. + * @param field Which field contains the integers. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public int[] getInts (IndexReader reader, String field) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none is found, + * reads the terms in field as integers and returns an array of + * size reader.maxDoc() of the value each document has in the + * given field. + * @param reader Used to get field values. + * @param field Which field contains the integers. + * @param parser Computes integer for string values. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public int[] getInts (IndexReader reader, String field, IntParser parser) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if + * none is found, reads the terms in field as floats and returns an array + * of size reader.maxDoc() of the value each document + * has in the given field. + * @param reader Used to get field values. + * @param field Which field contains the floats. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public float[] getFloats (IndexReader reader, String field) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if + * none is found, reads the terms in field as floats and returns an array + * of size reader.maxDoc() of the value each document + * has in the given field. + * @param reader Used to get field values. + * @param field Which field contains the floats. + * @param parser Computes float for string values. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public float[] getFloats (IndexReader reader, String field, + FloatParser parser) throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none + * is found, reads the term values in field and returns an array + * of size reader.maxDoc() containing the value each document + * has in the given field. + * @param reader Used to get field values. + * @param field Which field contains the strings. + * @return The values in the given field for each document. + * @throws IOException If any error occurs. + */ + public String[] getStrings (IndexReader reader, String field) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none + * is found reads the term values in field and returns + * an array of them in natural order, along with an array telling + * which element in the term array each document uses. + * @param reader Used to get field values. + * @param field Which field contains the strings. + * @return Array of terms and index into the array for each document. + * @throws IOException If any error occurs. + */ + public StringIndex getStringIndex (IndexReader reader, String field) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if + * none is found reads field to see if it contains integers, floats + * or strings, and then calls one of the other methods in this class to get the + * values. For string values, a StringIndex is returned. After + * calling this method, there is an entry in the cache for both + * type AUTO and the actual found type. + * @param reader Used to get field values. + * @param field Which field contains the values. + * @return int[], float[] or StringIndex. + * @throws IOException If any error occurs. + */ + public Object getAuto (IndexReader reader, String field) + throws IOException; + + /** Checks the internal cache for an appropriate entry, and if none + * is found reads the terms out of field and calls the given SortComparator + * to get the sort values. A hit in the cache will happen if reader, + * field, and comparator are the same (using equals()) + * as a previous call to this method. + * @param reader Used to get field values. + * @param field Which field contains the values. + * @param comparator Used to convert terms into something to sort by. + * @return Array of sort objects, one for each document. + * @throws IOException If any error occurs. + */ + public Comparable[] getCustom (IndexReader reader, String field, SortComparator comparator) + throws IOException; + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FieldCacheImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FieldCacheImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FieldCacheImpl.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,510 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermDocs; +import org.apache.lucene.index.TermEnum; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.WeakHashMap; + +/** + * Expert: The default cache implementation, storing all values in memory. + * A WeakHashMap is used for storage. + * + *

Created: May 19, 2004 4:40:36 PM + * + * @since lucene 1.4 + * @version $Id: FieldCacheImpl.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +class FieldCacheImpl +implements FieldCache { + + /** Expert: Internal cache. */ + abstract static class Cache { + private final Map readerCache = new WeakHashMap(); + + protected abstract Object createValue(IndexReader reader, Object key) + throws IOException; + + public Object get(IndexReader reader, Object key) throws IOException { + Map innerCache; + Object value; + synchronized (readerCache) { + innerCache = (Map) readerCache.get(reader); + if (innerCache == null) { + innerCache = new HashMap(); + readerCache.put(reader, innerCache); + value = null; + } else { + value = innerCache.get(key); + } + if (value == null) { + value = new CreationPlaceholder(); + innerCache.put(key, value); + } + } + if (value instanceof CreationPlaceholder) { + synchronized (value) { + CreationPlaceholder progress = (CreationPlaceholder) value; + if (progress.value == null) { + progress.value = createValue(reader, key); + synchronized (readerCache) { + innerCache.put(key, progress.value); + } + } + return progress.value; + } + } + return value; + } + } + + static final class CreationPlaceholder { + Object value; + } + + /** Expert: Every composite-key in the internal cache is of this type. */ + static class Entry { + final String field; // which Fieldable + final int type; // which SortField type + final Object custom; // which custom comparator + final Locale locale; // the locale we're sorting (if string) + + /** Creates one of these objects. */ + Entry (String field, int type, Locale locale) { + this.field = field.intern(); + this.type = type; + this.custom = null; + this.locale = locale; + } + + /** Creates one of these objects for a custom comparator. */ + Entry (String field, Object custom) { + this.field = field.intern(); + this.type = SortField.CUSTOM; + this.custom = custom; + this.locale = null; + } + + /** Two of these are equal iff they reference the same field and type. */ + public boolean equals (Object o) { + if (o instanceof Entry) { + Entry other = (Entry) o; + if (other.field == field && other.type == type) { + if (other.locale == null ? locale == null : other.locale.equals(locale)) { + if (other.custom == null) { + if (custom == null) return true; + } else if (other.custom.equals (custom)) { + return true; + } + } + } + } + return false; + } + + /** Composes a hashcode based on the field and type. */ + public int hashCode() { + return field.hashCode() ^ type ^ (custom==null ? 0 : custom.hashCode()) ^ (locale==null ? 0 : locale.hashCode()); + } + } + + private static final ByteParser BYTE_PARSER = new ByteParser() { + public byte parseByte(String value) { + return Byte.parseByte(value); + } + }; + + private static final ShortParser SHORT_PARSER = new ShortParser() { + public short parseShort(String value) { + return Short.parseShort(value); + } + }; + + private static final IntParser INT_PARSER = new IntParser() { + public int parseInt(String value) { + return Integer.parseInt(value); + } + }; + + + private static final FloatParser FLOAT_PARSER = new FloatParser() { + public float parseFloat(String value) { + return Float.parseFloat(value); + } + }; + + // inherit javadocs + public byte[] getBytes (IndexReader reader, String field) throws IOException { + return getBytes(reader, field, BYTE_PARSER); + } + + // inherit javadocs + public byte[] getBytes(IndexReader reader, String field, ByteParser parser) + throws IOException { + return (byte[]) bytesCache.get(reader, new Entry(field, parser)); + } + + Cache bytesCache = new Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + Entry entry = (Entry) entryKey; + String field = entry.field; + ByteParser parser = (ByteParser) entry.custom; + final byte[] retArray = new byte[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + byte termval = parser.parseByte(term.text()); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + + // inherit javadocs + public short[] getShorts (IndexReader reader, String field) throws IOException { + return getShorts(reader, field, SHORT_PARSER); + } + + // inherit javadocs + public short[] getShorts(IndexReader reader, String field, ShortParser parser) + throws IOException { + return (short[]) shortsCache.get(reader, new Entry(field, parser)); + } + + Cache shortsCache = new Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + Entry entry = (Entry) entryKey; + String field = entry.field; + ShortParser parser = (ShortParser) entry.custom; + final short[] retArray = new short[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + short termval = parser.parseShort(term.text()); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + + // inherit javadocs + public int[] getInts (IndexReader reader, String field) throws IOException { + return getInts(reader, field, INT_PARSER); + } + + // inherit javadocs + public int[] getInts(IndexReader reader, String field, IntParser parser) + throws IOException { + return (int[]) intsCache.get(reader, new Entry(field, parser)); + } + + Cache intsCache = new Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + Entry entry = (Entry) entryKey; + String field = entry.field; + IntParser parser = (IntParser) entry.custom; + final int[] retArray = new int[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + int termval = parser.parseInt(term.text()); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + + + // inherit javadocs + public float[] getFloats (IndexReader reader, String field) + throws IOException { + return getFloats(reader, field, FLOAT_PARSER); + } + + // inherit javadocs + public float[] getFloats(IndexReader reader, String field, FloatParser parser) + throws IOException { + return (float[]) floatsCache.get(reader, new Entry(field, parser)); + } + + Cache floatsCache = new Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + Entry entry = (Entry) entryKey; + String field = entry.field; + FloatParser parser = (FloatParser) entry.custom; + final float[] retArray = new float[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + float termval = parser.parseFloat(term.text()); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + + // inherit javadocs + public String[] getStrings(IndexReader reader, String field) + throws IOException { + return (String[]) stringsCache.get(reader, field); + } + + Cache stringsCache = new Cache() { + + protected Object createValue(IndexReader reader, Object fieldKey) + throws IOException { + String field = ((String) fieldKey).intern(); + final String[] retArray = new String[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + String termval = term.text(); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + + // inherit javadocs + public StringIndex getStringIndex(IndexReader reader, String field) + throws IOException { + return (StringIndex) stringsIndexCache.get(reader, field); + } + + Cache stringsIndexCache = new Cache() { + + protected Object createValue(IndexReader reader, Object fieldKey) + throws IOException { + String field = ((String) fieldKey).intern(); + final int[] retArray = new int[reader.maxDoc()]; + String[] mterms = new String[reader.maxDoc()+1]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + int t = 0; // current term number + + // an entry for documents that have no terms in this field + // should a document with no terms be at top or bottom? + // this puts them at the top - if it is changed, FieldDocSortedHitQueue + // needs to change as well. + mterms[t++] = null; + + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + + // store term text + // we expect that there is at most one term per document + if (t >= mterms.length) throw new RuntimeException ("there are more terms than " + + "documents in field \"" + field + "\", but it's impossible to sort on " + + "tokenized fields"); + mterms[t] = term.text(); + + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = t; + } + + t++; + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + + if (t == 0) { + // if there are no terms, make the term array + // have a single null entry + mterms = new String[1]; + } else if (t < mterms.length) { + // if there are less terms than documents, + // trim off the dead array space + String[] terms = new String[t]; + System.arraycopy (mterms, 0, terms, 0, t); + mterms = terms; + } + + StringIndex value = new StringIndex (retArray, mterms); + return value; + } + }; + + /** The pattern used to detect integer values in a field */ + /** removed for java 1.3 compatibility + protected static final Pattern pIntegers = Pattern.compile ("[0-9\\-]+"); + **/ + + /** The pattern used to detect float values in a field */ + /** + * removed for java 1.3 compatibility + * protected static final Object pFloats = Pattern.compile ("[0-9+\\-\\.eEfFdD]+"); + */ + + // inherit javadocs + public Object getAuto(IndexReader reader, String field) throws IOException { + return autoCache.get(reader, field); + } + + Cache autoCache = new Cache() { + + protected Object createValue(IndexReader reader, Object fieldKey) + throws IOException { + String field = ((String)fieldKey).intern(); + TermEnum enumerator = reader.terms (new Term (field)); + try { + Term term = enumerator.term(); + if (term == null) { + throw new RuntimeException ("no terms in field " + field + " - cannot determine sort type"); + } + Object ret = null; + if (term.field() == field) { + String termtext = term.text().trim(); + + /** + * Java 1.4 level code: + + if (pIntegers.matcher(termtext).matches()) + return IntegerSortedHitQueue.comparator (reader, enumerator, field); + + else if (pFloats.matcher(termtext).matches()) + return FloatSortedHitQueue.comparator (reader, enumerator, field); + */ + + // Java 1.3 level code: + try { + Integer.parseInt (termtext); + ret = getInts (reader, field); + } catch (NumberFormatException nfe1) { + try { + Float.parseFloat (termtext); + ret = getFloats (reader, field); + } catch (NumberFormatException nfe3) { + ret = getStringIndex (reader, field); + } + } + } else { + throw new RuntimeException ("field \"" + field + "\" does not appear to be indexed"); + } + return ret; + } finally { + enumerator.close(); + } + } + }; + + // inherit javadocs + public Comparable[] getCustom(IndexReader reader, String field, + SortComparator comparator) throws IOException { + return (Comparable[]) customCache.get(reader, new Entry(field, comparator)); + } + + Cache customCache = new Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + Entry entry = (Entry) entryKey; + String field = entry.field; + SortComparator comparator = (SortComparator) entry.custom; + final Comparable[] retArray = new Comparable[reader.maxDoc()]; + TermDocs termDocs = reader.termDocs(); + TermEnum termEnum = reader.terms (new Term (field)); + try { + do { + Term term = termEnum.term(); + if (term==null || term.field() != field) break; + Comparable termval = comparator.getComparable (term.text()); + termDocs.seek (termEnum); + while (termDocs.next()) { + retArray[termDocs.doc()] = termval; + } + } while (termEnum.next()); + } finally { + termDocs.close(); + termEnum.close(); + } + return retArray; + } + }; + +} + Index: 3rdParty_sources/lucene/org/apache/lucene/search/FieldDoc.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FieldDoc.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FieldDoc.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,63 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Expert: A ScoreDoc which also contains information about + * how to sort the referenced document. In addition to the + * document number and score, this object contains an array + * of values for the document from the field(s) used to sort. + * For example, if the sort criteria was to sort by fields + * "a", "b" then "c", the fields object array + * will have three elements, corresponding respectively to + * the term values for the document in fields "a", "b" and "c". + * The class of each element in the array will be either + * Integer, Float or String depending on the type of values + * in the terms of each field. + * + *

Created: Feb 11, 2004 1:23:38 PM + * + * @since lucene 1.4 + * @version $Id: FieldDoc.java,v 1.1 2012/08/17 14:54:57 marcin Exp $ + * @see ScoreDoc + * @see TopFieldDocs + */ +public class FieldDoc +extends ScoreDoc { + + /** Expert: The values which are used to sort the referenced document. + * The order of these will match the original sort criteria given by a + * Sort object. Each Object will be either an Integer, Float or String, + * depending on the type of values in the terms of the original field. + * @see Sort + * @see Searcher#search(Query,Filter,int,Sort) + */ + public Comparable[] fields; + + /** Expert: Creates one of these objects with empty sort information. */ + public FieldDoc (int doc, float score) { + super (doc, score); + } + + /** Expert: Creates one of these objects with the given sort information. */ + public FieldDoc (int doc, float score, Comparable[] fields) { + super (doc, score); + this.fields = fields; + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/search/FieldDocSortedHitQueue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FieldDocSortedHitQueue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FieldDocSortedHitQueue.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,202 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.util.PriorityQueue; + +import java.text.Collator; +import java.util.Locale; + +/** + * Expert: Collects sorted results from Searchable's and collates them. + * The elements put into this queue must be of type FieldDoc. + * + *

Created: Feb 11, 2004 2:04:21 PM + * + * @since lucene 1.4 + * @version $Id: FieldDocSortedHitQueue.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +class FieldDocSortedHitQueue +extends PriorityQueue { + + // this cannot contain AUTO fields - any AUTO fields should + // have been resolved by the time this class is used. + volatile SortField[] fields; + + // used in the case where the fields are sorted by locale + // based strings + volatile Collator[] collators; + + + /** + * Creates a hit queue sorted by the given list of fields. + * @param fields Fieldable names, in priority order (highest priority first). + * @param size The number of hits to retain. Must be greater than zero. + */ + FieldDocSortedHitQueue (SortField[] fields, int size) { + this.fields = fields; + this.collators = hasCollators (fields); + initialize (size); + } + + + /** + * Allows redefinition of sort fields if they are null. + * This is to handle the case using ParallelMultiSearcher where the + * original list contains AUTO and we don't know the actual sort + * type until the values come back. The fields can only be set once. + * This method is thread safe. + * @param fields + */ + synchronized void setFields (SortField[] fields) { + if (this.fields == null) { + this.fields = fields; + this.collators = hasCollators (fields); + } + } + + + /** Returns the fields being used to sort. */ + SortField[] getFields() { + return fields; + } + + + /** Returns an array of collators, possibly null. The collators + * correspond to any SortFields which were given a specific locale. + * @param fields Array of sort fields. + * @return Array, possibly null. + */ + private Collator[] hasCollators (final SortField[] fields) { + if (fields == null) return null; + Collator[] ret = new Collator[fields.length]; + for (int i=0; ia is less relevant than b. + * @param a ScoreDoc + * @param b ScoreDoc + * @return true if document a should be sorted after document b. + */ + protected final boolean lessThan (final Object a, final Object b) { + final FieldDoc docA = (FieldDoc) a; + final FieldDoc docB = (FieldDoc) b; + final int n = fields.length; + int c = 0; + for (int i=0; i r2) c = -1; + if (r1 < r2) c = 1; + break; + } + case SortField.DOC: + case SortField.INT:{ + int i1 = ((Integer)docA.fields[i]).intValue(); + int i2 = ((Integer)docB.fields[i]).intValue(); + if (i1 < i2) c = -1; + if (i1 > i2) c = 1; + break; + } + case SortField.LONG:{ + long l1 = ((Long)docA.fields[i]).longValue(); + long l2 = ((Long)docB.fields[i]).longValue(); + if (l1 < l2) c = -1; + if (l1 > l2) c = 1; + break; + } + case SortField.STRING:{ + String s1 = (String) docA.fields[i]; + String s2 = (String) docB.fields[i]; + // null values need to be sorted first, because of how FieldCache.getStringIndex() + // works - in that routine, any documents without a value in the given field are + // put first. If both are null, the next SortField is used + if (s1 == null) c = (s2==null) ? 0 : -1; + else if (s2 == null) c = 1; // + else if (fields[i].getLocale() == null) { + c = s1.compareTo(s2); + } else { + c = collators[i].compare (s1, s2); + } + break; + } + case SortField.FLOAT:{ + float f1 = ((Float)docA.fields[i]).floatValue(); + float f2 = ((Float)docB.fields[i]).floatValue(); + if (f1 < f2) c = -1; + if (f1 > f2) c = 1; + break; + } + case SortField.DOUBLE:{ + double d1 = ((Double)docA.fields[i]).doubleValue(); + double d2 = ((Double)docB.fields[i]).doubleValue(); + if (d1 < d2) c = -1; + if (d1 > d2) c = 1; + break; + } + case SortField.BYTE:{ + int i1 = ((Byte)docA.fields[i]).byteValue(); + int i2 = ((Byte)docB.fields[i]).byteValue(); + if (i1 < i2) c = -1; + if (i1 > i2) c = 1; + break; + } + case SortField.SHORT:{ + int i1 = ((Short)docA.fields[i]).shortValue(); + int i2 = ((Short)docB.fields[i]).shortValue(); + if (i1 < i2) c = -1; + if (i1 > i2) c = 1; + break; + } + case SortField.CUSTOM:{ + c = docA.fields[i].compareTo (docB.fields[i]); + break; + } + case SortField.AUTO:{ + // we cannot handle this - even if we determine the type of object (Float or + // Integer), we don't necessarily know how to compare them (both SCORE and + // FLOAT contain floats, but are sorted opposite of each other). Before + // we get here, each AUTO should have been replaced with its actual value. + throw new RuntimeException ("FieldDocSortedHitQueue cannot use an AUTO SortField"); + } + default:{ + throw new RuntimeException ("invalid SortField type: "+type); + } + } + if (fields[i].getReverse()) { + c = -c; + } + } + + // avoid random sort order that could lead to duplicates (bug #31241): + if (c == 0) + return docA.doc > docB.doc; + + return c > 0; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FieldSortedHitQueue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FieldSortedHitQueue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FieldSortedHitQueue.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,502 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.PriorityQueue; + +import java.io.IOException; +import java.text.Collator; +import java.util.Locale; + +/** + * Expert: A hit queue for sorting by hits by terms in more than one field. + * Uses FieldCache.DEFAULT for maintaining internal term lookup tables. + * + *

Created: Dec 8, 2003 12:56:03 PM + * + * @since lucene 1.4 + * @version $Id: FieldSortedHitQueue.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + * @see Searcher#search(Query,Filter,int,Sort) + * @see FieldCache + */ +public class FieldSortedHitQueue +extends PriorityQueue { + + /** + * Creates a hit queue sorted by the given list of fields. + * @param reader Index to use. + * @param fields Fieldable names, in priority order (highest priority first). Cannot be null or empty. + * @param size The number of hits to retain. Must be greater than zero. + * @throws IOException + */ + public FieldSortedHitQueue (IndexReader reader, SortField[] fields, int size) + throws IOException { + final int n = fields.length; + comparators = new ScoreDocComparator[n]; + this.fields = new SortField[n]; + for (int i=0; ia is less relevant than b. + * @param a ScoreDoc + * @param b ScoreDoc + * @return true if document a should be sorted after document b. + */ + protected boolean lessThan (final Object a, final Object b) { + final ScoreDoc docA = (ScoreDoc) a; + final ScoreDoc docB = (ScoreDoc) b; + + // run comparators + final int n = comparators.length; + int c = 0; + for (int i=0; i docB.doc; + return c > 0; + } + + + /** + * Given a FieldDoc object, stores the values used + * to sort the given document. These values are not the raw + * values out of the index, but the internal representation + * of them. This is so the given search hit can be collated + * by a MultiSearcher with other search hits. + * @param doc The FieldDoc to store sort values into. + * @return The same FieldDoc passed in. + * @see Searchable#search(Weight,Filter,int,Sort) + */ + FieldDoc fillFields (final FieldDoc doc) { + final int n = comparators.length; + final Comparable[] fields = new Comparable[n]; + for (int i=0; i 1.0f) doc.score /= maxscore; // normalize scores + return doc; + } + + + /** Returns the SortFields being used by this hit queue. */ + SortField[] getFields() { + return fields; + } + + static ScoreDocComparator getCachedComparator (IndexReader reader, String field, int type, Locale locale, SortComparatorSource factory) + throws IOException { + if (type == SortField.DOC) return ScoreDocComparator.INDEXORDER; + if (type == SortField.SCORE) return ScoreDocComparator.RELEVANCE; + FieldCacheImpl.Entry entry = (factory != null) + ? new FieldCacheImpl.Entry (field, factory) + : new FieldCacheImpl.Entry (field, type, locale); + return (ScoreDocComparator)Comparators.get(reader, entry); + } + + /** Internal cache of comparators. Similar to FieldCache, only + * caches comparators instead of term values. */ + static final FieldCacheImpl.Cache Comparators = new FieldCacheImpl.Cache() { + + protected Object createValue(IndexReader reader, Object entryKey) + throws IOException { + FieldCacheImpl.Entry entry = (FieldCacheImpl.Entry) entryKey; + String fieldname = entry.field; + int type = entry.type; + Locale locale = entry.locale; + SortComparatorSource factory = (SortComparatorSource) entry.custom; + ScoreDocComparator comparator; + switch (type) { + case SortField.AUTO: + comparator = comparatorAuto (reader, fieldname); + break; + case SortField.INT: + comparator = comparatorInt (reader, fieldname); + break; + case SortField.FLOAT: + comparator = comparatorFloat (reader, fieldname); + break; + case SortField.LONG: + comparator = comparatorLong(reader, fieldname); + break; + case SortField.DOUBLE: + comparator = comparatorDouble(reader, fieldname); + break; + case SortField.SHORT: + comparator = comparatorShort(reader, fieldname); + break; + case SortField.BYTE: + comparator = comparatorByte(reader, fieldname); + break; + case SortField.STRING: + if (locale != null) comparator = comparatorStringLocale (reader, fieldname, locale); + else comparator = comparatorString (reader, fieldname); + break; + case SortField.CUSTOM: + comparator = factory.newComparator (reader, fieldname); + break; + default: + throw new RuntimeException ("unknown field type: "+type); + } + return comparator; + } + }; + + /** + * Returns a comparator for sorting hits according to a field containing bytes. + * @param reader Index to use. + * @param fieldname Fieldable containg integer values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorByte(final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final byte[] fieldOrder = FieldCache.DEFAULT.getBytes(reader, field); + return new ScoreDocComparator() { + + public final int compare (final ScoreDoc i, final ScoreDoc j) { + final int fi = fieldOrder[i.doc]; + final int fj = fieldOrder[j.doc]; + if (fi < fj) return -1; + if (fi > fj) return 1; + return 0; + } + + public Comparable sortValue (final ScoreDoc i) { + return new Byte(fieldOrder[i.doc]); + } + + public int sortType() { + return SortField.INT; + } + }; + } + + /** + * Returns a comparator for sorting hits according to a field containing shorts. + * @param reader Index to use. + * @param fieldname Fieldable containg integer values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorShort(final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final short[] fieldOrder = FieldCache.DEFAULT.getShorts(reader, field); + return new ScoreDocComparator() { + + public final int compare (final ScoreDoc i, final ScoreDoc j) { + final int fi = fieldOrder[i.doc]; + final int fj = fieldOrder[j.doc]; + if (fi < fj) return -1; + if (fi > fj) return 1; + return 0; + } + + public Comparable sortValue (final ScoreDoc i) { + return new Short(fieldOrder[i.doc]); + } + + public int sortType() { + return SortField.SHORT; + } + }; + } + + /** + * Returns a comparator for sorting hits according to a field containing integers. + * @param reader Index to use. + * @param fieldname Fieldable containg integer values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorInt (final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final int[] fieldOrder = FieldCache.DEFAULT.getInts (reader, field); + return new ScoreDocComparator() { + + public final int compare (final ScoreDoc i, final ScoreDoc j) { + final int fi = fieldOrder[i.doc]; + final int fj = fieldOrder[j.doc]; + if (fi < fj) return -1; + if (fi > fj) return 1; + return 0; + } + + public Comparable sortValue (final ScoreDoc i) { + return new Integer (fieldOrder[i.doc]); + } + + public int sortType() { + return SortField.INT; + } + }; + } + + /** + * Returns a comparator for sorting hits according to a field containing integers. + * @param reader Index to use. + * @param fieldname Fieldable containg integer values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorLong (final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final long[] fieldOrder = ExtendedFieldCache.EXT_DEFAULT.getLongs (reader, field); + return new ScoreDocComparator() { + + public final int compare (final ScoreDoc i, final ScoreDoc j) { + final long li = fieldOrder[i.doc]; + final long lj = fieldOrder[j.doc]; + if (li < lj) return -1; + if (li > lj) return 1; + return 0; + } + + public Comparable sortValue (final ScoreDoc i) { + return new Long(fieldOrder[i.doc]); + } + + public int sortType() { + return SortField.LONG; + } + }; + } + + + /** + * Returns a comparator for sorting hits according to a field containing floats. + * @param reader Index to use. + * @param fieldname Fieldable containg float values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorFloat (final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final float[] fieldOrder = FieldCache.DEFAULT.getFloats (reader, field); + return new ScoreDocComparator () { + + public final int compare (final ScoreDoc i, final ScoreDoc j) { + final float fi = fieldOrder[i.doc]; + final float fj = fieldOrder[j.doc]; + if (fi < fj) return -1; + if (fi > fj) return 1; + return 0; + } + + public Comparable sortValue (final ScoreDoc i) { + return new Float (fieldOrder[i.doc]); + } + + public int sortType() { + return SortField.FLOAT; + } + }; + } + + /** + * Returns a comparator for sorting hits according to a field containing doubles. + * @param reader Index to use. + * @param fieldname Fieldable containg float values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorDouble(final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final double[] fieldOrder = ExtendedFieldCache.EXT_DEFAULT.getDoubles (reader, field); + return new ScoreDocComparator () { + + public final int compare (final ScoreDoc i, final ScoreDoc j) { + final double di = fieldOrder[i.doc]; + final double dj = fieldOrder[j.doc]; + if (di < dj) return -1; + if (di > dj) return 1; + return 0; + } + + public Comparable sortValue (final ScoreDoc i) { + return new Double (fieldOrder[i.doc]); + } + + public int sortType() { + return SortField.DOUBLE; + } + }; + } + + /** + * Returns a comparator for sorting hits according to a field containing strings. + * @param reader Index to use. + * @param fieldname Fieldable containg string values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorString (final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final FieldCache.StringIndex index = FieldCache.DEFAULT.getStringIndex (reader, field); + return new ScoreDocComparator () { + + public final int compare (final ScoreDoc i, final ScoreDoc j) { + final int fi = index.order[i.doc]; + final int fj = index.order[j.doc]; + if (fi < fj) return -1; + if (fi > fj) return 1; + return 0; + } + + public Comparable sortValue (final ScoreDoc i) { + return index.lookup[index.order[i.doc]]; + } + + public int sortType() { + return SortField.STRING; + } + }; + } + + /** + * Returns a comparator for sorting hits according to a field containing strings. + * @param reader Index to use. + * @param fieldname Fieldable containg string values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorStringLocale (final IndexReader reader, final String fieldname, final Locale locale) + throws IOException { + final Collator collator = Collator.getInstance (locale); + final String field = fieldname.intern(); + final String[] index = FieldCache.DEFAULT.getStrings (reader, field); + return new ScoreDocComparator() { + + public final int compare(final ScoreDoc i, final ScoreDoc j) { + String is = index[i.doc]; + String js = index[j.doc]; + if (is == js) { + return 0; + } else if (is == null) { + return -1; + } else if (js == null) { + return 1; + } else { + return collator.compare(is, js); + } + } + + public Comparable sortValue (final ScoreDoc i) { + return index[i.doc]; + } + + public int sortType() { + return SortField.STRING; + } + }; + } + + /** + * Returns a comparator for sorting hits according to values in the given field. + * The terms in the field are looked at to determine whether they contain integers, + * floats or strings. Once the type is determined, one of the other static methods + * in this class is called to get the comparator. + * @param reader Index to use. + * @param fieldname Fieldable containg values. + * @return Comparator for sorting hits. + * @throws IOException If an error occurs reading the index. + */ + static ScoreDocComparator comparatorAuto (final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + Object lookupArray = ExtendedFieldCache.EXT_DEFAULT.getAuto (reader, field); + if (lookupArray instanceof FieldCache.StringIndex) { + return comparatorString (reader, field); + } else if (lookupArray instanceof int[]) { + return comparatorInt (reader, field); + } else if (lookupArray instanceof long[]) { + return comparatorLong (reader, field); + } else if (lookupArray instanceof float[]) { + return comparatorFloat (reader, field); + } else if (lookupArray instanceof String[]) { + return comparatorString (reader, field); + } else { + throw new RuntimeException ("unknown data type in field '"+field+"'"); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Filter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Filter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Filter.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,51 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.BitSet; +import java.io.IOException; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.DocIdBitSet; + +/** Abstract base class providing a mechanism to use a subset of an index + * for restriction or permission of index search results. + *

+ * Note: In Lucene 3.0 {@link #bits(IndexReader)} will be removed + * and {@link #getDocIdSet(IndexReader)} will be defined as abstract. + * All implementing classes must therefore implement {@link #getDocIdSet(IndexReader)} + * in order to work with Lucene 3.0. + */ +public abstract class Filter implements java.io.Serializable { + /** + * @return A BitSet with true for documents which should be permitted in + * search results, and false for those that should not. + * @deprecated Use {@link #getDocIdSet(IndexReader)} instead. + */ + public BitSet bits(IndexReader reader) throws IOException { + return null; + } + + /** + * @return a DocIdSet that provides the documents which should be + * permitted or prohibited in search results. + * @see DocIdBitSet + */ + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + return new DocIdBitSet(bits(reader)); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FilterManager.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FilterManager.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FilterManager.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,204 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.TreeSet; + +/** + * Filter caching singleton. It can be used by {@link org.apache.lucene.search.RemoteCachingWrapperFilter} + * or just to save filters locally for reuse. + * This class makes it possble to cache Filters even when using RMI, as it + * keeps the cache on the seaercher side of the RMI connection. + * + * Also could be used as a persistent storage for any filter as long as the + * filter provides a proper hashCode(), as that is used as the key in the cache. + * + * The cache is periodically cleaned up from a separate thread to ensure the + * cache doesn't exceed the maximum size. + */ +public class FilterManager { + + protected static FilterManager manager; + + /** The default maximum number of Filters in the cache */ + protected static final int DEFAULT_CACHE_CLEAN_SIZE = 100; + /** The default frequency of cache clenup */ + protected static final long DEFAULT_CACHE_SLEEP_TIME = 1000 * 60 * 10; + + /** The cache itself */ + protected Map cache; + /** Maximum allowed cache size */ + protected int cacheCleanSize; + /** Cache cleaning frequency */ + protected long cleanSleepTime; + /** Cache cleaner that runs in a separate thread */ + protected FilterCleaner filterCleaner; + + public synchronized static FilterManager getInstance() { + if (manager == null) { + manager = new FilterManager(); + } + return manager; + } + + /** + * Sets up the FilterManager singleton. + */ + protected FilterManager() { + cache = new HashMap(); + cacheCleanSize = DEFAULT_CACHE_CLEAN_SIZE; // Let the cache get to 100 items + cleanSleepTime = DEFAULT_CACHE_SLEEP_TIME; // 10 minutes between cleanings + + filterCleaner = new FilterCleaner(); + Thread fcThread = new Thread(filterCleaner); + // setto be a Daemon so it doesn't have to be stopped + fcThread.setDaemon(true); + fcThread.start(); + } + + /** + * Sets the max size that cache should reach before it is cleaned up + * @param cacheCleanSize maximum allowed cache size + */ + public void setCacheSize(int cacheCleanSize) { + this.cacheCleanSize = cacheCleanSize; + } + + /** + * Sets the cache cleaning frequency in milliseconds. + * @param cleanSleepTime cleaning frequency in millioseconds + */ + public void setCleanThreadSleepTime(long cleanSleepTime) { + this.cleanSleepTime = cleanSleepTime; + } + + /** + * Returns the cached version of the filter. Allows the caller to pass up + * a small filter but this will keep a persistent version around and allow + * the caching filter to do its job. + * + * @param filter The input filter + * @return The cached version of the filter + */ + public Filter getFilter(Filter filter) { + synchronized(cache) { + FilterItem fi = null; + fi = (FilterItem)cache.get(new Integer(filter.hashCode())); + if (fi != null) { + fi.timestamp = new Date().getTime(); + return fi.filter; + } + cache.put(new Integer(filter.hashCode()), new FilterItem(filter)); + return filter; + } + } + + /** + * Holds the filter and the last time the filter was used, to make LRU-based + * cache cleaning possible. + * TODO: Clean this up when we switch to Java 1.5 + */ + protected class FilterItem { + public Filter filter; + public long timestamp; + + public FilterItem (Filter filter) { + this.filter = filter; + this.timestamp = new Date().getTime(); + } + } + + + /** + * Keeps the cache from getting too big. + * If we were using Java 1.5, we could use LinkedHashMap and we would not need this thread + * to clean out the cache. + * + * The SortedSet sortedFilterItems is used only to sort the items from the cache, + * so when it's time to clean up we have the TreeSet sort the FilterItems by + * timestamp. + * + * Removes 1.5 * the numbers of items to make the cache smaller. + * For example: + * If cache clean size is 10, and the cache is at 15, we would remove (15 - 10) * 1.5 = 7.5 round up to 8. + * This way we clean the cache a bit more, and avoid having the cache cleaner having to do it frequently. + */ + protected class FilterCleaner implements Runnable { + + private boolean running = true; + private TreeSet sortedFilterItems; + + public FilterCleaner() { + sortedFilterItems = new TreeSet(new Comparator() { + public int compare(Object a, Object b) { + if( a instanceof Map.Entry && b instanceof Map.Entry) { + FilterItem fia = (FilterItem) ((Map.Entry)a).getValue(); + FilterItem fib = (FilterItem) ((Map.Entry)b).getValue(); + if ( fia.timestamp == fib.timestamp ) { + return 0; + } + // smaller timestamp first + if ( fia.timestamp < fib.timestamp ) { + return -1; + } + // larger timestamp last + return 1; + } else { + throw new ClassCastException("Objects are not Map.Entry"); + } + } + }); + } + + public void run () { + while (running) { + + // sort items from oldest to newest + // we delete the oldest filters + if (cache.size() > cacheCleanSize) { + // empty the temporary set + sortedFilterItems.clear(); + synchronized (cache) { + sortedFilterItems.addAll(cache.entrySet()); + Iterator it = sortedFilterItems.iterator(); + int numToDelete = (int) ((cache.size() - cacheCleanSize) * 1.5); + int counter = 0; + // loop over the set and delete all of the cache entries not used in a while + while (it.hasNext() && counter++ < numToDelete) { + Map.Entry entry = (Map.Entry)it.next(); + cache.remove(entry.getKey()); + } + } + // empty the set so we don't tie up the memory + sortedFilterItems.clear(); + } + // take a nap + try { + Thread.sleep(cleanSleepTime); + } catch (InterruptedException e) { + // just keep going + } + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FilteredQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FilteredQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FilteredQuery.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,202 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.ToStringUtils; + +import java.io.IOException; +import java.util.Set; + + +/** + * A query that applies a filter to the results of another query. + * + *

Note: the bits are retrieved from the filter each time this + * query is used in a search - use a CachingWrapperFilter to avoid + * regenerating the bits every time. + * + *

Created: Apr 20, 2004 8:58:29 AM + * + * @since 1.4 + * @version $Id: FilteredQuery.java,v 1.1 2012/08/17 14:54:56 marcin Exp $ + * @see CachingWrapperFilter + */ +public class FilteredQuery +extends Query { + + Query query; + Filter filter; + + /** + * Constructs a new query which applies a filter to the results of the original query. + * Filter.getDocIdSet() will be called every time this query is used in a search. + * @param query Query to be filtered, cannot be null. + * @param filter Filter to apply to query results, cannot be null. + */ + public FilteredQuery (Query query, Filter filter) { + this.query = query; + this.filter = filter; + } + + + + /** + * Returns a Weight that applies the filter to the enclosed query's Weight. + * This is accomplished by overriding the Scorer returned by the Weight. + */ + protected Weight createWeight (final Searcher searcher) throws IOException { + final Weight weight = query.createWeight (searcher); + final Similarity similarity = query.getSimilarity(searcher); + return new Weight() { + private float value; + + // pass these methods through to enclosed query's weight + public float getValue() { return value; } + public float sumOfSquaredWeights() throws IOException { + return weight.sumOfSquaredWeights() * getBoost() * getBoost(); + } + public void normalize (float v) { + weight.normalize(v); + value = weight.getValue() * getBoost(); + } + public Explanation explain (IndexReader ir, int i) throws IOException { + Explanation inner = weight.explain (ir, i); + if (getBoost()!=1) { + Explanation preBoost = inner; + inner = new Explanation(inner.getValue()*getBoost(),"product of:"); + inner.addDetail(new Explanation(getBoost(),"boost")); + inner.addDetail(preBoost); + } + Filter f = FilteredQuery.this.filter; + DocIdSetIterator docIdSetIterator = f.getDocIdSet(ir).iterator(); + if (docIdSetIterator.skipTo(i) && (docIdSetIterator.doc() == i)) { + return inner; + } else { + Explanation result = new Explanation + (0.0f, "failure to match filter: " + f.toString()); + result.addDetail(inner); + return result; + } + } + + // return this query + public Query getQuery() { return FilteredQuery.this; } + + // return a filtering scorer + public Scorer scorer (IndexReader indexReader) throws IOException { + final Scorer scorer = weight.scorer(indexReader); + final DocIdSetIterator docIdSetIterator = filter.getDocIdSet(indexReader).iterator(); + + return new Scorer(similarity) { + + private boolean advanceToCommon() throws IOException { + while (scorer.doc() != docIdSetIterator.doc()) { + if (scorer.doc() < docIdSetIterator.doc()) { + if (!scorer.skipTo(docIdSetIterator.doc())) { + return false; + } + } else if (!docIdSetIterator.skipTo(scorer.doc())) { + return false; + } + } + return true; + } + + public boolean next() throws IOException { + return docIdSetIterator.next() && scorer.next() && advanceToCommon(); + } + + public int doc() { return scorer.doc(); } + + public boolean skipTo(int i) throws IOException { + return docIdSetIterator.skipTo(i) + && scorer.skipTo(docIdSetIterator.doc()) + && advanceToCommon(); + } + + public float score() throws IOException { return getBoost() * scorer.score(); } + + // add an explanation about whether the document was filtered + public Explanation explain (int i) throws IOException { + Explanation exp = scorer.explain(i); + + if (docIdSetIterator.skipTo(i) && (docIdSetIterator.doc() == i)) { + exp.setDescription ("allowed by filter: "+exp.getDescription()); + exp.setValue(getBoost() * exp.getValue()); + } else { + exp.setDescription ("removed by filter: "+exp.getDescription()); + exp.setValue(0.0f); + } + return exp; + } + }; + } + }; + } + + /** Rewrites the wrapped query. */ + public Query rewrite(IndexReader reader) throws IOException { + Query rewritten = query.rewrite(reader); + if (rewritten != query) { + FilteredQuery clone = (FilteredQuery)this.clone(); + clone.query = rewritten; + return clone; + } else { + return this; + } + } + + public Query getQuery() { + return query; + } + + public Filter getFilter() { + return filter; + } + + // inherit javadoc + public void extractTerms(Set terms) { + getQuery().extractTerms(terms); + } + + /** Prints a user-readable version of this query. */ + public String toString (String s) { + StringBuffer buffer = new StringBuffer(); + buffer.append("filtered("); + buffer.append(query.toString(s)); + buffer.append(")->"); + buffer.append(filter); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (o instanceof FilteredQuery) { + FilteredQuery fq = (FilteredQuery) o; + return (query.equals(fq.query) && filter.equals(fq.filter) && getBoost()==fq.getBoost()); + } + return false; + } + + /** Returns a hash code value for this object. */ + public int hashCode() { + return query.hashCode() ^ filter.hashCode() + Float.floatToRawIntBits(getBoost()); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FilteredTermEnum.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FilteredTermEnum.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FilteredTermEnum.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,92 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermEnum; + +/** Abstract class for enumerating a subset of all terms. + +

Term enumerations are always ordered by Term.compareTo(). Each term in + the enumeration is greater than all that precede it. */ +public abstract class FilteredTermEnum extends TermEnum { + private Term currentTerm = null; + private TermEnum actualEnum = null; + + public FilteredTermEnum() {} + + /** Equality compare on the term */ + protected abstract boolean termCompare(Term term); + + /** Equality measure on the term */ + public abstract float difference(); + + /** Indicates the end of the enumeration has been reached */ + protected abstract boolean endEnum(); + + protected void setEnum(TermEnum actualEnum) throws IOException { + this.actualEnum = actualEnum; + // Find the first term that matches + Term term = actualEnum.term(); + if (term != null && termCompare(term)) + currentTerm = term; + else next(); + } + + /** + * Returns the docFreq of the current Term in the enumeration. + * Returns -1 if no Term matches or all terms have been enumerated. + */ + public int docFreq() { + if (actualEnum == null) return -1; + return actualEnum.docFreq(); + } + + /** Increments the enumeration to the next element. True if one exists. */ + public boolean next() throws IOException { + if (actualEnum == null) return false; // the actual enumerator is not initialized! + currentTerm = null; + while (currentTerm == null) { + if (endEnum()) return false; + if (actualEnum.next()) { + Term term = actualEnum.term(); + if (termCompare(term)) { + currentTerm = term; + return true; + } + } + else return false; + } + currentTerm = null; + return false; + } + + /** Returns the current Term in the enumeration. + * Returns null if no Term matches or all terms have been enumerated. */ + public Term term() { + return currentTerm; + } + + /** Closes the enumeration to further activity, freeing resources. */ + public void close() throws IOException { + actualEnum.close(); + currentTerm = null; + actualEnum = null; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FuzzyQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FuzzyQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FuzzyQuery.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,209 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.util.PriorityQueue; +import org.apache.lucene.util.ToStringUtils; + +import java.io.IOException; + +/** Implements the fuzzy search query. The similiarity measurement + * is based on the Levenshtein (edit distance) algorithm. + */ +public class FuzzyQuery extends MultiTermQuery { + + public final static float defaultMinSimilarity = 0.5f; + public final static int defaultPrefixLength = 0; + + private float minimumSimilarity; + private int prefixLength; + + /** + * Create a new FuzzyQuery that will match terms with a similarity + * of at least minimumSimilarity to term. + * If a prefixLength > 0 is specified, a common prefix + * of that length is also required. + * + * @param term the term to search for + * @param minimumSimilarity a value between 0 and 1 to set the required similarity + * between the query term and the matching terms. For example, for a + * minimumSimilarity of 0.5 a term of the same length + * as the query term is considered similar to the query term if the edit distance + * between both terms is less than length(term)*0.5 + * @param prefixLength length of common (non-fuzzy) prefix + * @throws IllegalArgumentException if minimumSimilarity is >= 1 or < 0 + * or if prefixLength < 0 + */ + public FuzzyQuery(Term term, float minimumSimilarity, int prefixLength) throws IllegalArgumentException { + super(term); + + if (minimumSimilarity >= 1.0f) + throw new IllegalArgumentException("minimumSimilarity >= 1"); + else if (minimumSimilarity < 0.0f) + throw new IllegalArgumentException("minimumSimilarity < 0"); + if (prefixLength < 0) + throw new IllegalArgumentException("prefixLength < 0"); + + this.minimumSimilarity = minimumSimilarity; + this.prefixLength = prefixLength; + } + + /** + * Calls {@link #FuzzyQuery(Term, float) FuzzyQuery(term, minimumSimilarity, 0)}. + */ + public FuzzyQuery(Term term, float minimumSimilarity) throws IllegalArgumentException { + this(term, minimumSimilarity, defaultPrefixLength); + } + + /** + * Calls {@link #FuzzyQuery(Term, float) FuzzyQuery(term, 0.5f, 0)}. + */ + public FuzzyQuery(Term term) { + this(term, defaultMinSimilarity, defaultPrefixLength); + } + + /** + * Returns the minimum similarity that is required for this query to match. + * @return float value between 0.0 and 1.0 + */ + public float getMinSimilarity() { + return minimumSimilarity; + } + + /** + * Returns the non-fuzzy prefix length. This is the number of characters at the start + * of a term that must be identical (not fuzzy) to the query term if the query + * is to match that term. + */ + public int getPrefixLength() { + return prefixLength; + } + + protected FilteredTermEnum getEnum(IndexReader reader) throws IOException { + return new FuzzyTermEnum(reader, getTerm(), minimumSimilarity, prefixLength); + } + + public Query rewrite(IndexReader reader) throws IOException { + FilteredTermEnum enumerator = getEnum(reader); + int maxClauseCount = BooleanQuery.getMaxClauseCount(); + ScoreTermQueue stQueue = new ScoreTermQueue(maxClauseCount); + ScoreTerm reusableST = null; + + try { + do { + float score = 0.0f; + Term t = enumerator.term(); + if (t != null) { + score = enumerator.difference(); + if (reusableST == null) { + reusableST = new ScoreTerm(t, score); + } else if (score >= reusableST.score) { + // reusableST holds the last "rejected" entry, so, if + // this new score is not better than that, there's no + // need to try inserting it + reusableST.score = score; + reusableST.term = t; + } else { + continue; + } + + reusableST = (ScoreTerm) stQueue.insertWithOverflow(reusableST); + } + } while (enumerator.next()); + } finally { + enumerator.close(); + } + + BooleanQuery query = new BooleanQuery(true); + int size = stQueue.size(); + for(int i = 0; i < size; i++){ + ScoreTerm st = (ScoreTerm) stQueue.pop(); + TermQuery tq = new TermQuery(st.term); // found a match + tq.setBoost(getBoost() * st.score); // set the boost + query.add(tq, BooleanClause.Occur.SHOULD); // add to query + } + + return query; + } + + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + Term term = getTerm(); + if (!term.field().equals(field)) { + buffer.append(term.field()); + buffer.append(":"); + } + buffer.append(term.text()); + buffer.append('~'); + buffer.append(Float.toString(minimumSimilarity)); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + protected static class ScoreTerm { + public Term term; + public float score; + + public ScoreTerm(Term term, float score){ + this.term = term; + this.score = score; + } + } + + protected static class ScoreTermQueue extends PriorityQueue { + + public ScoreTermQueue(int size){ + initialize(size); + } + + /* (non-Javadoc) + * @see org.apache.lucene.util.PriorityQueue#lessThan(java.lang.Object, java.lang.Object) + */ + protected boolean lessThan(Object a, Object b) { + ScoreTerm termA = (ScoreTerm)a; + ScoreTerm termB = (ScoreTerm)b; + if (termA.score == termB.score) + return termA.term.compareTo(termB.term) > 0; + else + return termA.score < termB.score; + } + + } + + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof FuzzyQuery)) return false; + if (!super.equals(o)) return false; + + final FuzzyQuery fuzzyQuery = (FuzzyQuery) o; + + if (minimumSimilarity != fuzzyQuery.minimumSimilarity) return false; + if (prefixLength != fuzzyQuery.prefixLength) return false; + + return true; + } + + public int hashCode() { + int result = super.hashCode(); + result = 29 * result + minimumSimilarity != +0.0f ? Float.floatToIntBits(minimumSimilarity) : 0; + result = 29 * result + prefixLength; + return result; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/FuzzyTermEnum.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/FuzzyTermEnum.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/FuzzyTermEnum.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,307 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; + +import java.io.IOException; + +/** Subclass of FilteredTermEnum for enumerating all terms that are similiar + * to the specified filter term. + * + *

Term enumerations are always ordered by Term.compareTo(). Each term in + * the enumeration is greater than all that precede it. + */ +public final class FuzzyTermEnum extends FilteredTermEnum { + + /* This should be somewhere around the average long word. + * If it is longer, we waste time and space. If it is shorter, we waste a + * little bit of time growing the array as we encounter longer words. + */ + private static final int TYPICAL_LONGEST_WORD_IN_INDEX = 19; + + /* Allows us save time required to create a new array + * everytime similarity is called. + */ + private int[][] d; + + private float similarity; + private boolean endEnum = false; + + private Term searchTerm = null; + private final String field; + private final String text; + private final String prefix; + + private final float minimumSimilarity; + private final float scale_factor; + private final int[] maxDistances = new int[TYPICAL_LONGEST_WORD_IN_INDEX]; + + /** + * Creates a FuzzyTermEnum with an empty prefix and a minSimilarity of 0.5f. + *

+ * After calling the constructor the enumeration is already pointing to the first + * valid term if such a term exists. + * + * @param reader + * @param term + * @throws IOException + * @see #FuzzyTermEnum(IndexReader, Term, float, int) + */ + public FuzzyTermEnum(IndexReader reader, Term term) throws IOException { + this(reader, term, FuzzyQuery.defaultMinSimilarity, FuzzyQuery.defaultPrefixLength); + } + + /** + * Creates a FuzzyTermEnum with an empty prefix. + *

+ * After calling the constructor the enumeration is already pointing to the first + * valid term if such a term exists. + * + * @param reader + * @param term + * @param minSimilarity + * @throws IOException + * @see #FuzzyTermEnum(IndexReader, Term, float, int) + */ + public FuzzyTermEnum(IndexReader reader, Term term, float minSimilarity) throws IOException { + this(reader, term, minSimilarity, FuzzyQuery.defaultPrefixLength); + } + + /** + * Constructor for enumeration of all terms from specified reader which share a prefix of + * length prefixLength with term and which have a fuzzy similarity > + * minSimilarity. + *

+ * After calling the constructor the enumeration is already pointing to the first + * valid term if such a term exists. + * + * @param reader Delivers terms. + * @param term Pattern term. + * @param minSimilarity Minimum required similarity for terms from the reader. Default value is 0.5f. + * @param prefixLength Length of required common prefix. Default value is 0. + * @throws IOException + */ + public FuzzyTermEnum(IndexReader reader, Term term, final float minSimilarity, final int prefixLength) throws IOException { + super(); + + if (minSimilarity >= 1.0f) + throw new IllegalArgumentException("minimumSimilarity cannot be greater than or equal to 1"); + else if (minSimilarity < 0.0f) + throw new IllegalArgumentException("minimumSimilarity cannot be less than 0"); + if(prefixLength < 0) + throw new IllegalArgumentException("prefixLength cannot be less than 0"); + + this.minimumSimilarity = minSimilarity; + this.scale_factor = 1.0f / (1.0f - minimumSimilarity); + this.searchTerm = term; + this.field = searchTerm.field(); + + //The prefix could be longer than the word. + //It's kind of silly though. It means we must match the entire word. + final int fullSearchTermLength = searchTerm.text().length(); + final int realPrefixLength = prefixLength > fullSearchTermLength ? fullSearchTermLength : prefixLength; + + this.text = searchTerm.text().substring(realPrefixLength); + this.prefix = searchTerm.text().substring(0, realPrefixLength); + + initializeMaxDistances(); + this.d = initDistanceArray(); + + setEnum(reader.terms(new Term(searchTerm.field(), prefix))); + } + + /** + * The termCompare method in FuzzyTermEnum uses Levenshtein distance to + * calculate the distance between the given term and the comparing term. + */ + protected final boolean termCompare(Term term) { + if (field == term.field() && term.text().startsWith(prefix)) { + final String target = term.text().substring(prefix.length()); + this.similarity = similarity(target); + return (similarity > minimumSimilarity); + } + endEnum = true; + return false; + } + + public final float difference() { + return (float)((similarity - minimumSimilarity) * scale_factor); + } + + public final boolean endEnum() { + return endEnum; + } + + /****************************** + * Compute Levenshtein distance + ******************************/ + + /** + * Finds and returns the smallest of three integers + */ + private static final int min(int a, int b, int c) { + final int t = (a < b) ? a : b; + return (t < c) ? t : c; + } + + private final int[][] initDistanceArray(){ + return new int[this.text.length() + 1][TYPICAL_LONGEST_WORD_IN_INDEX]; + } + + /** + *

Similarity returns a number that is 1.0f or less (including negative numbers) + * based on how similar the Term is compared to a target term. It returns + * exactly 0.0f when + *

+   *    editDistance < maximumEditDistance
+ * Otherwise it returns: + *
+   *    1 - (editDistance / length)
+ * where length is the length of the shortest term (text or target) including a + * prefix that are identical and editDistance is the Levenshtein distance for + * the two words.

+ * + *

Embedded within this algorithm is a fail-fast Levenshtein distance + * algorithm. The fail-fast algorithm differs from the standard Levenshtein + * distance algorithm in that it is aborted if it is discovered that the + * mimimum distance between the words is greater than some threshold. + * + *

To calculate the maximum distance threshold we use the following formula: + *

+   *     (1 - minimumSimilarity) * length
+ * where length is the shortest term including any prefix that is not part of the + * similarity comparision. This formula was derived by solving for what maximum value + * of distance returns false for the following statements: + *
+   *   similarity = 1 - ((float)distance / (float) (prefixLength + Math.min(textlen, targetlen)));
+   *   return (similarity > minimumSimilarity);
+ * where distance is the Levenshtein distance for the two words. + *

+ *

Levenshtein distance (also known as edit distance) is a measure of similiarity + * between two strings where the distance is measured as the number of character + * deletions, insertions or substitutions required to transform one string to + * the other string. + * @param target the target word or phrase + * @return the similarity, 0.0 or less indicates that it matches less than the required + * threshold and 1.0 indicates that the text and target are identical + */ + private synchronized final float similarity(final String target) { + final int m = target.length(); + final int n = text.length(); + if (n == 0) { + //we don't have anything to compare. That means if we just add + //the letters for m we get the new word + return prefix.length() == 0 ? 0.0f : 1.0f - ((float) m / prefix.length()); + } + if (m == 0) { + return prefix.length() == 0 ? 0.0f : 1.0f - ((float) n / prefix.length()); + } + + final int maxDistance = getMaxDistance(m); + + if (maxDistance < Math.abs(m-n)) { + //just adding the characters of m to n or vice-versa results in + //too many edits + //for example "pre" length is 3 and "prefixes" length is 8. We can see that + //given this optimal circumstance, the edit distance cannot be less than 5. + //which is 8-3 or more precisesly Math.abs(3-8). + //if our maximum edit distance is 4, then we can discard this word + //without looking at it. + return 0.0f; + } + + //let's make sure we have enough room in our array to do the distance calculations. + if (d[0].length <= m) { + growDistanceArray(m); + } + + // init matrix d + for (int i = 0; i <= n; i++) d[i][0] = i; + for (int j = 0; j <= m; j++) d[0][j] = j; + + // start computing edit distance + for (int i = 1; i <= n; i++) { + int bestPossibleEditDistance = m; + final char s_i = text.charAt(i - 1); + for (int j = 1; j <= m; j++) { + if (s_i != target.charAt(j-1)) { + d[i][j] = min(d[i-1][j], d[i][j-1], d[i-1][j-1])+1; + } + else { + d[i][j] = min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]); + } + bestPossibleEditDistance = Math.min(bestPossibleEditDistance, d[i][j]); + } + + //After calculating row i, the best possible edit distance + //can be found by found by finding the smallest value in a given column. + //If the bestPossibleEditDistance is greater than the max distance, abort. + + if (i > maxDistance && bestPossibleEditDistance > maxDistance) { //equal is okay, but not greater + //the closest the target can be to the text is just too far away. + //this target is leaving the party early. + return 0.0f; + } + } + + // this will return less than 0.0 when the edit distance is + // greater than the number of characters in the shorter word. + // but this was the formula that was previously used in FuzzyTermEnum, + // so it has not been changed (even though minimumSimilarity must be + // greater than 0.0) + return 1.0f - ((float)d[n][m] / (float) (prefix.length() + Math.min(n, m))); + } + + /** + * Grow the second dimension of the array, so that we can calculate the + * Levenshtein difference. + */ + private void growDistanceArray(int m) { + for (int i = 0; i < d.length; i++) { + d[i] = new int[m+1]; + } + } + + /** + * The max Distance is the maximum Levenshtein distance for the text + * compared to some other value that results in score that is + * better than the minimum similarity. + * @param m the length of the "other value" + * @return the maximum levenshtein distance that we care about + */ + private final int getMaxDistance(int m) { + return (m < maxDistances.length) ? maxDistances[m] : calculateMaxDistance(m); + } + + private void initializeMaxDistances() { + for (int i = 0; i < maxDistances.length; i++) { + maxDistances[i] = calculateMaxDistance(i); + } + } + + private int calculateMaxDistance(int m) { + return (int) ((1-minimumSimilarity) * (Math.min(text.length(), m) + prefix.length())); + } + + public void close() throws IOException { + super.close(); //call super.close() and let the garbage collector do its work. + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Hit.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Hit.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Hit.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,132 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.search; + +import java.io.IOException; + +import org.apache.lucene.document.Document; +import org.apache.lucene.index.CorruptIndexException; + +/** + * Wrapper used by {@link HitIterator} to provide a lazily loaded hit + * from {@link Hits}. + * + * @deprecated Hits will be removed in Lucene 3.0. Use {@link TopDocCollector} and {@link TopDocs} instead. + */ +public class Hit implements java.io.Serializable { + + private Document doc = null; + + private boolean resolved = false; + + private Hits hits = null; + private int hitNumber; + + /** + * Constructed from {@link HitIterator} + * @param hits Hits returned from a search + * @param hitNumber Hit index in Hits + */ + Hit(Hits hits, int hitNumber) { + this.hits = hits; + this.hitNumber = hitNumber; + } + + /** + * Returns document for this hit. + * + * @see Hits#doc(int) + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public Document getDocument() throws CorruptIndexException, IOException { + if (!resolved) fetchTheHit(); + return doc; + } + + /** + * Returns score for this hit. + * + * @see Hits#score(int) + */ + public float getScore() throws IOException { + return hits.score(hitNumber); + } + + /** + * Returns id for this hit. + * + * @see Hits#id(int) + */ + public int getId() throws IOException { + return hits.id(hitNumber); + } + + private void fetchTheHit() throws CorruptIndexException, IOException { + doc = hits.doc(hitNumber); + resolved = true; + } + + // provide some of the Document style interface (the simple stuff) + + /** + * Returns the boost factor for this hit on any field of the underlying document. + * + * @see Document#getBoost() + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public float getBoost() throws CorruptIndexException, IOException { + return getDocument().getBoost(); + } + + /** + * Returns the string value of the field with the given name if any exist in + * this document, or null. If multiple fields exist with this name, this + * method returns the first value added. If only binary fields with this name + * exist, returns null. + * + * @see Document#get(String) + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public String get(String name) throws CorruptIndexException, IOException { + return getDocument().get(name); + } + + /** + * Prints the parameters to be used to discover the promised result. + */ + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("Hit<"); + buffer.append(hits.toString()); + buffer.append(" ["); + buffer.append(hitNumber); + buffer.append("] "); + if (resolved) { + buffer.append("resolved"); + } else { + buffer.append("unresolved"); + } + buffer.append(">"); + return buffer.toString(); + } + + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/HitCollector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/HitCollector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/HitCollector.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,52 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Lower-level search API. + *
HitCollectors are primarily meant to be used to implement queries, + * sorting and filtering. + * @see Searcher#search(Query,HitCollector) + * @version $Id: HitCollector.java,v 1.1 2012/08/17 14:54:57 marcin Exp $ + */ +public abstract class HitCollector { + /** Called once for every document matching a query, with the document + * number and its raw score. + * + *

If, for example, an application wished to collect all of the hits for a + * query in a BitSet, then it might:

+   *   Searcher searcher = new IndexSearcher(indexReader);
+   *   final BitSet bits = new BitSet(indexReader.maxDoc());
+   *   searcher.search(query, new HitCollector() {
+   *       public void collect(int doc, float score) {
+   *         bits.set(doc);
+   *       }
+   *     });
+   * 
+ * + *

Note: This is called in an inner search loop. For good search + * performance, implementations of this method should not call + * {@link Searcher#doc(int)} or + * {@link org.apache.lucene.index.IndexReader#document(int)} on every + * document number encountered. Doing so can slow searches by an order + * of magnitude or more. + *

Note: The score passed to this method is a raw score. + * In other words, the score will not necessarily be a float whose value is + * between 0 and 1. + */ + public abstract void collect(int doc, float score); +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/HitIterator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/HitIterator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/HitIterator.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,79 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.search; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * An iterator over {@link Hits} that provides lazy fetching of each document. + * {@link Hits#iterator()} returns an instance of this class. Calls to {@link #next()} + * return a {@link Hit} instance. + * + * @deprecated Hits will be removed in Lucene 3.0. Use {@link TopDocCollector} and {@link TopDocs} instead. + */ +public class HitIterator implements Iterator { + private Hits hits; + private int hitNumber = 0; + + /** + * Constructed from {@link Hits#iterator()}. + */ + HitIterator(Hits hits) { + this.hits = hits; + } + + /** + * @return true if current hit is less than the total number of {@link Hits}. + */ + public boolean hasNext() { + return hitNumber < hits.length(); + } + + /** + * Returns a {@link Hit} instance representing the next hit in {@link Hits}. + * + * @return Next {@link Hit}. + */ + public Object next() { + if (hitNumber == hits.length()) + throw new NoSuchElementException(); + + Object next = new Hit(hits, hitNumber); + hitNumber++; + return next; + } + + /** + * Unsupported operation. + * + * @throws UnsupportedOperationException + */ + public void remove() { + throw new UnsupportedOperationException(); + } + + /** + * Returns the total number of hits. + */ + public int length() { + return hits.length(); + } +} + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/HitQueue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/HitQueue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/HitQueue.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,35 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.util.PriorityQueue; + +final class HitQueue extends PriorityQueue { + HitQueue(int size) { + initialize(size); + } + + protected final boolean lessThan(Object a, Object b) { + ScoreDoc hitA = (ScoreDoc)a; + ScoreDoc hitB = (ScoreDoc)b; + if (hitA.score == hitB.score) + return hitA.doc > hitB.doc; + else + return hitA.score < hitB.score; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Hits.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Hits.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Hits.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,276 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.ConcurrentModificationException; +import java.util.Vector; +import java.util.Iterator; + +import org.apache.lucene.document.Document; +import org.apache.lucene.index.CorruptIndexException; + +/** A ranked list of documents, used to hold search results. + *

+ * Caution: Iterate only over the hits needed. Iterating over all + * hits is generally not desirable and may be the source of + * performance issues. If you need to iterate over many or all hits, consider + * using the search method that takes a {@link HitCollector}. + *

+ *

Note: Deleting matching documents concurrently with traversing + * the hits, might, when deleting hits that were not yet retrieved, decrease + * {@link #length()}. In such case, + * {@link java.util.ConcurrentModificationException ConcurrentModificationException} + * is thrown when accessing hit n ≥ current_{@link #length()} + * (but n < {@link #length()}_at_start). + * + * @deprecated Hits will be removed in Lucene 3.0.

+ * Instead e. g. {@link TopDocCollector} and {@link TopDocs} can be used:
+ *

+ *   TopDocCollector collector = new TopDocCollector(hitsPerPage);
+ *   searcher.search(query, collector);
+ *   ScoreDoc[] hits = collector.topDocs().scoreDocs;
+ *   for (int i = 0; i < hits.length; i++) {
+ *     int docId = hits[i].doc;
+ *     Document d = searcher.doc(docId);
+ *     // do something with current hit
+ *     ...
+ * 
+ */ +public final class Hits { + private Weight weight; + private Searcher searcher; + private Filter filter = null; + private Sort sort = null; + + private int length; // the total number of hits + private Vector hitDocs = new Vector(); // cache of hits retrieved + + private HitDoc first; // head of LRU cache + private HitDoc last; // tail of LRU cache + private int numDocs = 0; // number cached + private int maxDocs = 200; // max to cache + + private int nDeletions; // # deleted docs in the index. + private int lengthAtStart; // this is the number apps usually count on (although deletions can bring it down). + private int nDeletedHits = 0; // # of already collected hits that were meanwhile deleted. + + boolean debugCheckedForDeletions = false; // for test purposes. + + Hits(Searcher s, Query q, Filter f) throws IOException { + weight = q.weight(s); + searcher = s; + filter = f; + nDeletions = countDeletions(s); + getMoreDocs(50); // retrieve 100 initially + lengthAtStart = length; + } + + Hits(Searcher s, Query q, Filter f, Sort o) throws IOException { + weight = q.weight(s); + searcher = s; + filter = f; + sort = o; + nDeletions = countDeletions(s); + getMoreDocs(50); // retrieve 100 initially + lengthAtStart = length; + } + + // count # deletions, return -1 if unknown. + private int countDeletions(Searcher s) throws IOException { + int cnt = -1; + if (s instanceof IndexSearcher) { + cnt = s.maxDoc() - ((IndexSearcher) s).getIndexReader().numDocs(); + } + return cnt; + } + + /** + * Tries to add new documents to hitDocs. + * Ensures that the hit numbered min has been retrieved. + */ + private final void getMoreDocs(int min) throws IOException { + if (hitDocs.size() > min) { + min = hitDocs.size(); + } + + int n = min * 2; // double # retrieved + TopDocs topDocs = (sort == null) ? searcher.search(weight, filter, n) : searcher.search(weight, filter, n, sort); + + length = topDocs.totalHits; + ScoreDoc[] scoreDocs = topDocs.scoreDocs; + + float scoreNorm = 1.0f; + + if (length > 0 && topDocs.getMaxScore() > 1.0f) { + scoreNorm = 1.0f / topDocs.getMaxScore(); + } + + int start = hitDocs.size() - nDeletedHits; + + // any new deletions? + int nDels2 = countDeletions(searcher); + debugCheckedForDeletions = false; + if (nDeletions < 0 || nDels2 > nDeletions) { + // either we cannot count deletions, or some "previously valid hits" might have been deleted, so find exact start point + nDeletedHits = 0; + debugCheckedForDeletions = true; + int i2 = 0; + for (int i1=0; i1th document in this set. + *

Documents are cached, so that repeated requests for the same element may + * return the same Document object. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public final Document doc(int n) throws CorruptIndexException, IOException { + HitDoc hitDoc = hitDoc(n); + + // Update LRU cache of documents + remove(hitDoc); // remove from list, if there + addToFront(hitDoc); // add to front of list + if (numDocs > maxDocs) { // if cache is full + HitDoc oldLast = last; + remove(last); // flush last + oldLast.doc = null; // let doc get gc'd + } + + if (hitDoc.doc == null) { + hitDoc.doc = searcher.doc(hitDoc.id); // cache miss: read document + } + + return hitDoc.doc; + } + + /** Returns the score for the nth document in this set. */ + public final float score(int n) throws IOException { + return hitDoc(n).score; + } + + /** Returns the id for the nth document in this set. + * Note that ids may change when the index changes, so you cannot + * rely on the id to be stable. + */ + public final int id(int n) throws IOException { + return hitDoc(n).id; + } + + /** + * Returns a {@link HitIterator} to navigate the Hits. Each item returned + * from {@link Iterator#next()} is a {@link Hit}. + *

+ * Caution: Iterate only over the hits needed. Iterating over all + * hits is generally not desirable and may be the source of + * performance issues. If you need to iterate over many or all hits, consider + * using a search method that takes a {@link HitCollector}. + *

+ */ + public Iterator iterator() { + return new HitIterator(this); + } + + private final HitDoc hitDoc(int n) throws IOException { + if (n >= lengthAtStart) { + throw new IndexOutOfBoundsException("Not a valid hit number: " + n); + } + + if (n >= hitDocs.size()) { + getMoreDocs(n); + } + + if (n >= length) { + throw new ConcurrentModificationException("Not a valid hit number: " + n); + } + + return (HitDoc) hitDocs.elementAt(n); + } + + private final void addToFront(HitDoc hitDoc) { // insert at front of cache + if (first == null) { + last = hitDoc; + } else { + first.prev = hitDoc; + } + + hitDoc.next = first; + first = hitDoc; + hitDoc.prev = null; + + numDocs++; + } + + private final void remove(HitDoc hitDoc) { // remove from cache + if (hitDoc.doc == null) { // it's not in the list + return; // abort + } + + if (hitDoc.next == null) { + last = hitDoc.prev; + } else { + hitDoc.next.prev = hitDoc.prev; + } + + if (hitDoc.prev == null) { + first = hitDoc.next; + } else { + hitDoc.prev.next = hitDoc.next; + } + + numDocs--; + } +} + +final class HitDoc { + float score; + int id; + Document doc = null; + + HitDoc next; // in doubly-linked cache + HitDoc prev; // in doubly-linked cache + + HitDoc(float s, int i) { + score = s; + id = i; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/IndexSearcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/IndexSearcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/IndexSearcher.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,172 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.index.CorruptIndexException; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.store.Directory; + +import java.io.IOException; + +/** Implements search over a single IndexReader. + * + *

Applications usually need only call the inherited {@link #search(Query)} + * or {@link #search(Query,Filter)} methods. For performance reasons it is + * recommended to open only one IndexSearcher and use it for all of your searches. + * + *

Note that you can only access Hits from an IndexSearcher as long as it is + * not yet closed, otherwise an IOException will be thrown. + */ +public class IndexSearcher extends Searcher { + IndexReader reader; + private boolean closeReader; + + /** Creates a searcher searching the index in the named directory. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public IndexSearcher(String path) throws CorruptIndexException, IOException { + this(IndexReader.open(path), true); + } + + /** Creates a searcher searching the index in the provided directory. + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + public IndexSearcher(Directory directory) throws CorruptIndexException, IOException { + this(IndexReader.open(directory), true); + } + + /** Creates a searcher searching the provided index. */ + public IndexSearcher(IndexReader r) { + this(r, false); + } + + private IndexSearcher(IndexReader r, boolean closeReader) { + reader = r; + this.closeReader = closeReader; + } + + /** Return the {@link IndexReader} this searches. */ + public IndexReader getIndexReader() { + return reader; + } + + /** + * Note that the underlying IndexReader is not closed, if + * IndexSearcher was constructed with IndexSearcher(IndexReader r). + * If the IndexReader was supplied implicitly by specifying a directory, then + * the IndexReader gets closed. + */ + public void close() throws IOException { + if(closeReader) + reader.close(); + } + + // inherit javadoc + public int docFreq(Term term) throws IOException { + return reader.docFreq(term); + } + + // inherit javadoc + public Document doc(int i) throws CorruptIndexException, IOException { + return reader.document(i); + } + + // inherit javadoc + public Document doc(int i, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + return reader.document(i, fieldSelector); + } + + // inherit javadoc + public int maxDoc() throws IOException { + return reader.maxDoc(); + } + + // inherit javadoc + public TopDocs search(Weight weight, Filter filter, final int nDocs) + throws IOException { + + if (nDocs <= 0) // null might be returned from hq.top() below. + throw new IllegalArgumentException("nDocs must be > 0"); + + TopDocCollector collector = new TopDocCollector(nDocs); + search(weight, filter, collector); + return collector.topDocs(); + } + + // inherit javadoc + public TopFieldDocs search(Weight weight, Filter filter, final int nDocs, + Sort sort) + throws IOException { + + TopFieldDocCollector collector = + new TopFieldDocCollector(reader, sort, nDocs); + search(weight, filter, collector); + return (TopFieldDocs)collector.topDocs(); + } + + // inherit javadoc + public void search(Weight weight, Filter filter, + final HitCollector results) throws IOException { + + Scorer scorer = weight.scorer(reader); + if (scorer == null) + return; + + if (filter == null) { + scorer.score(results); + return; + } + + DocIdSetIterator filterDocIdIterator = filter.getDocIdSet(reader).iterator(); // CHECKME: use ConjunctionScorer here? + + boolean more = filterDocIdIterator.next() && scorer.skipTo(filterDocIdIterator.doc()); + + while (more) { + int filterDocId = filterDocIdIterator.doc(); + if (filterDocId > scorer.doc() && !scorer.skipTo(filterDocId)) { + more = false; + } else { + int scorerDocId = scorer.doc(); + if (scorerDocId == filterDocId) { // permitted by filter + results.collect(scorerDocId, scorer.score()); + more = filterDocIdIterator.next(); + } else { + more = filterDocIdIterator.skipTo(scorerDocId); + } + } + } + } + + public Query rewrite(Query original) throws IOException { + Query query = original; + for (Query rewrittenQuery = query.rewrite(reader); rewrittenQuery != query; + rewrittenQuery = query.rewrite(reader)) { + query = rewrittenQuery; + } + return query; + } + + public Explanation explain(Weight weight, int doc) throws IOException { + return weight.explain(reader, doc); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/MatchAllDocsQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/MatchAllDocsQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/MatchAllDocsQuery.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,156 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.Explanation; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Scorer; +import org.apache.lucene.search.Searcher; +import org.apache.lucene.search.Similarity; +import org.apache.lucene.search.Weight; +import org.apache.lucene.util.ToStringUtils; + +import java.util.Set; + +/** + * A query that matches all documents. + * + */ +public class MatchAllDocsQuery extends Query { + + public MatchAllDocsQuery() { + } + + private class MatchAllScorer extends Scorer { + + final IndexReader reader; + int id; + final int maxId; + final float score; + + MatchAllScorer(IndexReader reader, Similarity similarity, Weight w) { + super(similarity); + this.reader = reader; + id = -1; + maxId = reader.maxDoc() - 1; + score = w.getValue(); + } + + public Explanation explain(int doc) { + return null; // not called... see MatchAllDocsWeight.explain() + } + + public int doc() { + return id; + } + + public boolean next() { + while (id < maxId) { + id++; + if (!reader.isDeleted(id)) { + return true; + } + } + return false; + } + + public float score() { + return score; + } + + public boolean skipTo(int target) { + id = target - 1; + return next(); + } + + } + + private class MatchAllDocsWeight implements Weight { + private Similarity similarity; + private float queryWeight; + private float queryNorm; + + public MatchAllDocsWeight(Searcher searcher) { + this.similarity = searcher.getSimilarity(); + } + + public String toString() { + return "weight(" + MatchAllDocsQuery.this + ")"; + } + + public Query getQuery() { + return MatchAllDocsQuery.this; + } + + public float getValue() { + return queryWeight; + } + + public float sumOfSquaredWeights() { + queryWeight = getBoost(); + return queryWeight * queryWeight; + } + + public void normalize(float queryNorm) { + this.queryNorm = queryNorm; + queryWeight *= this.queryNorm; + } + + public Scorer scorer(IndexReader reader) { + return new MatchAllScorer(reader, similarity, this); + } + + public Explanation explain(IndexReader reader, int doc) { + // explain query weight + Explanation queryExpl = new ComplexExplanation + (true, getValue(), "MatchAllDocsQuery, product of:"); + if (getBoost() != 1.0f) { + queryExpl.addDetail(new Explanation(getBoost(),"boost")); + } + queryExpl.addDetail(new Explanation(queryNorm,"queryNorm")); + + return queryExpl; + } + } + + protected Weight createWeight(Searcher searcher) { + return new MatchAllDocsWeight(searcher); + } + + public void extractTerms(Set terms) { + } + + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + buffer.append("MatchAllDocsQuery"); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + public boolean equals(Object o) { + if (!(o instanceof MatchAllDocsQuery)) + return false; + MatchAllDocsQuery other = (MatchAllDocsQuery) o; + return this.getBoost() == other.getBoost(); + } + + public int hashCode() { + return Float.floatToIntBits(getBoost()) ^ 0x1AA71190; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/MultiPhraseQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/MultiPhraseQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/MultiPhraseQuery.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,326 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.*; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.MultipleTermPositions; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermPositions; +import org.apache.lucene.search.Query; +import org.apache.lucene.util.ToStringUtils; + +/** + * MultiPhraseQuery is a generalized version of PhraseQuery, with an added + * method {@link #add(Term[])}. + * To use this class, to search for the phrase "Microsoft app*" first use + * add(Term) on the term "Microsoft", then find all terms that have "app" as + * prefix using IndexReader.terms(Term), and use MultiPhraseQuery.add(Term[] + * terms) to add them to the query. + * + * @version 1.0 + */ +public class MultiPhraseQuery extends Query { + private String field; + private ArrayList termArrays = new ArrayList(); + private ArrayList positions = new ArrayList(); + + private int slop = 0; + + /** Sets the phrase slop for this query. + * @see PhraseQuery#setSlop(int) + */ + public void setSlop(int s) { slop = s; } + + /** Sets the phrase slop for this query. + * @see PhraseQuery#getSlop() + */ + public int getSlop() { return slop; } + + /** Add a single term at the next position in the phrase. + * @see PhraseQuery#add(Term) + */ + public void add(Term term) { add(new Term[]{term}); } + + /** Add multiple terms at the next position in the phrase. Any of the terms + * may match. + * + * @see PhraseQuery#add(Term) + */ + public void add(Term[] terms) { + int position = 0; + if (positions.size() > 0) + position = ((Integer) positions.get(positions.size()-1)).intValue() + 1; + + add(terms, position); + } + + /** + * Allows to specify the relative position of terms within the phrase. + * + * @see PhraseQuery#add(Term, int) + * @param terms + * @param position + */ + public void add(Term[] terms, int position) { + if (termArrays.size() == 0) + field = terms[0].field(); + + for (int i = 0; i < terms.length; i++) { + if (terms[i].field() != field) { + throw new IllegalArgumentException( + "All phrase terms must be in the same field (" + field + "): " + + terms[i]); + } + } + + termArrays.add(terms); + positions.add(new Integer(position)); + } + + /** + * Returns a List of the terms in the multiphrase. + * Do not modify the List or its contents. + */ + public List getTermArrays() { + return Collections.unmodifiableList(termArrays); + } + + /** + * Returns the relative positions of terms in this phrase. + */ + public int[] getPositions() { + int[] result = new int[positions.size()]; + for (int i = 0; i < positions.size(); i++) + result[i] = ((Integer) positions.get(i)).intValue(); + return result; + } + + // inherit javadoc + public void extractTerms(Set terms) { + for (Iterator iter = termArrays.iterator(); iter.hasNext();) { + Term[] arr = (Term[])iter.next(); + for (int i=0; i 1) + p = new MultipleTermPositions(reader, terms); + else + p = reader.termPositions(terms[0]); + + if (p == null) + return null; + + tps[i] = p; + } + + if (slop == 0) + return new ExactPhraseScorer(this, tps, getPositions(), similarity, + reader.norms(field)); + else + return new SloppyPhraseScorer(this, tps, getPositions(), similarity, + slop, reader.norms(field)); + } + + public Explanation explain(IndexReader reader, int doc) + throws IOException { + ComplexExplanation result = new ComplexExplanation(); + result.setDescription("weight("+getQuery()+" in "+doc+"), product of:"); + + Explanation idfExpl = new Explanation(idf, "idf("+getQuery()+")"); + + // explain query weight + Explanation queryExpl = new Explanation(); + queryExpl.setDescription("queryWeight(" + getQuery() + "), product of:"); + + Explanation boostExpl = new Explanation(getBoost(), "boost"); + if (getBoost() != 1.0f) + queryExpl.addDetail(boostExpl); + + queryExpl.addDetail(idfExpl); + + Explanation queryNormExpl = new Explanation(queryNorm,"queryNorm"); + queryExpl.addDetail(queryNormExpl); + + queryExpl.setValue(boostExpl.getValue() * + idfExpl.getValue() * + queryNormExpl.getValue()); + + result.addDetail(queryExpl); + + // explain field weight + ComplexExplanation fieldExpl = new ComplexExplanation(); + fieldExpl.setDescription("fieldWeight("+getQuery()+" in "+doc+ + "), product of:"); + + Explanation tfExpl = scorer(reader).explain(doc); + fieldExpl.addDetail(tfExpl); + fieldExpl.addDetail(idfExpl); + + Explanation fieldNormExpl = new Explanation(); + byte[] fieldNorms = reader.norms(field); + float fieldNorm = + fieldNorms!=null ? Similarity.decodeNorm(fieldNorms[doc]) : 0.0f; + fieldNormExpl.setValue(fieldNorm); + fieldNormExpl.setDescription("fieldNorm(field="+field+", doc="+doc+")"); + fieldExpl.addDetail(fieldNormExpl); + + fieldExpl.setMatch(Boolean.valueOf(tfExpl.isMatch())); + fieldExpl.setValue(tfExpl.getValue() * + idfExpl.getValue() * + fieldNormExpl.getValue()); + + result.addDetail(fieldExpl); + result.setMatch(fieldExpl.getMatch()); + + // combine them + result.setValue(queryExpl.getValue() * fieldExpl.getValue()); + + if (queryExpl.getValue() == 1.0f) + return fieldExpl; + + return result; + } + } + + public Query rewrite(IndexReader reader) { + if (termArrays.size() == 1) { // optimize one-term case + Term[] terms = (Term[])termArrays.get(0); + BooleanQuery boq = new BooleanQuery(true); + for (int i=0; i 1) { + buffer.append("("); + for (int j = 0; j < terms.length; j++) { + buffer.append(terms[j].text()); + if (j < terms.length-1) + buffer.append(" "); + } + buffer.append(")"); + } else { + buffer.append(terms[0].text()); + } + if (i.hasNext()) + buffer.append(" "); + } + buffer.append("\""); + + if (slop != 0) { + buffer.append("~"); + buffer.append(slop); + } + + buffer.append(ToStringUtils.boost(getBoost())); + + return buffer.toString(); + } + + + /** Returns true if o is equal to this. */ + public boolean equals(Object o) { + if (!(o instanceof MultiPhraseQuery)) return false; + MultiPhraseQuery other = (MultiPhraseQuery)o; + return this.getBoost() == other.getBoost() + && this.slop == other.slop + && this.termArrays.equals(other.termArrays) + && this.positions.equals(other.positions); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + return Float.floatToIntBits(getBoost()) + ^ slop + ^ termArrays.hashCode() + ^ positions.hashCode() + ^ 0x4AC65113; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/MultiSearcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/MultiSearcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/MultiSearcher.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,329 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.index.CorruptIndexException; +import org.apache.lucene.index.Term; + +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** Implements search over a set of Searchables. + * + *

Applications usually need only call the inherited {@link #search(Query)} + * or {@link #search(Query,Filter)} methods. + */ +public class MultiSearcher extends Searcher { + /** + * Document Frequency cache acting as a Dummy-Searcher. + * This class is no full-fledged Searcher, but only supports + * the methods necessary to initialize Weights. + */ + private static class CachedDfSource extends Searcher { + private Map dfMap; // Map from Terms to corresponding doc freqs + private int maxDoc; // document count + + public CachedDfSource(Map dfMap, int maxDoc, Similarity similarity) { + this.dfMap = dfMap; + this.maxDoc = maxDoc; + setSimilarity(similarity); + } + + public int docFreq(Term term) { + int df; + try { + df = ((Integer) dfMap.get(term)).intValue(); + } catch (NullPointerException e) { + throw new IllegalArgumentException("df for term " + term.text() + + " not available"); + } + return df; + } + + public int[] docFreqs(Term[] terms) { + int[] result = new int[terms.length]; + for (int i = 0; i < terms.length; i++) { + result[i] = docFreq(terms[i]); + } + return result; + } + + public int maxDoc() { + return maxDoc; + } + + public Query rewrite(Query query) { + // this is a bit of a hack. We know that a query which + // creates a Weight based on this Dummy-Searcher is + // always already rewritten (see preparedWeight()). + // Therefore we just return the unmodified query here + return query; + } + + public void close() { + throw new UnsupportedOperationException(); + } + + public Document doc(int i) { + throw new UnsupportedOperationException(); + } + + public Document doc(int i, FieldSelector fieldSelector) { + throw new UnsupportedOperationException(); + } + + public Explanation explain(Weight weight,int doc) { + throw new UnsupportedOperationException(); + } + + public void search(Weight weight, Filter filter, HitCollector results) { + throw new UnsupportedOperationException(); + } + + public TopDocs search(Weight weight,Filter filter,int n) { + throw new UnsupportedOperationException(); + } + + public TopFieldDocs search(Weight weight,Filter filter,int n,Sort sort) { + throw new UnsupportedOperationException(); + } + } + + + private Searchable[] searchables; + private int[] starts; + private int maxDoc = 0; + + /** Creates a searcher which searches searchables. */ + public MultiSearcher(Searchable[] searchables) throws IOException { + this.searchables = searchables; + + starts = new int[searchables.length + 1]; // build starts array + for (int i = 0; i < searchables.length; i++) { + starts[i] = maxDoc; + maxDoc += searchables[i].maxDoc(); // compute maxDocs + } + starts[searchables.length] = maxDoc; + } + + /** Return the array of {@link Searchable}s this searches. */ + public Searchable[] getSearchables() { + return searchables; + } + + protected int[] getStarts() { + return starts; + } + + // inherit javadoc + public void close() throws IOException { + for (int i = 0; i < searchables.length; i++) + searchables[i].close(); + } + + public int docFreq(Term term) throws IOException { + int docFreq = 0; + for (int i = 0; i < searchables.length; i++) + docFreq += searchables[i].docFreq(term); + return docFreq; + } + + // inherit javadoc + public Document doc(int n) throws CorruptIndexException, IOException { + int i = subSearcher(n); // find searcher index + return searchables[i].doc(n - starts[i]); // dispatch to searcher + } + + // inherit javadoc + public Document doc(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + int i = subSearcher(n); // find searcher index + return searchables[i].doc(n - starts[i], fieldSelector); // dispatch to searcher + } + + /** Returns index of the searcher for document n in the array + * used to construct this searcher. */ + public int subSearcher(int n) { // find searcher for doc n: + // replace w/ call to Arrays.binarySearch in Java 1.2 + int lo = 0; // search starts array + int hi = searchables.length - 1; // for first element less + // than n, return its index + while (hi >= lo) { + int mid = (lo + hi) >> 1; + int midValue = starts[mid]; + if (n < midValue) + hi = mid - 1; + else if (n > midValue) + lo = mid + 1; + else { // found a match + while (mid+1 < searchables.length && starts[mid+1] == midValue) { + mid++; // scan to last match + } + return mid; + } + } + return hi; + } + + /** Returns the document number of document n within its + * sub-index. */ + public int subDoc(int n) { + return n - starts[subSearcher(n)]; + } + + public int maxDoc() throws IOException { + return maxDoc; + } + + public TopDocs search(Weight weight, Filter filter, int nDocs) + throws IOException { + + HitQueue hq = new HitQueue(nDocs); + int totalHits = 0; + + for (int i = 0; i < searchables.length; i++) { // search each searcher + TopDocs docs = searchables[i].search(weight, filter, nDocs); + totalHits += docs.totalHits; // update totalHits + ScoreDoc[] scoreDocs = docs.scoreDocs; + for (int j = 0; j < scoreDocs.length; j++) { // merge scoreDocs into hq + ScoreDoc scoreDoc = scoreDocs[j]; + scoreDoc.doc += starts[i]; // convert doc + if(!hq.insert(scoreDoc)) + break; // no more scores > minScore + } + } + + ScoreDoc[] scoreDocs = new ScoreDoc[hq.size()]; + for (int i = hq.size()-1; i >= 0; i--) // put docs in array + scoreDocs[i] = (ScoreDoc)hq.pop(); + + float maxScore = (totalHits==0) ? Float.NEGATIVE_INFINITY : scoreDocs[0].score; + + return new TopDocs(totalHits, scoreDocs, maxScore); + } + + public TopFieldDocs search (Weight weight, Filter filter, int n, Sort sort) + throws IOException { + FieldDocSortedHitQueue hq = null; + int totalHits = 0; + + float maxScore=Float.NEGATIVE_INFINITY; + + for (int i = 0; i < searchables.length; i++) { // search each searcher + TopFieldDocs docs = searchables[i].search (weight, filter, n, sort); + + if (hq == null) hq = new FieldDocSortedHitQueue (docs.fields, n); + totalHits += docs.totalHits; // update totalHits + maxScore = Math.max(maxScore, docs.getMaxScore()); + ScoreDoc[] scoreDocs = docs.scoreDocs; + for (int j = 0; j < scoreDocs.length; j++) { // merge scoreDocs into hq + ScoreDoc scoreDoc = scoreDocs[j]; + scoreDoc.doc += starts[i]; // convert doc + if (!hq.insert (scoreDoc)) + break; // no more scores > minScore + } + } + + ScoreDoc[] scoreDocs = new ScoreDoc[hq.size()]; + for (int i = hq.size() - 1; i >= 0; i--) // put docs in array + scoreDocs[i] = (ScoreDoc) hq.pop(); + + return new TopFieldDocs (totalHits, scoreDocs, hq.getFields(), maxScore); + } + + + // inherit javadoc + public void search(Weight weight, Filter filter, final HitCollector results) + throws IOException { + for (int i = 0; i < searchables.length; i++) { + + final int start = starts[i]; + + searchables[i].search(weight, filter, new HitCollector() { + public void collect(int doc, float score) { + results.collect(doc + start, score); + } + }); + + } + } + + public Query rewrite(Query original) throws IOException { + Query[] queries = new Query[searchables.length]; + for (int i = 0; i < searchables.length; i++) { + queries[i] = searchables[i].rewrite(original); + } + return queries[0].combine(queries); + } + + public Explanation explain(Weight weight, int doc) throws IOException { + int i = subSearcher(doc); // find searcher index + return searchables[i].explain(weight,doc-starts[i]); // dispatch to searcher + } + + /** + * Create weight in multiple index scenario. + * + * Distributed query processing is done in the following steps: + * 1. rewrite query + * 2. extract necessary terms + * 3. collect dfs for these terms from the Searchables + * 4. create query weight using aggregate dfs. + * 5. distribute that weight to Searchables + * 6. merge results + * + * Steps 1-4 are done here, 5+6 in the search() methods + * + * @return rewritten queries + */ + protected Weight createWeight(Query original) throws IOException { + // step 1 + Query rewrittenQuery = rewrite(original); + + // step 2 + Set terms = new HashSet(); + rewrittenQuery.extractTerms(terms); + + // step3 + Term[] allTermsArray = new Term[terms.size()]; + terms.toArray(allTermsArray); + int[] aggregatedDfs = new int[terms.size()]; + for (int i = 0; i < searchables.length; i++) { + int[] dfs = searchables[i].docFreqs(allTermsArray); + for(int j=0; j + * MultiTermQuery is not designed to be used by itself. + *
+ * The reason being that it is not intialized with a {@link FilteredTermEnum} + * enumeration. A {@link FilteredTermEnum} enumeration needs to be provided. + *

+ * For example, {@link WildcardQuery} and {@link FuzzyQuery} extend + * MultiTermQuery to provide {@link WildcardTermEnum} and + * {@link FuzzyTermEnum}, respectively. + */ +public abstract class MultiTermQuery extends Query { + private Term term; + + /** Constructs a query for terms matching term. */ + public MultiTermQuery(Term term) { + this.term = term; + } + + /** Returns the pattern term. */ + public Term getTerm() { return term; } + + /** Construct the enumeration to be used, expanding the pattern term. */ + protected abstract FilteredTermEnum getEnum(IndexReader reader) + throws IOException; + + public Query rewrite(IndexReader reader) throws IOException { + FilteredTermEnum enumerator = getEnum(reader); + BooleanQuery query = new BooleanQuery(true); + try { + do { + Term t = enumerator.term(); + if (t != null) { + TermQuery tq = new TermQuery(t); // found a match + tq.setBoost(getBoost() * enumerator.difference()); // set the boost + query.add(tq, BooleanClause.Occur.SHOULD); // add to query + } + } while (enumerator.next()); + } finally { + enumerator.close(); + } + return query; + } + + /** Prints a user-readable version of this query. */ + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + if (!term.field().equals(field)) { + buffer.append(term.field()); + buffer.append(":"); + } + buffer.append(term.text()); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MultiTermQuery)) return false; + + final MultiTermQuery multiTermQuery = (MultiTermQuery) o; + + if (!term.equals(multiTermQuery.term)) return false; + + return getBoost() == multiTermQuery.getBoost(); + } + + public int hashCode() { + return term.hashCode() + Float.floatToRawIntBits(getBoost()); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/NonMatchingScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/NonMatchingScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/NonMatchingScorer.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,41 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** A scorer that matches no document at all. */ +class NonMatchingScorer extends Scorer { + public NonMatchingScorer() { super(null); } // no similarity used + + public int doc() { throw new UnsupportedOperationException(); } + + public boolean next() throws IOException { return false; } + + public float score() { throw new UnsupportedOperationException(); } + + public boolean skipTo(int target) { return false; } + + public Explanation explain(int doc) { + Explanation e = new Explanation(); + e.setDescription("No document matches."); + return e; + } +} + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/ParallelMultiSearcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ParallelMultiSearcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ParallelMultiSearcher.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,291 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.Term; +import org.apache.lucene.util.PriorityQueue; + +/** Implements parallel search over a set of Searchables. + * + *

Applications usually need only call the inherited {@link #search(Query)} + * or {@link #search(Query,Filter)} methods. + */ +public class ParallelMultiSearcher extends MultiSearcher { + + private Searchable[] searchables; + private int[] starts; + + /** Creates a searcher which searches searchables. */ + public ParallelMultiSearcher(Searchable[] searchables) throws IOException { + super(searchables); + this.searchables=searchables; + this.starts=getStarts(); + } + + /** + * TODO: parallelize this one too + */ + public int docFreq(Term term) throws IOException { + return super.docFreq(term); + } + + /** + * A search implementation which spans a new thread for each + * Searchable, waits for each search to complete and merge + * the results back together. + */ + public TopDocs search(Weight weight, Filter filter, int nDocs) + throws IOException { + HitQueue hq = new HitQueue(nDocs); + int totalHits = 0; + MultiSearcherThread[] msta = + new MultiSearcherThread[searchables.length]; + for (int i = 0; i < searchables.length; i++) { // search each searcher + // Assume not too many searchables and cost of creating a thread is by far inferior to a search + msta[i] = + new MultiSearcherThread( + searchables[i], + weight, + filter, + nDocs, + hq, + i, + starts, + "MultiSearcher thread #" + (i + 1)); + msta[i].start(); + } + + for (int i = 0; i < searchables.length; i++) { + try { + msta[i].join(); + } catch (InterruptedException ie) { + ; // TODO: what should we do with this??? + } + IOException ioe = msta[i].getIOException(); + if (ioe == null) { + totalHits += msta[i].hits(); + } else { + // if one search produced an IOException, rethrow it + throw ioe; + } + } + + ScoreDoc[] scoreDocs = new ScoreDoc[hq.size()]; + for (int i = hq.size() - 1; i >= 0; i--) // put docs in array + scoreDocs[i] = (ScoreDoc) hq.pop(); + + float maxScore = (totalHits==0) ? Float.NEGATIVE_INFINITY : scoreDocs[0].score; + + return new TopDocs(totalHits, scoreDocs, maxScore); + } + + /** + * A search implementation allowing sorting which spans a new thread for each + * Searchable, waits for each search to complete and merges + * the results back together. + */ + public TopFieldDocs search(Weight weight, Filter filter, int nDocs, Sort sort) + throws IOException { + // don't specify the fields - we'll wait to do this until we get results + FieldDocSortedHitQueue hq = new FieldDocSortedHitQueue (null, nDocs); + int totalHits = 0; + MultiSearcherThread[] msta = new MultiSearcherThread[searchables.length]; + for (int i = 0; i < searchables.length; i++) { // search each searcher + // Assume not too many searchables and cost of creating a thread is by far inferior to a search + msta[i] = + new MultiSearcherThread( + searchables[i], + weight, + filter, + nDocs, + hq, + sort, + i, + starts, + "MultiSearcher thread #" + (i + 1)); + msta[i].start(); + } + + float maxScore=Float.NEGATIVE_INFINITY; + + for (int i = 0; i < searchables.length; i++) { + try { + msta[i].join(); + } catch (InterruptedException ie) { + ; // TODO: what should we do with this??? + } + IOException ioe = msta[i].getIOException(); + if (ioe == null) { + totalHits += msta[i].hits(); + maxScore=Math.max(maxScore, msta[i].getMaxScore()); + } else { + // if one search produced an IOException, rethrow it + throw ioe; + } + } + + ScoreDoc[] scoreDocs = new ScoreDoc[hq.size()]; + for (int i = hq.size() - 1; i >= 0; i--) // put docs in array + scoreDocs[i] = (ScoreDoc) hq.pop(); + + return new TopFieldDocs(totalHits, scoreDocs, hq.getFields(), maxScore); + } + + /** Lower-level search API. + * + *

{@link HitCollector#collect(int,float)} is called for every matching + * document. + * + *

Applications should only use this if they need all of the + * matching documents. The high-level search API ({@link + * Searcher#search(Query)}) is usually more efficient, as it skips + * non-high-scoring hits. + * + * @param weight to match documents + * @param filter if non-null, a bitset used to eliminate some documents + * @param results to receive hits + * + * @todo parallelize this one too + */ + public void search(Weight weight, Filter filter, final HitCollector results) + throws IOException { + for (int i = 0; i < searchables.length; i++) { + + final int start = starts[i]; + + searchables[i].search(weight, filter, new HitCollector() { + public void collect(int doc, float score) { + results.collect(doc + start, score); + } + }); + + } + } + + /* + * TODO: this one could be parallelized too + * @see org.apache.lucene.search.Searchable#rewrite(org.apache.lucene.search.Query) + */ + public Query rewrite(Query original) throws IOException { + return super.rewrite(original); + } + +} + +/** + * A thread subclass for searching a single searchable + */ +class MultiSearcherThread extends Thread { + + private Searchable searchable; + private Weight weight; + private Filter filter; + private int nDocs; + private TopDocs docs; + private int i; + private PriorityQueue hq; + private int[] starts; + private IOException ioe; + private Sort sort; + + public MultiSearcherThread( + Searchable searchable, + Weight weight, + Filter filter, + int nDocs, + HitQueue hq, + int i, + int[] starts, + String name) { + super(name); + this.searchable = searchable; + this.weight = weight; + this.filter = filter; + this.nDocs = nDocs; + this.hq = hq; + this.i = i; + this.starts = starts; + } + + public MultiSearcherThread( + Searchable searchable, + Weight weight, + Filter filter, + int nDocs, + FieldDocSortedHitQueue hq, + Sort sort, + int i, + int[] starts, + String name) { + super(name); + this.searchable = searchable; + this.weight = weight; + this.filter = filter; + this.nDocs = nDocs; + this.hq = hq; + this.i = i; + this.starts = starts; + this.sort = sort; + } + + public void run() { + try { + docs = (sort == null) ? searchable.search (weight, filter, nDocs) + : searchable.search (weight, filter, nDocs, sort); + } + // Store the IOException for later use by the caller of this thread + catch (IOException ioe) { + this.ioe = ioe; + } + if (ioe == null) { + // if we are sorting by fields, we need to tell the field sorted hit queue + // the actual type of fields, in case the original list contained AUTO. + // if the searchable returns null for fields, we'll have problems. + if (sort != null) { + ((FieldDocSortedHitQueue)hq).setFields (((TopFieldDocs)docs).fields); + } + ScoreDoc[] scoreDocs = docs.scoreDocs; + for (int j = 0; + j < scoreDocs.length; + j++) { // merge scoreDocs into hq + ScoreDoc scoreDoc = scoreDocs[j]; + scoreDoc.doc += starts[i]; // convert doc + //it would be so nice if we had a thread-safe insert + synchronized (hq) { + if (!hq.insert(scoreDoc)) + break; + } // no more scores > minScore + } + } + } + + public int hits() { + return docs.totalHits; + } + + public float getMaxScore() { + return docs.getMaxScore(); + } + + public IOException getIOException() { + return ioe; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/PhrasePositions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/PhrasePositions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/PhrasePositions.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,81 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.index.*; + +/** + * Position of a term in a document that takes into account the term offset within the phrase. + */ +final class PhrasePositions { + int doc; // current doc + int position; // position in doc + int count; // remaining pos in this doc + int offset; // position in phrase + TermPositions tp; // stream of positions + PhrasePositions next; // used to make lists + boolean repeats; // there's other pp for same term (e.g. query="1st word 2nd word"~1) + + PhrasePositions(TermPositions t, int o) { + tp = t; + offset = o; + } + + final boolean next() throws IOException { // increments to next doc + if (!tp.next()) { + tp.close(); // close stream + doc = Integer.MAX_VALUE; // sentinel value + return false; + } + doc = tp.doc(); + position = 0; + return true; + } + + final boolean skipTo(int target) throws IOException { + if (!tp.skipTo(target)) { + tp.close(); // close stream + doc = Integer.MAX_VALUE; // sentinel value + return false; + } + doc = tp.doc(); + position = 0; + return true; + } + + + final void firstPosition() throws IOException { + count = tp.freq(); // read first pos + nextPosition(); + } + + /** + * Go to next location of this term current document, and set + * position as location - offset, so that a + * matching exact phrase is easily identified when all PhrasePositions + * have exactly the same position. + */ + final boolean nextPosition() throws IOException { + if (count-- > 0) { // read subsequent pos's + position = tp.nextPosition() - offset; + return true; + } else + return false; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/PhraseQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/PhraseQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/PhraseQuery.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,319 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Set; +import java.util.ArrayList; + +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermPositions; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.ToStringUtils; + +/** A Query that matches documents containing a particular sequence of terms. + * A PhraseQuery is built by QueryParser for input like "new york". + * + *

This query may be combined with other terms or queries with a {@link BooleanQuery}. + */ +public class PhraseQuery extends Query { + private String field; + private ArrayList terms = new ArrayList(4); + private ArrayList positions = new ArrayList(4); + private int maxPosition = 0; + private int slop = 0; + + /** Constructs an empty phrase query. */ + public PhraseQuery() {} + + /** Sets the number of other words permitted between words in query phrase. + If zero, then this is an exact phrase search. For larger values this works + like a WITHIN or NEAR operator. + +

The slop is in fact an edit-distance, where the units correspond to + moves of terms in the query phrase out of position. For example, to switch + the order of two words requires two moves (the first move places the words + atop one another), so to permit re-orderings of phrases, the slop must be + at least two. + +

More exact matches are scored higher than sloppier matches, thus search + results are sorted by exactness. + +

The slop is zero by default, requiring exact matches.*/ + public void setSlop(int s) { slop = s; } + /** Returns the slop. See setSlop(). */ + public int getSlop() { return slop; } + + /** + * Adds a term to the end of the query phrase. + * The relative position of the term is the one immediately after the last term added. + */ + public void add(Term term) { + int position = 0; + if(positions.size() > 0) + position = ((Integer) positions.get(positions.size()-1)).intValue() + 1; + + add(term, position); + } + + /** + * Adds a term to the end of the query phrase. + * The relative position of the term within the phrase is specified explicitly. + * This allows e.g. phrases with more than one term at the same position + * or phrases with gaps (e.g. in connection with stopwords). + * + * @param term + * @param position + */ + public void add(Term term, int position) { + if (terms.size() == 0) + field = term.field(); + else if (term.field() != field) + throw new IllegalArgumentException("All phrase terms must be in the same field: " + term); + + terms.add(term); + positions.add(new Integer(position)); + if (position > maxPosition) maxPosition = position; + } + + /** Returns the set of terms in this phrase. */ + public Term[] getTerms() { + return (Term[])terms.toArray(new Term[0]); + } + + /** + * Returns the relative positions of terms in this phrase. + */ + public int[] getPositions() { + int[] result = new int[positions.size()]; + for(int i = 0; i < positions.size(); i++) + result[i] = ((Integer) positions.get(i)).intValue(); + return result; + } + + private class PhraseWeight implements Weight { + private Similarity similarity; + private float value; + private float idf; + private float queryNorm; + private float queryWeight; + + public PhraseWeight(Searcher searcher) + throws IOException { + this.similarity = getSimilarity(searcher); + + idf = similarity.idf(terms, searcher); + } + + public String toString() { return "weight(" + PhraseQuery.this + ")"; } + + public Query getQuery() { return PhraseQuery.this; } + public float getValue() { return value; } + + public float sumOfSquaredWeights() { + queryWeight = idf * getBoost(); // compute query weight + return queryWeight * queryWeight; // square it + } + + public void normalize(float queryNorm) { + this.queryNorm = queryNorm; + queryWeight *= queryNorm; // normalize query weight + value = queryWeight * idf; // idf for document + } + + public Scorer scorer(IndexReader reader) throws IOException { + if (terms.size() == 0) // optimize zero-term case + return null; + + TermPositions[] tps = new TermPositions[terms.size()]; + for (int i = 0; i < terms.size(); i++) { + TermPositions p = reader.termPositions((Term)terms.get(i)); + if (p == null) + return null; + tps[i] = p; + } + + if (slop == 0) // optimize exact case + return new ExactPhraseScorer(this, tps, getPositions(), similarity, + reader.norms(field)); + else + return + new SloppyPhraseScorer(this, tps, getPositions(), similarity, slop, + reader.norms(field)); + + } + + public Explanation explain(IndexReader reader, int doc) + throws IOException { + + Explanation result = new Explanation(); + result.setDescription("weight("+getQuery()+" in "+doc+"), product of:"); + + StringBuffer docFreqs = new StringBuffer(); + StringBuffer query = new StringBuffer(); + query.append('\"'); + for (int i = 0; i < terms.size(); i++) { + if (i != 0) { + docFreqs.append(" "); + query.append(" "); + } + + Term term = (Term)terms.get(i); + + docFreqs.append(term.text()); + docFreqs.append("="); + docFreqs.append(reader.docFreq(term)); + + query.append(term.text()); + } + query.append('\"'); + + Explanation idfExpl = + new Explanation(idf, "idf(" + field + ": " + docFreqs + ")"); + + // explain query weight + Explanation queryExpl = new Explanation(); + queryExpl.setDescription("queryWeight(" + getQuery() + "), product of:"); + + Explanation boostExpl = new Explanation(getBoost(), "boost"); + if (getBoost() != 1.0f) + queryExpl.addDetail(boostExpl); + queryExpl.addDetail(idfExpl); + + Explanation queryNormExpl = new Explanation(queryNorm,"queryNorm"); + queryExpl.addDetail(queryNormExpl); + + queryExpl.setValue(boostExpl.getValue() * + idfExpl.getValue() * + queryNormExpl.getValue()); + + result.addDetail(queryExpl); + + // explain field weight + Explanation fieldExpl = new Explanation(); + fieldExpl.setDescription("fieldWeight("+field+":"+query+" in "+doc+ + "), product of:"); + + Explanation tfExpl = scorer(reader).explain(doc); + fieldExpl.addDetail(tfExpl); + fieldExpl.addDetail(idfExpl); + + Explanation fieldNormExpl = new Explanation(); + byte[] fieldNorms = reader.norms(field); + float fieldNorm = + fieldNorms!=null ? Similarity.decodeNorm(fieldNorms[doc]) : 0.0f; + fieldNormExpl.setValue(fieldNorm); + fieldNormExpl.setDescription("fieldNorm(field="+field+", doc="+doc+")"); + fieldExpl.addDetail(fieldNormExpl); + + fieldExpl.setValue(tfExpl.getValue() * + idfExpl.getValue() * + fieldNormExpl.getValue()); + + result.addDetail(fieldExpl); + + // combine them + result.setValue(queryExpl.getValue() * fieldExpl.getValue()); + + if (queryExpl.getValue() == 1.0f) + return fieldExpl; + + return result; + } + } + + protected Weight createWeight(Searcher searcher) throws IOException { + if (terms.size() == 1) { // optimize one-term case + Term term = (Term)terms.get(0); + Query termQuery = new TermQuery(term); + termQuery.setBoost(getBoost()); + return termQuery.createWeight(searcher); + } + return new PhraseWeight(searcher); + } + + /** + * @see org.apache.lucene.search.Query#extractTerms(java.util.Set) + */ + public void extractTerms(Set queryTerms) { + queryTerms.addAll(terms); + } + + /** Prints a user-readable version of this query. */ + public String toString(String f) { + StringBuffer buffer = new StringBuffer(); + if (field != null && !field.equals(f)) { + buffer.append(field); + buffer.append(":"); + } + + buffer.append("\""); + String[] pieces = new String[maxPosition + 1]; + for (int i = 0; i < terms.size(); i++) { + int pos = ((Integer)positions.get(i)).intValue(); + String s = pieces[pos]; + if (s == null) { + s = ((Term)terms.get(i)).text(); + } else { + s = s + "|" + ((Term)terms.get(i)).text(); + } + pieces[pos] = s; + } + for (int i = 0; i < pieces.length; i++) { + if (i > 0) { + buffer.append(' '); + } + String s = pieces[i]; + if (s == null) { + buffer.append('?'); + } else { + buffer.append(s); + } + } + buffer.append("\""); + + if (slop != 0) { + buffer.append("~"); + buffer.append(slop); + } + + buffer.append(ToStringUtils.boost(getBoost())); + + return buffer.toString(); + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (!(o instanceof PhraseQuery)) + return false; + PhraseQuery other = (PhraseQuery)o; + return (this.getBoost() == other.getBoost()) + && (this.slop == other.slop) + && this.terms.equals(other.terms) + && this.positions.equals(other.positions); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + return Float.floatToIntBits(getBoost()) + ^ slop + ^ terms.hashCode() + ^ positions.hashCode(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/PhraseQueue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/PhraseQueue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/PhraseQueue.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,40 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.util.PriorityQueue; + +final class PhraseQueue extends PriorityQueue { + PhraseQueue(int size) { + initialize(size); + } + + protected final boolean lessThan(Object o1, Object o2) { + PhrasePositions pp1 = (PhrasePositions)o1; + PhrasePositions pp2 = (PhrasePositions)o2; + if (pp1.doc == pp2.doc) + if (pp1.position == pp2.position) + // same doc and pp.position, so decide by actual term positions. + // rely on: pp.position == tp.position - offset. + return pp1.offset < pp2.offset; + else + return pp1.position < pp2.position; + else + return pp1.doc < pp2.doc; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/PhraseScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/PhraseScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/PhraseScorer.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,177 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.*; + +/** Expert: Scoring functionality for phrase queries. + *
A document is considered matching if it contains the phrase-query terms + * at "valid" positons. What "valid positions" are + * depends on the type of the phrase query: for an exact phrase query terms are required + * to appear in adjacent locations, while for a sloppy phrase query some distance between + * the terms is allowed. The abstract method {@link #phraseFreq()} of extending classes + * is invoked for each document containing all the phrase query terms, in order to + * compute the frequency of the phrase query in that document. A non zero frequency + * means a match. + */ +abstract class PhraseScorer extends Scorer { + private Weight weight; + protected byte[] norms; + protected float value; + + private boolean firstTime = true; + private boolean more = true; + protected PhraseQueue pq; + protected PhrasePositions first, last; + + private float freq; //prhase frequency in current doc as computed by phraseFreq(). + + + PhraseScorer(Weight weight, TermPositions[] tps, int[] offsets, Similarity similarity, + byte[] norms) { + super(similarity); + this.norms = norms; + this.weight = weight; + this.value = weight.getValue(); + + // convert tps to a list of phrase positions. + // note: phrase-position differs from term-position in that its position + // reflects the phrase offset: pp.pos = tp.pos - offset. + // this allows to easily identify a matching (exact) phrase + // when all PhrasePositions have exactly the same position. + for (int i = 0; i < tps.length; i++) { + PhrasePositions pp = new PhrasePositions(tps[i], offsets[i]); + if (last != null) { // add next to end of list + last.next = pp; + } else + first = pp; + last = pp; + } + + pq = new PhraseQueue(tps.length); // construct empty pq + + } + + public int doc() { return first.doc; } + + public boolean next() throws IOException { + if (firstTime) { + init(); + firstTime = false; + } else if (more) { + more = last.next(); // trigger further scanning + } + return doNext(); + } + + // next without initial increment + private boolean doNext() throws IOException { + while (more) { + while (more && first.doc < last.doc) { // find doc w/ all the terms + more = first.skipTo(last.doc); // skip first upto last + firstToLast(); // and move it to the end + } + + if (more) { + // found a doc with all of the terms + freq = phraseFreq(); // check for phrase + if (freq == 0.0f) // no match + more = last.next(); // trigger further scanning + else + return true; // found a match + } + } + return false; // no more matches + } + + public float score() throws IOException { + //System.out.println("scoring " + first.doc); + float raw = getSimilarity().tf(freq) * value; // raw score + return raw * Similarity.decodeNorm(norms[first.doc]); // normalize + } + + public boolean skipTo(int target) throws IOException { + firstTime = false; + for (PhrasePositions pp = first; more && pp != null; pp = pp.next) { + more = pp.skipTo(target); + } + if (more) + sort(); // re-sort + return doNext(); + } + + /** + * For a document containing all the phrase query terms, compute the + * frequency of the phrase in that document. + * A non zero frequency means a match. + *
Note, that containing all phrase terms does not guarantee a match - they have to be found in matching locations. + * @return frequency of the phrase in current doc, 0 if not found. + */ + protected abstract float phraseFreq() throws IOException; + + private void init() throws IOException { + for (PhrasePositions pp = first; more && pp != null; pp = pp.next) + more = pp.next(); + if(more) + sort(); + } + + private void sort() { + pq.clear(); + for (PhrasePositions pp = first; pp != null; pp = pp.next) + pq.put(pp); + pqToList(); + } + + protected final void pqToList() { + last = first = null; + while (pq.top() != null) { + PhrasePositions pp = (PhrasePositions) pq.pop(); + if (last != null) { // add next to end of list + last.next = pp; + } else + first = pp; + last = pp; + pp.next = null; + } + } + + protected final void firstToLast() { + last.next = first; // move first to end of list + last = first; + first = first.next; + last.next = null; + } + + public Explanation explain(final int doc) throws IOException { + Explanation tfExplanation = new Explanation(); + + while (next() && doc() < doc) {} + + float phraseFreq = (doc() == doc) ? freq : 0.0f; + tfExplanation.setValue(getSimilarity().tf(phraseFreq)); + tfExplanation.setDescription("tf(phraseFreq=" + phraseFreq + ")"); + + return tfExplanation; + } + + public String toString() { return "scorer(" + weight + ")"; } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/PrefixFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/PrefixFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/PrefixFilter.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,122 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.search.Filter; +import org.apache.lucene.util.OpenBitSet; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.TermEnum; +import org.apache.lucene.index.TermDocs; + +import java.util.BitSet; +import java.io.IOException; + +/** + * + * @version $Id: PrefixFilter.java,v 1.1 2012/08/17 14:54:55 marcin Exp $ + */ +public class PrefixFilter extends Filter { + protected final Term prefix; + + public PrefixFilter(Term prefix) { + this.prefix = prefix; + } + + public Term getPrefix() { return prefix; } + + /** + * @deprecated Use {@link #getDocIdSet(IndexReader)} instead. + */ + public BitSet bits(IndexReader reader) throws IOException { + final BitSet bitSet = new BitSet(reader.maxDoc()); + new PrefixGenerator(prefix) { + public void handleDoc(int doc) { + bitSet.set(doc); + } + }.generate(reader); + return bitSet; + } + + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + final OpenBitSet bitSet = new OpenBitSet(reader.maxDoc()); + new PrefixGenerator(prefix) { + public void handleDoc(int doc) { + bitSet.set(doc); + } + }.generate(reader); + return bitSet; + } + + /** Prints a user-readable version of this query. */ + public String toString () { + StringBuffer buffer = new StringBuffer(); + buffer.append("PrefixFilter("); + buffer.append(prefix.toString()); + buffer.append(")"); + return buffer.toString(); + } +} + +// keep this protected until I decide if it's a good way +// to separate id generation from collection (or should +// I just reuse hitcollector???) +interface IdGenerator { + public void generate(IndexReader reader) throws IOException; + public void handleDoc(int doc); +} + + +abstract class PrefixGenerator implements IdGenerator { + protected final Term prefix; + + PrefixGenerator(Term prefix) { + this.prefix = prefix; + } + + public void generate(IndexReader reader) throws IOException { + TermEnum enumerator = reader.terms(prefix); + TermDocs termDocs = reader.termDocs(); + + try { + + String prefixText = prefix.text(); + String prefixField = prefix.field(); + do { + Term term = enumerator.term(); + if (term != null && + term.text().startsWith(prefixText) && + term.field() == prefixField) // interned comparison + { + termDocs.seek(term); + while (termDocs.next()) { + handleDoc(termDocs.doc()); + } + } else { + break; + } + } while (enumerator.next()); + } finally { + termDocs.close(); + enumerator.close(); + } + } +} + + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/PrefixQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/PrefixQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/PrefixQuery.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,92 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermEnum; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.ToStringUtils; + +/** A Query that matches documents containing terms with a specified prefix. A PrefixQuery + * is built by QueryParser for input like app*. */ +public class PrefixQuery extends Query { + private Term prefix; + + /** Constructs a query for terms starting with prefix. */ + public PrefixQuery(Term prefix) { + this.prefix = prefix; + } + + /** Returns the prefix of this query. */ + public Term getPrefix() { return prefix; } + + public Query rewrite(IndexReader reader) throws IOException { + BooleanQuery query = new BooleanQuery(true); + TermEnum enumerator = reader.terms(prefix); + try { + String prefixText = prefix.text(); + String prefixField = prefix.field(); + do { + Term term = enumerator.term(); + if (term != null && + term.text().startsWith(prefixText) && + term.field() == prefixField) // interned comparison + { + TermQuery tq = new TermQuery(term); // found a match + tq.setBoost(getBoost()); // set the boost + query.add(tq, BooleanClause.Occur.SHOULD); // add to query + //System.out.println("added " + term); + } else { + break; + } + } while (enumerator.next()); + } finally { + enumerator.close(); + } + return query; + } + + /** Prints a user-readable version of this query. */ + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + if (!prefix.field().equals(field)) { + buffer.append(prefix.field()); + buffer.append(":"); + } + buffer.append(prefix.text()); + buffer.append('*'); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (!(o instanceof PrefixQuery)) + return false; + PrefixQuery other = (PrefixQuery)o; + return (this.getBoost() == other.getBoost()) + && this.prefix.equals(other.prefix); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + return Float.floatToIntBits(getBoost()) ^ prefix.hashCode() ^ 0x6634D93C; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Query.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Query.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Query.java 17 Aug 2012 14:54:57 -0000 1.1 @@ -0,0 +1,207 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.apache.lucene.index.IndexReader; + +/** The abstract base class for queries. +

Instantiable subclasses are: +

    +
  • {@link TermQuery} +
  • {@link MultiTermQuery} +
  • {@link BooleanQuery} +
  • {@link WildcardQuery} +
  • {@link PhraseQuery} +
  • {@link PrefixQuery} +
  • {@link MultiPhraseQuery} +
  • {@link FuzzyQuery} +
  • {@link RangeQuery} +
  • {@link org.apache.lucene.search.spans.SpanQuery} +
+

A parser for queries is contained in: +

    +
  • {@link org.apache.lucene.queryParser.QueryParser QueryParser} +
+*/ +public abstract class Query implements java.io.Serializable, Cloneable { + private float boost = 1.0f; // query boost factor + + /** Sets the boost for this query clause to b. Documents + * matching this clause will (in addition to the normal weightings) have + * their score multiplied by b. + */ + public void setBoost(float b) { boost = b; } + + /** Gets the boost for this clause. Documents matching + * this clause will (in addition to the normal weightings) have their score + * multiplied by b. The boost is 1.0 by default. + */ + public float getBoost() { return boost; } + + /** Prints a query to a string, with field assumed to be the + * default field and omitted. + *

The representation used is one that is supposed to be readable + * by {@link org.apache.lucene.queryParser.QueryParser QueryParser}. However, + * there are the following limitations: + *

    + *
  • If the query was created by the parser, the printed + * representation may not be exactly what was parsed. For example, + * characters that need to be escaped will be represented without + * the required backslash.
  • + *
  • Some of the more complicated queries (e.g. span queries) + * don't have a representation that can be parsed by QueryParser.
  • + *
+ */ + public abstract String toString(String field); + + /** Prints a query to a string. */ + public String toString() { + return toString(""); + } + + /** Expert: Constructs an appropriate Weight implementation for this query. + * + *

Only implemented by primitive queries, which re-write to themselves. + */ + protected Weight createWeight(Searcher searcher) throws IOException { + throw new UnsupportedOperationException(); + } + + /** Expert: Constructs and initializes a Weight for a top-level query. */ + public Weight weight(Searcher searcher) + throws IOException { + Query query = searcher.rewrite(this); + Weight weight = query.createWeight(searcher); + float sum = weight.sumOfSquaredWeights(); + float norm = getSimilarity(searcher).queryNorm(sum); + weight.normalize(norm); + return weight; + } + + /** Expert: called to re-write queries into primitive queries. For example, + * a PrefixQuery will be rewritten into a BooleanQuery that consists + * of TermQuerys. + */ + public Query rewrite(IndexReader reader) throws IOException { + return this; + } + + /** Expert: called when re-writing queries under MultiSearcher. + * + * Create a single query suitable for use by all subsearchers (in 1-1 + * correspondence with queries). This is an optimization of the OR of + * all queries. We handle the common optimization cases of equal + * queries and overlapping clauses of boolean OR queries (as generated + * by MultiTermQuery.rewrite() and RangeQuery.rewrite()). + * Be careful overriding this method as queries[0] determines which + * method will be called and is not necessarily of the same type as + * the other queries. + */ + public Query combine(Query[] queries) { + HashSet uniques = new HashSet(); + for (int i = 0; i < queries.length; i++) { + Query query = queries[i]; + BooleanClause[] clauses = null; + // check if we can split the query into clauses + boolean splittable = (query instanceof BooleanQuery); + if(splittable){ + BooleanQuery bq = (BooleanQuery) query; + splittable = bq.isCoordDisabled(); + clauses = bq.getClauses(); + for (int j = 0; splittable && j < clauses.length; j++) { + splittable = (clauses[j].getOccur() == BooleanClause.Occur.SHOULD); + } + } + if(splittable){ + for (int j = 0; j < clauses.length; j++) { + uniques.add(clauses[j].getQuery()); + } + } else { + uniques.add(query); + } + } + // optimization: if we have just one query, just return it + if(uniques.size() == 1){ + return (Query)uniques.iterator().next(); + } + Iterator it = uniques.iterator(); + BooleanQuery result = new BooleanQuery(true); + while (it.hasNext()) + result.add((Query) it.next(), BooleanClause.Occur.SHOULD); + return result; + } + + /** + * Expert: adds all terms occuring in this query to the terms set. Only + * works if this query is in its {@link #rewrite rewritten} form. + * + * @throws UnsupportedOperationException if this query is not yet rewritten + */ + public void extractTerms(Set terms) { + // needs to be implemented by query subclasses + throw new UnsupportedOperationException(); + } + + + /** Expert: merges the clauses of a set of BooleanQuery's into a single + * BooleanQuery. + * + *

A utility for use by {@link #combine(Query[])} implementations. + */ + public static Query mergeBooleanQueries(Query[] queries) { + HashSet allClauses = new HashSet(); + for (int i = 0; i < queries.length; i++) { + BooleanClause[] clauses = ((BooleanQuery)queries[i]).getClauses(); + for (int j = 0; j < clauses.length; j++) { + allClauses.add(clauses[j]); + } + } + + boolean coordDisabled = + queries.length==0? false : ((BooleanQuery)queries[0]).isCoordDisabled(); + BooleanQuery result = new BooleanQuery(coordDisabled); + Iterator i = allClauses.iterator(); + while (i.hasNext()) { + result.add((BooleanClause)i.next()); + } + return result; + } + + /** Expert: Returns the Similarity implementation to be used for this query. + * Subclasses may override this method to specify their own Similarity + * implementation, perhaps one that delegates through that of the Searcher. + * By default the Searcher's Similarity implementation is returned.*/ + public Similarity getSimilarity(Searcher searcher) { + return searcher.getSimilarity(); + } + + /** Returns a clone of this query. */ + public Object clone() { + try { + return (Query)super.clone(); + } catch (CloneNotSupportedException e) { + throw new RuntimeException("Clone not supported: " + e.getMessage()); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/QueryFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/QueryFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/QueryFilter.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,44 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** Constrains search results to only match those which also match a provided + * query. Results are cached, so that searches after the first on the same + * index using this filter are much faster. + * + * @version $Id: QueryFilter.java,v 1.1 2012/08/17 14:54:56 marcin Exp $ + * @deprecated use a CachingWrapperFilter with QueryWrapperFilter + */ +public class QueryFilter extends CachingWrapperFilter { + + /** Constructs a filter which only matches documents matching + * query. + */ + public QueryFilter(Query query) { + super(new QueryWrapperFilter(query)); + } + + public boolean equals(Object o) { + return super.equals((QueryFilter)o); + } + + public int hashCode() { + return super.hashCode() ^ 0x923F64B9; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/QueryTermVector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/QueryTermVector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/QueryTermVector.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,142 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.Token; +import org.apache.lucene.analysis.TokenStream; +import org.apache.lucene.index.TermFreqVector; + +/** + * + * + **/ +public class QueryTermVector implements TermFreqVector { + private String [] terms = new String[0]; + private int [] termFreqs = new int[0]; + + public String getField() { return null; } + + /** + * + * @param queryTerms The original list of terms from the query, can contain duplicates + */ + public QueryTermVector(String [] queryTerms) { + + processTerms(queryTerms); + } + + public QueryTermVector(String queryString, Analyzer analyzer) { + if (analyzer != null) + { + TokenStream stream = analyzer.tokenStream("", new StringReader(queryString)); + if (stream != null) + { + List terms = new ArrayList(); + try { + final Token reusableToken = new Token(); + for (Token nextToken = stream.next(reusableToken); nextToken != null; nextToken = stream.next(reusableToken)) { + terms.add(nextToken.term()); + } + processTerms((String[])terms.toArray(new String[terms.size()])); + } catch (IOException e) { + } + } + } + } + + private void processTerms(String[] queryTerms) { + if (queryTerms != null) { + Arrays.sort(queryTerms); + Map tmpSet = new HashMap(queryTerms.length); + //filter out duplicates + List tmpList = new ArrayList(queryTerms.length); + List tmpFreqs = new ArrayList(queryTerms.length); + int j = 0; + for (int i = 0; i < queryTerms.length; i++) { + String term = queryTerms[i]; + Integer position = (Integer)tmpSet.get(term); + if (position == null) { + tmpSet.put(term, new Integer(j++)); + tmpList.add(term); + tmpFreqs.add(new Integer(1)); + } + else { + Integer integer = (Integer)tmpFreqs.get(position.intValue()); + tmpFreqs.set(position.intValue(), new Integer(integer.intValue() + 1)); + } + } + terms = (String[])tmpList.toArray(terms); + //termFreqs = (int[])tmpFreqs.toArray(termFreqs); + termFreqs = new int[tmpFreqs.size()]; + int i = 0; + for (Iterator iter = tmpFreqs.iterator(); iter.hasNext();) { + Integer integer = (Integer) iter.next(); + termFreqs[i++] = integer.intValue(); + } + } + } + + public final String toString() { + StringBuffer sb = new StringBuffer(); + sb.append('{'); + for (int i=0; i0) sb.append(", "); + sb.append(terms[i]).append('/').append(termFreqs[i]); + } + sb.append('}'); + return sb.toString(); + } + + + public int size() { + return terms.length; + } + + public String[] getTerms() { + return terms; + } + + public int[] getTermFrequencies() { + return termFreqs; + } + + public int indexOf(String term) { + int res = Arrays.binarySearch(terms, term); + return res >= 0 ? res : -1; + } + + public int[] indexesOf(String[] terms, int start, int len) { + int res[] = new int[len]; + + for (int i=0; i < len; i++) { + res[i] = indexOf(terms[i]); + } + return res; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/QueryWrapperFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/QueryWrapperFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/QueryWrapperFilter.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,86 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.BitSet; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.OpenBitSet; + +/** + * Constrains search results to only match those which also match a provided + * query. + * + *

This could be used, for example, with a {@link RangeQuery} on a suitably + * formatted date field to implement date filtering. One could re-use a single + * QueryFilter that matches, e.g., only documents modified within the last + * week. The QueryFilter and RangeQuery would only need to be reconstructed + * once per day. + * + * @version $Id: QueryWrapperFilter.java,v 1.1 2012/08/17 14:54:55 marcin Exp $ + */ +public class QueryWrapperFilter extends Filter { + private Query query; + + /** Constructs a filter which only matches documents matching + * query. + */ + public QueryWrapperFilter(Query query) { + this.query = query; + } + + /** + * @deprecated Use {@link #getDocIdSet(IndexReader)} instead. + */ + public BitSet bits(IndexReader reader) throws IOException { + final BitSet bits = new BitSet(reader.maxDoc()); + + new IndexSearcher(reader).search(query, new HitCollector() { + public final void collect(int doc, float score) { + bits.set(doc); // set bit for hit + } + }); + return bits; + } + + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + final OpenBitSet bits = new OpenBitSet(reader.maxDoc()); + + new IndexSearcher(reader).search(query, new HitCollector() { + public final void collect(int doc, float score) { + bits.set(doc); // set bit for hit + } + }); + return bits; + } + + public String toString() { + return "QueryWrapperFilter(" + query + ")"; + } + + public boolean equals(Object o) { + if (!(o instanceof QueryWrapperFilter)) + return false; + return this.query.equals(((QueryWrapperFilter)o).query); + } + + public int hashCode() { + return query.hashCode() ^ 0x923F64B9; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/RangeFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/RangeFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/RangeFilter.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,332 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermDocs; +import org.apache.lucene.index.TermEnum; +import org.apache.lucene.util.OpenBitSet; + +import java.io.IOException; +import java.util.BitSet; +import java.text.Collator; + +/** + * A Filter that restricts search results to a range of values in a given + * field. + * + *

+ * This code borrows heavily from {@link RangeQuery}, but is implemented as a Filter + * + *

+ */ +public class RangeFilter extends Filter { + + private String fieldName; + private String lowerTerm; + private String upperTerm; + private boolean includeLower; + private boolean includeUpper; + private Collator collator; + + /** + * @param fieldName The field this range applies to + * @param lowerTerm The lower bound on this range + * @param upperTerm The upper bound on this range + * @param includeLower Does this range include the lower bound? + * @param includeUpper Does this range include the upper bound? + * @throws IllegalArgumentException if both terms are null or if + * lowerTerm is null and includeLower is true (similar for upperTerm + * and includeUpper) + */ + public RangeFilter(String fieldName, String lowerTerm, String upperTerm, + boolean includeLower, boolean includeUpper) { + this.fieldName = fieldName; + this.lowerTerm = lowerTerm; + this.upperTerm = upperTerm; + this.includeLower = includeLower; + this.includeUpper = includeUpper; + + if (null == lowerTerm && null == upperTerm) { + throw new IllegalArgumentException + ("At least one value must be non-null"); + } + if (includeLower && null == lowerTerm) { + throw new IllegalArgumentException + ("The lower bound must be non-null to be inclusive"); + } + if (includeUpper && null == upperTerm) { + throw new IllegalArgumentException + ("The upper bound must be non-null to be inclusive"); + } + } + + /** + * WARNING: Using this constructor and supplying a non-null + * value in the collator parameter will cause every single + * index Term in the Field referenced by lowerTerm and/or upperTerm to be + * examined. Depending on the number of index Terms in this Field, the + * operation could be very slow. + * + * @param lowerTerm The lower bound on this range + * @param upperTerm The upper bound on this range + * @param includeLower Does this range include the lower bound? + * @param includeUpper Does this range include the upper bound? + * @param collator The collator to use when determining range inclusion; set + * to null to use Unicode code point ordering instead of collation. + * @throws IllegalArgumentException if both terms are null or if + * lowerTerm is null and includeLower is true (similar for upperTerm + * and includeUpper) + */ + public RangeFilter(String fieldName, String lowerTerm, String upperTerm, + boolean includeLower, boolean includeUpper, + Collator collator) { + this(fieldName, lowerTerm, upperTerm, includeLower, includeUpper); + this.collator = collator; + } + + /** + * Constructs a filter for field fieldName matching + * less than or equal to upperTerm. + */ + public static RangeFilter Less(String fieldName, String upperTerm) { + return new RangeFilter(fieldName, null, upperTerm, false, true); + } + + /** + * Constructs a filter for field fieldName matching + * greater than or equal to lowerTerm. + */ + public static RangeFilter More(String fieldName, String lowerTerm) { + return new RangeFilter(fieldName, lowerTerm, null, true, false); + } + + /** + * Returns a BitSet with true for documents which should be + * permitted in search results, and false for those that should + * not. + * @deprecated Use {@link #getDocIdSet(IndexReader)} instead. + */ + public BitSet bits(IndexReader reader) throws IOException { + BitSet bits = new BitSet(reader.maxDoc()); + TermEnum enumerator = + (null != lowerTerm && collator == null + ? reader.terms(new Term(fieldName, lowerTerm)) + : reader.terms(new Term(fieldName))); + + try { + + if (enumerator.term() == null) { + return bits; + } + + TermDocs termDocs = reader.termDocs(); + try { + if (collator != null) { + do { + Term term = enumerator.term(); + if (term != null && term.field().equals(fieldName)) { + if ((lowerTerm == null + || (includeLower + ? collator.compare(term.text(), lowerTerm) >= 0 + : collator.compare(term.text(), lowerTerm) > 0)) + && (upperTerm == null + || (includeUpper + ? collator.compare(term.text(), upperTerm) <= 0 + : collator.compare(term.text(), upperTerm) < 0))) { + /* we have a good term, find the docs */ + termDocs.seek(enumerator.term()); + while (termDocs.next()) { + bits.set(termDocs.doc()); + } + } + } + } + while (enumerator.next()); + } else { // collator is null - use Unicode code point ordering + boolean checkLower = false; + if (!includeLower) // make adjustments to set to exclusive + checkLower = true; + + do { + Term term = enumerator.term(); + if (term != null && term.field().equals(fieldName)) { + if (!checkLower || null==lowerTerm || term.text().compareTo(lowerTerm) > 0) { + checkLower = false; + if (upperTerm != null) { + int compare = upperTerm.compareTo(term.text()); + /* if beyond the upper term, or is exclusive and + * this is equal to the upper term, break out */ + if ((compare < 0) || + (!includeUpper && compare==0)) { + break; + } + } + /* we have a good term, find the docs */ + + termDocs.seek(enumerator.term()); + while (termDocs.next()) { + bits.set(termDocs.doc()); + } + } + } else { + break; + } + } + while (enumerator.next()); + } + } finally { + termDocs.close(); + } + } finally { + enumerator.close(); + } + + return bits; + } + + /** + * Returns a DocIdSet with documents that should be + * permitted in search results. + */ + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + OpenBitSet bits = new OpenBitSet(reader.maxDoc()); + + TermEnum enumerator = + (null != lowerTerm && collator == null + ? reader.terms(new Term(fieldName, lowerTerm)) + : reader.terms(new Term(fieldName))); + + try { + + if (enumerator.term() == null) { + return bits; + } + + TermDocs termDocs = reader.termDocs(); + + try { + if (collator != null) { + do { + Term term = enumerator.term(); + if (term != null && term.field().equals(fieldName)) { + if ((lowerTerm == null + || (includeLower + ? collator.compare(term.text(), lowerTerm) >= 0 + : collator.compare(term.text(), lowerTerm) > 0)) + && (upperTerm == null + || (includeUpper + ? collator.compare(term.text(), upperTerm) <= 0 + : collator.compare(term.text(), upperTerm) < 0))) { + /* we have a good term, find the docs */ + termDocs.seek(enumerator.term()); + while (termDocs.next()) { + bits.set(termDocs.doc()); + } + } + } + } + while (enumerator.next()); + } else { // collator is null - use Unicode code point ordering + boolean checkLower = false; + if (!includeLower) // make adjustments to set to exclusive + checkLower = true; + + do { + Term term = enumerator.term(); + if (term != null && term.field().equals(fieldName)) { + if (!checkLower || null==lowerTerm || term.text().compareTo(lowerTerm) > 0) { + checkLower = false; + if (upperTerm != null) { + int compare = upperTerm.compareTo(term.text()); + /* if beyond the upper term, or is exclusive and + * this is equal to the upper term, break out */ + if ((compare < 0) || + (!includeUpper && compare==0)) { + break; + } + } + /* we have a good term, find the docs */ + + termDocs.seek(enumerator.term()); + while (termDocs.next()) { + bits.set(termDocs.doc()); + } + } + } else { + break; + } + } + while (enumerator.next()); + } + + } finally { + termDocs.close(); + } + } finally { + enumerator.close(); + } + + return bits; + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append(fieldName); + buffer.append(":"); + buffer.append(includeLower ? "[" : "{"); + if (null != lowerTerm) { + buffer.append(lowerTerm); + } + buffer.append("-"); + if (null != upperTerm) { + buffer.append(upperTerm); + } + buffer.append(includeUpper ? "]" : "}"); + return buffer.toString(); + } + + /** Returns true if o is equal to this. */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof RangeFilter)) return false; + RangeFilter other = (RangeFilter) o; + + if (!this.fieldName.equals(other.fieldName) + || this.includeLower != other.includeLower + || this.includeUpper != other.includeUpper + || (this.collator != null && ! this.collator.equals(other.collator)) + ) { return false; } + if (this.lowerTerm != null ? !this.lowerTerm.equals(other.lowerTerm) : other.lowerTerm != null) return false; + if (this.upperTerm != null ? !this.upperTerm.equals(other.upperTerm) : other.upperTerm != null) return false; + return true; + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + int h = fieldName.hashCode(); + h ^= lowerTerm != null ? lowerTerm.hashCode() : 0xB6ECE882; + h = (h << 1) | (h >>> 31); // rotate to distinguish lower from upper + h ^= (upperTerm != null ? (upperTerm.hashCode()) : 0x91BEC2C2); + h ^= (includeLower ? 0xD484B933 : 0) + ^ (includeUpper ? 0x6AE423AC : 0); + h ^= collator != null ? collator.hashCode() : 0; + return h; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/RangeQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/RangeQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/RangeQuery.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,254 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.text.Collator; + +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermEnum; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.ToStringUtils; + +/** + * A Query that matches documents within an exclusive range. A RangeQuery + * is built by QueryParser for input like [010 TO 120] but only if the QueryParser has + * the useOldRangeQuery property set to true. The QueryParser default behaviour is to use + * the newer ConstantScoreRangeQuery class. This is generally preferable because: + *
    + *
  • It is faster than RangeQuery
  • + *
  • Unlike RangeQuery, it does not cause a BooleanQuery.TooManyClauses exception if the range of values is large
  • + *
  • Unlike RangeQuery it does not influence scoring based on the scarcity of individual terms that may match
  • + *
+ * + * + * @see ConstantScoreRangeQuery + * + * + * @version $Id: RangeQuery.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +public class RangeQuery extends Query +{ + private Term lowerTerm; + private Term upperTerm; + private boolean inclusive; + private Collator collator; + + /** Constructs a query selecting all terms greater than + * lowerTerm but less than upperTerm. + * There must be at least one term and either term may be null, + * in which case there is no bound on that side, but if there are + * two terms, both terms must be for the same field. + * + * @param lowerTerm The Term at the lower end of the range + * @param upperTerm The Term at the upper end of the range + * @param inclusive If true, both lowerTerm and + * upperTerm will themselves be included in the range. + */ + public RangeQuery(Term lowerTerm, Term upperTerm, boolean inclusive) + { + if (lowerTerm == null && upperTerm == null) + { + throw new IllegalArgumentException("At least one term must be non-null"); + } + if (lowerTerm != null && upperTerm != null && lowerTerm.field() != upperTerm.field()) + { + throw new IllegalArgumentException("Both terms must be for the same field"); + } + + // if we have a lowerTerm, start there. otherwise, start at beginning + if (lowerTerm != null) { + this.lowerTerm = lowerTerm; + } + else { + this.lowerTerm = new Term(upperTerm.field()); + } + + this.upperTerm = upperTerm; + this.inclusive = inclusive; + } + + /** Constructs a query selecting all terms greater than + * lowerTerm but less than upperTerm. + * There must be at least one term and either term may be null, + * in which case there is no bound on that side, but if there are + * two terms, both terms must be for the same field. + *

+ * If collator is not null, it will be used to decide whether + * index terms are within the given range, rather than using the Unicode code + * point order in which index terms are stored. + *

+ * WARNING: Using this constructor and supplying a non-null + * value in the collator parameter will cause every single + * index Term in the Field referenced by lowerTerm and/or upperTerm to be + * examined. Depending on the number of index Terms in this Field, the + * operation could be very slow. + * + * @param lowerTerm The Term at the lower end of the range + * @param upperTerm The Term at the upper end of the range + * @param inclusive If true, both lowerTerm and + * upperTerm will themselves be included in the range. + * @param collator The collator to use to collate index Terms, to determine + * their membership in the range bounded by lowerTerm and + * upperTerm. + */ + public RangeQuery(Term lowerTerm, Term upperTerm, boolean inclusive, + Collator collator) + { + this(lowerTerm, upperTerm, inclusive); + this.collator = collator; + } + + public Query rewrite(IndexReader reader) throws IOException { + + BooleanQuery query = new BooleanQuery(true); + String testField = getField(); + if (collator != null) { + TermEnum enumerator = reader.terms(new Term(testField, "")); + String lowerTermText = lowerTerm != null ? lowerTerm.text() : null; + String upperTermText = upperTerm != null ? upperTerm.text() : null; + + try { + do { + Term term = enumerator.term(); + if (term != null && term.field() == testField) { // interned comparison + if ((lowerTermText == null + || (inclusive ? collator.compare(term.text(), lowerTermText) >= 0 + : collator.compare(term.text(), lowerTermText) > 0)) + && (upperTermText == null + || (inclusive ? collator.compare(term.text(), upperTermText) <= 0 + : collator.compare(term.text(), upperTermText) < 0))) { + addTermToQuery(term, query); + } + } + } + while (enumerator.next()); + } + finally { + enumerator.close(); + } + } + else { // collator is null + TermEnum enumerator = reader.terms(lowerTerm); + + try { + + boolean checkLower = false; + if (!inclusive) // make adjustments to set to exclusive + checkLower = true; + + do { + Term term = enumerator.term(); + if (term != null && term.field() == testField) { // interned comparison + if (!checkLower || term.text().compareTo(lowerTerm.text()) > 0) { + checkLower = false; + if (upperTerm != null) { + int compare = upperTerm.text().compareTo(term.text()); + /* if beyond the upper term, or is exclusive and + * this is equal to the upper term, break out */ + if ((compare < 0) || (!inclusive && compare == 0)) + break; + } + addTermToQuery(term, query); // Found a match + } + } + else { + break; + } + } + while (enumerator.next()); + } + finally { + enumerator.close(); + } + } + return query; + } + + private void addTermToQuery(Term term, BooleanQuery query) { + TermQuery tq = new TermQuery(term); + tq.setBoost(getBoost()); // set the boost + query.add(tq, BooleanClause.Occur.SHOULD); // add to query + } + + /** Returns the field name for this query */ + public String getField() { + return (lowerTerm != null ? lowerTerm.field() : upperTerm.field()); + } + + /** Returns the lower term of this range query */ + public Term getLowerTerm() { return lowerTerm; } + + /** Returns the upper term of this range query */ + public Term getUpperTerm() { return upperTerm; } + + /** Returns true if the range query is inclusive */ + public boolean isInclusive() { return inclusive; } + + /** Returns the collator used to determine range inclusion, if any. */ + public Collator getCollator() { return collator; } + + + /** Prints a user-readable version of this query. */ + public String toString(String field) + { + StringBuffer buffer = new StringBuffer(); + if (!getField().equals(field)) + { + buffer.append(getField()); + buffer.append(":"); + } + buffer.append(inclusive ? "[" : "{"); + buffer.append(lowerTerm != null ? lowerTerm.text() : "null"); + buffer.append(" TO "); + buffer.append(upperTerm != null ? upperTerm.text() : "null"); + buffer.append(inclusive ? "]" : "}"); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof RangeQuery)) return false; + + final RangeQuery other = (RangeQuery) o; + if (this.getBoost() != other.getBoost()) return false; + if (this.inclusive != other.inclusive) return false; + if (this.collator != null && ! this.collator.equals(other.collator)) + return false; + + // one of lowerTerm and upperTerm can be null + if (this.lowerTerm != null ? !this.lowerTerm.equals(other.lowerTerm) : other.lowerTerm != null) return false; + if (this.upperTerm != null ? !this.upperTerm.equals(other.upperTerm) : other.upperTerm != null) return false; + return true; + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + int h = Float.floatToIntBits(getBoost()); + h ^= lowerTerm != null ? lowerTerm.hashCode() : 0; + // reversible mix to make lower and upper position dependent and + // to prevent them from cancelling out. + h ^= (h << 25) | (h >>> 8); + h ^= upperTerm != null ? upperTerm.hashCode() : 0; + h ^= this.inclusive ? 0x2742E74A : 0; + h ^= collator != null ? collator.hashCode() : 0; + return h; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/RemoteCachingWrapperFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/RemoteCachingWrapperFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/RemoteCachingWrapperFilter.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,69 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.BitSet; + +import org.apache.lucene.index.IndexReader; + +/** + * Provides caching of {@link Filter}s themselves on the remote end of an RMI connection. + * The cache is keyed on Filter's hashCode(), so if it sees the same filter twice + * it will reuse the original version. + *

+ * NOTE: This does NOT cache the Filter bits, but rather the Filter itself. + * Thus, this works hand-in-hand with {@link CachingWrapperFilter} to keep both + * file Filter cache and the Filter bits on the remote end, close to the searcher. + *

+ * Usage: + *

+ * To cache a result you must do something like + * RemoteCachingWrapperFilter f = new RemoteCachingWrapperFilter(new CachingWrapperFilter(myFilter)); + *

+ */ +public class RemoteCachingWrapperFilter extends Filter { + protected Filter filter; + + public RemoteCachingWrapperFilter(Filter filter) { + this.filter = filter; + } + + /** + * Uses the {@link FilterManager} to keep the cache for a filter on the + * searcher side of a remote connection. + * @param reader the index reader for the Filter + * @return the bitset + * @deprecated Use {@link #getDocIdSet(IndexReader)} instead. + */ + public BitSet bits(IndexReader reader) throws IOException { + Filter cachedFilter = FilterManager.getInstance().getFilter(filter); + return cachedFilter.bits(reader); + } + + /** + * Uses the {@link FilterManager} to keep the cache for a filter on the + * searcher side of a remote connection. + * @param reader the index reader for the Filter + * @return the DocIdSet + */ + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + Filter cachedFilter = FilterManager.getInstance().getFilter(filter); + return cachedFilter.getDocIdSet(reader); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/RemoteSearchable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/RemoteSearchable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/RemoteSearchable.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,122 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.CorruptIndexException; + +import java.io.IOException; +import java.rmi.Naming; +import java.rmi.RMISecurityManager; +import java.rmi.RemoteException; +import java.rmi.server.UnicastRemoteObject; + +/** + * A remote searchable implementation. + * + * @version $Id: RemoteSearchable.java,v 1.1 2012/08/17 14:54:56 marcin Exp $ + */ +public class RemoteSearchable + extends UnicastRemoteObject + implements Searchable { + + private Searchable local; + + /** Constructs and exports a remote searcher. */ + public RemoteSearchable(Searchable local) throws RemoteException { + super(); + this.local = local; + } + + + public void search(Weight weight, Filter filter, HitCollector results) + throws IOException { + local.search(weight, filter, results); + } + + public void close() throws IOException { + local.close(); + } + + public int docFreq(Term term) throws IOException { + return local.docFreq(term); + } + + + public int[] docFreqs(Term[] terms) throws IOException { + return local.docFreqs(terms); + } + + public int maxDoc() throws IOException { + return local.maxDoc(); + } + + public TopDocs search(Weight weight, Filter filter, int n) throws IOException { + return local.search(weight, filter, n); + } + + + public TopFieldDocs search (Weight weight, Filter filter, int n, Sort sort) + throws IOException { + return local.search (weight, filter, n, sort); + } + + public Document doc(int i) throws CorruptIndexException, IOException { + return local.doc(i); + } + + public Document doc(int i, FieldSelector fieldSelector) throws CorruptIndexException, IOException { + return local.doc(i, fieldSelector); + } + + public Query rewrite(Query original) throws IOException { + return local.rewrite(original); + } + + public Explanation explain(Weight weight, int doc) throws IOException { + return local.explain(weight, doc); + } + + /** Exports a searcher for the index in args[0] named + * "//localhost/Searchable". */ + public static void main(String args[]) throws Exception { + String indexName = null; + + if (args != null && args.length == 1) + indexName = args[0]; + + if (indexName == null) { + System.out.println("Usage: org.apache.lucene.search.RemoteSearchable "); + return; + } + + // create and install a security manager + if (System.getSecurityManager() == null) { + System.setSecurityManager(new RMISecurityManager()); + } + + Searchable local = new IndexSearcher(indexName); + RemoteSearchable impl = new RemoteSearchable(local); + + // bind the implementation to "Searchable" + Naming.rebind("//localhost/Searchable", impl); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ReqExclScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ReqExclScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ReqExclScorer.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,145 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + + +/** A Scorer for queries with a required subscorer and an excluding (prohibited) subscorer. + *
+ * This Scorer implements {@link Scorer#skipTo(int)}, + * and it uses the skipTo() on the given scorers. + */ +public class ReqExclScorer extends Scorer { + private Scorer reqScorer, exclScorer; + + /** Construct a ReqExclScorer. + * @param reqScorer The scorer that must match, except where + * @param exclScorer indicates exclusion. + */ + public ReqExclScorer( + Scorer reqScorer, + Scorer exclScorer) { + super(null); // No similarity used. + this.reqScorer = reqScorer; + this.exclScorer = exclScorer; + } + + private boolean firstTime = true; + + public boolean next() throws IOException { + if (firstTime) { + if (! exclScorer.next()) { + exclScorer = null; // exhausted at start + } + firstTime = false; + } + if (reqScorer == null) { + return false; + } + if (! reqScorer.next()) { + reqScorer = null; // exhausted, nothing left + return false; + } + if (exclScorer == null) { + return true; // reqScorer.next() already returned true + } + return toNonExcluded(); + } + + /** Advance to non excluded doc. + *
On entry: + *

    + *
  • reqScorer != null, + *
  • exclScorer != null, + *
  • reqScorer was advanced once via next() or skipTo() + * and reqScorer.doc() may still be excluded. + *
+ * Advances reqScorer a non excluded required doc, if any. + * @return true iff there is a non excluded required doc. + */ + private boolean toNonExcluded() throws IOException { + int exclDoc = exclScorer.doc(); + do { + int reqDoc = reqScorer.doc(); // may be excluded + if (reqDoc < exclDoc) { + return true; // reqScorer advanced to before exclScorer, ie. not excluded + } else if (reqDoc > exclDoc) { + if (! exclScorer.skipTo(reqDoc)) { + exclScorer = null; // exhausted, no more exclusions + return true; + } + exclDoc = exclScorer.doc(); + if (exclDoc > reqDoc) { + return true; // not excluded + } + } + } while (reqScorer.next()); + reqScorer = null; // exhausted, nothing left + return false; + } + + public int doc() { + return reqScorer.doc(); // reqScorer may be null when next() or skipTo() already return false + } + + /** Returns the score of the current document matching the query. + * Initially invalid, until {@link #next()} is called the first time. + * @return The score of the required scorer. + */ + public float score() throws IOException { + return reqScorer.score(); // reqScorer may be null when next() or skipTo() already return false + } + + /** Skips to the first match beyond the current whose document number is + * greater than or equal to a given target. + *
When this method is used the {@link #explain(int)} method should not be used. + * @param target The target document number. + * @return true iff there is such a match. + */ + public boolean skipTo(int target) throws IOException { + if (firstTime) { + firstTime = false; + if (! exclScorer.skipTo(target)) { + exclScorer = null; // exhausted + } + } + if (reqScorer == null) { + return false; + } + if (exclScorer == null) { + return reqScorer.skipTo(target); + } + if (! reqScorer.skipTo(target)) { + reqScorer = null; + return false; + } + return toNonExcluded(); + } + + public Explanation explain(int doc) throws IOException { + Explanation res = new Explanation(); + if (exclScorer.skipTo(doc) && (exclScorer.doc() == doc)) { + res.setDescription("excluded"); + } else { + res.setDescription("not excluded"); + res.addDetail(reqScorer.explain(doc)); + } + return res; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ReqOptSumScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ReqOptSumScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ReqOptSumScorer.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,98 @@ +package org.apache.lucene.search; +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** A Scorer for queries with a required part and an optional part. + * Delays skipTo() on the optional part until a score() is needed. + *
+ * This Scorer implements {@link Scorer#skipTo(int)}. + */ +public class ReqOptSumScorer extends Scorer { + /** The scorers passed from the constructor. + * These are set to null as soon as their next() or skipTo() returns false. + */ + private Scorer reqScorer; + private Scorer optScorer; + + /** Construct a ReqOptScorer. + * @param reqScorer The required scorer. This must match. + * @param optScorer The optional scorer. This is used for scoring only. + */ + public ReqOptSumScorer( + Scorer reqScorer, + Scorer optScorer) + { + super(null); // No similarity used. + this.reqScorer = reqScorer; + this.optScorer = optScorer; + } + + private boolean firstTimeOptScorer = true; + + public boolean next() throws IOException { + return reqScorer.next(); + } + + public boolean skipTo(int target) throws IOException { + return reqScorer.skipTo(target); + } + + public int doc() { + return reqScorer.doc(); + } + + /** Returns the score of the current document matching the query. + * Initially invalid, until {@link #next()} is called the first time. + * @return The score of the required scorer, eventually increased by the score + * of the optional scorer when it also matches the current document. + */ + public float score() throws IOException { + int curDoc = reqScorer.doc(); + float reqScore = reqScorer.score(); + if (firstTimeOptScorer) { + firstTimeOptScorer = false; + if (! optScorer.skipTo(curDoc)) { + optScorer = null; + return reqScore; + } + } else if (optScorer == null) { + return reqScore; + } else if ((optScorer.doc() < curDoc) && (! optScorer.skipTo(curDoc))) { + optScorer = null; + return reqScore; + } + // assert (optScorer != null) && (optScorer.doc() >= curDoc); + return (optScorer.doc() == curDoc) + ? reqScore + optScorer.score() + : reqScore; + } + + /** Explain the score of a document. + * @todo Also show the total score. + * See BooleanScorer.explain() on how to do this. + */ + public Explanation explain(int doc) throws IOException { + Explanation res = new Explanation(); + res.setDescription("required, optional"); + res.addDetail(reqScorer.explain(doc)); + res.addDetail(optScorer.explain(doc)); + return res; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/search/ScoreDoc.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ScoreDoc.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ScoreDoc.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,36 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Expert: Returned by low-level search implementations. + * @see TopDocs */ +public class ScoreDoc implements java.io.Serializable { + /** Expert: The score of this document for the query. */ + public float score; + + /** Expert: A hit document's number. + * @see Searcher#doc(int) + */ + public int doc; + + /** Expert: Constructs a ScoreDoc. */ + public ScoreDoc(int doc, float score) { + this.doc = doc; + this.score = score; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/ScoreDocComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/ScoreDocComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/ScoreDocComparator.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,96 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Expert: Compares two ScoreDoc objects for sorting. + * + *

Created: Feb 3, 2004 9:00:16 AM + * + * @since lucene 1.4 + * @version $Id: ScoreDocComparator.java,v 1.1 2012/08/17 14:54:56 marcin Exp $ + */ +public interface ScoreDocComparator { + + /** Special comparator for sorting hits according to computed relevance (document score). */ + static final ScoreDocComparator RELEVANCE = new ScoreDocComparator() { + public int compare (ScoreDoc i, ScoreDoc j) { + if (i.score > j.score) return -1; + if (i.score < j.score) return 1; + return 0; + } + public Comparable sortValue (ScoreDoc i) { + return new Float (i.score); + } + public int sortType() { + return SortField.SCORE; + } + }; + + /** Special comparator for sorting hits according to index order (document number). */ + static final ScoreDocComparator INDEXORDER = new ScoreDocComparator() { + public int compare (ScoreDoc i, ScoreDoc j) { + if (i.doc < j.doc) return -1; + if (i.doc > j.doc) return 1; + return 0; + } + public Comparable sortValue (ScoreDoc i) { + return new Integer (i.doc); + } + public int sortType() { + return SortField.DOC; + } + }; + + /** + * Compares two ScoreDoc objects and returns a result indicating their + * sort order. + * @param i First ScoreDoc + * @param j Second ScoreDoc + * @return a negative integer if i should come before j
+ * a positive integer if i should come after j
+ * 0 if they are equal + * @see java.util.Comparator + */ + int compare (ScoreDoc i, ScoreDoc j); + + /** + * Returns the value used to sort the given document. The + * object returned must implement the java.io.Serializable + * interface. This is used by multisearchers to determine how + * to collate results from their searchers. + * @see FieldDoc + * @param i Document + * @return Serializable object + */ + Comparable sortValue (ScoreDoc i); + + /** + * Returns the type of sort. Should return SortField.SCORE, + * SortField.DOC, SortField.STRING, + * SortField.INTEGER, SortField.FLOAT or + * SortField.CUSTOM. It is not valid to return + * SortField.AUTO. + * This is used by multisearchers to determine how to collate results + * from their searchers. + * @return One of the constants in SortField. + * @see SortField + */ + int sortType(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Scorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Scorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Scorer.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,92 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + * Expert: Common scoring functionality for different types of queries. + * + *

+ * A Scorer either iterates over documents matching a + * query in increasing order of doc Id, or provides an explanation of + * the score for a query for a given document. + *

+ *

+ * Document scores are computed using a given Similarity + * implementation. + *

+ * @see BooleanQuery#setAllowDocsOutOfOrder + */ +public abstract class Scorer extends DocIdSetIterator { + private Similarity similarity; + + /** Constructs a Scorer. + * @param similarity The Similarity implementation used by this scorer. + */ + protected Scorer(Similarity similarity) { + this.similarity = similarity; + } + + /** Returns the Similarity implementation used by this scorer. */ + public Similarity getSimilarity() { + return this.similarity; + } + + /** Scores and collects all matching documents. + * @param hc The collector to which all matching documents are passed through + * {@link HitCollector#collect(int, float)}. + *
When this method is used the {@link #explain(int)} method should not be used. + */ + public void score(HitCollector hc) throws IOException { + while (next()) { + hc.collect(doc(), score()); + } + } + + /** Expert: Collects matching documents in a range. Hook for optimization. + * Note that {@link #next()} must be called once before this method is called + * for the first time. + * @param hc The collector to which all matching documents are passed through + * {@link HitCollector#collect(int, float)}. + * @param max Do not score documents past this. + * @return true if more matching documents may remain. + */ + protected boolean score(HitCollector hc, int max) throws IOException { + while (doc() < max) { + hc.collect(doc(), score()); + if (!next()) + return false; + } + return true; + } + + /** Returns the score of the current document matching the query. + * Initially invalid, until {@link #next()} or {@link #skipTo(int)} + * is called the first time. + */ + public abstract float score() throws IOException; + + /** Returns an explanation of the score for a document. + *
When this method is used, the {@link #next()}, {@link #skipTo(int)} and + * {@link #score(HitCollector)} methods should not be used. + * @param doc The document number for the explanation. + */ + public abstract Explanation explain(int doc) throws IOException; + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Searchable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Searchable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Searchable.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,155 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.document.Document; +import org.apache.lucene.document.FieldSelector; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.CorruptIndexException; + +import java.io.IOException; // for javadoc + +/** The interface for search implementations. + * + *

Searchable is the abstract network protocol for searching. + * Implementations provide search over a single index, over multiple + * indices, and over indices on remote servers. + * + *

Queries, filters and sort criteria are designed to be compact so that + * they may be efficiently passed to a remote index, with only the top-scoring + * hits being returned, rather than every matching hit. + */ +public interface Searchable extends java.rmi.Remote { + /** Lower-level search API. + * + *

{@link HitCollector#collect(int,float)} is called for every non-zero + * scoring document. + *
HitCollector-based access to remote indexes is discouraged. + * + *

Applications should only use this if they need all of the + * matching documents. The high-level search API ({@link + * Searcher#search(Query)}) is usually more efficient, as it skips + * non-high-scoring hits. + * + * @param weight to match documents + * @param filter if non-null, used to permit documents to be collected. + * @param results to receive hits + * @throws BooleanQuery.TooManyClauses + */ + void search(Weight weight, Filter filter, HitCollector results) + throws IOException; + + + /** Frees resources associated with this Searcher. + * Be careful not to call this method while you are still using objects + * like {@link Hits}. + */ + void close() throws IOException; + + /** Expert: Returns the number of documents containing term. + * Called by search code to compute term weights. + * @see IndexReader#docFreq(Term) + */ + int docFreq(Term term) throws IOException; + + /** Expert: For each term in the terms array, calculates the number of + * documents containing term. Returns an array with these + * document frequencies. Used to minimize number of remote calls. + */ + int[] docFreqs(Term[] terms) throws IOException; + + /** Expert: Returns one greater than the largest possible document number. + * Called by search code to compute term weights. + * @see IndexReader#maxDoc() + */ + int maxDoc() throws IOException; + + /** Expert: Low-level search implementation. Finds the top n + * hits for query, applying filter if non-null. + * + *

Called by {@link Hits}. + * + *

Applications should usually call {@link Searcher#search(Query)} or + * {@link Searcher#search(Query,Filter)} instead. + * @throws BooleanQuery.TooManyClauses + */ + TopDocs search(Weight weight, Filter filter, int n) throws IOException; + + /** Expert: Returns the stored fields of document i. + * Called by {@link HitCollector} implementations. + * @see IndexReader#document(int) + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + */ + Document doc(int i) throws CorruptIndexException, IOException; + + /** + * Get the {@link org.apache.lucene.document.Document} at the nth position. The {@link org.apache.lucene.document.FieldSelector} + * may be used to determine what {@link org.apache.lucene.document.Field}s to load and how they should be loaded. + * + * NOTE: If the underlying Reader (more specifically, the underlying FieldsReader) is closed before the lazy {@link org.apache.lucene.document.Field} is + * loaded an exception may be thrown. If you want the value of a lazy {@link org.apache.lucene.document.Field} to be available after closing you must + * explicitly load it or fetch the Document again with a new loader. + * + * + * @param n Get the document at the nth position + * @param fieldSelector The {@link org.apache.lucene.document.FieldSelector} to use to determine what Fields should be loaded on the Document. May be null, in which case all Fields will be loaded. + * @return The stored fields of the {@link org.apache.lucene.document.Document} at the nth position + * @throws CorruptIndexException if the index is corrupt + * @throws IOException if there is a low-level IO error + * + * @see IndexReader#document(int, FieldSelector) + * @see org.apache.lucene.document.Fieldable + * @see org.apache.lucene.document.FieldSelector + * @see org.apache.lucene.document.SetBasedFieldSelector + * @see org.apache.lucene.document.LoadFirstFieldSelector + */ + Document doc(int n, FieldSelector fieldSelector) throws CorruptIndexException, IOException; + + /** Expert: called to re-write queries into primitive queries. + * @throws BooleanQuery.TooManyClauses + */ + Query rewrite(Query query) throws IOException; + + /** Expert: low-level implementation method + * Returns an Explanation that describes how doc scored against + * weight. + * + *

This is intended to be used in developing Similarity implementations, + * and, for good performance, should not be displayed with every hit. + * Computing an explanation is as expensive as executing the query over the + * entire index. + *

Applications should call {@link Searcher#explain(Query, int)}. + * @throws BooleanQuery.TooManyClauses + */ + Explanation explain(Weight weight, int doc) throws IOException; + + /** Expert: Low-level search implementation with arbitrary sorting. Finds + * the top n hits for query, applying + * filter if non-null, and sorting the hits by the criteria in + * sort. + * + *

Applications should usually call {@link + * Searcher#search(Query,Filter,Sort)} instead. + * @throws BooleanQuery.TooManyClauses + */ + TopFieldDocs search(Weight weight, Filter filter, int n, Sort sort) + throws IOException; + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Searcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Searcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Searcher.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,210 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.CorruptIndexException; +import org.apache.lucene.index.Term; +import org.apache.lucene.document.Document; + +/** An abstract base class for search implementations. + * Implements the main search methods. + * + *

Note that you can only access Hits from a Searcher as long as it is + * not yet closed, otherwise an IOException will be thrown. + */ +public abstract class Searcher implements Searchable { + + /** Returns the documents matching query. + * @throws BooleanQuery.TooManyClauses + * @deprecated Hits will be removed in Lucene 3.0. Use + * {@link #search(Query, Filter, int)} instead. + */ + public final Hits search(Query query) throws IOException { + return search(query, (Filter)null); + } + + /** Returns the documents matching query and + * filter. + * @throws BooleanQuery.TooManyClauses + * @deprecated Hits will be removed in Lucene 3.0. Use + * {@link #search(Query, Filter, int)} instead. + */ + public Hits search(Query query, Filter filter) throws IOException { + return new Hits(this, query, filter); + } + + /** Returns documents matching query sorted by + * sort. + * @throws BooleanQuery.TooManyClauses + * @deprecated Hits will be removed in Lucene 3.0. Use + * {@link #search(Query, Filter, int, Sort)} instead. + */ + public Hits search(Query query, Sort sort) + throws IOException { + return new Hits(this, query, null, sort); + } + + /** Returns documents matching query and filter, + * sorted by sort. + * @throws BooleanQuery.TooManyClauses + * @deprecated Hits will be removed in Lucene 3.0. Use + * {@link #search(Query, Filter, int, Sort)} instead. + */ + public Hits search(Query query, Filter filter, Sort sort) + throws IOException { + return new Hits(this, query, filter, sort); + } + + /** Search implementation with arbitrary sorting. Finds + * the top n hits for query, applying + * filter if non-null, and sorting the hits by the criteria in + * sort. + * + *

Applications should usually call {@link + * Searcher#search(Query,Filter,Sort)} instead. + * @throws BooleanQuery.TooManyClauses + */ + public TopFieldDocs search(Query query, Filter filter, int n, + Sort sort) throws IOException { + return search(createWeight(query), filter, n, sort); + } + + /** Lower-level search API. + * + *

{@link HitCollector#collect(int,float)} is called for every matching + * document. + * + *

Applications should only use this if they need all of the + * matching documents. The high-level search API ({@link + * Searcher#search(Query)}) is usually more efficient, as it skips + * non-high-scoring hits. + *

Note: The score passed to this method is a raw score. + * In other words, the score will not necessarily be a float whose value is + * between 0 and 1. + * @throws BooleanQuery.TooManyClauses + */ + public void search(Query query, HitCollector results) + throws IOException { + search(query, (Filter)null, results); + } + + /** Lower-level search API. + * + *

{@link HitCollector#collect(int,float)} is called for every matching + * document. + *
HitCollector-based access to remote indexes is discouraged. + * + *

Applications should only use this if they need all of the + * matching documents. The high-level search API ({@link + * Searcher#search(Query, Filter, int)}) is usually more efficient, as it skips + * non-high-scoring hits. + * + * @param query to match documents + * @param filter if non-null, used to permit documents to be collected. + * @param results to receive hits + * @throws BooleanQuery.TooManyClauses + */ + public void search(Query query, Filter filter, HitCollector results) + throws IOException { + search(createWeight(query), filter, results); + } + + /** Finds the top n + * hits for query, applying filter if non-null. + * + * @throws BooleanQuery.TooManyClauses + */ + public TopDocs search(Query query, Filter filter, int n) + throws IOException { + return search(createWeight(query), filter, n); + } + + /** Finds the top n + * hits for query. + * + * @throws BooleanQuery.TooManyClauses + */ + public TopDocs search(Query query, int n) + throws IOException { + return search(query, null, n); + } + + /** Returns an Explanation that describes how doc scored against + * query. + * + *

This is intended to be used in developing Similarity implementations, + * and, for good performance, should not be displayed with every hit. + * Computing an explanation is as expensive as executing the query over the + * entire index. + */ + public Explanation explain(Query query, int doc) throws IOException { + return explain(createWeight(query), doc); + } + + /** The Similarity implementation used by this searcher. */ + private Similarity similarity = Similarity.getDefault(); + + /** Expert: Set the Similarity implementation used by this Searcher. + * + * @see Similarity#setDefault(Similarity) + */ + public void setSimilarity(Similarity similarity) { + this.similarity = similarity; + } + + /** Expert: Return the Similarity implementation used by this Searcher. + * + *

This defaults to the current value of {@link Similarity#getDefault()}. + */ + public Similarity getSimilarity() { + return this.similarity; + } + + /** + * creates a weight for query + * @return new weight + */ + protected Weight createWeight(Query query) throws IOException { + return query.weight(this); + } + + // inherit javadoc + public int[] docFreqs(Term[] terms) throws IOException { + int[] result = new int[terms.length]; + for (int i = 0; i < terms.length; i++) { + result[i] = docFreq(terms[i]); + } + return result; + } + + /* The following abstract methods were added as a workaround for GCJ bug #15411. + * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=15411 + */ + abstract public void search(Weight weight, Filter filter, HitCollector results) throws IOException; + abstract public void close() throws IOException; + abstract public int docFreq(Term term) throws IOException; + abstract public int maxDoc() throws IOException; + abstract public TopDocs search(Weight weight, Filter filter, int n) throws IOException; + abstract public Document doc(int i) throws CorruptIndexException, IOException; + abstract public Query rewrite(Query query) throws IOException; + abstract public Explanation explain(Weight weight, int doc) throws IOException; + abstract public TopFieldDocs search(Weight weight, Filter filter, int n, Sort sort) throws IOException; + /* End patch for GCJ bug #15411. */ +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Similarity.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Similarity.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Similarity.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,526 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.Term; +import org.apache.lucene.util.SmallFloat; + +import java.io.IOException; +import java.io.Serializable; +import java.util.Collection; +import java.util.Iterator; + +/** Expert: Scoring API. + *

Subclasses implement search scoring. + * + *

The score of query q for document d correlates to the + * cosine-distance or dot-product between document and query vectors in a + * + * Vector Space Model (VSM) of Information Retrieval. + * A document whose vector is closer to the query vector in that model is scored higher. + * + * The score is computed as follows: + * + *

+ * + * + *
+ * + * + * + * + * + * + * + * + * + * + * + *
+ * score(q,d)   =   + * coord(q,d)  ·  + * queryNorm(q)  ·  + * + * + * + * ( + * tf(t in d)  ·  + * idf(t)2  ·  + * t.getBoost() ·  + * norm(t,d) + * ) + *
t in q
+ *
+ * + *

where + *

    + *
  1. + * + * tf(t in d) + * correlates to the term's frequency, + * defined as the number of times term t appears in the currently scored document d. + * Documents that have more occurrences of a given term receive a higher score. + * The default computation for tf(t in d) in + * {@link org.apache.lucene.search.DefaultSimilarity#tf(float) DefaultSimilarity} is: + * + *
     
    + * + * + * + * + * + *
    + * {@link org.apache.lucene.search.DefaultSimilarity#tf(float) tf(t in d)}   =   + * + * frequency½ + *
    + *
     
    + *
  2. + * + *
  3. + * + * idf(t) stands for Inverse Document Frequency. This value + * correlates to the inverse of docFreq + * (the number of documents in which the term t appears). + * This means rarer terms give higher contribution to the total score. + * The default computation for idf(t) in + * {@link org.apache.lucene.search.DefaultSimilarity#idf(int, int) DefaultSimilarity} is: + * + *
     
    + * + * + * + * + * + * + * + *
    + * {@link org.apache.lucene.search.DefaultSimilarity#idf(int, int) idf(t)}  =   + * + * 1 + log ( + * + * + * + * + * + *
    numDocs
    –––––––––
    docFreq+1
    + *
    + * ) + *
    + *
     
    + *
  4. + * + *
  5. + * + * coord(q,d) + * is a score factor based on how many of the query terms are found in the specified document. + * Typically, a document that contains more of the query's terms will receive a higher score + * than another document with fewer query terms. + * This is a search time factor computed in + * {@link #coord(int, int) coord(q,d)} + * by the Similarity in effect at search time. + *
     
    + *
  6. + * + *
  7. + * + * queryNorm(q) + * + * is a normalizing factor used to make scores between queries comparable. + * This factor does not affect document ranking (since all ranked documents are multiplied by the same factor), + * but rather just attempts to make scores from different queries (or even different indexes) comparable. + * This is a search time factor computed by the Similarity in effect at search time. + * + * The default computation in + * {@link org.apache.lucene.search.DefaultSimilarity#queryNorm(float) DefaultSimilarity} + * is: + *
     
    + * + * + * + * + * + *
    + * queryNorm(q)   =   + * {@link org.apache.lucene.search.DefaultSimilarity#queryNorm(float) queryNorm(sumOfSquaredWeights)} + *   =   + * + * + * + * + * + *
    1
    + * –––––––––––––– + *
    sumOfSquaredWeights½
    + *
    + *
     
    + * + * The sum of squared weights (of the query terms) is + * computed by the query {@link org.apache.lucene.search.Weight} object. + * For example, a {@link org.apache.lucene.search.BooleanQuery boolean query} + * computes this value as: + * + *
     
    + * + * + * + * + * + * + * + * + * + * + * + *
    + * {@link org.apache.lucene.search.Weight#sumOfSquaredWeights() sumOfSquaredWeights}   =   + * {@link org.apache.lucene.search.Query#getBoost() q.getBoost()} 2 + *  ·  + * + * + * + * ( + * idf(t)  ·  + * t.getBoost() + * ) 2 + *
    t in q
    + *
     
    + * + *
  8. + * + *
  9. + * + * t.getBoost() + * is a search time boost of term t in the query q as + * specified in the query text + * (see query syntax), + * or as set by application calls to + * {@link org.apache.lucene.search.Query#setBoost(float) setBoost()}. + * Notice that there is really no direct API for accessing a boost of one term in a multi term query, + * but rather multi terms are represented in a query as multi + * {@link org.apache.lucene.search.TermQuery TermQuery} objects, + * and so the boost of a term in the query is accessible by calling the sub-query + * {@link org.apache.lucene.search.Query#getBoost() getBoost()}. + *
     
    + *
  10. + * + *
  11. + * + * norm(t,d) encapsulates a few (indexing time) boost and length factors: + * + *
      + *
    • Document boost - set by calling + * {@link org.apache.lucene.document.Document#setBoost(float) doc.setBoost()} + * before adding the document to the index. + *
    • + *
    • Field boost - set by calling + * {@link org.apache.lucene.document.Fieldable#setBoost(float) field.setBoost()} + * before adding the field to a document. + *
    • + *
    • {@link #lengthNorm(String, int) lengthNorm(field)} - computed + * when the document is added to the index in accordance with the number of tokens + * of this field in the document, so that shorter fields contribute more to the score. + * LengthNorm is computed by the Similarity class in effect at indexing. + *
    • + *
    + * + *

    + * When a document is added to the index, all the above factors are multiplied. + * If the document has multiple fields with the same name, all their boosts are multiplied together: + * + *
     
    + * + * + * + * + * + * + * + * + * + * + * + *
    + * norm(t,d)   =   + * {@link org.apache.lucene.document.Document#getBoost() doc.getBoost()} + *  ·  + * {@link #lengthNorm(String, int) lengthNorm(field)} + *  ·  + * + * + * + * {@link org.apache.lucene.document.Fieldable#getBoost() f.getBoost}() + *
    field f in d named as t
    + *
     
    + * However the resulted norm value is {@link #encodeNorm(float) encoded} as a single byte + * before being stored. + * At search time, the norm byte value is read from the index + * {@link org.apache.lucene.store.Directory directory} and + * {@link #decodeNorm(byte) decoded} back to a float norm value. + * This encoding/decoding, while reducing index size, comes with the price of + * precision loss - it is not guaranteed that decode(encode(x)) = x. + * For instance, decode(encode(0.89)) = 0.75. + * Also notice that search time is too late to modify this norm part of scoring, e.g. by + * using a different {@link Similarity} for search. + *
     
    + *

  12. + *
+ * + * @see #setDefault(Similarity) + * @see org.apache.lucene.index.IndexWriter#setSimilarity(Similarity) + * @see Searcher#setSimilarity(Similarity) + */ +public abstract class Similarity implements Serializable { + /** The Similarity implementation used by default. */ + private static Similarity defaultImpl = new DefaultSimilarity(); + + /** Set the default Similarity implementation used by indexing and search + * code. + * + * @see Searcher#setSimilarity(Similarity) + * @see org.apache.lucene.index.IndexWriter#setSimilarity(Similarity) + */ + public static void setDefault(Similarity similarity) { + Similarity.defaultImpl = similarity; + } + + /** Return the default Similarity implementation used by indexing and search + * code. + * + *

This is initially an instance of {@link DefaultSimilarity}. + * + * @see Searcher#setSimilarity(Similarity) + * @see org.apache.lucene.index.IndexWriter#setSimilarity(Similarity) + */ + public static Similarity getDefault() { + return Similarity.defaultImpl; + } + + /** Cache of decoded bytes. */ + private static final float[] NORM_TABLE = new float[256]; + + static { + for (int i = 0; i < 256; i++) + NORM_TABLE[i] = SmallFloat.byte315ToFloat((byte)i); + } + + /** Decodes a normalization factor stored in an index. + * @see #encodeNorm(float) + */ + public static float decodeNorm(byte b) { + return NORM_TABLE[b & 0xFF]; // & 0xFF maps negative bytes to positive above 127 + } + + /** Returns a table for decoding normalization bytes. + * @see #encodeNorm(float) + */ + public static float[] getNormDecoder() { + return NORM_TABLE; + } + + /** Computes the normalization value for a field given the total number of + * terms contained in a field. These values, together with field boosts, are + * stored in an index and multipled into scores for hits on each field by the + * search code. + * + *

Matches in longer fields are less precise, so implementations of this + * method usually return smaller values when numTokens is large, + * and larger values when numTokens is small. + * + *

That these values are computed under + * {@link org.apache.lucene.index.IndexWriter#addDocument(org.apache.lucene.document.Document)} + * and stored then using + * {@link #encodeNorm(float)}. + * Thus they have limited precision, and documents + * must be re-indexed if this method is altered. + * + * @param fieldName the name of the field + * @param numTokens the total number of tokens contained in fields named + * fieldName of doc. + * @return a normalization factor for hits on this field of this document + * + * @see org.apache.lucene.document.Field#setBoost(float) + */ + public abstract float lengthNorm(String fieldName, int numTokens); + + /** Computes the normalization value for a query given the sum of the squared + * weights of each of the query terms. This value is then multipled into the + * weight of each query term. + * + *

This does not affect ranking, but rather just attempts to make scores + * from different queries comparable. + * + * @param sumOfSquaredWeights the sum of the squares of query term weights + * @return a normalization factor for query weights + */ + public abstract float queryNorm(float sumOfSquaredWeights); + + /** Encodes a normalization factor for storage in an index. + * + *

The encoding uses a three-bit mantissa, a five-bit exponent, and + * the zero-exponent point at 15, thus + * representing values from around 7x10^9 to 2x10^-9 with about one + * significant decimal digit of accuracy. Zero is also represented. + * Negative numbers are rounded up to zero. Values too large to represent + * are rounded down to the largest representable value. Positive values too + * small to represent are rounded up to the smallest positive representable + * value. + * + * @see org.apache.lucene.document.Field#setBoost(float) + * @see org.apache.lucene.util.SmallFloat + */ + public static byte encodeNorm(float f) { + return SmallFloat.floatToByte315(f); + } + + + /** Computes a score factor based on a term or phrase's frequency in a + * document. This value is multiplied by the {@link #idf(Term, Searcher)} + * factor for each term in the query and these products are then summed to + * form the initial score for a document. + * + *

Terms and phrases repeated in a document indicate the topic of the + * document, so implementations of this method usually return larger values + * when freq is large, and smaller values when freq + * is small. + * + *

The default implementation calls {@link #tf(float)}. + * + * @param freq the frequency of a term within a document + * @return a score factor based on a term's within-document frequency + */ + public float tf(int freq) { + return tf((float)freq); + } + + /** Computes the amount of a sloppy phrase match, based on an edit distance. + * This value is summed for each sloppy phrase match in a document to form + * the frequency that is passed to {@link #tf(float)}. + * + *

A phrase match with a small edit distance to a document passage more + * closely matches the document, so implementations of this method usually + * return larger values when the edit distance is small and smaller values + * when it is large. + * + * @see PhraseQuery#setSlop(int) + * @param distance the edit distance of this sloppy phrase match + * @return the frequency increment for this match + */ + public abstract float sloppyFreq(int distance); + + /** Computes a score factor based on a term or phrase's frequency in a + * document. This value is multiplied by the {@link #idf(Term, Searcher)} + * factor for each term in the query and these products are then summed to + * form the initial score for a document. + * + *

Terms and phrases repeated in a document indicate the topic of the + * document, so implementations of this method usually return larger values + * when freq is large, and smaller values when freq + * is small. + * + * @param freq the frequency of a term within a document + * @return a score factor based on a term's within-document frequency + */ + public abstract float tf(float freq); + + /** Computes a score factor for a simple term. + * + *

The default implementation is:

+   *   return idf(searcher.docFreq(term), searcher.maxDoc());
+   * 
+ * + * Note that {@link Searcher#maxDoc()} is used instead of + * {@link org.apache.lucene.index.IndexReader#numDocs()} because it is proportional to + * {@link Searcher#docFreq(Term)} , i.e., when one is inaccurate, + * so is the other, and in the same direction. + * + * @param term the term in question + * @param searcher the document collection being searched + * @return a score factor for the term + */ + public float idf(Term term, Searcher searcher) throws IOException { + return idf(searcher.docFreq(term), searcher.maxDoc()); + } + + /** Computes a score factor for a phrase. + * + *

The default implementation sums the {@link #idf(Term,Searcher)} factor + * for each term in the phrase. + * + * @param terms the terms in the phrase + * @param searcher the document collection being searched + * @return a score factor for the phrase + */ + public float idf(Collection terms, Searcher searcher) throws IOException { + float idf = 0.0f; + Iterator i = terms.iterator(); + while (i.hasNext()) { + idf += idf((Term)i.next(), searcher); + } + return idf; + } + + /** Computes a score factor based on a term's document frequency (the number + * of documents which contain the term). This value is multiplied by the + * {@link #tf(int)} factor for each term in the query and these products are + * then summed to form the initial score for a document. + * + *

Terms that occur in fewer documents are better indicators of topic, so + * implementations of this method usually return larger values for rare terms, + * and smaller values for common terms. + * + * @param docFreq the number of documents which contain the term + * @param numDocs the total number of documents in the collection + * @return a score factor based on the term's document frequency + */ + public abstract float idf(int docFreq, int numDocs); + + /** Computes a score factor based on the fraction of all query terms that a + * document contains. This value is multiplied into scores. + * + *

The presence of a large portion of the query terms indicates a better + * match with the query, so implementations of this method usually return + * larger values when the ratio between these parameters is large and smaller + * values when the ratio between them is small. + * + * @param overlap the number of query terms matched in the document + * @param maxOverlap the total number of terms in the query + * @return a score factor based on term overlap with the query + */ + public abstract float coord(int overlap, int maxOverlap); + + + /** + * Calculate a scoring factor based on the data in the payload. Overriding implementations + * are responsible for interpreting what is in the payload. Lucene makes no assumptions about + * what is in the byte array. + *

+ * The default implementation returns 1. + * + * @param fieldName The fieldName of the term this payload belongs to + * @param payload The payload byte array to be scored + * @param offset The offset into the payload array + * @param length The length in the array + * @return An implementation dependent float to be used as a scoring factor + */ + public float scorePayload(String fieldName, byte [] payload, int offset, int length) + { + //Do nothing + return 1; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/SimilarityDelegator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SimilarityDelegator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SimilarityDelegator.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,62 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Expert: Delegating scoring implementation. Useful in {@link + * Query#getSimilarity(Searcher)} implementations, to override only certain + * methods of a Searcher's Similiarty implementation.. */ +public class SimilarityDelegator extends Similarity { + + private Similarity delegee; + + /** Construct a {@link Similarity} that delegates all methods to another. + * + * @param delegee the Similarity implementation to delegate to + */ + public SimilarityDelegator(Similarity delegee) { + this.delegee = delegee; + } + + public float lengthNorm(String fieldName, int numTerms) { + return delegee.lengthNorm(fieldName, numTerms); + } + + public float queryNorm(float sumOfSquaredWeights) { + return delegee.queryNorm(sumOfSquaredWeights); + } + + public float tf(float freq) { + return delegee.tf(freq); + } + + public float sloppyFreq(int distance) { + return delegee.sloppyFreq(distance); + } + + public float idf(int docFreq, int numDocs) { + return delegee.idf(docFreq, numDocs); + } + + public float coord(int overlap, int maxOverlap) { + return delegee.coord(overlap, maxOverlap); + } + + public float scorePayload(String fieldName, byte[] payload, int offset, int length) { + return delegee.scorePayload(fieldName, payload, offset, length); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/SloppyPhraseScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SloppyPhraseScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SloppyPhraseScorer.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,216 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.TermPositions; + +import java.io.IOException; +import java.util.HashMap; + +final class SloppyPhraseScorer extends PhraseScorer { + private int slop; + private PhrasePositions repeats[]; + private PhrasePositions tmpPos[]; // for flipping repeating pps. + private boolean checkedRepeats; + + SloppyPhraseScorer(Weight weight, TermPositions[] tps, int[] offsets, Similarity similarity, + int slop, byte[] norms) { + super(weight, tps, offsets, similarity, norms); + this.slop = slop; + } + + /** + * Score a candidate doc for all slop-valid position-combinations (matches) + * encountered while traversing/hopping the PhrasePositions. + *
The score contribution of a match depends on the distance: + *
- highest score for distance=0 (exact match). + *
- score gets lower as distance gets higher. + *
Example: for query "a b"~2, a document "x a b a y" can be scored twice: + * once for "a b" (distance=0), and once for "b a" (distance=2). + *
Pssibly not all valid combinations are encountered, because for efficiency + * we always propagate the least PhrasePosition. This allows to base on + * PriorityQueue and move forward faster. + * As result, for example, document "a b c b a" + * would score differently for queries "a b c"~4 and "c b a"~4, although + * they really are equivalent. + * Similarly, for doc "a b c b a f g", query "c b"~2 + * would get same score as "g f"~2, although "c b"~2 could be matched twice. + * We may want to fix this in the future (currently not, for performance reasons). + */ + protected final float phraseFreq() throws IOException { + int end = initPhrasePositions(); + + float freq = 0.0f; + boolean done = (end<0); + while (!done) { + PhrasePositions pp = (PhrasePositions) pq.pop(); + int start = pp.position; + int next = ((PhrasePositions) pq.top()).position; + + boolean tpsDiffer = true; + for (int pos = start; pos <= next || !tpsDiffer; pos = pp.position) { + if (pos<=next && tpsDiffer) + start = pos; // advance pp to min window + if (!pp.nextPosition()) { + done = true; // ran out of a term -- done + break; + } + PhrasePositions pp2 = null; + tpsDiffer = !pp.repeats || (pp2 = termPositionsDiffer(pp))==null; + if (pp2!=null && pp2!=pp) { + pp = flip(pp,pp2); // flip pp to pp2 + } + } + + int matchLength = end - start; + if (matchLength <= slop) + freq += getSimilarity().sloppyFreq(matchLength); // score match + + if (pp.position > end) + end = pp.position; + pq.put(pp); // restore pq + } + + return freq; + } + + // flip pp2 and pp in the queue: pop until finding pp2, insert back all but pp2, insert pp back. + // assumes: pp!=pp2, pp2 in pq, pp not in pq. + // called only when there are repeating pps. + private PhrasePositions flip(PhrasePositions pp, PhrasePositions pp2) { + int n=0; + PhrasePositions pp3; + //pop until finding pp2 + while ((pp3=(PhrasePositions)pq.pop()) != pp2) { + tmpPos[n++] = pp3; + } + //insert back all but pp2 + for (n--; n>=0; n--) { + pq.insert(tmpPos[n]); + } + //insert pp back + pq.put(pp); + return pp2; + } + + /** + * Init PhrasePositions in place. + * There is a one time initialization for this scorer: + *
- Put in repeats[] each pp that has another pp with same position in the doc. + *
- Also mark each such pp by pp.repeats = true. + *
Later can consult with repeats[] in termPositionsDiffer(pp), making that check efficient. + * In particular, this allows to score queries with no repetitions with no overhead due to this computation. + *
- Example 1 - query with no repetitions: "ho my"~2 + *
- Example 2 - query with repetitions: "ho my my"~2 + *
- Example 3 - query with repetitions: "my ho my"~2 + *
Init per doc w/repeats in query, includes propagating some repeating pp's to avoid false phrase detection. + * @return end (max position), or -1 if any term ran out (i.e. done) + * @throws IOException + */ + private int initPhrasePositions() throws IOException { + int end = 0; + + // no repeats at all (most common case is also the simplest one) + if (checkedRepeats && repeats==null) { + // build queue from list + pq.clear(); + for (PhrasePositions pp = first; pp != null; pp = pp.next) { + pp.firstPosition(); + if (pp.position > end) + end = pp.position; + pq.put(pp); // build pq from list + } + return end; + } + + // position the pp's + for (PhrasePositions pp = first; pp != null; pp = pp.next) + pp.firstPosition(); + + // one time initializatin for this scorer + if (!checkedRepeats) { + checkedRepeats = true; + // check for repeats + HashMap m = null; + for (PhrasePositions pp = first; pp != null; pp = pp.next) { + int tpPos = pp.position + pp.offset; + for (PhrasePositions pp2 = pp.next; pp2 != null; pp2 = pp2.next) { + int tpPos2 = pp2.position + pp2.offset; + if (tpPos2 == tpPos) { + if (m == null) + m = new HashMap(); + pp.repeats = true; + pp2.repeats = true; + m.put(pp,null); + m.put(pp2,null); + } + } + } + if (m!=null) + repeats = (PhrasePositions[]) m.keySet().toArray(new PhrasePositions[0]); + } + + // with repeats must advance some repeating pp's so they all start with differing tp's + if (repeats!=null) { + for (int i = 0; i < repeats.length; i++) { + PhrasePositions pp = repeats[i]; + PhrasePositions pp2; + while ((pp2 = termPositionsDiffer(pp)) != null) { + if (!pp2.nextPosition()) // out of pps that do not differ, advance the pp with higher offset + return -1; // ran out of a term -- done + } + } + } + + // build queue from list + pq.clear(); + for (PhrasePositions pp = first; pp != null; pp = pp.next) { + if (pp.position > end) + end = pp.position; + pq.put(pp); // build pq from list + } + + if (repeats!=null) { + tmpPos = new PhrasePositions[pq.size()]; + } + return end; + } + + /** + * We disallow two pp's to have the same TermPosition, thereby verifying multiple occurrences + * in the query of the same word would go elsewhere in the matched doc. + * @return null if differ (i.e. valid) otherwise return the higher offset PhrasePositions + * out of the first two PPs found to not differ. + */ + private PhrasePositions termPositionsDiffer(PhrasePositions pp) { + // efficiency note: a more efficient implementation could keep a map between repeating + // pp's, so that if pp1a, pp1b, pp1c are repeats term1, and pp2a, pp2b are repeats + // of term2, pp2a would only be checked against pp2b but not against pp1a, pp1b, pp1c. + // However this would complicate code, for a rather rare case, so choice is to compromise here. + int tpPos = pp.position + pp.offset; + for (int i = 0; i < repeats.length; i++) { + PhrasePositions pp2 = repeats[i]; + if (pp2 == pp) + continue; + int tpPos2 = pp2.position + pp2.offset; + if (tpPos2 == tpPos) + return pp.offset > pp2.offset ? pp : pp2; // do not differ: return the one with higher offset. + } + return null; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/Sort.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Sort.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Sort.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,225 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Serializable; + + +/** + * Encapsulates sort criteria for returned hits. + * + *

The fields used to determine sort order must be carefully chosen. + * Documents must contain a single term in such a field, + * and the value of the term should indicate the document's relative position in + * a given sort order. The field must be indexed, but should not be tokenized, + * and does not need to be stored (unless you happen to want it back with the + * rest of your document data). In other words: + * + *

document.add (new Field ("byNumber", Integer.toString(x), Field.Store.NO, Field.Index.NOT_ANALYZED));

+ * + * + *

Valid Types of Values

+ * + *

There are four possible kinds of term values which may be put into + * sorting fields: Integers, Longs, Floats, or Strings. Unless + * {@link SortField SortField} objects are specified, the type of value + * in the field is determined by parsing the first term in the field. + * + *

Integer term values should contain only digits and an optional + * preceding negative sign. Values must be base 10 and in the range + * Integer.MIN_VALUE and Integer.MAX_VALUE inclusive. + * Documents which should appear first in the sort + * should have low value integers, later documents high values + * (i.e. the documents should be numbered 1..n where + * 1 is the first and n the last). + * + *

Long term values should contain only digits and an optional + * preceding negative sign. Values must be base 10 and in the range + * Long.MIN_VALUE and Long.MAX_VALUE inclusive. + * Documents which should appear first in the sort + * should have low value integers, later documents high values. + * + *

Float term values should conform to values accepted by + * {@link Float Float.valueOf(String)} (except that NaN + * and Infinity are not supported). + * Documents which should appear first in the sort + * should have low values, later documents high values. + * + *

String term values can contain any valid String, but should + * not be tokenized. The values are sorted according to their + * {@link Comparable natural order}. Note that using this type + * of term value has higher memory requirements than the other + * two types. + * + *

Object Reuse

+ * + *

One of these objects can be + * used multiple times and the sort order changed between usages. + * + *

This class is thread safe. + * + *

Memory Usage

+ * + *

Sorting uses of caches of term values maintained by the + * internal HitQueue(s). The cache is static and contains an integer + * or float array of length IndexReader.maxDoc() for each field + * name for which a sort is performed. In other words, the size of the + * cache in bytes is: + * + *

4 * IndexReader.maxDoc() * (# of different fields actually used to sort) + * + *

For String fields, the cache is larger: in addition to the + * above array, the value of every term in the field is kept in memory. + * If there are many unique terms in the field, this could + * be quite large. + * + *

Note that the size of the cache is not affected by how many + * fields are in the index and might be used to sort - only by + * the ones actually used to sort a result set. + * + *

Created: Feb 12, 2004 10:53:57 AM + * + * @since lucene 1.4 + * @version $Id: Sort.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +public class Sort +implements Serializable { + + /** + * Represents sorting by computed relevance. Using this sort criteria returns + * the same results as calling + * {@link Searcher#search(Query) Searcher#search()}without a sort criteria, + * only with slightly more overhead. + */ + public static final Sort RELEVANCE = new Sort(); + + /** Represents sorting by index order. */ + public static final Sort INDEXORDER = new Sort(SortField.FIELD_DOC); + + // internal representation of the sort criteria + SortField[] fields; + + /** + * Sorts by computed relevance. This is the same sort criteria as calling + * {@link Searcher#search(Query) Searcher#search()}without a sort criteria, + * only with slightly more overhead. + */ + public Sort() { + this(new SortField[] { SortField.FIELD_SCORE, SortField.FIELD_DOC }); + } + + /** + * Sorts by the terms in field then by index order (document + * number). The type of value in field is determined + * automatically. + * + * @see SortField#AUTO + */ + public Sort(String field) { + setSort(field, false); + } + + /** + * Sorts possibly in reverse by the terms in field then by + * index order (document number). The type of value in field is + * determined automatically. + * + * @see SortField#AUTO + */ + public Sort(String field, boolean reverse) { + setSort(field, reverse); + } + + /** + * Sorts in succession by the terms in each field. The type of value in + * field is determined automatically. + * + * @see SortField#AUTO + */ + public Sort(String[] fields) { + setSort(fields); + } + + /** Sorts by the criteria in the given SortField. */ + public Sort(SortField field) { + setSort(field); + } + + /** Sorts in succession by the criteria in each SortField. */ + public Sort(SortField[] fields) { + setSort(fields); + } + + /** + * Sets the sort to the terms in field then by index order + * (document number). + */ + public final void setSort(String field) { + setSort(field, false); + } + + /** + * Sets the sort to the terms in field possibly in reverse, + * then by index order (document number). + */ + public void setSort(String field, boolean reverse) { + SortField[] nfields = new SortField[] { + new SortField(field, SortField.AUTO, reverse), SortField.FIELD_DOC }; + fields = nfields; + } + + /** Sets the sort to the terms in each field in succession. */ + public void setSort(String[] fieldnames) { + final int n = fieldnames.length; + SortField[] nfields = new SortField[n]; + for (int i = 0; i < n; ++i) { + nfields[i] = new SortField(fieldnames[i], SortField.AUTO); + } + fields = nfields; + } + + /** Sets the sort to the given criteria. */ + public void setSort(SortField field) { + this.fields = new SortField[] { field }; + } + + /** Sets the sort to the given criteria in succession. */ + public void setSort(SortField[] fields) { + this.fields = fields; + } + + /** + * Representation of the sort criteria. + * @return Array of SortField objects used in this sort criteria + */ + public SortField[] getSort() { + return fields; + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + + for (int i = 0; i < fields.length; i++) { + buffer.append(fields[i].toString()); + if ((i+1) < fields.length) + buffer.append(','); + } + + return buffer.toString(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/SortComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SortComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SortComparator.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,82 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; + +/** + * Abstract base class for sorting hits returned by a Query. + * + *

This class should only be used if the other SortField + * types (SCORE, DOC, STRING, INT, FLOAT) do not provide an + * adequate sorting. It maintains an internal cache of values which + * could be quite large. The cache is an array of Comparable, + * one for each document in the index. There is a distinct + * Comparable for each unique term in the field - if + * some documents have the same term in the field, the cache + * array will have entries which reference the same Comparable. + * + *

Created: Apr 21, 2004 5:08:38 PM + * + * + * @version $Id: SortComparator.java,v 1.1 2012/08/17 14:54:55 marcin Exp $ + * @since 1.4 + */ +public abstract class SortComparator +implements SortComparatorSource { + + // inherit javadocs + public ScoreDocComparator newComparator (final IndexReader reader, final String fieldname) + throws IOException { + final String field = fieldname.intern(); + final Comparable[] cachedValues = FieldCache.DEFAULT.getCustom (reader, field, SortComparator.this); + + return new ScoreDocComparator() { + + public int compare (ScoreDoc i, ScoreDoc j) { + return cachedValues[i.doc].compareTo (cachedValues[j.doc]); + } + + public Comparable sortValue (ScoreDoc i) { + return cachedValues[i.doc]; + } + + public int sortType(){ + return SortField.CUSTOM; + } + }; + } + + /** + * Returns an object which, when sorted according to natural order, + * will order the Term values in the correct order. + *

For example, if the Terms contained integer values, this method + * would return new Integer(termtext). Note that this + * might not always be the most efficient implementation - for this + * particular example, a better implementation might be to make a + * ScoreDocLookupComparator that uses an internal lookup table of int. + * @param termtext The textual value of the term. + * @return An object representing termtext that sorts according to the natural order of termtext. + * @see Comparable + * @see ScoreDocComparator + */ + protected abstract Comparable getComparable (String termtext); + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/SortComparatorSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SortComparatorSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SortComparatorSource.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,45 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import java.io.IOException; +import java.io.Serializable; + +/** + * Expert: returns a comparator for sorting ScoreDocs. + * + *

Created: Apr 21, 2004 3:49:28 PM + * + * + * @version $Id: SortComparatorSource.java,v 1.1 2012/08/17 14:54:56 marcin Exp $ + * @since 1.4 + */ +public interface SortComparatorSource +extends Serializable { + + /** + * Creates a comparator for the field in the given index. + * @param reader Index to create comparator for. + * @param fieldname Name of the field to create comparator for. + * @return Comparator of ScoreDoc objects. + * @throws IOException If an error occurs reading the index. + */ + ScoreDocComparator newComparator (IndexReader reader, String fieldname) + throws IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/SortField.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SortField.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SortField.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,247 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Serializable; +import java.util.Locale; + +/** + * Stores information about how to sort documents by terms in an individual + * field. Fields must be indexed in order to sort by them. + * + *

Created: Feb 11, 2004 1:25:29 PM + * + * @since lucene 1.4 + * @version $Id: SortField.java,v 1.1 2012/08/17 14:54:55 marcin Exp $ + * @see Sort + */ +public class SortField +implements Serializable { + + /** Sort by document score (relevancy). Sort values are Float and higher + * values are at the front. */ + public static final int SCORE = 0; + + /** Sort by document number (index order). Sort values are Integer and lower + * values are at the front. */ + public static final int DOC = 1; + + /** Guess type of sort based on field contents. A regular expression is used + * to look at the first term indexed for the field and determine if it + * represents an integer number, a floating point number, or just arbitrary + * string characters. */ + public static final int AUTO = 2; + + /** Sort using term values as Strings. Sort values are String and lower + * values are at the front. */ + public static final int STRING = 3; + + /** Sort using term values as encoded Integers. Sort values are Integer and + * lower values are at the front. */ + public static final int INT = 4; + + /** Sort using term values as encoded Floats. Sort values are Float and + * lower values are at the front. */ + public static final int FLOAT = 5; + + /** Sort using term values as encoded Longs. Sort values are Long and + * lower values are at the front. */ + public static final int LONG = 6; + + /** Sort using term values as encoded Doubles. Sort values are Double and + * lower values are at the front. */ + public static final int DOUBLE = 7; + + /** + * Sort using term values as encoded Shorts. Sort values are shorts and lower values are at the front + */ + public static final int SHORT = 8; + + + /** Sort using a custom Comparator. Sort values are any Comparable and + * sorting is done according to natural order. */ + public static final int CUSTOM = 9; + /** + * Sort using term values as encoded bytes. Sort values are bytes and lower values are at the front + */ + public static final int BYTE = 10; + + + // IMPLEMENTATION NOTE: the FieldCache.STRING_INDEX is in the same "namespace" + // as the above static int values. Any new values must not have the same value + // as FieldCache.STRING_INDEX. + + + /** Represents sorting by document score (relevancy). */ + public static final SortField FIELD_SCORE = new SortField (null, SCORE); + + /** Represents sorting by document number (index order). */ + public static final SortField FIELD_DOC = new SortField (null, DOC); + + + private String field; + private int type = AUTO; // defaults to determining type dynamically + private Locale locale; // defaults to "natural order" (no Locale) + boolean reverse = false; // defaults to natural order + private SortComparatorSource factory; + + /** Creates a sort by terms in the given field where the type of term value + * is determined dynamically ({@link #AUTO AUTO}). + * @param field Name of field to sort by, cannot be null. + */ + public SortField (String field) { + this.field = field.intern(); + } + + /** Creates a sort, possibly in reverse, by terms in the given field where + * the type of term value is determined dynamically ({@link #AUTO AUTO}). + * @param field Name of field to sort by, cannot be null. + * @param reverse True if natural order should be reversed. + */ + public SortField (String field, boolean reverse) { + this.field = field.intern(); + this.reverse = reverse; + } + + /** Creates a sort by terms in the given field with the type of term + * values explicitly given. + * @param field Name of field to sort by. Can be null if + * type is SCORE or DOC. + * @param type Type of values in the terms. + */ + public SortField (String field, int type) { + this.field = (field != null) ? field.intern() : field; + this.type = type; + } + + /** Creates a sort, possibly in reverse, by terms in the given field with the + * type of term values explicitly given. + * @param field Name of field to sort by. Can be null if + * type is SCORE or DOC. + * @param type Type of values in the terms. + * @param reverse True if natural order should be reversed. + */ + public SortField (String field, int type, boolean reverse) { + this.field = (field != null) ? field.intern() : field; + this.type = type; + this.reverse = reverse; + } + + /** Creates a sort by terms in the given field sorted + * according to the given locale. + * @param field Name of field to sort by, cannot be null. + * @param locale Locale of values in the field. + */ + public SortField (String field, Locale locale) { + this.field = field.intern(); + this.type = STRING; + this.locale = locale; + } + + /** Creates a sort, possibly in reverse, by terms in the given field sorted + * according to the given locale. + * @param field Name of field to sort by, cannot be null. + * @param locale Locale of values in the field. + */ + public SortField (String field, Locale locale, boolean reverse) { + this.field = field.intern(); + this.type = STRING; + this.locale = locale; + this.reverse = reverse; + } + + /** Creates a sort with a custom comparison function. + * @param field Name of field to sort by; cannot be null. + * @param comparator Returns a comparator for sorting hits. + */ + public SortField (String field, SortComparatorSource comparator) { + this.field = (field != null) ? field.intern() : field; + this.type = CUSTOM; + this.factory = comparator; + } + + /** Creates a sort, possibly in reverse, with a custom comparison function. + * @param field Name of field to sort by; cannot be null. + * @param comparator Returns a comparator for sorting hits. + * @param reverse True if natural order should be reversed. + */ + public SortField (String field, SortComparatorSource comparator, boolean reverse) { + this.field = (field != null) ? field.intern() : field; + this.type = CUSTOM; + this.reverse = reverse; + this.factory = comparator; + } + + /** Returns the name of the field. Could return null + * if the sort is by SCORE or DOC. + * @return Name of field, possibly null. + */ + public String getField() { + return field; + } + + /** Returns the type of contents in the field. + * @return One of the constants SCORE, DOC, AUTO, STRING, INT or FLOAT. + */ + public int getType() { + return type; + } + + /** Returns the Locale by which term values are interpreted. + * May return null if no Locale was specified. + * @return Locale, or null. + */ + public Locale getLocale() { + return locale; + } + + /** Returns whether the sort should be reversed. + * @return True if natural order should be reversed. + */ + public boolean getReverse() { + return reverse; + } + + public SortComparatorSource getFactory() { + return factory; + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + switch (type) { + case SCORE: buffer.append(""); + break; + + case DOC: buffer.append(""); + break; + + case CUSTOM: + buffer.append("'); + break; + + default: + buffer.append('\"').append(field).append('\"'); + break; + } + + if (locale != null) buffer.append('(').append(locale).append(')'); + if (reverse) buffer.append('!'); + + return buffer.toString(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/SpanFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SpanFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SpanFilter.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,38 @@ +package org.apache.lucene.search; +/** + * Copyright 2007 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; + +/** Abstract base class providing a mechanism to restrict searches to a subset + of an index and also maintains and returns position information. + + This is useful if you want to compare the positions from a SpanQuery with the positions of items in + a filter. For instance, if you had a SpanFilter that marked all the occurrences of the word "foo" in documents, + and then you entered a new SpanQuery containing bar, you could not only filter by the word foo, but you could + then compare position information for post processing. + */ +public abstract class SpanFilter extends Filter{ + /** Returns a SpanFilterResult with true for documents which should be permitted in + search results, and false for those that should not and Spans for where the true docs match. + * @param reader The {@link org.apache.lucene.index.IndexReader} to load position and DocIdSet information from + * @return A {@link SpanFilterResult} + * @throws java.io.IOException if there was an issue accessing the necessary information + * */ + public abstract SpanFilterResult bitSpans(IndexReader reader) throws IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/SpanFilterResult.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SpanFilterResult.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SpanFilterResult.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,138 @@ +package org.apache.lucene.search; +/** + * Copyright 2005 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; + + +/** + * The results of a SpanQueryFilter. Wraps the BitSet and the position infomration from the SpanQuery + * + *

+ * NOTE: This API is still experimental and subject to change. + * + **/ +public class SpanFilterResult { + /** @deprecated */ + private BitSet bits; + + private DocIdSet docIdSet; + private List positions;//Spans spans; + + /** + * + * @param bits The bits for the Filter + * @param positions A List of {@link org.apache.lucene.search.SpanFilterResult.PositionInfo} objects + * @deprecated Use {@link #SpanFilterResult(DocIdSet, List)} instead + */ + public SpanFilterResult(BitSet bits, List positions) { + this.bits = bits; + this.positions = positions; + } + + /** + * + * @param docIdSet The DocIdSet for the Filter + * @param positions A List of {@link org.apache.lucene.search.SpanFilterResult.PositionInfo} objects + */ + public SpanFilterResult(DocIdSet docIdSet, List positions) { + this.docIdSet = docIdSet; + this.positions = positions; + } + + /** + * The first entry in the array corresponds to the first "on" bit. + * Entries are increasing by document order + * @return A List of PositionInfo objects + */ + public List getPositions() { + return positions; + } + + /** + * @deprecated Use {@link #getDocIdSet()} + */ + public BitSet getBits() { + return bits; + } + + /** Returns the docIdSet */ + public DocIdSet getDocIdSet() { + return docIdSet; + } + + public static class PositionInfo { + private int doc; + private List positions; + + + public PositionInfo(int doc) { + this.doc = doc; + positions = new ArrayList(); + } + + public void addPosition(int start, int end) + { + positions.add(new StartEnd(start, end)); + } + + public int getDoc() { + return doc; + } + + /** + * + * @return A List of {@link org.apache.lucene.search.SpanFilterResult.StartEnd} objects + */ + public List getPositions() { + return positions; + } + } + + public static class StartEnd + { + private int start; + private int end; + + + public StartEnd(int start, int end) { + this.start = start; + this.end = end; + } + + /** + * + * @return The end position of this match + */ + public int getEnd() { + return end; + } + + /** + * The Start position + * @return The start position of this match + */ + public int getStart() { + return start; + } + + } +} + + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/SpanQueryFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/SpanQueryFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/SpanQueryFilter.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,100 @@ +package org.apache.lucene.search; +/** + * Copyright 2007 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.spans.SpanQuery; +import org.apache.lucene.search.spans.Spans; +import org.apache.lucene.util.OpenBitSet; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Constrains search results to only match those which also match a provided + * query. Also provides position information about where each document matches + * at the cost of extra space compared with the QueryWrapperFilter. + * There is an added cost to this above what is stored in a {@link QueryWrapperFilter}. Namely, + * the position information for each matching document is stored. + *

+ * This filter does not cache. See the {@link org.apache.lucene.search.CachingSpanFilter} for a wrapper that + * caches. + * + * + * @version $Id: SpanQueryFilter.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +public class SpanQueryFilter extends SpanFilter { + protected SpanQuery query; + + protected SpanQueryFilter() + { + + } + + /** Constructs a filter which only matches documents matching + * query. + * @param query The {@link org.apache.lucene.search.spans.SpanQuery} to use as the basis for the Filter. + */ + public SpanQueryFilter(SpanQuery query) { + this.query = query; + } + + public DocIdSet getDocIdSet(IndexReader reader) throws IOException { + SpanFilterResult result = bitSpans(reader); + return result.getDocIdSet(); + } + + public SpanFilterResult bitSpans(IndexReader reader) throws IOException { + + final OpenBitSet bits = new OpenBitSet(reader.maxDoc()); + Spans spans = query.getSpans(reader); + List tmp = new ArrayList(20); + int currentDoc = -1; + SpanFilterResult.PositionInfo currentInfo = null; + while (spans.next()) + { + int doc = spans.doc(); + bits.set(doc); + if (currentDoc != doc) + { + currentInfo = new SpanFilterResult.PositionInfo(doc); + tmp.add(currentInfo); + currentDoc = doc; + } + currentInfo.addPosition(spans.start(), spans.end()); + } + return new SpanFilterResult(bits, tmp); + } + + + public SpanQuery getQuery() { + return query; + } + + public String toString() { + return "QueryWrapperFilter(" + query + ")"; + } + + public boolean equals(Object o) { + return o instanceof SpanQueryFilter && this.query.equals(((SpanQueryFilter) o).query); + } + + public int hashCode() { + return query.hashCode() ^ 0x923F64B9; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/TermQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/TermQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/TermQuery.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,179 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Set; + +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermDocs; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.ToStringUtils; + +/** A Query that matches documents containing a term. + This may be combined with other terms with a {@link BooleanQuery}. + */ +public class TermQuery extends Query { + private Term term; + + private class TermWeight implements Weight { + private Similarity similarity; + private float value; + private float idf; + private float queryNorm; + private float queryWeight; + + public TermWeight(Searcher searcher) + throws IOException { + this.similarity = getSimilarity(searcher); + idf = similarity.idf(term, searcher); // compute idf + } + + public String toString() { return "weight(" + TermQuery.this + ")"; } + + public Query getQuery() { return TermQuery.this; } + public float getValue() { return value; } + + public float sumOfSquaredWeights() { + queryWeight = idf * getBoost(); // compute query weight + return queryWeight * queryWeight; // square it + } + + public void normalize(float queryNorm) { + this.queryNorm = queryNorm; + queryWeight *= queryNorm; // normalize query weight + value = queryWeight * idf; // idf for document + } + + public Scorer scorer(IndexReader reader) throws IOException { + TermDocs termDocs = reader.termDocs(term); + + if (termDocs == null) + return null; + + return new TermScorer(this, termDocs, similarity, + reader.norms(term.field())); + } + + public Explanation explain(IndexReader reader, int doc) + throws IOException { + + ComplexExplanation result = new ComplexExplanation(); + result.setDescription("weight("+getQuery()+" in "+doc+"), product of:"); + + Explanation idfExpl = + new Explanation(idf, "idf(docFreq=" + reader.docFreq(term) + + ", numDocs=" + reader.numDocs() + ")"); + + // explain query weight + Explanation queryExpl = new Explanation(); + queryExpl.setDescription("queryWeight(" + getQuery() + "), product of:"); + + Explanation boostExpl = new Explanation(getBoost(), "boost"); + if (getBoost() != 1.0f) + queryExpl.addDetail(boostExpl); + queryExpl.addDetail(idfExpl); + + Explanation queryNormExpl = new Explanation(queryNorm,"queryNorm"); + queryExpl.addDetail(queryNormExpl); + + queryExpl.setValue(boostExpl.getValue() * + idfExpl.getValue() * + queryNormExpl.getValue()); + + result.addDetail(queryExpl); + + // explain field weight + String field = term.field(); + ComplexExplanation fieldExpl = new ComplexExplanation(); + fieldExpl.setDescription("fieldWeight("+term+" in "+doc+ + "), product of:"); + + Explanation tfExpl = scorer(reader).explain(doc); + fieldExpl.addDetail(tfExpl); + fieldExpl.addDetail(idfExpl); + + Explanation fieldNormExpl = new Explanation(); + byte[] fieldNorms = reader.norms(field); + float fieldNorm = + fieldNorms!=null ? Similarity.decodeNorm(fieldNorms[doc]) : 0.0f; + fieldNormExpl.setValue(fieldNorm); + fieldNormExpl.setDescription("fieldNorm(field="+field+", doc="+doc+")"); + fieldExpl.addDetail(fieldNormExpl); + + fieldExpl.setMatch(Boolean.valueOf(tfExpl.isMatch())); + fieldExpl.setValue(tfExpl.getValue() * + idfExpl.getValue() * + fieldNormExpl.getValue()); + + result.addDetail(fieldExpl); + result.setMatch(fieldExpl.getMatch()); + + // combine them + result.setValue(queryExpl.getValue() * fieldExpl.getValue()); + + if (queryExpl.getValue() == 1.0f) + return fieldExpl; + + return result; + } + } + + /** Constructs a query for the term t. */ + public TermQuery(Term t) { + term = t; + } + + /** Returns the term of this query. */ + public Term getTerm() { return term; } + + protected Weight createWeight(Searcher searcher) throws IOException { + return new TermWeight(searcher); + } + + public void extractTerms(Set terms) { + terms.add(getTerm()); + } + + /** Prints a user-readable version of this query. */ + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + if (!term.field().equals(field)) { + buffer.append(term.field()); + buffer.append(":"); + } + buffer.append(term.text()); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (!(o instanceof TermQuery)) + return false; + TermQuery other = (TermQuery)o; + return (this.getBoost() == other.getBoost()) + && this.term.equals(other.term); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + return Float.floatToIntBits(getBoost()) ^ term.hashCode(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/TermScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/TermScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/TermScorer.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,189 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.TermDocs; + +/** Expert: A Scorer for documents matching a Term. + */ +final class TermScorer extends Scorer { + private Weight weight; + private TermDocs termDocs; + private byte[] norms; + private float weightValue; + private int doc; + + private final int[] docs = new int[32]; // buffered doc numbers + private final int[] freqs = new int[32]; // buffered term freqs + private int pointer; + private int pointerMax; + + private static final int SCORE_CACHE_SIZE = 32; + private float[] scoreCache = new float[SCORE_CACHE_SIZE]; + + /** Construct a TermScorer. + * @param weight The weight of the Term in the query. + * @param td An iterator over the documents matching the Term. + * @param similarity The Similarity implementation to be used for score computations. + * @param norms The field norms of the document fields for the Term. + */ + TermScorer(Weight weight, TermDocs td, Similarity similarity, + byte[] norms) { + super(similarity); + this.weight = weight; + this.termDocs = td; + this.norms = norms; + this.weightValue = weight.getValue(); + + for (int i = 0; i < SCORE_CACHE_SIZE; i++) + scoreCache[i] = getSimilarity().tf(i) * weightValue; + } + + public void score(HitCollector hc) throws IOException { + next(); + score(hc, Integer.MAX_VALUE); + } + + protected boolean score(HitCollector c, int end) throws IOException { + Similarity similarity = getSimilarity(); // cache sim in local + float[] normDecoder = Similarity.getNormDecoder(); + while (doc < end) { // for docs in window + int f = freqs[pointer]; + float score = // compute tf(f)*weight + f < SCORE_CACHE_SIZE // check cache + ? scoreCache[f] // cache hit + : similarity.tf(f)*weightValue; // cache miss + + score *= normDecoder[norms[doc] & 0xFF]; // normalize for field + + c.collect(doc, score); // collect score + + if (++pointer >= pointerMax) { + pointerMax = termDocs.read(docs, freqs); // refill buffers + if (pointerMax != 0) { + pointer = 0; + } else { + termDocs.close(); // close stream + doc = Integer.MAX_VALUE; // set to sentinel value + return false; + } + } + doc = docs[pointer]; + } + return true; + } + + /** Returns the current document number matching the query. + * Initially invalid, until {@link #next()} is called the first time. + */ + public int doc() { return doc; } + + /** Advances to the next document matching the query. + *
The iterator over the matching documents is buffered using + * {@link TermDocs#read(int[],int[])}. + * @return true iff there is another document matching the query. + */ + public boolean next() throws IOException { + pointer++; + if (pointer >= pointerMax) { + pointerMax = termDocs.read(docs, freqs); // refill buffer + if (pointerMax != 0) { + pointer = 0; + } else { + termDocs.close(); // close stream + doc = Integer.MAX_VALUE; // set to sentinel value + return false; + } + } + doc = docs[pointer]; + return true; + } + + public float score() { + int f = freqs[pointer]; + float raw = // compute tf(f)*weight + f < SCORE_CACHE_SIZE // check cache + ? scoreCache[f] // cache hit + : getSimilarity().tf(f)*weightValue; // cache miss + + return raw * Similarity.decodeNorm(norms[doc]); // normalize for field + } + + /** Skips to the first match beyond the current whose document number is + * greater than or equal to a given target. + *
The implementation uses {@link TermDocs#skipTo(int)}. + * @param target The target document number. + * @return true iff there is such a match. + */ + public boolean skipTo(int target) throws IOException { + // first scan in cache + for (pointer++; pointer < pointerMax; pointer++) { + if (docs[pointer] >= target) { + doc = docs[pointer]; + return true; + } + } + + // not found in cache, seek underlying stream + boolean result = termDocs.skipTo(target); + if (result) { + pointerMax = 1; + pointer = 0; + docs[pointer] = doc = termDocs.doc(); + freqs[pointer] = termDocs.freq(); + } else { + doc = Integer.MAX_VALUE; + } + return result; + } + + /** Returns an explanation of the score for a document. + *
When this method is used, the {@link #next()} method + * and the {@link #score(HitCollector)} method should not be used. + * @param doc The document number for the explanation. + */ + public Explanation explain(int doc) throws IOException { + TermQuery query = (TermQuery)weight.getQuery(); + Explanation tfExplanation = new Explanation(); + int tf = 0; + while (pointer < pointerMax) { + if (docs[pointer] == doc) + tf = freqs[pointer]; + pointer++; + } + if (tf == 0) { + if (termDocs.skipTo(doc)) + { + if (termDocs.doc() == doc) + { + tf = termDocs.freq(); + } + } + } + termDocs.close(); + tfExplanation.setValue(getSimilarity().tf(tf)); + tfExplanation.setDescription("tf(termFreq("+query.getTerm()+")="+tf+")"); + + return tfExplanation; + } + + /** Returns a string representation of this TermScorer. */ + public String toString() { return "scorer(" + weight + ")"; } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/TimeLimitedCollector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/TimeLimitedCollector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/TimeLimitedCollector.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,219 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + *

The TimeLimitedCollector is used to timeout search requests that + * take longer than the maximum allowed search time limit. After this + * time is exceeded, the search thread is stopped by throwing a + * TimeExceeded Exception.

+ */ +public class TimeLimitedCollector extends HitCollector { + + /** + * Default timer resolution. + * @see #setResolution(long) + */ + public static final int DEFAULT_RESOLUTION = 20; + + /** + * Default for {@link #isGreedy()}. + * @see #isGreedy() + */ + public boolean DEFAULT_GREEDY = false; + + private static long resolution = DEFAULT_RESOLUTION; + + private boolean greedy = DEFAULT_GREEDY ; + + private static class TimerThread extends Thread { + + // NOTE: we can avoid explicit synchronization here for several reasons: + // * updates to volatile long variables are atomic + // * only single thread modifies this value + // * use of volatile keyword ensures that it does not reside in + // a register, but in main memory (so that changes are visible to + // other threads). + // * visibility of changes does not need to be instantanous, we can + // afford losing a tick or two. + // + // See section 17 of the Java Language Specification for details. + private volatile long time = 0; + + /** + * TimerThread provides a pseudo-clock service to all searching + * threads, so that they can count elapsed time with less overhead + * than repeatedly calling System.currentTimeMillis. A single + * thread should be created to be used for all searches. + */ + private TimerThread() { + super("TimeLimitedCollector timer thread"); + this.setDaemon( true ); + } + + public void run() { + boolean interrupted = false; + try { + while( true ) { + // TODO: Use System.nanoTime() when Lucene moves to Java SE 5. + time += resolution; + try { + Thread.sleep( resolution ); + } catch( final InterruptedException e ) { + interrupted = true; + } + } + } + finally { + if( interrupted ) { + Thread.currentThread().interrupt(); + } + } + } + + /** + * Get the timer value in milliseconds. + */ + public long getMilliseconds() { + return time; + } + } + + /** + * Thrown when elapsed search time exceeds allowed search time. + */ + public static class TimeExceededException extends RuntimeException { + private long timeAllowed; + private long timeElapsed; + private int lastDocCollected; + private TimeExceededException(long timeAllowed, long timeElapsed, int lastDocCollected) { + super("Elapsed time: " + timeElapsed + "Exceeded allowed search time: " + timeAllowed + " ms."); + this.timeAllowed = timeAllowed; + this.timeElapsed = timeElapsed; + this.lastDocCollected = lastDocCollected; + } + /** + * Returns allowed time (milliseconds). + */ + public long getTimeAllowed() { + return timeAllowed; + } + /** + * Returns elapsed time (milliseconds). + */ + public long getTimeElapsed() { + return timeElapsed; + } + /** + * Returns last doc that was collected when the search time exceeded. + */ + public int getLastDocCollected() { + return lastDocCollected; + } + } + + // Declare and initialize a single static timer thread to be used by + // all TimeLimitedCollector instances. The JVM assures that + // this only happens once. + private final static TimerThread TIMER_THREAD = new TimerThread(); + + static { + TIMER_THREAD.start(); + } + + private final long t0; + private final long timeout; + private final HitCollector hc; + + /** + * Create a TimeLimitedCollector wrapper over another HitCollector with a specified timeout. + * @param hc the wrapped HitCollector + * @param timeAllowed max time allowed for collecting hits after which {@link TimeExceededException} is thrown + */ + public TimeLimitedCollector( final HitCollector hc, final long timeAllowed ) { + this.hc = hc; + t0 = TIMER_THREAD.getMilliseconds(); + this.timeout = t0 + timeAllowed; + } + + /** + * Calls collect() on the decorated HitCollector. + * + * @throws TimeExceededException if the time allowed has been exceeded. + */ + public void collect( final int doc, final float score ) { + long time = TIMER_THREAD.getMilliseconds(); + if( timeout < time) { + if (greedy) { + //System.out.println(this+" greedy: before failing, collecting doc: "+doc+" "+(time-t0)); + hc.collect( doc, score ); + } + //System.out.println(this+" failing on: "+doc+" "+(time-t0)); + throw new TimeExceededException( timeout-t0, time-t0, doc ); + } + //System.out.println(this+" collecting: "+doc+" "+(time-t0)); + hc.collect( doc, score ); + } + + /** + * Return the timer resolution. + * @see #setResolution(long) + */ + public static long getResolution() { + return resolution; + } + + /** + * Set the timer resolution. + * The default timer resolution is 20 milliseconds. + * This means that a search required to take no longer than + * 800 milliseconds may be stopped after 780 to 820 milliseconds. + *
Note that: + *
    + *
  • Finer (smaller) resolution is more accurate but less efficient.
  • + *
  • Setting resolution to less than 5 milliseconds will be silently modified to 5 milliseconds.
  • + *
  • Setting resolution smaller than current resolution might take effect only after current + * resolution. (Assume current resolution of 20 milliseconds is modified to 5 milliseconds, + * then it can take up to 20 milliseconds for the change to have effect.
  • + *
+ */ + public static void setResolution(long newResolution) { + resolution = Math.max(newResolution,5); // 5 milliseconds is about the minimum reasonable time for a Object.wait(long) call. + } + + /** + * Checks if this time limited collector is greedy in collecting the last hit. + * A non greedy collector, upon a timeout, would throw a {@link TimeExceededException} + * without allowing the wrapped collector to collect current doc. A greedy one would + * first allow the wrapped hit collector to collect current doc and only then + * throw a {@link TimeExceededException}. + * @see #setGreedy(boolean) + */ + public boolean isGreedy() { + return greedy; + } + + /** + * Sets whether this time limited collector is greedy. + * @param greedy true to make this time limited greedy + * @see #isGreedy() + */ + public void setGreedy(boolean greedy) { + this.greedy = greedy; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/TopDocCollector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/TopDocCollector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/TopDocCollector.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,95 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.util.PriorityQueue; + +/** A {@link HitCollector} implementation that collects the top-scoring + * documents, returning them as a {@link TopDocs}. This is used by {@link + * IndexSearcher} to implement {@link TopDocs}-based search. + * + *

This may be extended, overriding the collect method to, e.g., + * conditionally invoke super() in order to filter which + * documents are collected. + **/ +public class TopDocCollector extends HitCollector { + + private ScoreDoc reusableSD; + + /** The total number of hits the collector encountered. */ + protected int totalHits; + + /** The priority queue which holds the top-scoring documents. */ + protected PriorityQueue hq; + + /** Construct to collect a given number of hits. + * @param numHits the maximum number of hits to collect + */ + public TopDocCollector(int numHits) { + this(new HitQueue(numHits)); + } + + /** @deprecated use TopDocCollector(hq) instead. numHits is not used by this + * constructor. It will be removed in a future release. + */ + TopDocCollector(int numHits, PriorityQueue hq) { + this.hq = hq; + } + + /** Constructor to collect the top-scoring documents by using the given PQ. + * @param hq the PQ to use by this instance. + */ + protected TopDocCollector(PriorityQueue hq) { + this.hq = hq; + } + + // javadoc inherited + public void collect(int doc, float score) { + if (score > 0.0f) { + totalHits++; + if (reusableSD == null) { + reusableSD = new ScoreDoc(doc, score); + } else if (score >= reusableSD.score) { + // reusableSD holds the last "rejected" entry, so, if + // this new score is not better than that, there's no + // need to try inserting it + reusableSD.doc = doc; + reusableSD.score = score; + } else { + return; + } + reusableSD = (ScoreDoc) hq.insertWithOverflow(reusableSD); + } + } + + /** The total number of documents that matched this query. */ + public int getTotalHits() { return totalHits; } + + /** The top-scoring hits. */ + public TopDocs topDocs() { + ScoreDoc[] scoreDocs = new ScoreDoc[hq.size()]; + for (int i = hq.size()-1; i >= 0; i--) // put docs in array + scoreDocs[i] = (ScoreDoc)hq.pop(); + + float maxScore = (totalHits==0) + ? Float.NEGATIVE_INFINITY + : scoreDocs[0].score; + + return new TopDocs(totalHits, scoreDocs, maxScore); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/TopDocs.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/TopDocs.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/TopDocs.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,48 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Expert: Returned by low-level search implementations. + * @see Searcher#search(Query,Filter,int) */ +public class TopDocs implements java.io.Serializable { + /** Expert: The total number of hits for the query. + * @see Hits#length() + */ + public int totalHits; + /** Expert: The top hits for the query. */ + public ScoreDoc[] scoreDocs; + /** Expert: Stores the maximum score value encountered, needed for normalizing. */ + private float maxScore; + + /** Expert: Returns the maximum score value encountered. */ + public float getMaxScore() { + return maxScore; + } + + /** Expert: Sets the maximum score value encountered. */ + public void setMaxScore(float maxScore) { + this.maxScore=maxScore; + } + + /** Expert: Constructs a TopDocs.*/ + public TopDocs(int totalHits, ScoreDoc[] scoreDocs, float maxScore) { + this.totalHits = totalHits; + this.scoreDocs = scoreDocs; + this.maxScore = maxScore; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/TopFieldDocCollector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/TopFieldDocCollector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/TopFieldDocCollector.java 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,75 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.IndexReader; + +/** A {@link HitCollector} implementation that collects the top-sorting + * documents, returning them as a {@link TopFieldDocs}. This is used by {@link + * IndexSearcher} to implement {@link TopFieldDocs}-based search. + * + *

This may be extended, overriding the collect method to, e.g., + * conditionally invoke super() in order to filter which + * documents are collected. + **/ +public class TopFieldDocCollector extends TopDocCollector { + + private FieldDoc reusableFD; + + /** Construct to collect a given number of hits. + * @param reader the index to be searched + * @param sort the sort criteria + * @param numHits the maximum number of hits to collect + */ + public TopFieldDocCollector(IndexReader reader, Sort sort, int numHits) + throws IOException { + super(new FieldSortedHitQueue(reader, sort.fields, numHits)); + } + + // javadoc inherited + public void collect(int doc, float score) { + if (score > 0.0f) { + totalHits++; + if (reusableFD == null) + reusableFD = new FieldDoc(doc, score); + else { + // Whereas TopDocCollector can skip this if the + // score is not competitive, we cannot because the + // comparators in the FieldSortedHitQueue.lessThan + // aren't in general congruent with "higher score + // wins" + reusableFD.score = score; + reusableFD.doc = doc; + } + reusableFD = (FieldDoc) hq.insertWithOverflow(reusableFD); + } + } + + // javadoc inherited + public TopDocs topDocs() { + FieldSortedHitQueue fshq = (FieldSortedHitQueue)hq; + ScoreDoc[] scoreDocs = new ScoreDoc[fshq.size()]; + for (int i = fshq.size()-1; i >= 0; i--) // put docs in array + scoreDocs[i] = fshq.fillFields ((FieldDoc) fshq.pop()); + + return new TopFieldDocs(totalHits, scoreDocs, + fshq.getFields(), fshq.getMaxScore()); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/TopFieldDocs.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/TopFieldDocs.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/TopFieldDocs.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,46 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Expert: Returned by low-level sorted search implementations. + * + *

Created: Feb 12, 2004 8:58:46 AM + * + * @since lucene 1.4 + * @version $Id: TopFieldDocs.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + * @see Searcher#search(Query,Filter,int,Sort) + */ +public class TopFieldDocs +extends TopDocs { + + /** The fields which were used to sort results by. */ + public SortField[] fields; + + /** Creates one of these objects. + * @param totalHits Total number of hits for the query. + * @param scoreDocs The top hits for the query. + * @param fields The sort criteria used to find the top hits. + * @param maxScore The maximum score encountered. + */ + TopFieldDocs (int totalHits, ScoreDoc[] scoreDocs, SortField[] fields, float maxScore) { + super (totalHits, scoreDocs, maxScore); + this.fields = fields; + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/search/Weight.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/Weight.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/Weight.java 17 Aug 2012 14:54:55 -0000 1.1 @@ -0,0 +1,62 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.IndexReader; + +/** Expert: Calculate query weights and build query scorers. + *

+ * The purpose of Weight is to make it so that searching does not modify + * a Query, so that a Query instance can be reused.
+ * Searcher dependent state of the query should reside in the Weight.
+ * IndexReader dependent state should reside in the Scorer. + *

+ * A Weight is used in the following way: + *

    + *
  1. A Weight is constructed by a top-level query, + * given a Searcher ({@link Query#createWeight(Searcher)}). + *
  2. The {@link #sumOfSquaredWeights()} method is called + * on the Weight to compute + * the query normalization factor {@link Similarity#queryNorm(float)} + * of the query clauses contained in the query. + *
  3. The query normalization factor is passed to {@link #normalize(float)}. + * At this point the weighting is complete. + *
  4. A Scorer is constructed by {@link #scorer(IndexReader)}. + *
+ */ +public interface Weight extends java.io.Serializable { + /** The query that this concerns. */ + Query getQuery(); + + /** The weight for this query. */ + float getValue(); + + /** The sum of squared weights of contained query clauses. */ + float sumOfSquaredWeights() throws IOException; + + /** Assigns the query normalization factor to this. */ + void normalize(float norm); + + /** Constructs a scorer for this. */ + Scorer scorer(IndexReader reader) throws IOException; + + /** An explanation of the score computation for the named document. */ + Explanation explain(IndexReader reader, int doc) throws IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/WildcardQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/WildcardQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/WildcardQuery.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,59 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import java.io.IOException; + +/** Implements the wildcard search query. Supported wildcards are *, which + * matches any character sequence (including the empty one), and ?, + * which matches any single character. Note this query can be slow, as it + * needs to iterate over many terms. In order to prevent extremely slow WildcardQueries, + * a Wildcard term should not start with one of the wildcards * or + * ?. + * + * @see WildcardTermEnum + */ +public class WildcardQuery extends MultiTermQuery { + private boolean termContainsWildcard; + + public WildcardQuery(Term term) { + super(term); + this.termContainsWildcard = (term.text().indexOf('*') != -1) || (term.text().indexOf('?') != -1); + } + + protected FilteredTermEnum getEnum(IndexReader reader) throws IOException { + return new WildcardTermEnum(reader, getTerm()); + } + + public boolean equals(Object o) { + if (o instanceof WildcardQuery) + return super.equals(o); + + return false; + } + + public Query rewrite(IndexReader reader) throws IOException { + if (this.termContainsWildcard) { + return super.rewrite(reader); + } + + return new TermQuery(getTerm()); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/WildcardTermEnum.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/WildcardTermEnum.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/WildcardTermEnum.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,199 @@ +package org.apache.lucene.search; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; + +/** + * Subclass of FilteredTermEnum for enumerating all terms that match the + * specified wildcard filter term. + *

+ * Term enumerations are always ordered by Term.compareTo(). Each term in + * the enumeration is greater than all that precede it. + * + * @version $Id: WildcardTermEnum.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +public class WildcardTermEnum extends FilteredTermEnum { + Term searchTerm; + String field = ""; + String text = ""; + String pre = ""; + int preLen = 0; + boolean endEnum = false; + + /** + * Creates a new WildcardTermEnum. Passing in a + * {@link org.apache.lucene.index.Term Term} that does not contain a + * WILDCARD_CHAR will cause an exception to be thrown. + *

+ * After calling the constructor the enumeration is already pointing to the first + * valid term if such a term exists. + */ + public WildcardTermEnum(IndexReader reader, Term term) throws IOException { + super(); + searchTerm = term; + field = searchTerm.field(); + text = searchTerm.text(); + + int sidx = text.indexOf(WILDCARD_STRING); + int cidx = text.indexOf(WILDCARD_CHAR); + int idx = sidx; + if (idx == -1) { + idx = cidx; + } + else if (cidx >= 0) { + idx = Math.min(idx, cidx); + } + + pre = searchTerm.text().substring(0,idx); + preLen = pre.length(); + text = text.substring(preLen); + setEnum(reader.terms(new Term(searchTerm.field(), pre))); + } + + protected final boolean termCompare(Term term) { + if (field == term.field()) { + String searchText = term.text(); + if (searchText.startsWith(pre)) { + return wildcardEquals(text, 0, searchText, preLen); + } + } + endEnum = true; + return false; + } + + public final float difference() { + return 1.0f; + } + + public final boolean endEnum() { + return endEnum; + } + + /******************************************** + * String equality with support for wildcards + ********************************************/ + + public static final char WILDCARD_STRING = '*'; + public static final char WILDCARD_CHAR = '?'; + + /** + * Determines if a word matches a wildcard pattern. + * Work released by Granta Design Ltd after originally being done on + * company time. + */ + public static final boolean wildcardEquals(String pattern, int patternIdx, + String string, int stringIdx) + { + int p = patternIdx; + + for (int s = stringIdx; ; ++p, ++s) + { + // End of string yet? + boolean sEnd = (s >= string.length()); + // End of pattern yet? + boolean pEnd = (p >= pattern.length()); + + // If we're looking at the end of the string... + if (sEnd) + { + // Assume the only thing left on the pattern is/are wildcards + boolean justWildcardsLeft = true; + + // Current wildcard position + int wildcardSearchPos = p; + // While we haven't found the end of the pattern, + // and haven't encountered any non-wildcard characters + while (wildcardSearchPos < pattern.length() && justWildcardsLeft) + { + // Check the character at the current position + char wildchar = pattern.charAt(wildcardSearchPos); + + // If it's not a wildcard character, then there is more + // pattern information after this/these wildcards. + if (wildchar != WILDCARD_CHAR && wildchar != WILDCARD_STRING) + { + justWildcardsLeft = false; + } + else + { + // to prevent "cat" matches "ca??" + if (wildchar == WILDCARD_CHAR) { + return false; + } + + // Look at the next character + wildcardSearchPos++; + } + } + + // This was a prefix wildcard search, and we've matched, so + // return true. + if (justWildcardsLeft) + { + return true; + } + } + + // If we've gone past the end of the string, or the pattern, + // return false. + if (sEnd || pEnd) + { + break; + } + + // Match a single character, so continue. + if (pattern.charAt(p) == WILDCARD_CHAR) + { + continue; + } + + // + if (pattern.charAt(p) == WILDCARD_STRING) + { + // Look at the character beyond the '*'. + ++p; + // Examine the string, starting at the last character. + for (int i = string.length(); i >= s; --i) + { + if (wildcardEquals(pattern, p, string, i)) + { + return true; + } + } + break; + } + if (pattern.charAt(p) != string.charAt(s)) + { + break; + } + } + return false; + } + + public void close() throws IOException + { + super.close(); + searchTerm = null; + field = null; + text = null; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/package.html 17 Aug 2012 14:54:56 -0000 1.1 @@ -0,0 +1,374 @@ + + + + + + + + + +Code to search indices. + +

Table Of Contents

+

+

    +
  1. Search Basics
  2. +
  3. The Query Classes
  4. +
  5. Changing the Scoring
  6. +
+

+ +

Search

+

+Search over indices. + +Applications usually call {@link +org.apache.lucene.search.Searcher#search(Query)} or {@link +org.apache.lucene.search.Searcher#search(Query,Filter)}. + + +

+ +

Query Classes

+

+ TermQuery +

+ +

Of the various implementations of + Query, the + TermQuery + is the easiest to understand and the most often used in applications. A TermQuery matches all the documents that contain the + specified + Term, + which is a word that occurs in a certain + Field. + Thus, a TermQuery identifies and scores all + Documents that have a Field with the specified string in it. + Constructing a TermQuery + is as simple as: +

+        TermQuery tq = new TermQuery(new Term("fieldName", "term"));
+    
In this example, the Query identifies all Documents that have the Field named "fieldName" + containing the word "term". +

+

+ BooleanQuery +

+ +

Things start to get interesting when one combines multiple + TermQuery instances into a BooleanQuery. + A BooleanQuery contains multiple + BooleanClauses, + where each clause contains a sub-query (Query + instance) and an operator (from BooleanClause.Occur) + describing how that sub-query is combined with the other clauses: +

    + +
  1. SHOULD — Use this operator when a clause can occur in the result set, but is not required. + If a query is made up of all SHOULD clauses, then every document in the result + set matches at least one of these clauses.

  2. + +
  3. MUST — Use this operator when a clause is required to occur in the result set. Every + document in the result set will match + all such clauses.

  4. + +
  5. MUST NOT — Use this operator when a + clause must not occur in the result set. No + document in the result set will match + any such clauses.

  6. +
+ Boolean queries are constructed by adding two or more + BooleanClause + instances. If too many clauses are added, a TooManyClauses + exception will be thrown during searching. This most often occurs + when a Query + is rewritten into a BooleanQuery with many + TermQuery clauses, + for example by WildcardQuery. + The default setting for the maximum number + of clauses 1024, but this can be changed via the + static method setMaxClauseCount + in BooleanQuery. +

+ +

Phrases

+ +

Another common search is to find documents containing certain phrases. This + is handled two different ways: +

    +
  1. +

    PhraseQuery + — Matches a sequence of + Terms. + PhraseQuery uses a slop factor to determine + how many positions may occur between any two terms in the phrase and still be considered a match.

    +
  2. +
  3. +

    SpanNearQuery + — Matches a sequence of other + SpanQuery + instances. SpanNearQuery allows for + much more + complicated phrase queries since it is constructed from other SpanQuery + instances, instead of only TermQuery + instances.

    +
  4. +
+

+

+ RangeQuery +

+ +

The + RangeQuery + matches all documents that occur in the + exclusive range of a lower + Term + and an upper + Term. + For example, one could find all documents + that have terms beginning with the letters a through c. This type of Query is frequently used to + find + documents that occur in a specific date range. +

+

+ PrefixQuery, + WildcardQuery +

+ +

While the + PrefixQuery + has a different implementation, it is essentially a special case of the + WildcardQuery. + The PrefixQuery allows an application + to identify all documents with terms that begin with a certain string. The WildcardQuery generalizes this by allowing + for the use of * (matches 0 or more characters) and ? (matches exactly one character) wildcards. + Note that the WildcardQuery can be quite slow. Also + note that + WildcardQuery should + not start with * and ?, as these are extremely slow. + To remove this protection and allow a wildcard at the beginning of a term, see method + setAllowLeadingWildcard in + QueryParser. +

+

+ FuzzyQuery +

+ +

A + FuzzyQuery + matches documents that contain terms similar to the specified term. Similarity is + determined using + Levenshtein (edit) distance. + This type of query can be useful when accounting for spelling variations in the collection. +

+ +

Changing Similarity

+ +

Chances are DefaultSimilarity is sufficient for all + your searching needs. + However, in some applications it may be necessary to customize your Similarity implementation. For instance, some + applications do not need to + distinguish between shorter and longer documents (see a "fair" similarity).

+ +

To change Similarity, one must do so for both indexing and + searching, and the changes must happen before + either of these actions take place. Although in theory there is nothing stopping you from changing mid-stream, it + just isn't well-defined what is going to happen. +

+ +

To make this change, implement your own Similarity (likely + you'll want to simply subclass + DefaultSimilarity) and then use the new + class by calling + IndexWriter.setSimilarity + before indexing and + Searcher.setSimilarity + before searching. +

+ +

+ If you are interested in use cases for changing your similarity, see the Lucene users's mailing list at Overriding Similarity. + In summary, here are a few use cases: +

    +
  1. SweetSpotSimilaritySweetSpotSimilarity gives small increases + as the frequency increases a small amount + and then greater increases when you hit the "sweet spot", i.e. where you think the frequency of terms is + more significant.

  2. +
  3. Overriding tf — In some applications, it doesn't matter what the score of a document is as long as a + matching term occurs. In these + cases people have overridden Similarity to return 1 from the tf() method.

  4. +
  5. Changing Length Normalization — By overriding lengthNorm, + it is possible to discount how the length of a field contributes + to a score. In DefaultSimilarity, + lengthNorm = 1 / (numTerms in field)^0.5, but if one changes this to be + 1 / (numTerms in field), all fields will be treated + "fairly".

  6. +
+ In general, Chris Hostetter sums it up best in saying (from the Lucene users's mailing list): +
[One would override the Similarity in] ... any situation where you know more about your data then just + that + it's "text" is a situation where it *might* make sense to to override your + Similarity method.
+

+ +

Changing Scoring — Expert Level

+ +

Changing scoring is an expert level task, so tread carefully and be prepared to share your code if + you want help. +

+ +

With the warning out of the way, it is possible to change a lot more than just the Similarity + when it comes to scoring in Lucene. Lucene's scoring is a complex mechanism that is grounded by + three main classes: +

    +
  1. + Query — The abstract object representation of the + user's information need.
  2. +
  3. + Weight — The internal interface representation of + the user's Query, so that Query objects may be reused.
  4. +
  5. + Scorer — An abstract class containing common + functionality for scoring. Provides both scoring and explanation capabilities.
  6. +
+ Details on each of these classes, and their children, can be found in the subsections below. +

+

The Query Class

+

In some sense, the + Query + class is where it all begins. Without a Query, there would be + nothing to score. Furthermore, the Query class is the catalyst for the other scoring classes as it + is often responsible + for creating them or coordinating the functionality between them. The + Query class has several methods that are important for + derived classes: +

    +
  1. createWeight(Searcher searcher) — A + Weight is the internal representation of the + Query, so each Query implementation must + provide an implementation of Weight. See the subsection on The Weight Interface below for details on implementing the Weight + interface.
  2. +
  3. rewrite(IndexReader reader) — Rewrites queries into primitive queries. Primitive queries are: + TermQuery, + BooleanQuery, OTHERS????
  4. +
+

+

The Weight Interface

+

The + Weight + interface provides an internal representation of the Query so that it can be reused. Any + Searcher + dependent state should be stored in the Weight implementation, + not in the Query class. The interface defines six methods that must be implemented: +

    +
  1. + Weight#getQuery() — Pointer to the + Query that this Weight represents.
  2. +
  3. + Weight#getValue() — The weight for + this Query. For example, the TermQuery.TermWeight value is + equal to the idf^2 * boost * queryNorm
  4. +
  5. + + Weight#sumOfSquaredWeights() — The sum of squared weights. For TermQuery, this is (idf * + boost)^2
  6. +
  7. + + Weight#normalize(float) — Determine the query normalization factor. The query normalization may + allow for comparing scores between queries.
  8. +
  9. + + Weight#scorer(IndexReader) — Construct a new + Scorer + for this Weight. See + The Scorer Class + below for help defining a Scorer. As the name implies, the + Scorer is responsible for doing the actual scoring of documents given the Query. +
  10. +
  11. + + Weight#explain(IndexReader, int) — Provide a means for explaining why a given document was + scored + the way it was.
  12. +
+

+

The Scorer Class

+

The + Scorer + abstract class provides common scoring functionality for all Scorer implementations and + is the heart of the Lucene scoring process. The Scorer defines the following abstract methods which + must be implemented: +

    +
  1. + Scorer#next() — Advances to the next + document that matches this Query, returning true if and only + if there is another document that matches.
  2. +
  3. + Scorer#doc() — Returns the id of the + Document + that contains the match. It is not valid until next() has been called at least once. +
  4. +
  5. + Scorer#score() — Return the score of the + current document. This value can be determined in any + appropriate way for an application. For instance, the + TermScorer + returns the tf * Weight.getValue() * fieldNorm. +
  6. +
  7. + Scorer#skipTo(int) — Skip ahead in + the document matches to the document whose id is greater than + or equal to the passed in value. In many instances, skipTo can be + implemented more efficiently than simply looping through all the matching documents until + the target document is identified.
  8. +
  9. + Scorer#explain(int) — Provides + details on why the score came about.
  10. +
+

+

Why would I want to add my own Query?

+ +

In a nutshell, you want to add your own custom Query implementation when you think that Lucene's + aren't appropriate for the + task that you want to do. You might be doing some cutting edge research or you need more information + back + out of Lucene (similar to Doug adding SpanQuery functionality).

+

Examples

+

FILL IN HERE

+ + + Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/ByteFieldSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/ByteFieldSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/ByteFieldSource.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,105 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.FieldCache; +import org.apache.lucene.search.function.DocValues; + +import java.io.IOException; + +/** + * Expert: obtains single byte field values from the + * {@link org.apache.lucene.search.FieldCache FieldCache} + * using getBytes() and makes those values + * available as other numeric types, casting as needed. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * @see org.apache.lucene.search.function.FieldCacheSource for requirements + * on the field. + */ +public class ByteFieldSource extends FieldCacheSource { + private FieldCache.ByteParser parser; + + /** + * Create a cached byte field source with default string-to-byte parser. + */ + public ByteFieldSource(String field) { + this(field, null); + } + + /** + * Create a cached byte field source with a specific string-to-byte parser. + */ + public ByteFieldSource(String field, FieldCache.ByteParser parser) { + super(field); + this.parser = parser; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */ + public String description() { + return "byte(" + super.description() + ')'; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#getCachedValues(org.apache.lucene.search.FieldCache, java.lang.String, org.apache.lucene.index.IndexReader) */ + public DocValues getCachedFieldValues (FieldCache cache, String field, IndexReader reader) throws IOException { + final byte[] arr = (parser==null) ? + cache.getBytes(reader, field) : + cache.getBytes(reader, field, parser); + return new DocValues() { + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */ + public float floatVal(int doc) { + return (float) arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#intVal(int) */ + public int intVal(int doc) { + return arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */ + public String toString(int doc) { + return description() + '=' + intVal(doc); + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */ + Object getInnerArray() { + return arr; + } + }; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceEquals(org.apache.lucene.search.function.FieldCacheSource) */ + public boolean cachedFieldSourceEquals(FieldCacheSource o) { + if (o.getClass() != ByteFieldSource.class) { + return false; + } + ByteFieldSource other = (ByteFieldSource)o; + return this.parser==null ? + other.parser==null : + this.parser.getClass() == other.parser.getClass(); + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceHashCode() */ + public int cachedFieldSourceHashCode() { + return parser==null ? + Byte.class.hashCode() : parser.getClass().hashCode(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/CustomScoreQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/CustomScoreQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/CustomScoreQuery.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,460 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.Set; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.ComplexExplanation; +import org.apache.lucene.search.Explanation; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Scorer; +import org.apache.lucene.search.Searcher; +import org.apache.lucene.search.Similarity; +import org.apache.lucene.search.Weight; +import org.apache.lucene.util.ToStringUtils; + +/** + * Query that sets document score as a programmatic function of several (sub) scores. + *

    + *
  1. the score of its subQuery (any query)
  2. + *
  3. (optional) the score of its ValueSourceQuery (or queries). + * For most simple/convenient use cases this query is likely to be a + * {@link org.apache.lucene.search.function.FieldScoreQuery FieldScoreQuery}
  4. + *
+ * Subclasses can modify the computation by overriding {@link #customScore(int, float, float)}. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + */ +public class CustomScoreQuery extends Query { + + private Query subQuery; + private ValueSourceQuery[] valSrcQueries; // never null (empty array if there are no valSrcQueries). + private boolean strict = false; // if true, valueSource part of query does not take part in weights normalization. + + /** + * Create a CustomScoreQuery over input subQuery. + * @param subQuery the sub query whose scored is being customed. Must not be null. + */ + public CustomScoreQuery(Query subQuery) { + this(subQuery, new ValueSourceQuery[0]); + } + + /** + * Create a CustomScoreQuery over input subQuery and a {@link ValueSourceQuery}. + * @param subQuery the sub query whose score is being customed. Must not be null. + * @param valSrcQuery a value source query whose scores are used in the custom score + * computation. For most simple/convineient use case this would be a + * {@link org.apache.lucene.search.function.FieldScoreQuery FieldScoreQuery}. + * This parameter is optional - it can be null. + */ + public CustomScoreQuery(Query subQuery, ValueSourceQuery valSrcQuery) { + this(subQuery, valSrcQuery!=null ? // don't want an array that contains a single null.. + new ValueSourceQuery[] {valSrcQuery} : new ValueSourceQuery[0]); + } + + /** + * Create a CustomScoreQuery over input subQuery and a {@link ValueSourceQuery}. + * @param subQuery the sub query whose score is being customed. Must not be null. + * @param valSrcQueries value source queries whose scores are used in the custom score + * computation. For most simple/convineient use case these would be + * {@link org.apache.lucene.search.function.FieldScoreQuery FieldScoreQueries}. + * This parameter is optional - it can be null or even an empty array. + */ + public CustomScoreQuery(Query subQuery, ValueSourceQuery valSrcQueries[]) { + super(); + this.subQuery = subQuery; + this.valSrcQueries = valSrcQueries!=null? + valSrcQueries : new ValueSourceQuery[0]; + if (subQuery == null) throw new IllegalArgumentException(" must not be null!"); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Query#rewrite(org.apache.lucene.index.IndexReader) */ + public Query rewrite(IndexReader reader) throws IOException { + subQuery = subQuery.rewrite(reader); + for(int i = 0; i < valSrcQueries.length; i++) { + valSrcQueries[i] = (ValueSourceQuery) valSrcQueries[i].rewrite(reader); + } + return this; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Query#extractTerms(java.util.Set) */ + public void extractTerms(Set terms) { + subQuery.extractTerms(terms); + for(int i = 0; i < valSrcQueries.length; i++) { + valSrcQueries[i].extractTerms(terms); + } + } + + /*(non-Javadoc) @see org.apache.lucene.search.Query#clone() */ + public Object clone() { + CustomScoreQuery clone = (CustomScoreQuery)super.clone(); + clone.subQuery = (Query) subQuery.clone(); + clone.valSrcQueries = new ValueSourceQuery[valSrcQueries.length]; + for(int i = 0; i < valSrcQueries.length; i++) { + clone.valSrcQueries[i] = (ValueSourceQuery) valSrcQueries[i].clone(); + } + return clone; + } + + /* (non-Javadoc) @see org.apache.lucene.search.Query#toString(java.lang.String) */ + public String toString(String field) { + StringBuffer sb = new StringBuffer(name()).append("("); + sb.append(subQuery.toString(field)); + for(int i = 0; i < valSrcQueries.length; i++) { + sb.append(", ").append(valSrcQueries[i].toString(field)); + } + sb.append(")"); + sb.append(strict?" STRICT" : ""); + return sb.toString() + ToStringUtils.boost(getBoost()); + } + + /** Returns true if o is equal to this. */ + public boolean equals(Object o) { + if (getClass() != o.getClass()) { + return false; + } + CustomScoreQuery other = (CustomScoreQuery)o; + if (this.getBoost() != other.getBoost() || + !this.subQuery.equals(other.subQuery)|| + this.valSrcQueries.length != other.valSrcQueries.length) { + return false; + } + for (int i=0; i + * Subclasses can override this method to modify the custom score. + *

+ * If your custom scoring is different than the default herein you + * should override at least one of the two customScore() methods. + * If the number of ValueSourceQueries is always < 2 it is + * sufficient to override the other + * {@link #customScore(int, float, float) costomScore()} + * method, which is simpler. + *

+ * The default computation herein is: + *

+   *     ModifiedScore = valSrcScore * subQueryScore[0] * subQueryScore[1] * ...
+   * 
+ * + * @param doc id of scored doc. + * @param subQueryScore score of that doc by the subQuery. + * @param valSrcScores score of that doc by the ValueSourceQuery. + * @return custom score. + */ + public float customScore(int doc, float subQueryScore, float valSrcScores[]) { + if(valSrcScores.length == 1) { + return customScore(doc, subQueryScore, valSrcScores[0]); + } + if (valSrcScores.length == 0) { + return customScore(doc, subQueryScore, 1); + } + float score = subQueryScore; + for(int i = 0; i < valSrcScores.length; i++) { + score *= valSrcScores[i]; + } + return score; + } + + /** + * Compute a custom score by the subQuery score and the ValueSourceQuery score. + *

+ * Subclasses can override this method to modify the custom score. + *

+ * If your custom scoring is different than the default herein you + * should override at least one of the two customScore() methods. + * If the number of ValueSourceQueries is always < 2 it is + * sufficient to override this costomScore() method, which is simpler. + *

+ * The default computation herein is: + *

+   *     ModifiedScore = valSrcScore * subQueryScore
+   * 
+ * + * @param doc id of scored doc. + * @param subQueryScore score of that doc by the subQuery. + * @param valSrcScore score of that doc by the ValueSourceQuery. + * @return custom score. + */ + public float customScore(int doc, float subQueryScore, float valSrcScore) { + return subQueryScore * valSrcScore; + } + + /** + * Explain the custom score. + * Whenever overriding {@link #customScore(int, float, float[])}, + * this method should also be overridden to provide the correct explanation + * for the part of the custom scoring. + * + * @param doc doc being explained. + * @param subQueryExpl explanation for the sub-query part. + * @param valSrcExpls explanation for the value source part. + * @return an explanation for the custom score + */ + public Explanation customExplain(int doc, Explanation subQueryExpl, Explanation valSrcExpls[]) { + if(valSrcExpls.length == 1) { + return customExplain(doc, subQueryExpl, valSrcExpls[0]); + } + if (valSrcExpls.length == 0) { + return subQueryExpl; + } + float valSrcScore = 1; + for(int i = 0; i < valSrcExpls.length; i++) { + valSrcScore *= valSrcExpls[i].getValue(); + } + Explanation exp = new Explanation( valSrcScore * subQueryExpl.getValue(), "custom score: product of:"); + exp.addDetail(subQueryExpl); + for(int i = 0; i < valSrcExpls.length; i++) { + exp.addDetail(valSrcExpls[i]); + } + return exp; + } + + /** + * Explain the custom score. + * Whenever overriding {@link #customScore(int, float, float)}, + * this method should also be overridden to provide the correct explanation + * for the part of the custom scoring. + * + * @param doc doc being explained. + * @param subQueryExpl explanation for the sub-query part. + * @param valSrcExpl explanation for the value source part. + * @return an explanation for the custom score + */ + public Explanation customExplain(int doc, Explanation subQueryExpl, Explanation valSrcExpl) { + float valSrcScore = 1; + if (valSrcExpl != null) { + valSrcScore *= valSrcExpl.getValue(); + } + Explanation exp = new Explanation( valSrcScore * subQueryExpl.getValue(), "custom score: product of:"); + exp.addDetail(subQueryExpl); + exp.addDetail(valSrcExpl); + return exp; + } + + //=========================== W E I G H T ============================ + + private class CustomWeight implements Weight { + Similarity similarity; + Weight subQueryWeight; + Weight[] valSrcWeights; + boolean qStrict; + + public CustomWeight(Searcher searcher) throws IOException { + this.similarity = getSimilarity(searcher); + this.subQueryWeight = subQuery.weight(searcher); + this.subQueryWeight = subQuery.weight(searcher); + this.valSrcWeights = new Weight[valSrcQueries.length]; + for(int i = 0; i < valSrcQueries.length; i++) { + this.valSrcWeights[i] = valSrcQueries[i].createWeight(searcher); + } + this.qStrict = strict; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#getQuery() */ + public Query getQuery() { + return CustomScoreQuery.this; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#getValue() */ + public float getValue() { + return getBoost(); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#sumOfSquaredWeights() */ + public float sumOfSquaredWeights() throws IOException { + float sum = subQueryWeight.sumOfSquaredWeights(); + for(int i = 0; i < valSrcWeights.length; i++) { + if (qStrict) { + valSrcWeights[i].sumOfSquaredWeights(); // do not include ValueSource part in the query normalization + } else { + sum += valSrcWeights[i].sumOfSquaredWeights(); + } + } + sum *= getBoost() * getBoost(); // boost each sub-weight + return sum ; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#normalize(float) */ + public void normalize(float norm) { + norm *= getBoost(); // incorporate boost + subQueryWeight.normalize(norm); + for(int i = 0; i < valSrcWeights.length; i++) { + if (qStrict) { + valSrcWeights[i].normalize(1); // do not normalize the ValueSource part + } else { + valSrcWeights[i].normalize(norm); + } + } + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#scorer(org.apache.lucene.index.IndexReader) */ + public Scorer scorer(IndexReader reader) throws IOException { + Scorer subQueryScorer = subQueryWeight.scorer(reader); + Scorer[] valSrcScorers = new Scorer[valSrcWeights.length]; + for(int i = 0; i < valSrcScorers.length; i++) { + valSrcScorers[i] = valSrcWeights[i].scorer(reader); + } + return new CustomScorer(similarity, reader, this, subQueryScorer, valSrcScorers); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#explain(org.apache.lucene.index.IndexReader, int) */ + public Explanation explain(IndexReader reader, int doc) throws IOException { + return scorer(reader).explain(doc); + } + } + + + //=========================== S C O R E R ============================ + + /** + * A scorer that applies a (callback) function on scores of the subQuery. + */ + private class CustomScorer extends Scorer { + private final CustomWeight weight; + private final float qWeight; + private Scorer subQueryScorer; + private Scorer[] valSrcScorers; + private IndexReader reader; + private float vScores[]; // reused in score() to avoid allocating this array for each doc + + // constructor + private CustomScorer(Similarity similarity, IndexReader reader, CustomWeight w, + Scorer subQueryScorer, Scorer[] valSrcScorers) throws IOException { + super(similarity); + this.weight = w; + this.qWeight = w.getValue(); + this.subQueryScorer = subQueryScorer; + this.valSrcScorers = valSrcScorers; + this.reader = reader; + this.vScores = new float[valSrcScorers.length]; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#next() */ + public boolean next() throws IOException { + boolean hasNext = subQueryScorer.next(); + if(hasNext) { + for(int i = 0; i < valSrcScorers.length; i++) { + valSrcScorers[i].skipTo(subQueryScorer.doc()); + } + } + return hasNext; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#doc() */ + public int doc() { + return subQueryScorer.doc(); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#score() */ + public float score() throws IOException { + for(int i = 0; i < valSrcScorers.length; i++) { + vScores[i] = valSrcScorers[i].score(); + } + return qWeight * customScore(subQueryScorer.doc(), subQueryScorer.score(), vScores); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#skipTo(int) */ + public boolean skipTo(int target) throws IOException { + boolean hasNext = subQueryScorer.skipTo(target); + if(hasNext) { + for(int i = 0; i < valSrcScorers.length; i++) { + valSrcScorers[i].skipTo(subQueryScorer.doc()); + } + } + return hasNext; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#explain(int) */ + public Explanation explain(int doc) throws IOException { + Explanation subQueryExpl = weight.subQueryWeight.explain(reader,doc); + if (!subQueryExpl.isMatch()) { + return subQueryExpl; + } + // match + Explanation[] valSrcExpls = new Explanation[valSrcScorers.length]; + for(int i = 0; i < valSrcScorers.length; i++) { + valSrcExpls[i] = valSrcScorers[i].explain(doc); + } + Explanation customExp = customExplain(doc,subQueryExpl,valSrcExpls); + float sc = qWeight * customExp.getValue(); + Explanation res = new ComplexExplanation( + true, sc, CustomScoreQuery.this.toString() + ", product of:"); + res.addDetail(customExp); + res.addDetail(new Explanation(qWeight, "queryBoost")); // actually using the q boost as q weight (== weight value) + return res; + } + } + + /*(non-Javadoc) @see org.apache.lucene.search.Query#createWeight(org.apache.lucene.search.Searcher) */ + protected Weight createWeight(Searcher searcher) throws IOException { + return new CustomWeight(searcher); + } + + /** + * Checks if this is strict custom scoring. + * In strict custom scoring, the ValueSource part does not participate in weight normalization. + * This may be useful when one wants full control over how scores are modified, and does + * not care about normalizing by the ValueSource part. + * One particular case where this is useful if for testing this query. + *

+ * Note: only has effect when the ValueSource part is not null. + */ + public boolean isStrict() { + return strict; + } + + /** + * Set the strict mode of this query. + * @param strict The strict mode to set. + * @see #isStrict() + */ + public void setStrict(boolean strict) { + this.strict = strict; + } + + /** + * A short name of this query, used in {@link #toString(String)}. + */ + public String name() { + return "custom"; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/DocValues.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/DocValues.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/DocValues.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,170 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.search.Explanation; + +/** + * Expert: represents field values as different types. + * Normally created via a + * {@link org.apache.lucene.search.function.ValueSource ValueSuorce} + * for a particular field and reader. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * + */ +public abstract class DocValues { + /* + * DocValues is distinct from ValueSource because + * there needs to be an object created at query evaluation time that + * is not referenced by the query itself because: + * - Query objects should be MT safe + * - For caching, Query objects are often used as keys... you don't + * want the Query carrying around big objects + */ + + /** + * Return doc value as a float. + *

Mandatory: every DocValues implementation must implement at least this method. + * @param doc document whose float value is requested. + */ + public abstract float floatVal(int doc); + + /** + * Return doc value as an int. + *

Optional: DocValues implementation can (but don't have to) override this method. + * @param doc document whose int value is requested. + */ + public int intVal(int doc) { + return (int) floatVal(doc); + } + + /** + * Return doc value as a long. + *

Optional: DocValues implementation can (but don't have to) override this method. + * @param doc document whose long value is requested. + */ + public long longVal(int doc) { + return (long) floatVal(doc); + } + + /** + * Return doc value as a double. + *

Optional: DocValues implementation can (but don't have to) override this method. + * @param doc document whose double value is requested. + */ + public double doubleVal(int doc) { + return (double) floatVal(doc); + } + + /** + * Return doc value as a string. + *

Optional: DocValues implementation can (but don't have to) override this method. + * @param doc document whose string value is requested. + */ + public String strVal(int doc) { + return Float.toString(floatVal(doc)); + } + + /** + * Return a string representation of a doc value, as reuired for Explanations. + */ + public abstract String toString(int doc); + + /** + * Explain the scoring value for the input doc. + */ + public Explanation explain(int doc) { + return new Explanation(floatVal(doc), toString(doc)); + } + + /** + * Expert: for test purposes only, return the inner array of values, or null if not applicable. + *

+ * Allows tests to verify that loaded values are: + *

    + *
  1. indeed cached/reused.
  2. + *
  3. stored in the expected size/type (byte/short/int/float).
  4. + *
+ * Note: implementations of DocValues must override this method for + * these test elements to be tested, Otherwise the test would not fail, just + * print a warning. + */ + Object getInnerArray() { + throw new UnsupportedOperationException("this optional method is for test purposes only"); + } + + // --- some simple statistics on values + private float minVal; + private float maxVal; + private float avgVal; + private boolean computed=false; + // compute optional values + private void compute () { + if (computed) { + return; + } + minVal = Float.MAX_VALUE; + maxVal = 0; + float sum = 0; + int n = 0; + while (true) { + float val; + try { + val = floatVal(n); + } catch (ArrayIndexOutOfBoundsException e) { + break; + } + sum += val; + minVal = Math.min(minVal,val); + maxVal = Math.max(maxVal,val); + } + avgVal = sum / n; + computed = true; + } + /** + * Optional op. + * Returns the minimum of all values. + */ + public float getMinValue () { + compute(); + return minVal; + } + + /** + * Optional op. + * Returns the maximum of all values. + */ + public float getMaxValue () { + compute(); + return maxVal; + } + + /** + * Returns the average of all values. + */ + public float getAverageValue () { + compute(); + return avgVal; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/FieldCacheSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/FieldCacheSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/FieldCacheSource.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,101 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.FieldCache; + +/** + * Expert: A base class for ValueSource implementations that retrieve values for + * a single field from the {@link org.apache.lucene.search.FieldCache FieldCache}. + *

+ * Fields used herein nust be indexed (doesn't matter if these fields are stored or not). + *

+ * It is assumed that each such indexed field is untokenized, or at least has a single token in a document. + * For documents with multiple tokens of the same field, behavior is undefined (It is likely that current + * code would use the value of one of these tokens, but this is not guaranteed). + *

+ * Document with no tokens in this field are assigned the Zero value. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + */ +public abstract class FieldCacheSource extends ValueSource { + private String field; + + /** + * Create a cached field source for the input field. + */ + public FieldCacheSource(String field) { + this.field=field; + } + + /* (non-Javadoc) @see org.apache.lucene.search.function.ValueSource#getValues(org.apache.lucene.index.IndexReader) */ + public final DocValues getValues(IndexReader reader) throws IOException { + return getCachedFieldValues(FieldCache.DEFAULT, field, reader); + } + + /* (non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */ + public String description() { + return field; + } + + /** + * Return cached DocValues for input field and reader. + * @param cache FieldCache so that values of a field are loaded once per reader (RAM allowing) + * @param field Field for which values are required. + * @see ValueSource + */ + public abstract DocValues getCachedFieldValues(FieldCache cache, String field, IndexReader reader) throws IOException; + + /*(non-Javadoc) @see java.lang.Object#equals(java.lang.Object) */ + public final boolean equals(Object o) { + if (!(o instanceof FieldCacheSource)) { + return false; + } + FieldCacheSource other = (FieldCacheSource) o; + return + this.field.equals(other.field) && + cachedFieldSourceEquals(other); + } + + /*(non-Javadoc) @see java.lang.Object#hashCode() */ + public final int hashCode() { + return + field.hashCode() + + cachedFieldSourceHashCode(); + } + + /** + * Check if equals to another {@link FieldCacheSource}, already knowing that cache and field are equal. + * @see Object#equals(java.lang.Object) + */ + public abstract boolean cachedFieldSourceEquals(FieldCacheSource other); + + /** + * Return a hash code of a {@link FieldCacheSource}, without the hash-codes of the field + * and the cache (those are taken care of elsewhere). + * @see Object#hashCode() + */ + public abstract int cachedFieldSourceHashCode(); +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/FieldScoreQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/FieldScoreQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/FieldScoreQuery.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,127 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A query that scores each document as the value of the numeric input field. + *

+ * The query matches all documents, and scores each document according to the numeric + * value of that field. + *

+ * It is assumed, and expected, that: + *

    + *
  • The field used here is indexed, and has exactly + * one token in every scored document.
  • + *
  • Best if this field is un_tokenized.
  • + *
  • That token is parsable to the selected type.
  • + *
+ *

+ * Combining this query in a FunctionQuery allows much freedom in affecting document scores. + * Note, that with this freedom comes responsibility: it is more than likely that the + * default Lucene scoring is superior in quality to scoring modified as explained here. + * However, in some cases, and certainly for research experiments, this capability may turn useful. + *

+ * When contructing this query, select the appropriate type. That type should match the data stored in the + * field. So in fact the "right" type should be selected before indexing. Type selection + * has effect on the RAM usage: + *

    + *
  • {@link Type#BYTE} consumes 1 * maxDocs bytes.
  • + *
  • {@link Type#SHORT} consumes 2 * maxDocs bytes.
  • + *
  • {@link Type#INT} consumes 4 * maxDocs bytes.
  • + *
  • {@link Type#FLOAT} consumes 8 * maxDocs bytes.
  • + *
+ *

+ * Caching: + * Values for the numeric field are loaded once and cached in memory for further use with the same IndexReader. + * To take advantage of this, it is extremely important to reuse index-readers or index-searchers, + * otherwise, for instance if for each query a new index reader is opened, large penalties would be + * paid for loading the field values into memory over and over again! + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + */ +public class FieldScoreQuery extends ValueSourceQuery { + + /** + * Type of score field, indicating how field values are interpreted/parsed. + *

+ * The type selected at search search time should match the data stored in the field. + * Different types have different RAM requirements: + *

    + *
  • {@link #BYTE} consumes 1 * maxDocs bytes.
  • + *
  • {@link #SHORT} consumes 2 * maxDocs bytes.
  • + *
  • {@link #INT} consumes 4 * maxDocs bytes.
  • + *
  • {@link #FLOAT} consumes 8 * maxDocs bytes.
  • + *
+ */ + public static class Type { + + /** field values are interpreted as numeric byte values. */ + public static final Type BYTE = new Type("byte"); + + /** field values are interpreted as numeric short values. */ + public static final Type SHORT = new Type("short"); + + /** field values are interpreted as numeric int values. */ + public static final Type INT = new Type("int"); + + /** field values are interpreted as numeric float values. */ + public static final Type FLOAT = new Type("float"); + + private String typeName; + private Type (String name) { + this.typeName = name; + } + /*(non-Javadoc) @see java.lang.Object#toString() */ + public String toString() { + return getClass().getName()+"::"+typeName; + } + } + + /** + * Create a FieldScoreQuery - a query that scores each document as the value of the numeric input field. + *

+ * The type param tells how to parse the field string values into a numeric score value. + * @param field the numeric field to be used. + * @param type the type of the field: either + * {@link Type#BYTE}, {@link Type#SHORT}, {@link Type#INT}, or {@link Type#FLOAT}. + */ + public FieldScoreQuery(String field, Type type) { + super(getValueSource(field,type)); + } + + // create the appropriate (cached) field value source. + private static ValueSource getValueSource(String field, Type type) { + if (type == Type.BYTE) { + return new ByteFieldSource(field); + } + if (type == Type.SHORT) { + return new ShortFieldSource(field); + } + if (type == Type.INT) { + return new IntFieldSource(field); + } + if (type == Type.FLOAT) { + return new FloatFieldSource(field); + } + throw new IllegalArgumentException(type+" is not a known Field Score Query Type!"); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/FloatFieldSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/FloatFieldSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/FloatFieldSource.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,101 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.FieldCache; +import org.apache.lucene.search.function.DocValues; + +import java.io.IOException; + +/** + * Expert: obtains float field values from the + * {@link org.apache.lucene.search.FieldCache FieldCache} + * using getFloats() and makes those values + * available as other numeric types, casting as needed. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * @see org.apache.lucene.search.function.FieldCacheSource for requirements + * on the field. + * + */ +public class FloatFieldSource extends FieldCacheSource { + private FieldCache.FloatParser parser; + + /** + * Create a cached float field source with default string-to-float parser. + */ + public FloatFieldSource(String field) { + this(field, null); + } + + /** + * Create a cached float field source with a specific string-to-float parser. + */ + public FloatFieldSource(String field, FieldCache.FloatParser parser) { + super(field); + this.parser = parser; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */ + public String description() { + return "float(" + super.description() + ')'; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#getCachedValues(org.apache.lucene.search.FieldCache, java.lang.String, org.apache.lucene.index.IndexReader) */ + public DocValues getCachedFieldValues (FieldCache cache, String field, IndexReader reader) throws IOException { + final float[] arr = (parser==null) ? + cache.getFloats(reader, field) : + cache.getFloats(reader, field, parser); + return new DocValues() { + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */ + public float floatVal(int doc) { + return arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */ + public String toString(int doc) { + return description() + '=' + arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */ + Object getInnerArray() { + return arr; + } + }; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceEquals(org.apache.lucene.search.function.FieldCacheSource) */ + public boolean cachedFieldSourceEquals(FieldCacheSource o) { + if (o.getClass() != FloatFieldSource.class) { + return false; + } + FloatFieldSource other = (FloatFieldSource)o; + return this.parser==null ? + other.parser==null : + this.parser.getClass() == other.parser.getClass(); + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceHashCode() */ + public int cachedFieldSourceHashCode() { + return parser==null ? + Float.class.hashCode() : parser.getClass().hashCode(); + } +} \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/IntFieldSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/IntFieldSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/IntFieldSource.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,107 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.FieldCache; +import org.apache.lucene.search.function.DocValues; + +import java.io.IOException; + +/** + * Expert: obtains int field values from the + * {@link org.apache.lucene.search.FieldCache FieldCache} + * using getInts() and makes those values + * available as other numeric types, casting as needed. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * @see org.apache.lucene.search.function.FieldCacheSource for requirements + * on the field. + * + * + */ +public class IntFieldSource extends FieldCacheSource { + private FieldCache.IntParser parser; + + /** + * Create a cached int field source with default string-to-int parser. + */ + public IntFieldSource(String field) { + this(field, null); + } + + /** + * Create a cached int field source with a specific string-to-int parser. + */ + public IntFieldSource(String field, FieldCache.IntParser parser) { + super(field); + this.parser = parser; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */ + public String description() { + return "int(" + super.description() + ')'; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#getCachedValues(org.apache.lucene.search.FieldCache, java.lang.String, org.apache.lucene.index.IndexReader) */ + public DocValues getCachedFieldValues (FieldCache cache, String field, IndexReader reader) throws IOException { + final int[] arr = (parser==null) ? + cache.getInts(reader, field) : + cache.getInts(reader, field, parser); + return new DocValues() { + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */ + public float floatVal(int doc) { + return (float) arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#intVal(int) */ + public int intVal(int doc) { + return arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */ + public String toString(int doc) { + return description() + '=' + intVal(doc); + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */ + Object getInnerArray() { + return arr; + } + }; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceEquals(org.apache.lucene.search.function.FieldCacheSource) */ + public boolean cachedFieldSourceEquals(FieldCacheSource o) { + if (o.getClass() != IntFieldSource.class) { + return false; + } + IntFieldSource other = (IntFieldSource)o; + return this.parser==null ? + other.parser==null : + this.parser.getClass() == other.parser.getClass(); + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceHashCode() */ + public int cachedFieldSourceHashCode() { + return parser==null ? + Integer.class.hashCode() : parser.getClass().hashCode(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/OrdFieldSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/OrdFieldSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/OrdFieldSource.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,102 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.search.function; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.FieldCache; + +import java.io.IOException; + +/** + * Expert: obtains the ordinal of the field value from the default Lucene + * {@link org.apache.lucene.search.FieldCache Fieldcache} using getStringIndex(). + *

+ * The native lucene index order is used to assign an ordinal value for each field value. + *

+ * Example: + *
If there were only three field values: "apple","banana","pear" + *
then ord("apple")=1, ord("banana")=2, ord("pear")=3 + *

+ * WARNING: + * ord() depends on the position in an index and can thus change + * when other documents are inserted or deleted, + * or if a MultiSearcher is used. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + */ + +public class OrdFieldSource extends ValueSource { + protected String field; + + /** + * Contructor for a certain field. + * @param field field whose values order is used. + */ + public OrdFieldSource(String field) { + this.field = field; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */ + public String description() { + return "ord(" + field + ')'; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#getValues(org.apache.lucene.index.IndexReader) */ + public DocValues getValues(IndexReader reader) throws IOException { + final int[] arr = FieldCache.DEFAULT.getStringIndex(reader, field).order; + return new DocValues() { + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */ + public float floatVal(int doc) { + return (float)arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#strVal(int) */ + public String strVal(int doc) { + // the string value of the ordinal, not the string itself + return Integer.toString(arr[doc]); + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */ + public String toString(int doc) { + return description() + '=' + intVal(doc); + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */ + Object getInnerArray() { + return arr; + } + }; + } + + /*(non-Javadoc) @see java.lang.Object#equals(java.lang.Object) */ + public boolean equals(Object o) { + if (o.getClass() != OrdFieldSource.class) return false; + OrdFieldSource other = (OrdFieldSource)o; + return this.field.equals(other.field); + } + + private static final int hcode = OrdFieldSource.class.hashCode(); + + /*(non-Javadoc) @see java.lang.Object#hashCode() */ + public int hashCode() { + return hcode + field.hashCode(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/ReverseOrdFieldSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/ReverseOrdFieldSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/ReverseOrdFieldSource.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,111 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.search.function; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.FieldCache; + +import java.io.IOException; + +/** + * Expert: obtains the ordinal of the field value from the default Lucene + * {@link org.apache.lucene.search.FieldCache FieldCache} using getStringIndex() + * and reverses the order. + *

+ * The native lucene index order is used to assign an ordinal value for each field value. + *

+ * Field values (terms) are lexicographically ordered by unicode value, and numbered starting at 1. + *
+ * Example of reverse ordinal (rord): + *
If there were only three field values: "apple","banana","pear" + *
then rord("apple")=3, rord("banana")=2, ord("pear")=1 + *

+ * WARNING: + * rord() depends on the position in an index and can thus change + * when other documents are inserted or deleted, + * or if a MultiSearcher is used. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + */ + +public class ReverseOrdFieldSource extends ValueSource { + public String field; + + /** + * Contructor for a certain field. + * @param field field whose values reverse order is used. + */ + public ReverseOrdFieldSource(String field) { + this.field = field; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */ + public String description() { + return "rord("+field+')'; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#getValues(org.apache.lucene.index.IndexReader) */ + public DocValues getValues(IndexReader reader) throws IOException { + final FieldCache.StringIndex sindex = FieldCache.DEFAULT.getStringIndex(reader, field); + + final int arr[] = sindex.order; + final int end = sindex.lookup.length; + + return new DocValues() { + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */ + public float floatVal(int doc) { + return (float)(end - arr[doc]); + } + /* (non-Javadoc) @see org.apache.lucene.search.function.DocValues#intVal(int) */ + public int intVal(int doc) { + return end - arr[doc]; + } + /* (non-Javadoc) @see org.apache.lucene.search.function.DocValues#strVal(int) */ + public String strVal(int doc) { + // the string value of the ordinal, not the string itself + return Integer.toString(intVal(doc)); + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */ + public String toString(int doc) { + return description() + '=' + strVal(doc); + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */ + Object getInnerArray() { + return arr; + } + }; + } + + /*(non-Javadoc) @see java.lang.Object#equals(java.lang.Object) */ + public boolean equals(Object o) { + if (o.getClass() != ReverseOrdFieldSource.class) return false; + ReverseOrdFieldSource other = (ReverseOrdFieldSource)o; + return this.field.equals(other.field); + } + + private static final int hcode = ReverseOrdFieldSource.class.hashCode(); + + /*(non-Javadoc) @see java.lang.Object#hashCode() */ + public int hashCode() { + return hcode + field.hashCode(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/ShortFieldSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/ShortFieldSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/ShortFieldSource.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,105 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.FieldCache; +import org.apache.lucene.search.function.DocValues; + +import java.io.IOException; + +/** + * Expert: obtains short field values from the + * {@link org.apache.lucene.search.FieldCache FieldCache} + * using getShorts() and makes those values + * available as other numeric types, casting as needed. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * @see org.apache.lucene.search.function.FieldCacheSource for requirements + * on the field. + */ +public class ShortFieldSource extends FieldCacheSource { + private FieldCache.ShortParser parser; + + /** + * Create a cached short field source with default string-to-short parser. + */ + public ShortFieldSource(String field) { + this(field, null); + } + + /** + * Create a cached short field source with a specific string-to-short parser. + */ + public ShortFieldSource(String field, FieldCache.ShortParser parser) { + super(field); + this.parser = parser; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */ + public String description() { + return "short(" + super.description() + ')'; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#getCachedValues(org.apache.lucene.search.FieldCache, java.lang.String, org.apache.lucene.index.IndexReader) */ + public DocValues getCachedFieldValues (FieldCache cache, String field, IndexReader reader) throws IOException { + final short[] arr = (parser==null) ? + cache.getShorts(reader, field) : + cache.getShorts(reader, field, parser); + return new DocValues() { + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */ + public float floatVal(int doc) { + return (float) arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#intVal(int) */ + public int intVal(int doc) { + return arr[doc]; + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */ + public String toString(int doc) { + return description() + '=' + intVal(doc); + } + /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */ + Object getInnerArray() { + return arr; + } + }; + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceEquals(org.apache.lucene.search.function.FieldCacheSource) */ + public boolean cachedFieldSourceEquals(FieldCacheSource o) { + if (o.getClass() != ShortFieldSource.class) { + return false; + } + ShortFieldSource other = (ShortFieldSource)o; + return this.parser==null ? + other.parser==null : + this.parser.getClass() == other.parser.getClass(); + } + + /*(non-Javadoc) @see org.apache.lucene.search.function.FieldCacheSource#cachedFieldSourceHashCode() */ + public int cachedFieldSourceHashCode() { + return parser==null ? + Short.class.hashCode() : parser.getClass().hashCode(); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/ValueSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/ValueSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/ValueSource.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,73 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.function.DocValues; + +import java.io.IOException; +import java.io.Serializable; + +/** + * Expert: source of values for basic function queries. + *

At its default/simplest form, values - one per doc - are used as the score of that doc. + *

Values are instantiated as + * {@link org.apache.lucene.search.function.DocValues DocValues} for a particular reader. + *

ValueSource implementations differ in RAM requirements: it would always be a factor + * of the number of documents, but for each document the number of bytes can be 1, 2, 4, or 8. + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * + */ +public abstract class ValueSource implements Serializable { + + /** + * Return the DocValues used by the function query. + * @param reader the IndexReader used to read these values. + * If any caching is involved, that caching would also be IndexReader based. + * @throws IOException for any error. + */ + public abstract DocValues getValues(IndexReader reader) throws IOException; + + /** + * description of field, used in explain() + */ + public abstract String description(); + + /* (non-Javadoc) @see java.lang.Object#toString() */ + public String toString() { + return description(); + } + + /** + * Needed for possible caching of query results - used by {@link ValueSourceQuery#equals(Object)}. + * @see Object#equals(Object) + */ + public abstract boolean equals(Object o); + + /** + * Needed for possible caching of query results - used by {@link ValueSourceQuery#hashCode()}. + * @see Object#hashCode() + */ + public abstract int hashCode(); + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/ValueSourceQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/ValueSourceQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/ValueSourceQuery.java 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,199 @@ +package org.apache.lucene.search.function; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.*; +import org.apache.lucene.util.ToStringUtils; + +import java.io.IOException; +import java.util.Set; + +/** + * Expert: A Query that sets the scores of document to the + * values obtained from a {@link org.apache.lucene.search.function.ValueSource ValueSource}. + *

+ * The value source can be based on a (cached) value of an indexed field, but it + * can also be based on an external source, e.g. values read from an external database. + *

+ * Score is set as: Score(doc,query) = query.getBoost()2 * valueSource(doc). + * + *

+ * WARNING: The status of the search.function package is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + */ +public class ValueSourceQuery extends Query { + ValueSource valSrc; + + /** + * Create a value source query + * @param valSrc provides the values defines the function to be used for scoring + */ + public ValueSourceQuery(ValueSource valSrc) { + this.valSrc=valSrc; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Query#rewrite(org.apache.lucene.index.IndexReader) */ + public Query rewrite(IndexReader reader) throws IOException { + return this; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Query#extractTerms(java.util.Set) */ + public void extractTerms(Set terms) { + // no terms involved here + } + + private class ValueSourceWeight implements Weight { + Similarity similarity; + float queryNorm; + float queryWeight; + + public ValueSourceWeight(Searcher searcher) { + this.similarity = getSimilarity(searcher); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#getQuery() */ + public Query getQuery() { + return ValueSourceQuery.this; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#getValue() */ + public float getValue() { + return queryWeight; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#sumOfSquaredWeights() */ + public float sumOfSquaredWeights() throws IOException { + queryWeight = getBoost(); + return queryWeight * queryWeight; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#normalize(float) */ + public void normalize(float norm) { + this.queryNorm = norm; + queryWeight *= this.queryNorm; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#scorer(org.apache.lucene.index.IndexReader) */ + public Scorer scorer(IndexReader reader) throws IOException { + return new ValueSourceScorer(similarity, reader, this); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Weight#explain(org.apache.lucene.index.IndexReader, int) */ + public Explanation explain(IndexReader reader, int doc) throws IOException { + return scorer(reader).explain(doc); + } + } + + /** + * A scorer that (simply) matches all documents, and scores each document with + * the value of the value soure in effect. As an example, if the value source + * is a (cached) field source, then value of that field in that document will + * be used. (assuming field is indexed for this doc, with a single token.) + */ + private class ValueSourceScorer extends Scorer { + private final IndexReader reader; + private final ValueSourceWeight weight; + private final int maxDoc; + private final float qWeight; + private int doc=-1; + private final DocValues vals; + + // constructor + private ValueSourceScorer(Similarity similarity, IndexReader reader, ValueSourceWeight w) throws IOException { + super(similarity); + this.weight = w; + this.qWeight = w.getValue(); + this.reader = reader; + this.maxDoc = reader.maxDoc(); + // this is when/where the values are first created. + vals = valSrc.getValues(reader); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#next() */ + public boolean next() throws IOException { + for(;;) { + ++doc; + if (doc>=maxDoc) { + return false; + } + if (reader.isDeleted(doc)) { + continue; + } + return true; + } + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#doc() + */ + public int doc() { + return doc; + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#score() */ + public float score() throws IOException { + return qWeight * vals.floatVal(doc); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#skipTo(int) */ + public boolean skipTo(int target) throws IOException { + doc=target-1; + return next(); + } + + /*(non-Javadoc) @see org.apache.lucene.search.Scorer#explain(int) */ + public Explanation explain(int doc) throws IOException { + float sc = qWeight * vals.floatVal(doc); + + Explanation result = new ComplexExplanation( + true, sc, ValueSourceQuery.this.toString() + ", product of:"); + + result.addDetail(vals.explain(doc)); + result.addDetail(new Explanation(getBoost(), "boost")); + result.addDetail(new Explanation(weight.queryNorm,"queryNorm")); + return result; + } + } + + /*(non-Javadoc) @see org.apache.lucene.search.Query#createWeight(org.apache.lucene.search.Searcher) */ + protected Weight createWeight(Searcher searcher) { + return new ValueSourceQuery.ValueSourceWeight(searcher); + } + + /* (non-Javadoc) @see org.apache.lucene.search.Query#toString(java.lang.String) */ + public String toString(String field) { + return valSrc.toString() + ToStringUtils.boost(getBoost()); + } + + /** Returns true if o is equal to this. */ + public boolean equals(Object o) { + if (getClass() != o.getClass()) { + return false; + } + ValueSourceQuery other = (ValueSourceQuery)o; + return this.getBoost() == other.getBoost() + && this.valSrc.equals(other.valSrc); + } + + /** Returns a hash code value for this object. */ + public int hashCode() { + return (getClass().hashCode() + valSrc.hashCode()) ^ Float.floatToIntBits(getBoost()); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/function/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/function/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/function/package.html 17 Aug 2012 14:55:04 -0000 1.1 @@ -0,0 +1,197 @@ + + + + org.apache.lucene.search.function + + +

+ Programmatic control over documents scores. +
+
+ The function package provides tight control over documents scores. +
+
+ +WARNING: The status of the search.function package is experimental. The APIs +introduced here might change in the future and will not be supported anymore +in such a case. + +
+
+ Two types of queries are available in this package: +
+
+
    +
  1. + Custom Score queries - allowing to set the score + of a matching document as a mathematical expression over scores + of that document by contained (sub) queries. +
  2. +
  3. + Field score queries - allowing to base the score of a + document on numeric values of indexed fields. +
  4. +
+
+
 
+
+ Some possible uses of these queries: +
+
+
    +
  1. + Normalizing the document scores by values indexed in a special field - + for instance, experimenting with a different doc length normalization. +
  2. +
  3. + Introducing some static scoring element, to the score of a document, - + for instance using some topological attribute of the links to/from a document. +
  4. +
  5. + Computing the score of a matching document as an arbitrary odd function of + its score by a certain query. +
  6. +
+
+
+ Performance and Quality Considerations: +
+
+
    +
  1. + When scoring by values of indexed fields, + these values are loaded into memory. + Unlike the regular scoring, where the required information is read from + disk as necessary, here field values are loaded once and cached by Lucene in memory + for further use, anticipating reuse by further queries. While all this is carefully + cached with performance in mind, it is recommended to + use these features only when the default Lucene scoring does + not match your "special" application needs. +
  2. +
  3. + Use only with carefully selected fields, because in most cases, + search quality with regular Lucene scoring + would outperform that of scoring by field values. +
  4. +
  5. + Values of fields used for scoring should match. + Do not apply on a field containing arbitrary (long) text. + Do not mix values in the same field if that field is used for scoring. +
  6. +
  7. + Smaller (shorter) field tokens means less RAM (something always desired). + When using FieldScoreQuery, + select the shortest FieldScoreQuery.Type + that is sufficient for the used field values. +
  8. +
  9. + Reusing IndexReaders/IndexSearchers is essential, because the caching of field tokens + is based on an IndexReader. Whenever a new IndexReader is used, values currently in the cache + cannot be used and new values must be loaded from disk. So replace/refresh readers/searchers in + a controlled manner. +
  10. +
+
+
+ History and Credits: +
    +
  • + A large part of the code of this package was originated from Yonik's FunctionQuery code that was + imported from Solr + (see LUCENE-446). +
  • +
  • + The idea behind CustomScoreQurey is borrowed from + the "Easily create queries that transform sub-query scores arbitrarily" contribution by Mike Klaas + (see LUCENE-850) + though the implementation and API here are different. +
  • +
+
+
+ Code sample: +

+ Note: code snippets here should work, but they were never really compiled... so, + tests sources under TestCustomScoreQuery, TestFieldScoreQuery and TestOrdValues + may also be useful. +

    +
  1. + Using field (byte) values to as scores: +

    + Indexing: +

    +      f = new Field("score", "7", Field.Store.NO, Field.Index.UN_TOKENIZED);
    +      f.setOmitNorms(true);
    +      d1.add(f);
    +    
    +

    + Search: +

    +      Query q = new FieldScoreQuery("score", FieldScoreQuery.Type.BYTE);
    +    
    + Document d1 above would get a score of 7. +
  2. +

    +

  3. + Manipulating scores +

    + Dividing the original score of each document by a square root of its docid + (just to demonstrate what it takes to manipulate scores this way) +

    +      Query q = queryParser.parse("my query text");
    +      CustomScoreQuery customQ = new CustomScoreQuery(q) {
    +        public float customScore(int doc, float subQueryScore, float valSrcScore) {
    +          return subQueryScore / Math.sqrt(docid);
    +        }
    +      };
    +    
    +

    + For more informative debug info on the custom query, also override the name() method: +

    +      CustomScoreQuery customQ = new CustomScoreQuery(q) {
    +        public float customScore(int doc, float subQueryScore, float valSrcScore) {
    +          return subQueryScore / Math.sqrt(docid);
    +        }
    +        public String name() {
    +          return "1/sqrt(docid)";
    +        }
    +      };
    +    
    +

    + Taking the square root of the original score and multiplying it by a "short field driven score", ie, the + short value that was indexed for the scored doc in a certain field: +

    +      Query q = queryParser.parse("my query text");
    +      FieldScoreQuery qf = new FieldScoreQuery("shortScore", FieldScoreQuery.Type.SHORT);
    +      CustomScoreQuery customQ = new CustomScoreQuery(q,qf) {
    +        public float customScore(int doc, float subQueryScore, float valSrcScore) {
    +          return Math.sqrt(subQueryScore) * valSrcScore;
    +        }
    +        public String name() {
    +          return "shortVal*sqrt(score)";
    +        }
    +      };
    +    
    + +
  4. +
+
+ + \ No newline at end of file Index: 3rdParty_sources/lucene/org/apache/lucene/search/payloads/BoostingTermQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/payloads/BoostingTermQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/payloads/BoostingTermQuery.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,158 @@ +package org.apache.lucene.search.payloads; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermPositions; +import org.apache.lucene.search.*; +import org.apache.lucene.search.spans.SpanScorer; +import org.apache.lucene.search.spans.SpanTermQuery; +import org.apache.lucene.search.spans.SpanWeight; +import org.apache.lucene.search.spans.TermSpans; + +import java.io.IOException; + +/** + * Copyright 2004 The Apache Software Foundation + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The BoostingTermQuery is very similar to the {@link org.apache.lucene.search.spans.SpanTermQuery} except + * that it factors in the value of the payload located at each of the positions where the + * {@link org.apache.lucene.index.Term} occurs. + *

+ * In order to take advantage of this, you must override {@link org.apache.lucene.search.Similarity#scorePayload(String, byte[],int,int)} + * which returns 1 by default. + *

+ * Payload scores are averaged across term occurrences in the document. + * + * @see org.apache.lucene.search.Similarity#scorePayload(String, byte[], int, int) + */ +public class BoostingTermQuery extends SpanTermQuery{ + + + public BoostingTermQuery(Term term) { + super(term); + } + + + protected Weight createWeight(Searcher searcher) throws IOException { + return new BoostingTermWeight(this, searcher); + } + + protected class BoostingTermWeight extends SpanWeight implements Weight { + + + public BoostingTermWeight(BoostingTermQuery query, Searcher searcher) throws IOException { + super(query, searcher); + } + + + + + public Scorer scorer(IndexReader reader) throws IOException { + return new BoostingSpanScorer((TermSpans)query.getSpans(reader), this, similarity, + reader.norms(query.getField())); + } + + protected class BoostingSpanScorer extends SpanScorer { + + //TODO: is this the best way to allocate this? + byte[] payload = new byte[256]; + private TermPositions positions; + protected float payloadScore; + private int payloadsSeen; + + public BoostingSpanScorer(TermSpans spans, Weight weight, + Similarity similarity, byte[] norms) throws IOException { + super(spans, weight, similarity, norms); + positions = spans.getPositions(); + + } + + protected boolean setFreqCurrentDoc() throws IOException { + if (!more) { + return false; + } + doc = spans.doc(); + freq = 0.0f; + payloadScore = 0; + payloadsSeen = 0; + Similarity similarity1 = getSimilarity(); + while (more && doc == spans.doc()) { + int matchLength = spans.end() - spans.start(); + + freq += similarity1.sloppyFreq(matchLength); + processPayload(similarity1); + + more = spans.next();//this moves positions to the next match in this document + } + return more || (freq != 0); + } + + + protected void processPayload(Similarity similarity) throws IOException { + if (positions.isPayloadAvailable()) { + payload = positions.getPayload(payload, 0); + payloadScore += similarity.scorePayload(term.field(), payload, 0, positions.getPayloadLength()); + payloadsSeen++; + + } else { + //zero out the payload? + } + + } + + public float score() throws IOException { + + return super.score() * (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1); + } + + + public Explanation explain(final int doc) throws IOException { + ComplexExplanation result = new ComplexExplanation(); + Explanation nonPayloadExpl = super.explain(doc); + result.addDetail(nonPayloadExpl); + //QUESTION: Is there a wau to avoid this skipTo call? We need to know whether to load the payload or not + + Explanation payloadBoost = new Explanation(); + result.addDetail(payloadBoost); +/* + if (skipTo(doc) == true) { + processPayload(); + } +*/ + + float avgPayloadScore = (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1); + payloadBoost.setValue(avgPayloadScore); + //GSI: I suppose we could toString the payload, but I don't think that would be a good idea + payloadBoost.setDescription("scorePayload(...)"); + result.setValue(nonPayloadExpl.getValue() * avgPayloadScore); + result.setDescription("btq, product of:"); + result.setMatch(nonPayloadExpl.getValue()==0 ? Boolean.FALSE : Boolean.TRUE); // LUCENE-1303 + return result; + } + } + + } + + + public boolean equals(Object o) { + if (!(o instanceof BoostingTermQuery)) + return false; + BoostingTermQuery other = (BoostingTermQuery) o; + return (this.getBoost() == other.getBoost()) + && this.term.equals(other.term); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/payloads/PayloadSpanUtil.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/payloads/PayloadSpanUtil.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/payloads/PayloadSpanUtil.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,190 @@ +package org.apache.lucene.search.payloads; + +import org.apache.lucene.search.BooleanClause; +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.DisjunctionMaxQuery; +import org.apache.lucene.search.FilteredQuery; +import org.apache.lucene.search.MultiPhraseQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.spans.PayloadSpans; +import org.apache.lucene.search.spans.SpanNearQuery; +import org.apache.lucene.search.spans.SpanOrQuery; +import org.apache.lucene.search.spans.SpanQuery; +import org.apache.lucene.search.spans.SpanTermQuery; + +/** + * Experimental class to get set of payloads for most standard Lucene queries. + * Operates like Highlighter - IndexReader should only contain doc of interest, + * best to use MemoryIndex. + * + *

+ * + * WARNING: The status of the Payloads feature is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + */ +public class PayloadSpanUtil { + private IndexReader reader; + + /** + * @param reader + * that contains doc with payloads to extract + */ + public PayloadSpanUtil(IndexReader reader) { + this.reader = reader; + } + + /** + * Query should be rewritten for wild/fuzzy support. + * + * @param query + * @return payloads Collection + * @throws IOException + */ + public Collection getPayloadsForQuery(Query query) throws IOException { + Collection payloads = new ArrayList(); + queryToSpanQuery(query, payloads); + return payloads; + } + + private void queryToSpanQuery(Query query, Collection payloads) + throws IOException { + if (query instanceof BooleanQuery) { + BooleanClause[] queryClauses = ((BooleanQuery) query).getClauses(); + + for (int i = 0; i < queryClauses.length; i++) { + if (!queryClauses[i].isProhibited()) { + queryToSpanQuery(queryClauses[i].getQuery(), payloads); + } + } + + } else if (query instanceof PhraseQuery) { + Term[] phraseQueryTerms = ((PhraseQuery) query).getTerms(); + SpanQuery[] clauses = new SpanQuery[phraseQueryTerms.length]; + for (int i = 0; i < phraseQueryTerms.length; i++) { + clauses[i] = new SpanTermQuery(phraseQueryTerms[i]); + } + + int slop = ((PhraseQuery) query).getSlop(); + boolean inorder = false; + + if (slop == 0) { + inorder = true; + } + + SpanNearQuery sp = new SpanNearQuery(clauses, slop, inorder); + sp.setBoost(query.getBoost()); + getPayloads(payloads, sp); + } else if (query instanceof TermQuery) { + SpanTermQuery stq = new SpanTermQuery(((TermQuery) query).getTerm()); + stq.setBoost(query.getBoost()); + getPayloads(payloads, stq); + } else if (query instanceof SpanQuery) { + getPayloads(payloads, (SpanQuery) query); + } else if (query instanceof FilteredQuery) { + queryToSpanQuery(((FilteredQuery) query).getQuery(), payloads); + } else if (query instanceof DisjunctionMaxQuery) { + + for (Iterator iterator = ((DisjunctionMaxQuery) query).iterator(); iterator + .hasNext();) { + queryToSpanQuery((Query) iterator.next(), payloads); + } + + } else if (query instanceof MultiPhraseQuery) { + final MultiPhraseQuery mpq = (MultiPhraseQuery) query; + final List termArrays = mpq.getTermArrays(); + final int[] positions = mpq.getPositions(); + if (positions.length > 0) { + + int maxPosition = positions[positions.length - 1]; + for (int i = 0; i < positions.length - 1; ++i) { + if (positions[i] > maxPosition) { + maxPosition = positions[i]; + } + } + + final List[] disjunctLists = new List[maxPosition + 1]; + int distinctPositions = 0; + + for (int i = 0; i < termArrays.size(); ++i) { + final Term[] termArray = (Term[]) termArrays.get(i); + List disjuncts = disjunctLists[positions[i]]; + if (disjuncts == null) { + disjuncts = (disjunctLists[positions[i]] = new ArrayList( + termArray.length)); + ++distinctPositions; + } + for (int j = 0; j < termArray.length; ++j) { + disjuncts.add(new SpanTermQuery(termArray[j])); + } + } + + int positionGaps = 0; + int position = 0; + final SpanQuery[] clauses = new SpanQuery[distinctPositions]; + for (int i = 0; i < disjunctLists.length; ++i) { + List disjuncts = disjunctLists[i]; + if (disjuncts != null) { + clauses[position++] = new SpanOrQuery((SpanQuery[]) disjuncts + .toArray(new SpanQuery[disjuncts.size()])); + } else { + ++positionGaps; + } + } + + final int slop = mpq.getSlop(); + final boolean inorder = (slop == 0); + + SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps, + inorder); + sp.setBoost(query.getBoost()); + getPayloads(payloads, sp); + } + } + } + + private void getPayloads(Collection payloads, SpanQuery query) + throws IOException { + PayloadSpans spans = query.getPayloadSpans(reader); + + while (spans.next() == true) { + if (spans.isPayloadAvailable()) { + Collection payload = spans.getPayload(); + Iterator it = payload.iterator(); + while (it.hasNext()) { + byte[] bytes = (byte[]) it.next(); + payloads.add(bytes); + } + + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/payloads/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/payloads/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/payloads/package.html 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,36 @@ + + + org.apache.lucene.search.payloads + + +

The payloads package provides Query mechanisms for finding and using payloads. + + The following Query implementations are provided: +
+
+
    +
  1. BoostingTermQuery -- Boost a term's score based on the value of the payload located at that term
  2. +
+
+
 
+
+
+ + Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/NearSpansOrdered.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/NearSpansOrdered.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/NearSpansOrdered.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,291 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; +import java.util.Collection; + +/** A Spans that is formed from the ordered subspans of a SpanNearQuery + * where the subspans do not overlap and have a maximum slop between them. + *

+ * The formed spans only contains minimum slop matches.
+ * The matching slop is computed from the distance(s) between + * the non overlapping matching Spans.
+ * Successive matches are always formed from the successive Spans + * of the SpanNearQuery. + *

+ * The formed spans may contain overlaps when the slop is at least 1. + * For example, when querying using + *

t1 t2 t3
+ * with slop at least 1, the fragment: + *
t1 t2 t1 t3 t2 t3
+ * matches twice: + *
t1 t2 .. t3      
+ *
      t1 .. t2 t3
+ */ +class NearSpansOrdered implements PayloadSpans { + private final int allowedSlop; + private boolean firstTime = true; + private boolean more = false; + + /** The spans in the same order as the SpanNearQuery */ + private final PayloadSpans[] subSpans; + + /** Indicates that all subSpans have same doc() */ + private boolean inSameDoc = false; + + private int matchDoc = -1; + private int matchStart = -1; + private int matchEnd = -1; + private List/**/ matchPayload; + + private final PayloadSpans[] subSpansByDoc; + private final Comparator spanDocComparator = new Comparator() { + public int compare(Object o1, Object o2) { + return ((Spans)o1).doc() - ((Spans)o2).doc(); + } + }; + + private SpanNearQuery query; + + public NearSpansOrdered(SpanNearQuery spanNearQuery, IndexReader reader) + throws IOException { + if (spanNearQuery.getClauses().length < 2) { + throw new IllegalArgumentException("Less than 2 clauses: " + + spanNearQuery); + } + allowedSlop = spanNearQuery.getSlop(); + SpanQuery[] clauses = spanNearQuery.getClauses(); + subSpans = new PayloadSpans[clauses.length]; + matchPayload = new LinkedList(); + subSpansByDoc = new PayloadSpans[clauses.length]; + for (int i = 0; i < clauses.length; i++) { + subSpans[i] = clauses[i].getPayloadSpans(reader); + subSpansByDoc[i] = subSpans[i]; // used in toSameDoc() + } + query = spanNearQuery; // kept for toString() only. + } + + // inherit javadocs + public int doc() { return matchDoc; } + + // inherit javadocs + public int start() { return matchStart; } + + // inherit javadocs + public int end() { return matchEnd; } + + // TODO: Remove warning after API has been finalized + public Collection/**/ getPayload() throws IOException { + return matchPayload; + } + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return matchPayload.isEmpty() == false; + } + + // inherit javadocs + public boolean next() throws IOException { + if (firstTime) { + firstTime = false; + for (int i = 0; i < subSpans.length; i++) { + if (! subSpans[i].next()) { + more = false; + return false; + } + } + more = true; + } + matchPayload.clear(); + return advanceAfterOrdered(); + } + + // inherit javadocs + public boolean skipTo(int target) throws IOException { + if (firstTime) { + firstTime = false; + for (int i = 0; i < subSpans.length; i++) { + if (! subSpans[i].skipTo(target)) { + more = false; + return false; + } + } + more = true; + } else if (more && (subSpans[0].doc() < target)) { + if (subSpans[0].skipTo(target)) { + inSameDoc = false; + } else { + more = false; + return false; + } + } + matchPayload.clear(); + return advanceAfterOrdered(); + } + + /** Advances the subSpans to just after an ordered match with a minimum slop + * that is smaller than the slop allowed by the SpanNearQuery. + * @return true iff there is such a match. + */ + private boolean advanceAfterOrdered() throws IOException { + while (more && (inSameDoc || toSameDoc())) { + if (stretchToOrder() && shrinkToAfterShortestMatch()) { + return true; + } + } + return false; // no more matches + } + + + /** Advance the subSpans to the same document */ + private boolean toSameDoc() throws IOException { + Arrays.sort(subSpansByDoc, spanDocComparator); + int firstIndex = 0; + int maxDoc = subSpansByDoc[subSpansByDoc.length - 1].doc(); + while (subSpansByDoc[firstIndex].doc() != maxDoc) { + if (! subSpansByDoc[firstIndex].skipTo(maxDoc)) { + more = false; + inSameDoc = false; + return false; + } + maxDoc = subSpansByDoc[firstIndex].doc(); + if (++firstIndex == subSpansByDoc.length) { + firstIndex = 0; + } + } + for (int i = 0; i < subSpansByDoc.length; i++) { + assert (subSpansByDoc[i].doc() == maxDoc) + : " NearSpansOrdered.toSameDoc() spans " + subSpansByDoc[0] + + "\n at doc " + subSpansByDoc[i].doc() + + ", but should be at " + maxDoc; + } + inSameDoc = true; + return true; + } + + /** Check whether two Spans in the same document are ordered. + * @param spans1 + * @param spans2 + * @return true iff spans1 starts before spans2 + * or the spans start at the same position, + * and spans1 ends before spans2. + */ + static final boolean docSpansOrdered(Spans spans1, Spans spans2) { + assert spans1.doc() == spans2.doc() : "doc1 " + spans1.doc() + " != doc2 " + spans2.doc(); + int start1 = spans1.start(); + int start2 = spans2.start(); + /* Do not call docSpansOrdered(int,int,int,int) to avoid invoking .end() : */ + return (start1 == start2) ? (spans1.end() < spans2.end()) : (start1 < start2); + } + + /** Like {@link #docSpansOrdered(Spans,Spans)}, but use the spans + * starts and ends as parameters. + */ + private static final boolean docSpansOrdered(int start1, int end1, int start2, int end2) { + return (start1 == start2) ? (end1 < end2) : (start1 < start2); + } + + /** Order the subSpans within the same document by advancing all later spans + * after the previous one. + */ + private boolean stretchToOrder() throws IOException { + matchDoc = subSpans[0].doc(); + for (int i = 1; inSameDoc && (i < subSpans.length); i++) { + while (! docSpansOrdered(subSpans[i-1], subSpans[i])) { + if (! subSpans[i].next()) { + inSameDoc = false; + more = false; + break; + } else if (matchDoc != subSpans[i].doc()) { + inSameDoc = false; + break; + } + } + } + return inSameDoc; + } + + /** The subSpans are ordered in the same doc, so there is a possible match. + * Compute the slop while making the match as short as possible by advancing + * all subSpans except the last one in reverse order. + */ + private boolean shrinkToAfterShortestMatch() throws IOException { + matchStart = subSpans[subSpans.length - 1].start(); + matchEnd = subSpans[subSpans.length - 1].end(); + if (subSpans[subSpans.length - 1].isPayloadAvailable()) { + matchPayload.addAll(subSpans[subSpans.length - 1].getPayload()); + } + int matchSlop = 0; + int lastStart = matchStart; + int lastEnd = matchEnd; + for (int i = subSpans.length - 2; i >= 0; i--) { + PayloadSpans prevSpans = subSpans[i]; + + if (subSpans[i].isPayloadAvailable()) { + matchPayload.addAll(0, subSpans[i].getPayload()); + } + + int prevStart = prevSpans.start(); + int prevEnd = prevSpans.end(); + while (true) { // Advance prevSpans until after (lastStart, lastEnd) + if (! prevSpans.next()) { + inSameDoc = false; + more = false; + break; // Check remaining subSpans for final match. + } else if (matchDoc != prevSpans.doc()) { + inSameDoc = false; // The last subSpans is not advanced here. + break; // Check remaining subSpans for last match in this document. + } else { + int ppStart = prevSpans.start(); + int ppEnd = prevSpans.end(); // Cannot avoid invoking .end() + if (! docSpansOrdered(ppStart, ppEnd, lastStart, lastEnd)) { + break; // Check remaining subSpans. + } else { // prevSpans still before (lastStart, lastEnd) + prevStart = ppStart; + prevEnd = ppEnd; + } + } + } + assert prevStart <= matchStart; + if (matchStart > prevEnd) { // Only non overlapping spans add to slop. + matchSlop += (matchStart - prevEnd); + } + + /* Do not break on (matchSlop > allowedSlop) here to make sure + * that subSpans[0] is advanced after the match, if any. + */ + matchStart = prevStart; + lastStart = prevStart; + lastEnd = prevEnd; + } + return matchSlop <= allowedSlop; // ordered and allowed slop + } + + public String toString() { + return getClass().getName() + "("+query.toString()+")@"+ + (firstTime?"START":(more?(doc()+":"+start()+"-"+end()):"END")); + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/NearSpansUnordered.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/NearSpansUnordered.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/NearSpansUnordered.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,290 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.PriorityQueue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.HashSet; + +class NearSpansUnordered implements PayloadSpans { + private SpanNearQuery query; + + private List ordered = new ArrayList(); // spans in query order + private int slop; // from query + + private SpansCell first; // linked list of spans + private SpansCell last; // sorted by doc only + + private int totalLength; // sum of current lengths + + private CellQueue queue; // sorted queue of spans + private SpansCell max; // max element in queue + + private boolean more = true; // true iff not done + private boolean firstTime = true; // true before first next() + + private class CellQueue extends PriorityQueue { + public CellQueue(int size) { + initialize(size); + } + + protected final boolean lessThan(Object o1, Object o2) { + SpansCell spans1 = (SpansCell)o1; + SpansCell spans2 = (SpansCell)o2; + if (spans1.doc() == spans2.doc()) { + return NearSpansOrdered.docSpansOrdered(spans1, spans2); + } else { + return spans1.doc() < spans2.doc(); + } + } + } + + + /** Wraps a Spans, and can be used to form a linked list. */ + private class SpansCell implements PayloadSpans { + private PayloadSpans spans; + private SpansCell next; + private int length = -1; + private int index; + + public SpansCell(PayloadSpans spans, int index) { + this.spans = spans; + this.index = index; + } + + public boolean next() throws IOException { + return adjust(spans.next()); + } + + public boolean skipTo(int target) throws IOException { + return adjust(spans.skipTo(target)); + } + + private boolean adjust(boolean condition) { + if (length != -1) { + totalLength -= length; // subtract old length + } + if (condition) { + length = end() - start(); + totalLength += length; // add new length + + if (max == null || doc() > max.doc() + || (doc() == max.doc()) && (end() > max.end())) { + max = this; + } + } + more = condition; + return condition; + } + + public int doc() { return spans.doc(); } + public int start() { return spans.start(); } + public int end() { return spans.end(); } + // TODO: Remove warning after API has been finalized + public Collection/**/ getPayload() throws IOException { + return new ArrayList(spans.getPayload()); + } + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return spans.isPayloadAvailable(); + } + + public String toString() { return spans.toString() + "#" + index; } + } + + + public NearSpansUnordered(SpanNearQuery query, IndexReader reader) + throws IOException { + this.query = query; + this.slop = query.getSlop(); + + SpanQuery[] clauses = query.getClauses(); + queue = new CellQueue(clauses.length); + for (int i = 0; i < clauses.length; i++) { + SpansCell cell = + new SpansCell(clauses[i].getPayloadSpans(reader), i); + ordered.add(cell); + } + } + + public boolean next() throws IOException { + if (firstTime) { + initList(true); + listToQueue(); // initialize queue + firstTime = false; + } else if (more) { + if (min().next()) { // trigger further scanning + queue.adjustTop(); // maintain queue + } else { + more = false; + } + } + + while (more) { + + boolean queueStale = false; + + if (min().doc() != max.doc()) { // maintain list + queueToList(); + queueStale = true; + } + + // skip to doc w/ all clauses + + while (more && first.doc() < last.doc()) { + more = first.skipTo(last.doc()); // skip first upto last + firstToLast(); // and move it to the end + queueStale = true; + } + + if (!more) return false; + + // found doc w/ all clauses + + if (queueStale) { // maintain the queue + listToQueue(); + queueStale = false; + } + + if (atMatch()) { + return true; + } + + more = min().next(); + if (more) { + queue.adjustTop(); // maintain queue + } + } + return false; // no more matches + } + + public boolean skipTo(int target) throws IOException { + if (firstTime) { // initialize + initList(false); + for (SpansCell cell = first; more && cell!=null; cell=cell.next) { + more = cell.skipTo(target); // skip all + } + if (more) { + listToQueue(); + } + firstTime = false; + } else { // normal case + while (more && min().doc() < target) { // skip as needed + if (min().skipTo(target)) { + queue.adjustTop(); + } else { + more = false; + } + } + } + return more && (atMatch() || next()); + } + + private SpansCell min() { return (SpansCell)queue.top(); } + + public int doc() { return min().doc(); } + public int start() { return min().start(); } + public int end() { return max.end(); } + + // TODO: Remove warning after API has been finalized + /** + * WARNING: The List is not necessarily in order of the the positions + * @return + * @throws IOException + */ + public Collection/**/ getPayload() throws IOException { + Set/* + * WARNING: The status of the Payloads feature is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + **/ +public interface PayloadSpans extends Spans{ + /** + * Returns the payload data for the current span. + * This is invalid until {@link #next()} is called for + * the first time. + * This method must not be called more than once after each call + * of {@link #next()}. However, payloads are loaded lazily, + * so if the payload data for the current position is not needed, + * this method may not be called at all for performance reasons.
+ *
+ * Note that the return type is a collection, thus the ordering should not be relied upon. + *
+ *

+ * WARNING: The status of the Payloads feature is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * @return a List of byte arrays containing the data of this payload, otherwise null if isPayloadAvailable is false + * @throws java.io.IOException + */ + // TODO: Remove warning after API has been finalized + Collection/**/ getPayload() throws IOException; + + /** + * Checks if a payload can be loaded at this position. + *

+ * Payloads can only be loaded once per call to + * {@link #next()}. + *

+ *

+ * WARNING: The status of the Payloads feature is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + * + * @return true if there is a payload available at this position that can be loaded + */ + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable(); + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanFirstQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanFirstQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanFirstQuery.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,154 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import java.util.Collection; +import java.util.Set; +import java.util.ArrayList; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.Query; +import org.apache.lucene.util.ToStringUtils; + +/** Matches spans near the beginning of a field. */ +public class SpanFirstQuery extends SpanQuery { + private SpanQuery match; + private int end; + + /** Construct a SpanFirstQuery matching spans in match whose end + * position is less than or equal to end. */ + public SpanFirstQuery(SpanQuery match, int end) { + this.match = match; + this.end = end; + } + + /** Return the SpanQuery whose matches are filtered. */ + public SpanQuery getMatch() { return match; } + + /** Return the maximum end position permitted in a match. */ + public int getEnd() { return end; } + + public String getField() { return match.getField(); } + + /** Returns a collection of all terms matched by this query. + * @deprecated use extractTerms instead + * @see #extractTerms(Set) + */ + public Collection getTerms() { return match.getTerms(); } + + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + buffer.append("spanFirst("); + buffer.append(match.toString(field)); + buffer.append(", "); + buffer.append(end); + buffer.append(")"); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + public void extractTerms(Set terms) { + match.extractTerms(terms); + } + + public PayloadSpans getPayloadSpans(IndexReader reader) throws IOException { + return (PayloadSpans) getSpans(reader); + } + + public Spans getSpans(final IndexReader reader) throws IOException { + return new PayloadSpans() { + private PayloadSpans spans = match.getPayloadSpans(reader); + + public boolean next() throws IOException { + while (spans.next()) { // scan to next match + if (end() <= end) + return true; + } + return false; + } + + public boolean skipTo(int target) throws IOException { + if (!spans.skipTo(target)) + return false; + + return spans.end() <= end || next(); + + } + + public int doc() { return spans.doc(); } + public int start() { return spans.start(); } + public int end() { return spans.end(); } + + // TODO: Remove warning after API has been finalized + public Collection/**/ getPayload() throws IOException { + ArrayList result = null; + if (spans.isPayloadAvailable()) { + result = new ArrayList(spans.getPayload()); + } + return result;//TODO: any way to avoid the new construction? + } + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return spans.isPayloadAvailable(); + } + + public String toString() { + return "spans(" + SpanFirstQuery.this.toString() + ")"; + } + + }; + } + + public Query rewrite(IndexReader reader) throws IOException { + SpanFirstQuery clone = null; + + SpanQuery rewritten = (SpanQuery) match.rewrite(reader); + if (rewritten != match) { + clone = (SpanFirstQuery) this.clone(); + clone.match = rewritten; + } + + if (clone != null) { + return clone; // some clauses rewrote + } else { + return this; // no clauses rewrote + } + } + + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof SpanFirstQuery)) return false; + + SpanFirstQuery other = (SpanFirstQuery)o; + return this.end == other.end + && this.match.equals(other.match) + && this.getBoost() == other.getBoost(); + } + + public int hashCode() { + int h = match.hashCode(); + h ^= (h << 8) | (h >>> 25); // reversible + h ^= Float.floatToRawIntBits(getBoost()) ^ end; + return h; + } + + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanNearQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanNearQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanNearQuery.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,181 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import java.util.Collection; +import java.util.List; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Set; + + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.Query; +import org.apache.lucene.util.ToStringUtils; + +/** Matches spans which are near one another. One can specify slop, the + * maximum number of intervening unmatched positions, as well as whether + * matches are required to be in-order. */ +public class SpanNearQuery extends SpanQuery { + private List clauses; + private int slop; + private boolean inOrder; + + private String field; + + /** Construct a SpanNearQuery. Matches spans matching a span from each + * clause, with up to slop total unmatched positions between + * them. * When inOrder is true, the spans from each clause + * must be * ordered as in clauses. */ + public SpanNearQuery(SpanQuery[] clauses, int slop, boolean inOrder) { + + // copy clauses array into an ArrayList + this.clauses = new ArrayList(clauses.length); + for (int i = 0; i < clauses.length; i++) { + SpanQuery clause = clauses[i]; + if (i == 0) { // check field + field = clause.getField(); + } else if (!clause.getField().equals(field)) { + throw new IllegalArgumentException("Clauses must have same field."); + } + this.clauses.add(clause); + } + + this.slop = slop; + this.inOrder = inOrder; + } + + /** Return the clauses whose spans are matched. */ + public SpanQuery[] getClauses() { + return (SpanQuery[])clauses.toArray(new SpanQuery[clauses.size()]); + } + + /** Return the maximum number of intervening unmatched positions permitted.*/ + public int getSlop() { return slop; } + + /** Return true if matches are required to be in-order.*/ + public boolean isInOrder() { return inOrder; } + + public String getField() { return field; } + + /** Returns a collection of all terms matched by this query. + * @deprecated use extractTerms instead + * @see #extractTerms(Set) + */ + public Collection getTerms() { + Collection terms = new ArrayList(); + Iterator i = clauses.iterator(); + while (i.hasNext()) { + SpanQuery clause = (SpanQuery)i.next(); + terms.addAll(clause.getTerms()); + } + return terms; + } + + public void extractTerms(Set terms) { + Iterator i = clauses.iterator(); + while (i.hasNext()) { + SpanQuery clause = (SpanQuery)i.next(); + clause.extractTerms(terms); + } + } + + + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + buffer.append("spanNear(["); + Iterator i = clauses.iterator(); + while (i.hasNext()) { + SpanQuery clause = (SpanQuery)i.next(); + buffer.append(clause.toString(field)); + if (i.hasNext()) { + buffer.append(", "); + } + } + buffer.append("], "); + buffer.append(slop); + buffer.append(", "); + buffer.append(inOrder); + buffer.append(")"); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + public Spans getSpans(final IndexReader reader) throws IOException { + if (clauses.size() == 0) // optimize 0-clause case + return new SpanOrQuery(getClauses()).getPayloadSpans(reader); + + if (clauses.size() == 1) // optimize 1-clause case + return ((SpanQuery)clauses.get(0)).getPayloadSpans(reader); + + return inOrder + ? (PayloadSpans) new NearSpansOrdered(this, reader) + : (PayloadSpans) new NearSpansUnordered(this, reader); + } + + public PayloadSpans getPayloadSpans(IndexReader reader) throws IOException { + return (PayloadSpans) getSpans(reader); + } + + public Query rewrite(IndexReader reader) throws IOException { + SpanNearQuery clone = null; + for (int i = 0 ; i < clauses.size(); i++) { + SpanQuery c = (SpanQuery)clauses.get(i); + SpanQuery query = (SpanQuery) c.rewrite(reader); + if (query != c) { // clause rewrote: must clone + if (clone == null) + clone = (SpanNearQuery) this.clone(); + clone.clauses.set(i,query); + } + } + if (clone != null) { + return clone; // some clauses rewrote + } else { + return this; // no clauses rewrote + } + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof SpanNearQuery)) return false; + + final SpanNearQuery spanNearQuery = (SpanNearQuery) o; + + if (inOrder != spanNearQuery.inOrder) return false; + if (slop != spanNearQuery.slop) return false; + if (!clauses.equals(spanNearQuery.clauses)) return false; + + return getBoost() == spanNearQuery.getBoost(); + } + + public int hashCode() { + int result; + result = clauses.hashCode(); + // Mix bits before folding in things like boost, since it could cancel the + // last element of clauses. This particular mix also serves to + // differentiate SpanNearQuery hashcodes from others. + result ^= (result << 14) | (result >>> 19); // reversible + result += Float.floatToRawIntBits(getBoost()); + result += slop; + result ^= (inOrder ? 0x99AFD3BD : 0); + return result; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanNotQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanNotQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanNotQuery.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,200 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.Query; +import org.apache.lucene.util.ToStringUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Set; + +/** Removes matches which overlap with another SpanQuery. */ +public class SpanNotQuery extends SpanQuery { + private SpanQuery include; + private SpanQuery exclude; + + /** Construct a SpanNotQuery matching spans from include which + * have no overlap with spans from exclude.*/ + public SpanNotQuery(SpanQuery include, SpanQuery exclude) { + this.include = include; + this.exclude = exclude; + + if (!include.getField().equals(exclude.getField())) + throw new IllegalArgumentException("Clauses must have same field."); + } + + /** Return the SpanQuery whose matches are filtered. */ + public SpanQuery getInclude() { return include; } + + /** Return the SpanQuery whose matches must not overlap those returned. */ + public SpanQuery getExclude() { return exclude; } + + public String getField() { return include.getField(); } + + /** Returns a collection of all terms matched by this query. + * @deprecated use extractTerms instead + * @see #extractTerms(Set) + */ + public Collection getTerms() { return include.getTerms(); } + + public void extractTerms(Set terms) { include.extractTerms(terms); } + + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + buffer.append("spanNot("); + buffer.append(include.toString(field)); + buffer.append(", "); + buffer.append(exclude.toString(field)); + buffer.append(")"); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + + public Spans getSpans(final IndexReader reader) throws IOException { + return new PayloadSpans() { + private PayloadSpans includeSpans = include.getPayloadSpans(reader); + private boolean moreInclude = true; + + private Spans excludeSpans = exclude.getSpans(reader); + private boolean moreExclude = excludeSpans.next(); + + public boolean next() throws IOException { + if (moreInclude) // move to next include + moreInclude = includeSpans.next(); + + while (moreInclude && moreExclude) { + + if (includeSpans.doc() > excludeSpans.doc()) // skip exclude + moreExclude = excludeSpans.skipTo(includeSpans.doc()); + + while (moreExclude // while exclude is before + && includeSpans.doc() == excludeSpans.doc() + && excludeSpans.end() <= includeSpans.start()) { + moreExclude = excludeSpans.next(); // increment exclude + } + + if (!moreExclude // if no intersection + || includeSpans.doc() != excludeSpans.doc() + || includeSpans.end() <= excludeSpans.start()) + break; // we found a match + + moreInclude = includeSpans.next(); // intersected: keep scanning + } + return moreInclude; + } + + public boolean skipTo(int target) throws IOException { + if (moreInclude) // skip include + moreInclude = includeSpans.skipTo(target); + + if (!moreInclude) + return false; + + if (moreExclude // skip exclude + && includeSpans.doc() > excludeSpans.doc()) + moreExclude = excludeSpans.skipTo(includeSpans.doc()); + + while (moreExclude // while exclude is before + && includeSpans.doc() == excludeSpans.doc() + && excludeSpans.end() <= includeSpans.start()) { + moreExclude = excludeSpans.next(); // increment exclude + } + + if (!moreExclude // if no intersection + || includeSpans.doc() != excludeSpans.doc() + || includeSpans.end() <= excludeSpans.start()) + return true; // we found a match + + return next(); // scan to next match + } + + public int doc() { return includeSpans.doc(); } + public int start() { return includeSpans.start(); } + public int end() { return includeSpans.end(); } + + // TODO: Remove warning after API has been finalizedb + public Collection/**/ getPayload() throws IOException { + ArrayList result = null; + if (includeSpans.isPayloadAvailable()) { + result = new ArrayList(includeSpans.getPayload()); + } + return result; + } + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return includeSpans.isPayloadAvailable(); + } + + public String toString() { + return "spans(" + SpanNotQuery.this.toString() + ")"; + } + + }; + } + + public PayloadSpans getPayloadSpans(IndexReader reader) throws IOException { + return (PayloadSpans) getSpans(reader); + } + + public Query rewrite(IndexReader reader) throws IOException { + SpanNotQuery clone = null; + + SpanQuery rewrittenInclude = (SpanQuery) include.rewrite(reader); + if (rewrittenInclude != include) { + clone = (SpanNotQuery) this.clone(); + clone.include = rewrittenInclude; + } + SpanQuery rewrittenExclude = (SpanQuery) exclude.rewrite(reader); + if (rewrittenExclude != exclude) { + if (clone == null) clone = (SpanNotQuery) this.clone(); + clone.exclude = rewrittenExclude; + } + + if (clone != null) { + return clone; // some clauses rewrote + } else { + return this; // no clauses rewrote + } + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof SpanNotQuery)) return false; + + SpanNotQuery other = (SpanNotQuery)o; + return this.include.equals(other.include) + && this.exclude.equals(other.exclude) + && this.getBoost() == other.getBoost(); + } + + public int hashCode() { + int h = include.hashCode(); + h = (h<<1) | (h >>> 31); // rotate left + h ^= exclude.hashCode(); + h = (h<<1) | (h >>> 31); // rotate left + h ^= Float.floatToRawIntBits(getBoost()); + return h; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanOrQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanOrQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanOrQuery.java 17 Aug 2012 14:55:07 -0000 1.1 @@ -0,0 +1,246 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import java.util.List; +import java.util.Collection; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Set; + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.util.PriorityQueue; +import org.apache.lucene.util.ToStringUtils; +import org.apache.lucene.search.Query; + +/** Matches the union of its clauses.*/ +public class SpanOrQuery extends SpanQuery { + private List clauses; + private String field; + + /** Construct a SpanOrQuery merging the provided clauses. */ + public SpanOrQuery(SpanQuery[] clauses) { + + // copy clauses array into an ArrayList + this.clauses = new ArrayList(clauses.length); + for (int i = 0; i < clauses.length; i++) { + SpanQuery clause = clauses[i]; + if (i == 0) { // check field + field = clause.getField(); + } else if (!clause.getField().equals(field)) { + throw new IllegalArgumentException("Clauses must have same field."); + } + this.clauses.add(clause); + } + } + + /** Return the clauses whose spans are matched. */ + public SpanQuery[] getClauses() { + return (SpanQuery[])clauses.toArray(new SpanQuery[clauses.size()]); + } + + public String getField() { return field; } + + /** Returns a collection of all terms matched by this query. + * @deprecated use extractTerms instead + * @see #extractTerms(Set) + */ + public Collection getTerms() { + Collection terms = new ArrayList(); + Iterator i = clauses.iterator(); + while (i.hasNext()) { + SpanQuery clause = (SpanQuery)i.next(); + terms.addAll(clause.getTerms()); + } + return terms; + } + + public void extractTerms(Set terms) { + Iterator i = clauses.iterator(); + while (i.hasNext()) { + SpanQuery clause = (SpanQuery)i.next(); + clause.extractTerms(terms); + } + } + + public Query rewrite(IndexReader reader) throws IOException { + SpanOrQuery clone = null; + for (int i = 0 ; i < clauses.size(); i++) { + SpanQuery c = (SpanQuery)clauses.get(i); + SpanQuery query = (SpanQuery) c.rewrite(reader); + if (query != c) { // clause rewrote: must clone + if (clone == null) + clone = (SpanOrQuery) this.clone(); + clone.clauses.set(i,query); + } + } + if (clone != null) { + return clone; // some clauses rewrote + } else { + return this; // no clauses rewrote + } + } + + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + buffer.append("spanOr(["); + Iterator i = clauses.iterator(); + while (i.hasNext()) { + SpanQuery clause = (SpanQuery)i.next(); + buffer.append(clause.toString(field)); + if (i.hasNext()) { + buffer.append(", "); + } + } + buffer.append("])"); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + final SpanOrQuery that = (SpanOrQuery) o; + + if (!clauses.equals(that.clauses)) return false; + if (!field.equals(that.field)) return false; + + return getBoost() == that.getBoost(); + } + + public int hashCode() { + int h = clauses.hashCode(); + h ^= (h << 10) | (h >>> 23); + h ^= Float.floatToRawIntBits(getBoost()); + return h; + } + + + private class SpanQueue extends PriorityQueue { + public SpanQueue(int size) { + initialize(size); + } + + protected final boolean lessThan(Object o1, Object o2) { + Spans spans1 = (Spans)o1; + Spans spans2 = (Spans)o2; + if (spans1.doc() == spans2.doc()) { + if (spans1.start() == spans2.start()) { + return spans1.end() < spans2.end(); + } else { + return spans1.start() < spans2.start(); + } + } else { + return spans1.doc() < spans2.doc(); + } + } + } + + public PayloadSpans getPayloadSpans(final IndexReader reader) throws IOException { + return (PayloadSpans)getSpans(reader); + } + + public Spans getSpans(final IndexReader reader) throws IOException { + if (clauses.size() == 1) // optimize 1-clause case + return ((SpanQuery)clauses.get(0)).getPayloadSpans(reader); + + return new PayloadSpans() { + private SpanQueue queue = null; + + private boolean initSpanQueue(int target) throws IOException { + queue = new SpanQueue(clauses.size()); + Iterator i = clauses.iterator(); + while (i.hasNext()) { + PayloadSpans spans = ((SpanQuery)i.next()).getPayloadSpans(reader); + if ( ((target == -1) && spans.next()) + || ((target != -1) && spans.skipTo(target))) { + queue.put(spans); + } + } + return queue.size() != 0; + } + + public boolean next() throws IOException { + if (queue == null) { + return initSpanQueue(-1); + } + + if (queue.size() == 0) { // all done + return false; + } + + if (top().next()) { // move to next + queue.adjustTop(); + return true; + } + + queue.pop(); // exhausted a clause + return queue.size() != 0; + } + + private PayloadSpans top() { return (PayloadSpans)queue.top(); } + + public boolean skipTo(int target) throws IOException { + if (queue == null) { + return initSpanQueue(target); + } + + while (queue.size() != 0 && top().doc() < target) { + if (top().skipTo(target)) { + queue.adjustTop(); + } else { + queue.pop(); + } + } + + return queue.size() != 0; + } + + public int doc() { return top().doc(); } + public int start() { return top().start(); } + public int end() { return top().end(); } + + // TODO: Remove warning after API has been finalized + public Collection/**/ getPayload() throws IOException { + ArrayList result = null; + PayloadSpans theTop = top(); + if (theTop != null && theTop.isPayloadAvailable()) { + result = new ArrayList(theTop.getPayload()); + } + return result; + } + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + PayloadSpans top = top(); + return top != null && top.isPayloadAvailable(); + } + + public String toString() { + return "spans("+SpanOrQuery.this+")@"+ + ((queue == null)?"START" + :(queue.size()>0?(doc()+":"+start()+"-"+end()):"END")); + } + + }; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanQuery.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,65 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Searcher; +import org.apache.lucene.search.Weight; + +import java.io.IOException; +import java.util.Collection; +import java.util.Set; + +/** Base class for span-based queries. */ +public abstract class SpanQuery extends Query { + /** Expert: Returns the matches for this query in an index. Used internally + * to search for spans. */ + public abstract Spans getSpans(IndexReader reader) throws IOException; + + /** + * Returns the matches for this query in an index, including access to any {@link org.apache.lucene.index.Payload}s at those + * positions. Implementing classes that want access to the payloads will need to implement this. + * @param reader The {@link org.apache.lucene.index.IndexReader} to use to get spans/payloads + * @return null + * @throws IOException if there is an error accessing the payload + * + * + * WARNING: The status of the Payloads feature is experimental. + * The APIs introduced here might change in the future and will not be + * supported anymore in such a case. + */ + public PayloadSpans getPayloadSpans(IndexReader reader) throws IOException{ + return null; + }; + + /** Returns the name of the field matched by this query.*/ + public abstract String getField(); + + /** Returns a collection of all terms matched by this query. + * @deprecated use extractTerms instead + * @see Query#extractTerms(Set) + */ + public abstract Collection getTerms(); + + protected Weight createWeight(Searcher searcher) throws IOException { + return new SpanWeight(this, searcher); + } + +} + Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanScorer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanScorer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanScorer.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,107 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.search.Explanation; +import org.apache.lucene.search.Scorer; +import org.apache.lucene.search.Similarity; +import org.apache.lucene.search.Weight; + +import java.io.IOException; + +/** + * Public for extension only. + */ +public class SpanScorer extends Scorer { + protected Spans spans; + protected Weight weight; + protected byte[] norms; + protected float value; + + protected boolean firstTime = true; + protected boolean more = true; + + protected int doc; + protected float freq; + + protected SpanScorer(Spans spans, Weight weight, Similarity similarity, byte[] norms) + throws IOException { + super(similarity); + this.spans = spans; + this.norms = norms; + this.weight = weight; + this.value = weight.getValue(); + doc = -1; + } + + public boolean next() throws IOException { + if (firstTime) { + more = spans.next(); + firstTime = false; + } + return setFreqCurrentDoc(); + } + + public boolean skipTo(int target) throws IOException { + if (firstTime) { + more = spans.skipTo(target); + firstTime = false; + } + if (! more) { + return false; + } + if (spans.doc() < target) { // setFreqCurrentDoc() leaves spans.doc() ahead + more = spans.skipTo(target); + } + return setFreqCurrentDoc(); + } + + protected boolean setFreqCurrentDoc() throws IOException { + if (! more) { + return false; + } + doc = spans.doc(); + freq = 0.0f; + do { + int matchLength = spans.end() - spans.start(); + freq += getSimilarity().sloppyFreq(matchLength); + more = spans.next(); + } while (more && (doc == spans.doc())); + return true; + } + + public int doc() { return doc; } + + public float score() throws IOException { + float raw = getSimilarity().tf(freq) * value; // raw score + return raw * Similarity.decodeNorm(norms[doc]); // normalize + } + + public Explanation explain(final int doc) throws IOException { + Explanation tfExplanation = new Explanation(); + + skipTo(doc); + + float phraseFreq = (doc() == doc) ? freq : 0.0f; + tfExplanation.setValue(getSimilarity().tf(phraseFreq)); + tfExplanation.setDescription("tf(phraseFreq=" + phraseFreq + ")"); + + return tfExplanation; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanTermQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanTermQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanTermQuery.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,87 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.util.ToStringUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Set; + +/** Matches spans containing a term. */ +public class SpanTermQuery extends SpanQuery { + protected Term term; + + /** Construct a SpanTermQuery matching the named term's spans. */ + public SpanTermQuery(Term term) { this.term = term; } + + /** Return the term whose spans are matched. */ + public Term getTerm() { return term; } + + public String getField() { return term.field(); } + + /** Returns a collection of all terms matched by this query. + * @deprecated use extractTerms instead + * @see #extractTerms(Set) + */ + public Collection getTerms() { + Collection terms = new ArrayList(); + terms.add(term); + return terms; + } + public void extractTerms(Set terms) { + terms.add(term); + } + + public String toString(String field) { + StringBuffer buffer = new StringBuffer(); + if (term.field().equals(field)) + buffer.append(term.text()); + else + buffer.append(term.toString()); + buffer.append(ToStringUtils.boost(getBoost())); + return buffer.toString(); + } + + /** Returns true iff o is equal to this. */ + public boolean equals(Object o) { + if (!(o instanceof SpanTermQuery)) + return false; + SpanTermQuery other = (SpanTermQuery)o; + return (this.getBoost() == other.getBoost()) + && this.term.equals(other.term); + } + + /** Returns a hash code value for this object.*/ + public int hashCode() { + return Float.floatToIntBits(getBoost()) ^ term.hashCode() ^ 0xD23FE494; + } + + public Spans getSpans(final IndexReader reader) throws IOException { + return new TermSpans(reader.termPositions(term), term); + } + + + public PayloadSpans getPayloadSpans(IndexReader reader) throws IOException { + return (PayloadSpans) getSpans(reader); + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanWeight.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanWeight.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/SpanWeight.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,146 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.*; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +/** + * Expert-only. Public for use by other weight implementations + */ +public class SpanWeight implements Weight { + protected Similarity similarity; + protected float value; + protected float idf; + protected float queryNorm; + protected float queryWeight; + + protected Set terms; + protected SpanQuery query; + + public SpanWeight(SpanQuery query, Searcher searcher) + throws IOException { + this.similarity = query.getSimilarity(searcher); + this.query = query; + terms=new HashSet(); + query.extractTerms(terms); + + idf = this.query.getSimilarity(searcher).idf(terms, searcher); + } + + public Query getQuery() { return query; } + public float getValue() { return value; } + + public float sumOfSquaredWeights() throws IOException { + queryWeight = idf * query.getBoost(); // compute query weight + return queryWeight * queryWeight; // square it + } + + public void normalize(float queryNorm) { + this.queryNorm = queryNorm; + queryWeight *= queryNorm; // normalize query weight + value = queryWeight * idf; // idf for document + } + + public Scorer scorer(IndexReader reader) throws IOException { + return new SpanScorer(query.getSpans(reader), this, + similarity, + reader.norms(query.getField())); + } + + public Explanation explain(IndexReader reader, int doc) + throws IOException { + + ComplexExplanation result = new ComplexExplanation(); + result.setDescription("weight("+getQuery()+" in "+doc+"), product of:"); + String field = ((SpanQuery)getQuery()).getField(); + + StringBuffer docFreqs = new StringBuffer(); + Iterator i = terms.iterator(); + while (i.hasNext()) { + Term term = (Term)i.next(); + docFreqs.append(term.text()); + docFreqs.append("="); + docFreqs.append(reader.docFreq(term)); + + if (i.hasNext()) { + docFreqs.append(" "); + } + } + + Explanation idfExpl = + new Explanation(idf, "idf(" + field + ": " + docFreqs + ")"); + + // explain query weight + Explanation queryExpl = new Explanation(); + queryExpl.setDescription("queryWeight(" + getQuery() + "), product of:"); + + Explanation boostExpl = new Explanation(getQuery().getBoost(), "boost"); + if (getQuery().getBoost() != 1.0f) + queryExpl.addDetail(boostExpl); + queryExpl.addDetail(idfExpl); + + Explanation queryNormExpl = new Explanation(queryNorm,"queryNorm"); + queryExpl.addDetail(queryNormExpl); + + queryExpl.setValue(boostExpl.getValue() * + idfExpl.getValue() * + queryNormExpl.getValue()); + + result.addDetail(queryExpl); + + // explain field weight + ComplexExplanation fieldExpl = new ComplexExplanation(); + fieldExpl.setDescription("fieldWeight("+field+":"+query.toString(field)+ + " in "+doc+"), product of:"); + + Explanation tfExpl = scorer(reader).explain(doc); + fieldExpl.addDetail(tfExpl); + fieldExpl.addDetail(idfExpl); + + Explanation fieldNormExpl = new Explanation(); + byte[] fieldNorms = reader.norms(field); + float fieldNorm = + fieldNorms!=null ? Similarity.decodeNorm(fieldNorms[doc]) : 0.0f; + fieldNormExpl.setValue(fieldNorm); + fieldNormExpl.setDescription("fieldNorm(field="+field+", doc="+doc+")"); + fieldExpl.addDetail(fieldNormExpl); + + fieldExpl.setMatch(Boolean.valueOf(tfExpl.isMatch())); + fieldExpl.setValue(tfExpl.getValue() * + idfExpl.getValue() * + fieldNormExpl.getValue()); + + result.addDetail(fieldExpl); + result.setMatch(fieldExpl.getMatch()); + + // combine them + result.setValue(queryExpl.getValue() * fieldExpl.getValue()); + + if (queryExpl.getValue() == 1.0f) + return fieldExpl; + + return result; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/Spans.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/Spans.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/Spans.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,54 @@ +package org.apache.lucene.search.spans; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** Expert: an enumeration of span matches. Used to implement span searching. + * Each span represents a range of term positions within a document. Matches + * are enumerated in order, by increasing document number, within that by + * increasing start position and finally by increasing end position. */ +public interface Spans { + /** Move to the next match, returning true iff any such exists. */ + boolean next() throws IOException; + + /** Skips to the first match beyond the current, whose document number is + * greater than or equal to target.

Returns true iff there is such + * a match.

Behaves as if written:

+   *   boolean skipTo(int target) {
+   *     do {
+   *       if (!next())
+   * 	     return false;
+   *     } while (target > doc());
+   *     return true;
+   *   }
+   * 
+ * Most implementations are considerably more efficient than that. + */ + boolean skipTo(int target) throws IOException; + + /** Returns the document number of the current match. Initially invalid. */ + int doc(); + + /** Returns the start position of the current match. Initially invalid. */ + int start(); + + /** Returns the end position of the current match. Initially invalid. */ + int end(); + +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/TermSpans.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/TermSpans.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/TermSpans.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,115 @@ +package org.apache.lucene.search.spans; +/** + * Copyright 2005 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import org.apache.lucene.index.Term; +import org.apache.lucene.index.TermPositions; + +import java.io.IOException; +import java.util.Collections; +import java.util.Collection; + +/** + * Expert: + * Public for extension only + */ +public class TermSpans implements PayloadSpans { + protected TermPositions positions; + protected Term term; + protected int doc; + protected int freq; + protected int count; + protected int position; + + + public TermSpans(TermPositions positions, Term term) throws IOException { + + this.positions = positions; + this.term = term; + doc = -1; + } + + public boolean next() throws IOException { + if (count == freq) { + if (!positions.next()) { + doc = Integer.MAX_VALUE; + return false; + } + doc = positions.doc(); + freq = positions.freq(); + count = 0; + } + position = positions.nextPosition(); + count++; + return true; + } + + public boolean skipTo(int target) throws IOException { + // are we already at the correct position? + if (doc >= target) { + return true; + } + + if (!positions.skipTo(target)) { + doc = Integer.MAX_VALUE; + return false; + } + + doc = positions.doc(); + freq = positions.freq(); + count = 0; + + position = positions.nextPosition(); + count++; + + return true; + } + + public int doc() { + return doc; + } + + public int start() { + return position; + } + + public int end() { + return position + 1; + } + + // TODO: Remove warning after API has been finalized + public Collection/**/ getPayload() throws IOException { + byte [] bytes = new byte[positions.getPayloadLength()]; + bytes = positions.getPayload(bytes, 0); + return Collections.singletonList(bytes); + } + + // TODO: Remove warning after API has been finalized + public boolean isPayloadAvailable() { + return positions.isPayloadAvailable(); + } + + public String toString() { + return "spans(" + term.toString() + ")@" + + (doc == -1 ? "START" : (doc == Integer.MAX_VALUE) ? "END" : doc + "-" + position); + } + + + public TermPositions getPositions() { + return positions; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/search/spans/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/search/spans/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/search/spans/package.html 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,92 @@ + + + + + +The calculus of spans. + +

A span is a <doc,startPosition,endPosition> tuple.

+ +

The following span query operators are implemented: + +

    + +
  • A SpanTermQuery matches all spans +containing a particular Term.
  • + +
  • A SpanNearQuery matches spans +which occur near one another, and can be used to implement things like +phrase search (when constructed from SpanTermQueries) and inter-phrase +proximity (when constructed from other SpanNearQueries).
  • + +
  • A SpanOrQuery merges spans from a +number of other SpanQueries.
  • + +
  • A SpanNotQuery removes spans +matching one SpanQuery which overlap +another. This can be used, e.g., to implement within-paragraph +search.
  • + +
  • A SpanFirstQuery matches spans +matching q whose end position is less than +n. This can be used to constrain matches to the first +part of the document.
  • + +
+ +In all cases, output spans are minimally inclusive. In other words, a +span formed by matching a span in x and y starts at the lesser of the +two starts and ends at the greater of the two ends. +

+ +

For example, a span query which matches "John Kerry" within ten +words of "George Bush" within the first 100 words of the document +could be constructed with: +

+SpanQuery john   = new SpanTermQuery(new Term("content", "john"));
+SpanQuery kerry  = new SpanTermQuery(new Term("content", "kerry"));
+SpanQuery george = new SpanTermQuery(new Term("content", "george"));
+SpanQuery bush   = new SpanTermQuery(new Term("content", "bush"));
+
+SpanQuery johnKerry =
+   new SpanNearQuery(new SpanQuery[] {john, kerry}, 0, true);
+
+SpanQuery georgeBush =
+   new SpanNearQuery(new SpanQuery[] {george, bush}, 0, true);
+
+SpanQuery johnKerryNearGeorgeBush =
+   new SpanNearQuery(new SpanQuery[] {johnKerry, georgeBush}, 10, false);
+
+SpanQuery johnKerryNearGeorgeBushAtStart =
+   new SpanFirstQuery(johnKerryNearGeorgeBush, 100);
+
+ +

Span queries may be freely intermixed with other Lucene queries. +So, for example, the above query can be restricted to documents which +also use the word "iraq" with: + +

+Query query = new BooleanQuery();
+query.add(johnKerryNearGeorgeBushAtStart, true, false);
+query.add(new TermQuery("content", "iraq"), true, false);
+
+ + + Index: 3rdParty_sources/lucene/org/apache/lucene/store/AlreadyClosedException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/AlreadyClosedException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/AlreadyClosedException.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,28 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * This exception is thrown when there is an attempt to + * access something that has already been closed. + */ +public class AlreadyClosedException extends IllegalStateException { + public AlreadyClosedException(String message) { + super(message); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/BufferedIndexInput.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/BufferedIndexInput.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/BufferedIndexInput.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,202 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** Base implementation class for buffered {@link IndexInput}. */ +public abstract class BufferedIndexInput extends IndexInput { + + /** Default buffer size */ + public static final int BUFFER_SIZE = 1024; + + private int bufferSize = BUFFER_SIZE; + + protected byte[] buffer; + + private long bufferStart = 0; // position in file of buffer + private int bufferLength = 0; // end of valid bytes + private int bufferPosition = 0; // next byte to read + + public byte readByte() throws IOException { + if (bufferPosition >= bufferLength) + refill(); + return buffer[bufferPosition++]; + } + + public BufferedIndexInput() {} + + /** Inits BufferedIndexInput with a specific bufferSize */ + public BufferedIndexInput(int bufferSize) { + checkBufferSize(bufferSize); + this.bufferSize = bufferSize; + } + + /** Change the buffer size used by this IndexInput */ + public void setBufferSize(int newSize) { + assert buffer == null || bufferSize == buffer.length: "buffer=" + buffer + " bufferSize=" + bufferSize + " buffer.length=" + (buffer != null ? buffer.length : 0); + if (newSize != bufferSize) { + checkBufferSize(newSize); + bufferSize = newSize; + if (buffer != null) { + // Resize the existing buffer and carefully save as + // many bytes as possible starting from the current + // bufferPosition + byte[] newBuffer = new byte[newSize]; + final int leftInBuffer = bufferLength-bufferPosition; + final int numToCopy; + if (leftInBuffer > newSize) + numToCopy = newSize; + else + numToCopy = leftInBuffer; + System.arraycopy(buffer, bufferPosition, newBuffer, 0, numToCopy); + bufferStart += bufferPosition; + bufferPosition = 0; + bufferLength = numToCopy; + newBuffer(newBuffer); + } + } + } + + protected void newBuffer(byte[] newBuffer) { + // Subclasses can do something here + buffer = newBuffer; + } + + /** Returns buffer size. @see #setBufferSize */ + public int getBufferSize() { + return bufferSize; + } + + private void checkBufferSize(int bufferSize) { + if (bufferSize <= 0) + throw new IllegalArgumentException("bufferSize must be greater than 0 (got " + bufferSize + ")"); + } + + public void readBytes(byte[] b, int offset, int len) throws IOException { + readBytes(b, offset, len, true); + } + + public void readBytes(byte[] b, int offset, int len, boolean useBuffer) throws IOException { + + if(len <= (bufferLength-bufferPosition)){ + // the buffer contains enough data to satisfy this request + if(len>0) // to allow b to be null if len is 0... + System.arraycopy(buffer, bufferPosition, b, offset, len); + bufferPosition+=len; + } else { + // the buffer does not have enough data. First serve all we've got. + int available = bufferLength - bufferPosition; + if(available > 0){ + System.arraycopy(buffer, bufferPosition, b, offset, available); + offset += available; + len -= available; + bufferPosition += available; + } + // and now, read the remaining 'len' bytes: + if (useBuffer && len length()) + throw new IOException("read past EOF"); + readInternal(b, offset, len); + bufferStart = after; + bufferPosition = 0; + bufferLength = 0; // trigger refill() on read + } + } + } + + private void refill() throws IOException { + long start = bufferStart + bufferPosition; + long end = start + bufferSize; + if (end > length()) // don't read past EOF + end = length(); + int newLength = (int)(end - start); + if (newLength <= 0) + throw new IOException("read past EOF"); + + if (buffer == null) { + newBuffer(new byte[bufferSize]); // allocate buffer lazily + seekInternal(bufferStart); + } + readInternal(buffer, 0, newLength); + bufferLength = newLength; + bufferStart = start; + bufferPosition = 0; + } + + /** Expert: implements buffer refill. Reads bytes from the current position + * in the input. + * @param b the array to read bytes into + * @param offset the offset in the array to start storing bytes + * @param length the number of bytes to read + */ + protected abstract void readInternal(byte[] b, int offset, int length) + throws IOException; + + public long getFilePointer() { return bufferStart + bufferPosition; } + + public void seek(long pos) throws IOException { + if (pos >= bufferStart && pos < (bufferStart + bufferLength)) + bufferPosition = (int)(pos - bufferStart); // seek within buffer + else { + bufferStart = pos; + bufferPosition = 0; + bufferLength = 0; // trigger refill() on read() + seekInternal(pos); + } + } + + /** Expert: implements seek. Sets current position in this file, where the + * next {@link #readInternal(byte[],int,int)} will occur. + * @see #readInternal(byte[],int,int) + */ + protected abstract void seekInternal(long pos) throws IOException; + + public Object clone() { + BufferedIndexInput clone = (BufferedIndexInput)super.clone(); + + clone.buffer = null; + clone.bufferLength = 0; + clone.bufferPosition = 0; + clone.bufferStart = getFilePointer(); + + return clone; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/BufferedIndexOutput.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/BufferedIndexOutput.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/BufferedIndexOutput.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,132 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** Base implementation class for buffered {@link IndexOutput}. */ +public abstract class BufferedIndexOutput extends IndexOutput { + static final int BUFFER_SIZE = 16384; + + private final byte[] buffer = new byte[BUFFER_SIZE]; + private long bufferStart = 0; // position in file of buffer + private int bufferPosition = 0; // position in buffer + + /** Writes a single byte. + * @see IndexInput#readByte() + */ + public void writeByte(byte b) throws IOException { + if (bufferPosition >= BUFFER_SIZE) + flush(); + buffer[bufferPosition++] = b; + } + + /** Writes an array of bytes. + * @param b the bytes to write + * @param length the number of bytes to write + * @see IndexInput#readBytes(byte[],int,int) + */ + public void writeBytes(byte[] b, int offset, int length) throws IOException { + int bytesLeft = BUFFER_SIZE - bufferPosition; + // is there enough space in the buffer? + if (bytesLeft >= length) { + // we add the data to the end of the buffer + System.arraycopy(b, offset, buffer, bufferPosition, length); + bufferPosition += length; + // if the buffer is full, flush it + if (BUFFER_SIZE - bufferPosition == 0) + flush(); + } else { + // is data larger then buffer? + if (length > BUFFER_SIZE) { + // we flush the buffer + if (bufferPosition > 0) + flush(); + // and write data at once + flushBuffer(b, offset, length); + bufferStart += length; + } else { + // we fill/flush the buffer (until the input is written) + int pos = 0; // position in the input data + int pieceLength; + while (pos < length) { + pieceLength = (length - pos < bytesLeft) ? length - pos : bytesLeft; + System.arraycopy(b, pos + offset, buffer, bufferPosition, pieceLength); + pos += pieceLength; + bufferPosition += pieceLength; + // if the buffer is full, flush it + bytesLeft = BUFFER_SIZE - bufferPosition; + if (bytesLeft == 0) { + flush(); + bytesLeft = BUFFER_SIZE; + } + } + } + } + } + + /** Forces any buffered output to be written. */ + public void flush() throws IOException { + flushBuffer(buffer, bufferPosition); + bufferStart += bufferPosition; + bufferPosition = 0; + } + + /** Expert: implements buffer write. Writes bytes at the current position in + * the output. + * @param b the bytes to write + * @param len the number of bytes to write + */ + private void flushBuffer(byte[] b, int len) throws IOException { + flushBuffer(b, 0, len); + } + + /** Expert: implements buffer write. Writes bytes at the current position in + * the output. + * @param b the bytes to write + * @param offset the offset in the byte array + * @param len the number of bytes to write + */ + protected abstract void flushBuffer(byte[] b, int offset, int len) throws IOException; + + /** Closes this stream to further operations. */ + public void close() throws IOException { + flush(); + } + + /** Returns the current position in this file, where the next write will + * occur. + * @see #seek(long) + */ + public long getFilePointer() { + return bufferStart + bufferPosition; + } + + /** Sets current position in this file, where the next write will occur. + * @see #getFilePointer() + */ + public void seek(long pos) throws IOException { + flush(); + bufferStart = pos; + } + + /** The number of bytes in the file. */ + public abstract long length() throws IOException; + + +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/ChecksumIndexInput.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/ChecksumIndexInput.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/ChecksumIndexInput.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,67 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.zip.CRC32; +import java.util.zip.Checksum; + +/** Writes bytes through to a primary IndexOutput, computing + * checksum as it goes. Note that you cannot use seek(). */ +public class ChecksumIndexInput extends IndexInput { + IndexInput main; + Checksum digest; + + public ChecksumIndexInput(IndexInput main) { + this.main = main; + digest = new CRC32(); + } + + public byte readByte() throws IOException { + final byte b = main.readByte(); + digest.update(b); + return b; + } + + public void readBytes(byte[] b, int offset, int len) + throws IOException { + main.readBytes(b, offset, len); + digest.update(b, offset, len); + } + + + public long getChecksum() { + return digest.getValue(); + } + + public void close() throws IOException { + main.close(); + } + + public long getFilePointer() { + return main.getFilePointer(); + } + + public void seek(long pos) { + throw new RuntimeException("not allowed"); + } + + public long length() { + return main.length(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/ChecksumIndexOutput.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/ChecksumIndexOutput.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/ChecksumIndexOutput.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,92 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.zip.CRC32; +import java.util.zip.Checksum; + +/** Writes bytes through to a primary IndexOutput, computing + * checksum. Note that you cannot use seek().*/ +public class ChecksumIndexOutput extends IndexOutput { + IndexOutput main; + Checksum digest; + + public ChecksumIndexOutput(IndexOutput main) { + this.main = main; + digest = new CRC32(); + } + + public void writeByte(byte b) throws IOException { + digest.update(b); + main.writeByte(b); + } + + public void writeBytes(byte[] b, int offset, int length) throws IOException { + digest.update(b, offset, length); + main.writeBytes(b, offset, length); + } + + public long getChecksum() { + return digest.getValue(); + } + + public void flush() throws IOException { + main.flush(); + } + + public void close() throws IOException { + main.close(); + } + + public long getFilePointer() { + return main.getFilePointer(); + } + + public void seek(long pos) { + throw new RuntimeException("not allowed"); + } + + /** + * Starts but does not complete the commit of this file (= + * writing of the final checksum at the end). After this + * is called must call {@link #finishCommit} and the + * {@link #close} to complete the commit. + */ + public void prepareCommit() throws IOException { + final long checksum = getChecksum(); + // Intentionally write a mismatched checksum. This is + // because we want to 1) test, as best we can, that we + // are able to write a long to the file, but 2) not + // actually "commit" the file yet. This (prepare + // commit) is phase 1 of a two-phase commit. + final long pos = main.getFilePointer(); + main.writeLong(checksum-1); + main.flush(); + main.seek(pos); + } + + /** See {@link #prepareCommit} */ + public void finishCommit() throws IOException { + main.writeLong(getChecksum()); + } + + public long length() throws IOException { + return main.length(); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/Directory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/Directory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/Directory.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,222 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** A Directory is a flat list of files. Files may be written once, when they + * are created. Once a file is created it may only be opened for read, or + * deleted. Random access is permitted both when reading and writing. + * + *

Java's i/o APIs not used directly, but rather all i/o is + * through this API. This permits things such as:

    + *
  • implementation of RAM-based indices; + *
  • implementation indices stored in a database, via JDBC; + *
  • implementation of an index as a single file; + *
+ * + * Directory locking is implemented by an instance of {@link + * LockFactory}, and can be changed for each Directory + * instance using {@link #setLockFactory}. + * + */ +public abstract class Directory { + + volatile boolean isOpen = true; + + /** Holds the LockFactory instance (implements locking for + * this Directory instance). */ + protected LockFactory lockFactory; + + /** Returns an array of strings, one for each file in the + * directory. This method may return null (for example for + * {@link FSDirectory} if the underlying directory doesn't + * exist in the filesystem or there are permissions + * problems).*/ + public abstract String[] list() + throws IOException; + + /** Returns true iff a file with the given name exists. */ + public abstract boolean fileExists(String name) + throws IOException; + + /** Returns the time the named file was last modified. */ + public abstract long fileModified(String name) + throws IOException; + + /** Set the modified time of an existing file to now. */ + public abstract void touchFile(String name) + throws IOException; + + /** Removes an existing file in the directory. */ + public abstract void deleteFile(String name) + throws IOException; + + /** Renames an existing file in the directory. + * If a file already exists with the new name, then it is replaced. + * This replacement is not guaranteed to be atomic. + * @deprecated + */ + public abstract void renameFile(String from, String to) + throws IOException; + + /** Returns the length of a file in the directory. */ + public abstract long fileLength(String name) + throws IOException; + + + /** Creates a new, empty file in the directory with the given name. + Returns a stream writing this file. */ + public abstract IndexOutput createOutput(String name) throws IOException; + + /** Ensure that any writes to this file are moved to + * stable storage. Lucene uses this to properly commit + * changes to the index, to prevent a machine/OS crash + * from corrupting the index. */ + public void sync(String name) throws IOException {} + + /** Returns a stream reading an existing file. */ + public abstract IndexInput openInput(String name) + throws IOException; + + /** Returns a stream reading an existing file, with the + * specified read buffer size. The particular Directory + * implementation may ignore the buffer size. Currently + * the only Directory implementations that respect this + * parameter are {@link FSDirectory} and {@link + * org.apache.lucene.index.CompoundFileReader}. + */ + public IndexInput openInput(String name, int bufferSize) throws IOException { + return openInput(name); + } + + /** Construct a {@link Lock}. + * @param name the name of the lock file + */ + public Lock makeLock(String name) { + return lockFactory.makeLock(name); + } + /** + * Attempt to clear (forcefully unlock and remove) the + * specified lock. Only call this at a time when you are + * certain this lock is no longer in use. + * @param name name of the lock to be cleared. + */ + public void clearLock(String name) throws IOException { + if (lockFactory != null) { + lockFactory.clearLock(name); + } + } + + /** Closes the store. */ + public abstract void close() + throws IOException; + + /** + * Set the LockFactory that this Directory instance should + * use for its locking implementation. Each * instance of + * LockFactory should only be used for one directory (ie, + * do not share a single instance across multiple + * Directories). + * + * @param lockFactory instance of {@link LockFactory}. + */ + public void setLockFactory(LockFactory lockFactory) { + this.lockFactory = lockFactory; + lockFactory.setLockPrefix(this.getLockID()); + } + + /** + * Get the LockFactory that this Directory instance is + * using for its locking implementation. Note that this + * may be null for Directory implementations that provide + * their own locking implementation. + */ + public LockFactory getLockFactory() { + return this.lockFactory; + } + + /** + * Return a string identifier that uniquely differentiates + * this Directory instance from other Directory instances. + * This ID should be the same if two Directory instances + * (even in different JVMs and/or on different machines) + * are considered "the same index". This is how locking + * "scopes" to the right index. + */ + public String getLockID() { + return this.toString(); + } + + /** + * Copy contents of a directory src to a directory dest. + * If a file in src already exists in dest then the + * one in dest will be blindly overwritten. + * + * @param src source directory + * @param dest destination directory + * @param closeDirSrc if true, call {@link #close()} method on source directory + * @throws IOException + */ + public static void copy(Directory src, Directory dest, boolean closeDirSrc) throws IOException { + final String[] files = src.list(); + + if (files == null) + throw new IOException("cannot read directory " + src + ": list() returned null"); + + byte[] buf = new byte[BufferedIndexOutput.BUFFER_SIZE]; + for (int i = 0; i < files.length; i++) { + IndexOutput os = null; + IndexInput is = null; + try { + // create file in dest directory + os = dest.createOutput(files[i]); + // read current file + is = src.openInput(files[i]); + // and copy to dest directory + long len = is.length(); + long readCount = 0; + while (readCount < len) { + int toRead = readCount + BufferedIndexOutput.BUFFER_SIZE > len ? (int)(len - readCount) : BufferedIndexOutput.BUFFER_SIZE; + is.readBytes(buf, 0, toRead); + os.writeBytes(buf, toRead); + readCount += toRead; + } + } finally { + // graceful cleanup + try { + if (os != null) + os.close(); + } finally { + if (is != null) + is.close(); + } + } + } + if(closeDirSrc) + src.close(); + } + + /** + * @throws AlreadyClosedException if this Directory is closed + */ + protected final void ensureOpen() throws AlreadyClosedException { + if (!isOpen) + throw new AlreadyClosedException("this Directory is closed"); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/FSDirectory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/FSDirectory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/FSDirectory.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,680 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.lucene.index.IndexFileNameFilter; + +// Used only for WRITE_LOCK_NAME in deprecated create=true case: +import org.apache.lucene.index.IndexWriter; + +/** + * Straightforward implementation of {@link Directory} as a directory of files. + * Locking implementation is by default the {@link SimpleFSLockFactory}, but + * can be changed either by passing in a {@link LockFactory} instance to + * getDirectory, or specifying the LockFactory class by setting + * org.apache.lucene.store.FSDirectoryLockFactoryClass Java system + * property, or by calling {@link #setLockFactory} after creating + * the Directory. + + *

Directories are cached, so that, for a given canonical + * path, the same FSDirectory instance will always be + * returned by getDirectory. This permits + * synchronization on directories.

+ * + * @see Directory + */ +public class FSDirectory extends Directory { + + /** This cache of directories ensures that there is a unique Directory + * instance per path, so that synchronization on the Directory can be used to + * synchronize access between readers and writers. We use + * refcounts to ensure when the last use of an FSDirectory + * instance for a given canonical path is closed, we remove the + * instance from the cache. See LUCENE-776 + * for some relevant discussion. + */ + private static final Map DIRECTORIES = new HashMap(); + + private static boolean disableLocks = false; + + // TODO: should this move up to the Directory base class? Also: should we + // make a per-instance (in addition to the static "default") version? + + /** + * Set whether Lucene's use of lock files is disabled. By default, + * lock files are enabled. They should only be disabled if the index + * is on a read-only medium like a CD-ROM. + */ + public static void setDisableLocks(boolean doDisableLocks) { + FSDirectory.disableLocks = doDisableLocks; + } + + /** + * Returns whether Lucene's use of lock files is disabled. + * @return true if locks are disabled, false if locks are enabled. + */ + public static boolean getDisableLocks() { + return FSDirectory.disableLocks; + } + + /** + * Directory specified by org.apache.lucene.lockDir + * or java.io.tmpdir system property. + + * @deprecated As of 2.1, LOCK_DIR is unused + * because the write.lock is now stored by default in the + * index directory. If you really want to store locks + * elsewhere you can create your own {@link + * SimpleFSLockFactory} (or {@link NativeFSLockFactory}, + * etc.) passing in your preferred lock directory. Then, + * pass this LockFactory instance to one of + * the getDirectory methods that take a + * lockFactory (for example, {@link #getDirectory(String, LockFactory)}). + */ + public static final String LOCK_DIR = System.getProperty("org.apache.lucene.lockDir", + System.getProperty("java.io.tmpdir")); + + /** The default class which implements filesystem-based directories. */ + private static Class IMPL; + static { + try { + String name = + System.getProperty("org.apache.lucene.FSDirectory.class", + FSDirectory.class.getName()); + IMPL = Class.forName(name); + } catch (ClassNotFoundException e) { + throw new RuntimeException("cannot load FSDirectory class: " + e.toString(), e); + } catch (SecurityException se) { + try { + IMPL = Class.forName(FSDirectory.class.getName()); + } catch (ClassNotFoundException e) { + throw new RuntimeException("cannot load default FSDirectory class: " + e.toString(), e); + } + } + } + + private static MessageDigest DIGESTER; + + static { + try { + DIGESTER = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e.toString(), e); + } + } + + /** A buffer optionally used in renameTo method */ + private byte[] buffer = null; + + /** Returns the directory instance for the named location. + * @param path the path to the directory. + * @return the FSDirectory for the named file. */ + public static FSDirectory getDirectory(String path) + throws IOException { + return getDirectory(new File(path), null); + } + + /** Returns the directory instance for the named location. + * @param path the path to the directory. + * @param lockFactory instance of {@link LockFactory} providing the + * locking implementation. + * @return the FSDirectory for the named file. */ + public static FSDirectory getDirectory(String path, LockFactory lockFactory) + throws IOException { + return getDirectory(new File(path), lockFactory); + } + + /** Returns the directory instance for the named location. + * @param file the path to the directory. + * @return the FSDirectory for the named file. */ + public static FSDirectory getDirectory(File file) + throws IOException { + return getDirectory(file, null); + } + + /** Returns the directory instance for the named location. + * @param file the path to the directory. + * @param lockFactory instance of {@link LockFactory} providing the + * locking implementation. + * @return the FSDirectory for the named file. */ + public static FSDirectory getDirectory(File file, LockFactory lockFactory) + throws IOException + { + file = new File(file.getCanonicalPath()); + + if (file.exists() && !file.isDirectory()) + throw new IOException(file + " not a directory"); + + if (!file.exists()) + if (!file.mkdirs()) + throw new IOException("Cannot create directory: " + file); + + FSDirectory dir; + synchronized (DIRECTORIES) { + dir = (FSDirectory)DIRECTORIES.get(file); + if (dir == null) { + try { + dir = (FSDirectory)IMPL.newInstance(); + } catch (Exception e) { + throw new RuntimeException("cannot load FSDirectory class: " + e.toString(), e); + } + dir.init(file, lockFactory); + DIRECTORIES.put(file, dir); + } else { + // Catch the case where a Directory is pulled from the cache, but has a + // different LockFactory instance. + if (lockFactory != null && lockFactory != dir.getLockFactory()) { + throw new IOException("Directory was previously created with a different LockFactory instance; please pass null as the lockFactory instance and use setLockFactory to change it"); + } + } + } + synchronized (dir) { + dir.refCount++; + } + return dir; + } + + + /** Returns the directory instance for the named location. + * + * @deprecated Use IndexWriter's create flag, instead, to + * create a new index. + * + * @param path the path to the directory. + * @param create if true, create, or erase any existing contents. + * @return the FSDirectory for the named file. */ + public static FSDirectory getDirectory(String path, boolean create) + throws IOException { + return getDirectory(new File(path), create); + } + + /** Returns the directory instance for the named location. + * + * @deprecated Use IndexWriter's create flag, instead, to + * create a new index. + * + * @param file the path to the directory. + * @param create if true, create, or erase any existing contents. + * @return the FSDirectory for the named file. */ + public static FSDirectory getDirectory(File file, boolean create) + throws IOException + { + FSDirectory dir = getDirectory(file, null); + + // This is now deprecated (creation should only be done + // by IndexWriter): + if (create) { + dir.create(); + } + + return dir; + } + + private void create() throws IOException { + if (directory.exists()) { + String[] files = directory.list(IndexFileNameFilter.getFilter()); // clear old files + if (files == null) + throw new IOException("cannot read directory " + directory.getAbsolutePath() + ": list() returned null"); + for (int i = 0; i < files.length; i++) { + File file = new File(directory, files[i]); + if (!file.delete()) + throw new IOException("Cannot delete " + file); + } + } + lockFactory.clearLock(IndexWriter.WRITE_LOCK_NAME); + } + + private File directory = null; + private int refCount; + + protected FSDirectory() {}; // permit subclassing + + private void init(File path, LockFactory lockFactory) throws IOException { + + // Set up lockFactory with cascaded defaults: if an instance was passed in, + // use that; else if locks are disabled, use NoLockFactory; else if the + // system property org.apache.lucene.store.FSDirectoryLockFactoryClass is set, + // instantiate that; else, use SimpleFSLockFactory: + + directory = path; + + boolean doClearLockID = false; + + if (lockFactory == null) { + + if (disableLocks) { + // Locks are disabled: + lockFactory = NoLockFactory.getNoLockFactory(); + } else { + String lockClassName = System.getProperty("org.apache.lucene.store.FSDirectoryLockFactoryClass"); + + if (lockClassName != null && !lockClassName.equals("")) { + Class c; + + try { + c = Class.forName(lockClassName); + } catch (ClassNotFoundException e) { + throw new IOException("unable to find LockClass " + lockClassName); + } + + try { + lockFactory = (LockFactory) c.newInstance(); + } catch (IllegalAccessException e) { + throw new IOException("IllegalAccessException when instantiating LockClass " + lockClassName); + } catch (InstantiationException e) { + throw new IOException("InstantiationException when instantiating LockClass " + lockClassName); + } catch (ClassCastException e) { + throw new IOException("unable to cast LockClass " + lockClassName + " instance to a LockFactory"); + } + + if (lockFactory instanceof NativeFSLockFactory) { + ((NativeFSLockFactory) lockFactory).setLockDir(path); + } else if (lockFactory instanceof SimpleFSLockFactory) { + ((SimpleFSLockFactory) lockFactory).setLockDir(path); + } + } else { + // Our default lock is SimpleFSLockFactory; + // default lockDir is our index directory: + lockFactory = new SimpleFSLockFactory(path); + doClearLockID = true; + } + } + } + + setLockFactory(lockFactory); + + if (doClearLockID) { + // Clear the prefix because write.lock will be + // stored in our directory: + lockFactory.setLockPrefix(null); + } + } + + /** Returns an array of strings, one for each Lucene index file in the directory. */ + public String[] list() { + ensureOpen(); + return directory.list(IndexFileNameFilter.getFilter()); + } + + /** Returns true iff a file with the given name exists. */ + public boolean fileExists(String name) { + ensureOpen(); + File file = new File(directory, name); + return file.exists(); + } + + /** Returns the time the named file was last modified. */ + public long fileModified(String name) { + ensureOpen(); + File file = new File(directory, name); + return file.lastModified(); + } + + /** Returns the time the named file was last modified. */ + public static long fileModified(File directory, String name) { + File file = new File(directory, name); + return file.lastModified(); + } + + /** Set the modified time of an existing file to now. */ + public void touchFile(String name) { + ensureOpen(); + File file = new File(directory, name); + file.setLastModified(System.currentTimeMillis()); + } + + /** Returns the length in bytes of a file in the directory. */ + public long fileLength(String name) { + ensureOpen(); + File file = new File(directory, name); + return file.length(); + } + + /** Removes an existing file in the directory. */ + public void deleteFile(String name) throws IOException { + ensureOpen(); + File file = new File(directory, name); + if (!file.delete()) + throw new IOException("Cannot delete " + file); + } + + /** Renames an existing file in the directory. + * Warning: This is not atomic. + * @deprecated + */ + public synchronized void renameFile(String from, String to) + throws IOException { + ensureOpen(); + File old = new File(directory, from); + File nu = new File(directory, to); + + /* This is not atomic. If the program crashes between the call to + delete() and the call to renameTo() then we're screwed, but I've + been unable to figure out how else to do this... */ + + if (nu.exists()) + if (!nu.delete()) + throw new IOException("Cannot delete " + nu); + + // Rename the old file to the new one. Unfortunately, the renameTo() + // method does not work reliably under some JVMs. Therefore, if the + // rename fails, we manually rename by copying the old file to the new one + if (!old.renameTo(nu)) { + java.io.InputStream in = null; + java.io.OutputStream out = null; + try { + in = new FileInputStream(old); + out = new FileOutputStream(nu); + // see if the buffer needs to be initialized. Initialization is + // only done on-demand since many VM's will never run into the renameTo + // bug and hence shouldn't waste 1K of mem for no reason. + if (buffer == null) { + buffer = new byte[1024]; + } + int len; + while ((len = in.read(buffer)) >= 0) { + out.write(buffer, 0, len); + } + + // delete the old file. + old.delete(); + } + catch (IOException ioe) { + IOException newExc = new IOException("Cannot rename " + old + " to " + nu); + newExc.initCause(ioe); + throw newExc; + } + finally { + try { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + throw new RuntimeException("Cannot close input stream: " + e.toString(), e); + } + } + } finally { + if (out != null) { + try { + out.close(); + } catch (IOException e) { + throw new RuntimeException("Cannot close output stream: " + e.toString(), e); + } + } + } + } + } + } + + /** Creates a new, empty file in the directory with the given name. + Returns a stream writing this file. */ + public IndexOutput createOutput(String name) throws IOException { + ensureOpen(); + File file = new File(directory, name); + if (file.exists() && !file.delete()) // delete existing, if any + throw new IOException("Cannot overwrite: " + file); + + return new FSIndexOutput(file); + } + + public void sync(String name) throws IOException { + ensureOpen(); + File fullFile = new File(directory, name); + boolean success = false; + int retryCount = 0; + IOException exc = null; + while(!success && retryCount < 5) { + retryCount++; + RandomAccessFile file = null; + try { + try { + file = new RandomAccessFile(fullFile, "rw"); + file.getFD().sync(); + success = true; + } finally { + if (file != null) + file.close(); + } + } catch (IOException ioe) { + if (exc == null) + exc = ioe; + try { + // Pause 5 msec + Thread.sleep(5); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + } + } + if (!success) + // Throw original exception + throw exc; + } + + // Inherit javadoc + public IndexInput openInput(String name) throws IOException { + ensureOpen(); + return openInput(name, BufferedIndexInput.BUFFER_SIZE); + } + + // Inherit javadoc + public IndexInput openInput(String name, int bufferSize) throws IOException { + ensureOpen(); + return new FSIndexInput(new File(directory, name), bufferSize); + } + + /** + * So we can do some byte-to-hexchar conversion below + */ + private static final char[] HEX_DIGITS = + {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; + + + public String getLockID() { + ensureOpen(); + String dirName; // name to be hashed + try { + dirName = directory.getCanonicalPath(); + } catch (IOException e) { + throw new RuntimeException(e.toString(), e); + } + + byte digest[]; + synchronized (DIGESTER) { + digest = DIGESTER.digest(dirName.getBytes()); + } + StringBuffer buf = new StringBuffer(); + buf.append("lucene-"); + for (int i = 0; i < digest.length; i++) { + int b = digest[i]; + buf.append(HEX_DIGITS[(b >> 4) & 0xf]); + buf.append(HEX_DIGITS[b & 0xf]); + } + + return buf.toString(); + } + + /** Closes the store to future operations. */ + public synchronized void close() { + if (isOpen && --refCount <= 0) { + isOpen = false; + synchronized (DIRECTORIES) { + DIRECTORIES.remove(directory); + } + } + } + + public File getFile() { + ensureOpen(); + return directory; + } + + /** For debug output. */ + public String toString() { + return this.getClass().getName() + "@" + directory; + } + + protected static class FSIndexInput extends BufferedIndexInput { + + protected static class Descriptor extends RandomAccessFile { + // remember if the file is open, so that we don't try to close it + // more than once + protected volatile boolean isOpen; + long position; + final long length; + + public Descriptor(File file, String mode) throws IOException { + super(file, mode); + isOpen=true; + length=length(); + } + + public void close() throws IOException { + if (isOpen) { + isOpen=false; + super.close(); + } + } + + protected void finalize() throws Throwable { + try { + close(); + } finally { + super.finalize(); + } + } + } + + protected final Descriptor file; + boolean isClone; + + public FSIndexInput(File path) throws IOException { + this(path, BufferedIndexInput.BUFFER_SIZE); + } + + public FSIndexInput(File path, int bufferSize) throws IOException { + super(bufferSize); + file = new Descriptor(path, "r"); + } + + /** IndexInput methods */ + protected void readInternal(byte[] b, int offset, int len) + throws IOException { + synchronized (file) { + long position = getFilePointer(); + if (position != file.position) { + file.seek(position); + file.position = position; + } + int total = 0; + do { + int i = file.read(b, offset+total, len-total); + if (i == -1) + throw new IOException("read past EOF"); + file.position += i; + total += i; + } while (total < len); + } + } + + public void close() throws IOException { + // only close the file if this is not a clone + if (!isClone) file.close(); + } + + protected void seekInternal(long position) { + } + + public long length() { + return file.length; + } + + public Object clone() { + FSIndexInput clone = (FSIndexInput)super.clone(); + clone.isClone = true; + return clone; + } + + /** Method used for testing. Returns true if the underlying + * file descriptor is valid. + */ + boolean isFDValid() throws IOException { + return file.getFD().valid(); + } + } + + protected static class FSIndexOutput extends BufferedIndexOutput { + RandomAccessFile file = null; + + // remember if the file is open, so that we don't try to close it + // more than once + private volatile boolean isOpen; + + public FSIndexOutput(File path) throws IOException { + file = new RandomAccessFile(path, "rw"); + isOpen = true; + } + + /** output methods: */ + public void flushBuffer(byte[] b, int offset, int size) throws IOException { + file.write(b, offset, size); + } + public void close() throws IOException { + // only close the file if it has not been closed yet + if (isOpen) { + boolean success = false; + try { + super.close(); + success = true; + } finally { + isOpen = false; + if (!success) { + try { + file.close(); + } catch (Throwable t) { + // Suppress so we don't mask original exception + } + } else + file.close(); + } + } + } + + /** Random-access methods */ + public void seek(long pos) throws IOException { + super.seek(pos); + file.seek(pos); + } + public long length() throws IOException { + return file.length(); + } + public void setLength(long length) throws IOException { + file.setLength(length); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/IndexInput.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/IndexInput.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/IndexInput.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,229 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** Abstract base class for input from a file in a {@link Directory}. A + * random-access input stream. Used for all Lucene index input operations. + * @see Directory + */ +public abstract class IndexInput implements Cloneable { + private byte[] bytes; // used by readString() + private char[] chars; // used by readModifiedUTF8String() + private boolean preUTF8Strings; // true if we are reading old (modified UTF8) string format + + /** Reads and returns a single byte. + * @see IndexOutput#writeByte(byte) + */ + public abstract byte readByte() throws IOException; + + /** Reads a specified number of bytes into an array at the specified offset. + * @param b the array to read bytes into + * @param offset the offset in the array to start storing bytes + * @param len the number of bytes to read + * @see IndexOutput#writeBytes(byte[],int) + */ + public abstract void readBytes(byte[] b, int offset, int len) + throws IOException; + + /** Reads a specified number of bytes into an array at the + * specified offset with control over whether the read + * should be buffered (callers who have their own buffer + * should pass in "false" for useBuffer). Currently only + * {@link BufferedIndexInput} respects this parameter. + * @param b the array to read bytes into + * @param offset the offset in the array to start storing bytes + * @param len the number of bytes to read + * @param useBuffer set to false if the caller will handle + * buffering. + * @see IndexOutput#writeBytes(byte[],int) + */ + public void readBytes(byte[] b, int offset, int len, boolean useBuffer) + throws IOException + { + // Default to ignoring useBuffer entirely + readBytes(b, offset, len); + } + + /** Reads four bytes and returns an int. + * @see IndexOutput#writeInt(int) + */ + public int readInt() throws IOException { + return ((readByte() & 0xFF) << 24) | ((readByte() & 0xFF) << 16) + | ((readByte() & 0xFF) << 8) | (readByte() & 0xFF); + } + + /** Reads an int stored in variable-length format. Reads between one and + * five bytes. Smaller values take fewer bytes. Negative numbers are not + * supported. + * @see IndexOutput#writeVInt(int) + */ + public int readVInt() throws IOException { + byte b = readByte(); + int i = b & 0x7F; + for (int shift = 7; (b & 0x80) != 0; shift += 7) { + b = readByte(); + i |= (b & 0x7F) << shift; + } + return i; + } + + /** Reads eight bytes and returns a long. + * @see IndexOutput#writeLong(long) + */ + public long readLong() throws IOException { + return (((long)readInt()) << 32) | (readInt() & 0xFFFFFFFFL); + } + + /** Reads a long stored in variable-length format. Reads between one and + * nine bytes. Smaller values take fewer bytes. Negative numbers are not + * supported. */ + public long readVLong() throws IOException { + byte b = readByte(); + long i = b & 0x7F; + for (int shift = 7; (b & 0x80) != 0; shift += 7) { + b = readByte(); + i |= (b & 0x7FL) << shift; + } + return i; + } + + /** Call this if readString should read characters stored + * in the old modified UTF8 format (length in java chars + * and java's modified UTF8 encoding). This is used for + * indices written pre-2.4 See LUCENE-510 for details. */ + public void setModifiedUTF8StringsMode() { + preUTF8Strings = true; + } + + /** Reads a string. + * @see IndexOutput#writeString(String) + */ + public String readString() throws IOException { + if (preUTF8Strings) + return readModifiedUTF8String(); + int length = readVInt(); + if (bytes == null || length > bytes.length) + bytes = new byte[(int) (length*1.25)]; + readBytes(bytes, 0, length); + return new String(bytes, 0, length, "UTF-8"); + } + + private String readModifiedUTF8String() throws IOException { + int length = readVInt(); + if (chars == null || length > chars.length) + chars = new char[length]; + readChars(chars, 0, length); + return new String(chars, 0, length); + } + + /** Reads Lucene's old "modified UTF-8" encoded + * characters into an array. + * @param buffer the array to read characters into + * @param start the offset in the array to start storing characters + * @param length the number of characters to read + * @see IndexOutput#writeChars(String,int,int) + * @deprecated -- please use readString or readBytes + * instead, and construct the string + * from those utf8 bytes + */ + public void readChars(char[] buffer, int start, int length) + throws IOException { + final int end = start + length; + for (int i = start; i < end; i++) { + byte b = readByte(); + if ((b & 0x80) == 0) + buffer[i] = (char)(b & 0x7F); + else if ((b & 0xE0) != 0xE0) { + buffer[i] = (char)(((b & 0x1F) << 6) + | (readByte() & 0x3F)); + } else + buffer[i] = (char)(((b & 0x0F) << 12) + | ((readByte() & 0x3F) << 6) + | (readByte() & 0x3F)); + } + } + + /** + * Expert + * + * Similar to {@link #readChars(char[], int, int)} but does not do any conversion operations on the bytes it is reading in. It still + * has to invoke {@link #readByte()} just as {@link #readChars(char[], int, int)} does, but it does not need a buffer to store anything + * and it does not have to do any of the bitwise operations, since we don't actually care what is in the byte except to determine + * how many more bytes to read + * @param length The number of chars to read + * @deprecated this method operates on old "modified utf8" encoded + * strings + */ + public void skipChars(int length) throws IOException{ + for (int i = 0; i < length; i++) { + byte b = readByte(); + if ((b & 0x80) == 0){ + //do nothing, we only need one byte + } + else if ((b & 0xE0) != 0xE0) { + readByte();//read an additional byte + } else{ + //read two additional bytes. + readByte(); + readByte(); + } + } + } + + + /** Closes the stream to futher operations. */ + public abstract void close() throws IOException; + + /** Returns the current position in this file, where the next read will + * occur. + * @see #seek(long) + */ + public abstract long getFilePointer(); + + /** Sets current position in this file, where the next read will occur. + * @see #getFilePointer() + */ + public abstract void seek(long pos) throws IOException; + + /** The number of bytes in the file. */ + public abstract long length(); + + /** Returns a clone of this stream. + * + *

Clones of a stream access the same data, and are positioned at the same + * point as the stream they were cloned from. + * + *

Expert: Subclasses must ensure that clones may be positioned at + * different points in the input from each other and from the stream they + * were cloned from. + */ + public Object clone() { + IndexInput clone = null; + try { + clone = (IndexInput)super.clone(); + } catch (CloneNotSupportedException e) {} + + clone.bytes = null; + clone.chars = null; + + return clone; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/IndexOutput.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/IndexOutput.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/IndexOutput.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,209 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.util.UnicodeUtil; + +/** Abstract base class for output to a file in a Directory. A random-access + * output stream. Used for all Lucene index output operations. + * @see Directory + * @see IndexInput + */ +public abstract class IndexOutput { + + private UnicodeUtil.UTF8Result utf8Result = new UnicodeUtil.UTF8Result(); + + /** Writes a single byte. + * @see IndexInput#readByte() + */ + public abstract void writeByte(byte b) throws IOException; + + /** Writes an array of bytes. + * @param b the bytes to write + * @param length the number of bytes to write + * @see IndexInput#readBytes(byte[],int,int) + */ + public void writeBytes(byte[] b, int length) throws IOException { + writeBytes(b, 0, length); + } + + /** Writes an array of bytes. + * @param b the bytes to write + * @param offset the offset in the byte array + * @param length the number of bytes to write + * @see IndexInput#readBytes(byte[],int,int) + */ + public abstract void writeBytes(byte[] b, int offset, int length) throws IOException; + + /** Writes an int as four bytes. + * @see IndexInput#readInt() + */ + public void writeInt(int i) throws IOException { + writeByte((byte)(i >> 24)); + writeByte((byte)(i >> 16)); + writeByte((byte)(i >> 8)); + writeByte((byte) i); + } + + /** Writes an int in a variable-length format. Writes between one and + * five bytes. Smaller values take fewer bytes. Negative numbers are not + * supported. + * @see IndexInput#readVInt() + */ + public void writeVInt(int i) throws IOException { + while ((i & ~0x7F) != 0) { + writeByte((byte)((i & 0x7f) | 0x80)); + i >>>= 7; + } + writeByte((byte)i); + } + + /** Writes a long as eight bytes. + * @see IndexInput#readLong() + */ + public void writeLong(long i) throws IOException { + writeInt((int) (i >> 32)); + writeInt((int) i); + } + + /** Writes an long in a variable-length format. Writes between one and five + * bytes. Smaller values take fewer bytes. Negative numbers are not + * supported. + * @see IndexInput#readVLong() + */ + public void writeVLong(long i) throws IOException { + while ((i & ~0x7F) != 0) { + writeByte((byte)((i & 0x7f) | 0x80)); + i >>>= 7; + } + writeByte((byte)i); + } + + /** Writes a string. + * @see IndexInput#readString() + */ + public void writeString(String s) throws IOException { + UnicodeUtil.UTF16toUTF8(s, 0, s.length(), utf8Result); + writeVInt(utf8Result.length); + writeBytes(utf8Result.result, 0, utf8Result.length); + } + + /** Writes a sub sequence of characters from s as the old + * format (modified UTF-8 encoded bytes). + * @param s the source of the characters + * @param start the first character in the sequence + * @param length the number of characters in the sequence + * @deprecated -- please pre-convert to utf8 bytes + * instead or use {@link #writeString} + */ + public void writeChars(String s, int start, int length) + throws IOException { + final int end = start + length; + for (int i = start; i < end; i++) { + final int code = (int)s.charAt(i); + if (code >= 0x01 && code <= 0x7F) + writeByte((byte)code); + else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0) { + writeByte((byte)(0xC0 | (code >> 6))); + writeByte((byte)(0x80 | (code & 0x3F))); + } else { + writeByte((byte)(0xE0 | (code >>> 12))); + writeByte((byte)(0x80 | ((code >> 6) & 0x3F))); + writeByte((byte)(0x80 | (code & 0x3F))); + } + } + } + + /** Writes a sub sequence of characters from char[] as + * the old format (modified UTF-8 encoded bytes). + * @param s the source of the characters + * @param start the first character in the sequence + * @param length the number of characters in the sequence + * @deprecated -- please pre-convert to utf8 bytes instead or use {@link #writeString} + */ + public void writeChars(char[] s, int start, int length) + throws IOException { + final int end = start + length; + for (int i = start; i < end; i++) { + final int code = (int)s[i]; + if (code >= 0x01 && code <= 0x7F) + writeByte((byte)code); + else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0) { + writeByte((byte)(0xC0 | (code >> 6))); + writeByte((byte)(0x80 | (code & 0x3F))); + } else { + writeByte((byte)(0xE0 | (code >>> 12))); + writeByte((byte)(0x80 | ((code >> 6) & 0x3F))); + writeByte((byte)(0x80 | (code & 0x3F))); + } + } + } + + private static int COPY_BUFFER_SIZE = 16384; + private byte[] copyBuffer; + + /** Copy numBytes bytes from input to ourself. */ + public void copyBytes(IndexInput input, long numBytes) throws IOException { + long left = numBytes; + if (copyBuffer == null) + copyBuffer = new byte[COPY_BUFFER_SIZE]; + while(left > 0) { + final int toCopy; + if (left > COPY_BUFFER_SIZE) + toCopy = COPY_BUFFER_SIZE; + else + toCopy = (int) left; + input.readBytes(copyBuffer, 0, toCopy); + writeBytes(copyBuffer, 0, toCopy); + left -= toCopy; + } + } + + /** Forces any buffered output to be written. */ + public abstract void flush() throws IOException; + + /** Closes this stream to further operations. */ + public abstract void close() throws IOException; + + /** Returns the current position in this file, where the next write will + * occur. + * @see #seek(long) + */ + public abstract long getFilePointer(); + + /** Sets current position in this file, where the next write will occur. + * @see #getFilePointer() + */ + public abstract void seek(long pos) throws IOException; + + /** The number of bytes in the file. */ + public abstract long length() throws IOException; + + /** Set the file length. By default, this method does + * nothing (it's optional for a Directory to implement + * it). But, certain Directory implementations (for + * example @see FSDirectory) can use this to inform the + * underlying IO system to pre-allocate the file to the + * specified size. If the length is longer than the + * current file length, the bytes added to the file are + * undefined. Otherwise the file is truncated. + * @param length file length + */ + public void setLength(long length) throws IOException {}; +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/Lock.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/Lock.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/Lock.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,144 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** An interprocess mutex lock. + *

Typical use might look like:

+ * new Lock.With(directory.makeLock("my.lock")) {
+ *     public Object doBody() {
+ *       ... code to execute while locked ...
+ *     }
+ *   }.run();
+ * 
+ * + * + * @version $Id: Lock.java,v 1.1 2012/08/17 14:55:06 marcin Exp $ + * @see Directory#makeLock(String) + */ +public abstract class Lock { + + /** How long {@link #obtain(long)} waits, in milliseconds, + * in between attempts to acquire the lock. */ + public static long LOCK_POLL_INTERVAL = 1000; + + /** Pass this value to {@link #obtain(long)} to try + * forever to obtain the lock. */ + public static final long LOCK_OBTAIN_WAIT_FOREVER = -1; + + /** Attempts to obtain exclusive access and immediately return + * upon success or failure. + * @return true iff exclusive access is obtained + */ + public abstract boolean obtain() throws IOException; + + /** + * If a lock obtain called, this failureReason may be set + * with the "root cause" Exception as to why the lock was + * not obtained. + */ + protected Throwable failureReason; + + /** Attempts to obtain an exclusive lock within amount of + * time given. Polls once per {@link #LOCK_POLL_INTERVAL} + * (currently 1000) milliseconds until lockWaitTimeout is + * passed. + * @param lockWaitTimeout length of time to wait in + * milliseconds or {@link + * #LOCK_OBTAIN_WAIT_FOREVER} to retry forever + * @return true if lock was obtained + * @throws LockObtainFailedException if lock wait times out + * @throws IllegalArgumentException if lockWaitTimeout is + * out of bounds + * @throws IOException if obtain() throws IOException + */ + public boolean obtain(long lockWaitTimeout) throws LockObtainFailedException, IOException { + failureReason = null; + boolean locked = obtain(); + if (lockWaitTimeout < 0 && lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER) + throw new IllegalArgumentException("lockWaitTimeout should be LOCK_OBTAIN_WAIT_FOREVER or a non-negative number (got " + lockWaitTimeout + ")"); + + long maxSleepCount = lockWaitTimeout / LOCK_POLL_INTERVAL; + long sleepCount = 0; + while (!locked) { + if (lockWaitTimeout != LOCK_OBTAIN_WAIT_FOREVER && sleepCount++ >= maxSleepCount) { + String reason = "Lock obtain timed out: " + this.toString(); + if (failureReason != null) { + reason += ": " + failureReason; + } + LockObtainFailedException e = new LockObtainFailedException(reason); + if (failureReason != null) { + e.initCause(failureReason); + } + throw e; + } + try { + Thread.sleep(LOCK_POLL_INTERVAL); + } catch (InterruptedException e) { + throw new IOException(e.toString()); + } + locked = obtain(); + } + return locked; + } + + /** Releases exclusive access. */ + public abstract void release() throws IOException; + + /** Returns true if the resource is currently locked. Note that one must + * still call {@link #obtain()} before using the resource. */ + public abstract boolean isLocked(); + + + /** Utility class for executing code with exclusive access. */ + public abstract static class With { + private Lock lock; + private long lockWaitTimeout; + + + /** Constructs an executor that will grab the named lock. */ + public With(Lock lock, long lockWaitTimeout) { + this.lock = lock; + this.lockWaitTimeout = lockWaitTimeout; + } + + /** Code to execute with exclusive access. */ + protected abstract Object doBody() throws IOException; + + /** Calls {@link #doBody} while lock is obtained. Blocks if lock + * cannot be obtained immediately. Retries to obtain lock once per second + * until it is obtained, or until it has tried ten times. Lock is released when + * {@link #doBody} exits. + * @throws LockObtainFailedException if lock could not + * be obtained + * @throws IOException if {@link Lock#obtain} throws IOException + */ + public Object run() throws LockObtainFailedException, IOException { + boolean locked = false; + try { + locked = lock.obtain(lockWaitTimeout); + return doBody(); + } finally { + if (locked) + lock.release(); + } + } + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/LockFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/LockFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/LockFactory.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,74 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + *

Base class for Locking implementation. {@link Directory} uses + * instances of this class to implement locking.

+ * + *

Note that there are some useful tools to verify that + * your LockFactory is working correctly: {@link + * VerifyingLockFactory}, {@link LockStressTest}, {@link + * LockVerifyServer}.

+ * + * @see LockVerifyServer + * @see LockStressTest + * @see VerifyingLockFactory + */ + +public abstract class LockFactory { + + protected String lockPrefix = ""; + + /** + * Set the prefix in use for all locks created in this + * LockFactory. This is normally called once, when a + * Directory gets this LockFactory instance. However, you + * can also call this (after this instance is assigned to + * a Directory) to override the prefix in use. This + * is helpful if you're running Lucene on machines that + * have different mount points for the same shared + * directory. + */ + public void setLockPrefix(String lockPrefix) { + this.lockPrefix = lockPrefix; + } + + /** + * Get the prefix in use for all locks created in this LockFactory. + */ + public String getLockPrefix() { + return this.lockPrefix; + } + + /** + * Return a new Lock instance identified by lockName. + * @param lockName name of the lock to be created. + */ + public abstract Lock makeLock(String lockName); + + /** + * Attempt to clear (forcefully unlock and remove) the + * specified lock. Only call this at a time when you are + * certain this lock is no longer in use. + * @param lockName name of the lock to be cleared. + */ + abstract public void clearLock(String lockName) throws IOException; +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/LockObtainFailedException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/LockObtainFailedException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/LockObtainFailedException.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.store; + +import java.io.IOException; + +/** + * This exception is thrown when the write.lock + * could not be acquired. This + * happens when a writer tries to open an index + * that another writer already has open. + * @see Lock#obtain(long). + */ +public class LockObtainFailedException extends IOException { + public LockObtainFailedException(String message) { + super(message); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/LockReleaseFailedException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/LockReleaseFailedException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/LockReleaseFailedException.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,31 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.store; + +import java.io.IOException; + +/** + * This exception is thrown when the write.lock + * could not be released. + * @see Lock#release(). + */ +public class LockReleaseFailedException extends IOException { + public LockReleaseFailedException(String message) { + super(message); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/LockStressTest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/LockStressTest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/LockStressTest.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,117 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.File; + +/** + * Simple standalone tool that forever acquires & releases a + * lock using a specific LockFactory. Run without any args + * to see usage. + * + * @see VerifyingLockFactory + * @see LockVerifyServer + */ + +public class LockStressTest { + + public static void main(String[] args) throws Exception { + + if (args.length != 6) { + System.out.println("\nUsage: java org.apache.lucene.store.LockStressTest myID verifierHostOrIP verifierPort lockFactoryClassName lockDirName sleepTime\n" + + "\n" + + " myID = int from 0 .. 255 (should be unique for test process)\n" + + " verifierHostOrIP = host name or IP address where LockVerifyServer is running\n" + + " verifierPort = port that LockVerifyServer is listening on\n" + + " lockFactoryClassName = primary LockFactory class that we will use\n" + + " lockDirName = path to the lock directory (only set for Simple/NativeFSLockFactory\n" + + " sleepTimeMS = milliseconds to pause betweeen each lock obtain/release\n" + + "\n" + + "You should run multiple instances of this process, each with its own\n" + + "unique ID, and each pointing to the same lock directory, to verify\n" + + "that locking is working correctly.\n" + + "\n" + + "Make sure you are first running LockVerifyServer.\n" + + "\n"); + System.exit(1); + } + + final int myID = Integer.parseInt(args[0]); + + if (myID < 0 || myID > 255) { + System.out.println("myID must be a unique int 0..255"); + System.exit(1); + } + + final String verifierHost = args[1]; + final int verifierPort = Integer.parseInt(args[2]); + final String lockFactoryClassName = args[3]; + final String lockDirName = args[4]; + final int sleepTimeMS = Integer.parseInt(args[5]); + + Class c; + try { + c = Class.forName(lockFactoryClassName); + } catch (ClassNotFoundException e) { + throw new IOException("unable to find LockClass " + lockFactoryClassName); + } + + LockFactory lockFactory; + try { + lockFactory = (LockFactory) c.newInstance(); + } catch (IllegalAccessException e) { + throw new IOException("IllegalAccessException when instantiating LockClass " + lockFactoryClassName); + } catch (InstantiationException e) { + throw new IOException("InstantiationException when instantiating LockClass " + lockFactoryClassName); + } catch (ClassCastException e) { + throw new IOException("unable to cast LockClass " + lockFactoryClassName + " instance to a LockFactory"); + } + + File lockDir = new File(lockDirName); + + if (lockFactory instanceof NativeFSLockFactory) { + ((NativeFSLockFactory) lockFactory).setLockDir(lockDir); + } else if (lockFactory instanceof SimpleFSLockFactory) { + ((SimpleFSLockFactory) lockFactory).setLockDir(lockDir); + } + + lockFactory.setLockPrefix("test"); + + LockFactory verifyLF = new VerifyingLockFactory((byte) myID, lockFactory, verifierHost, verifierPort); + + Lock l = verifyLF.makeLock("test.lock"); + + while(true) { + + boolean obtained = false; + + try { + obtained = l.obtain(10); + } catch (LockObtainFailedException e) { + System.out.print("x"); + } + + if (obtained) { + System.out.print("l"); + l.release(); + } + Thread.sleep(sleepTimeMS); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/LockVerifyServer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/LockVerifyServer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/LockVerifyServer.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,96 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.net.ServerSocket; +import java.net.Socket; +import java.io.OutputStream; +import java.io.InputStream; +import java.io.IOException; + +/** + * Simple standalone server that must be running when you + * use {@link VerifyingLockFactory}. This server simply + * verifies at most one process holds the lock at a time. + * Run without any args to see usage. + * + * @see VerifyingLockFactory + * @see LockStressTest + */ + +public class LockVerifyServer { + + private static String getTime(long startTime) { + return "[" + ((System.currentTimeMillis()-startTime)/1000) + "s] "; + } + + public static void main(String[] args) throws IOException { + + if (args.length != 1) { + System.out.println("\nUsage: java org.apache.lucene.store.LockVerifyServer port\n"); + System.exit(1); + } + + final int port = Integer.parseInt(args[0]); + + ServerSocket s = new ServerSocket(port); + s.setReuseAddress(true); + System.out.println("\nReady on port " + port + "..."); + + int lockedID = 0; + long startTime = System.currentTimeMillis(); + + while(true) { + Socket cs = s.accept(); + OutputStream out = cs.getOutputStream(); + InputStream in = cs.getInputStream(); + + int id = in.read(); + int command = in.read(); + + boolean err = false; + + if (command == 1) { + // Locked + if (lockedID != 0) { + err = true; + System.out.println(getTime(startTime) + " ERROR: id " + id + " got lock, but " + lockedID + " already holds the lock"); + } + lockedID = id; + } else if (command == 0) { + if (lockedID != id) { + err = true; + System.out.println(getTime(startTime) + " ERROR: id " + id + " released the lock, but " + lockedID + " is the one holding the lock"); + } + lockedID = 0; + } else + throw new RuntimeException("unrecognized command " + command); + + System.out.print("."); + + if (err) + out.write(1); + else + out.write(0); + + out.close(); + in.close(); + cs.close(); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/MMapDirectory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/MMapDirectory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/MMapDirectory.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,205 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.File; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileChannel.MapMode; + +/** File-based {@link Directory} implementation that uses mmap for input. + * + *

To use this, invoke Java with the System property + * org.apache.lucene.FSDirectory.class set to + * org.apache.lucene.store.MMapDirectory. This will cause {@link + * FSDirectory#getDirectory(File,boolean)} to return instances of this class. + */ +public class MMapDirectory extends FSDirectory { + + private static class MMapIndexInput extends IndexInput { + + private ByteBuffer buffer; + private final long length; + + private MMapIndexInput(RandomAccessFile raf) throws IOException { + this.length = raf.length(); + this.buffer = raf.getChannel().map(MapMode.READ_ONLY, 0, length); + } + + public byte readByte() throws IOException { + return buffer.get(); + } + + public void readBytes(byte[] b, int offset, int len) + throws IOException { + buffer.get(b, offset, len); + } + + public long getFilePointer() { + return buffer.position(); + } + + public void seek(long pos) throws IOException { + buffer.position((int)pos); + } + + public long length() { + return length; + } + + public Object clone() { + MMapIndexInput clone = (MMapIndexInput)super.clone(); + clone.buffer = buffer.duplicate(); + return clone; + } + + public void close() throws IOException {} + } + + private static class MultiMMapIndexInput extends IndexInput { + + private ByteBuffer[] buffers; + private int[] bufSizes; // keep here, ByteBuffer.size() method is optional + + private final long length; + + private int curBufIndex; + private final int maxBufSize; + + private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex] + private int curAvail; // redundant for speed: (bufSizes[curBufIndex] - curBuf.position()) + + + public MultiMMapIndexInput(RandomAccessFile raf, int maxBufSize) + throws IOException { + this.length = raf.length(); + this.maxBufSize = maxBufSize; + + if (maxBufSize <= 0) + throw new IllegalArgumentException("Non positive maxBufSize: " + + maxBufSize); + + if ((length / maxBufSize) > Integer.MAX_VALUE) + throw new IllegalArgumentException + ("RandomAccessFile too big for maximum buffer size: " + + raf.toString()); + + int nrBuffers = (int) (length / maxBufSize); + if ((nrBuffers * maxBufSize) < length) nrBuffers++; + + this.buffers = new ByteBuffer[nrBuffers]; + this.bufSizes = new int[nrBuffers]; + + long bufferStart = 0; + FileChannel rafc = raf.getChannel(); + for (int bufNr = 0; bufNr < nrBuffers; bufNr++) { + int bufSize = (length > (bufferStart + maxBufSize)) + ? maxBufSize + : (int) (length - bufferStart); + this.buffers[bufNr] = rafc.map(MapMode.READ_ONLY,bufferStart,bufSize); + this.bufSizes[bufNr] = bufSize; + bufferStart += bufSize; + } + seek(0L); + } + + public byte readByte() throws IOException { + // Performance might be improved by reading ahead into an array of + // eg. 128 bytes and readByte() from there. + if (curAvail == 0) { + curBufIndex++; + curBuf = buffers[curBufIndex]; // index out of bounds when too many bytes requested + curBuf.position(0); + curAvail = bufSizes[curBufIndex]; + } + curAvail--; + return curBuf.get(); + } + + public void readBytes(byte[] b, int offset, int len) throws IOException { + while (len > curAvail) { + curBuf.get(b, offset, curAvail); + len -= curAvail; + offset += curAvail; + curBufIndex++; + curBuf = buffers[curBufIndex]; // index out of bounds when too many bytes requested + curBuf.position(0); + curAvail = bufSizes[curBufIndex]; + } + curBuf.get(b, offset, len); + curAvail -= len; + } + + public long getFilePointer() { + return (curBufIndex * (long) maxBufSize) + curBuf.position(); + } + + public void seek(long pos) throws IOException { + curBufIndex = (int) (pos / maxBufSize); + curBuf = buffers[curBufIndex]; + int bufOffset = (int) (pos - (curBufIndex * maxBufSize)); + curBuf.position(bufOffset); + curAvail = bufSizes[curBufIndex] - bufOffset; + } + + public long length() { + return length; + } + + public Object clone() { + MultiMMapIndexInput clone = (MultiMMapIndexInput)super.clone(); + clone.buffers = new ByteBuffer[buffers.length]; + // No need to clone bufSizes. + // Since most clones will use only one buffer, duplicate() could also be + // done lazy in clones, eg. when adapting curBuf. + for (int bufNr = 0; bufNr < buffers.length; bufNr++) { + clone.buffers[bufNr] = buffers[bufNr].duplicate(); + } + try { + clone.seek(getFilePointer()); + } catch(IOException ioe) { + RuntimeException newException = new RuntimeException(ioe); + newException.initCause(ioe); + throw newException; + }; + return clone; + } + + public void close() throws IOException {} + } + + private final int MAX_BBUF = Integer.MAX_VALUE; + + public IndexInput openInput(String name) throws IOException { + File f = new File(getFile(), name); + RandomAccessFile raf = new RandomAccessFile(f, "r"); + try { + return (raf.length() <= MAX_BBUF) + ? (IndexInput) new MMapIndexInput(raf) + : (IndexInput) new MultiMMapIndexInput(raf, MAX_BBUF); + } finally { + raf.close(); + } + } + + public IndexInput openInput(String name, int bufferSize) throws IOException { + return openInput(name); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/NIOFSDirectory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/NIOFSDirectory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/NIOFSDirectory.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,120 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; + +/** + * NIO version of FSDirectory. Uses FileChannel.read(ByteBuffer dst, long position) method + * which allows multiple threads to read from the file without synchronizing. FSDirectory + * synchronizes in the FSIndexInput.readInternal method which can cause pileups when there + * are many threads accessing the Directory concurrently. + * + * This class only uses FileChannel when reading; writing + * with an IndexOutput is inherited from FSDirectory. + * + * Note: NIOFSDirectory is not recommended on Windows because of a bug + * in how FileChannel.read is implemented in Sun's JRE. + * Inside of the implementation the position is apparently + * synchronized. See here for details: + + * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6265734 + * + * @see FSDirectory + */ + +public class NIOFSDirectory extends FSDirectory { + + // Inherit javadoc + public IndexInput openInput(String name, int bufferSize) throws IOException { + ensureOpen(); + return new NIOFSIndexInput(new File(getFile(), name), bufferSize); + } + + private static class NIOFSIndexInput extends FSDirectory.FSIndexInput { + + private ByteBuffer byteBuf; // wraps the buffer for NIO + + private byte[] otherBuffer; + private ByteBuffer otherByteBuf; + + final FileChannel channel; + + public NIOFSIndexInput(File path, int bufferSize) throws IOException { + super(path, bufferSize); + channel = file.getChannel(); + } + + protected void newBuffer(byte[] newBuffer) { + super.newBuffer(newBuffer); + byteBuf = ByteBuffer.wrap(newBuffer); + } + + public void close() throws IOException { + if (!isClone && file.isOpen) { + // Close the channel & file + try { + channel.close(); + } finally { + file.close(); + } + } + } + + protected void readInternal(byte[] b, int offset, int len) throws IOException { + + final ByteBuffer bb; + + // Determine the ByteBuffer we should use + if (b == buffer && 0 == offset) { + // Use our own pre-wrapped byteBuf: + assert byteBuf != null; + byteBuf.clear(); + byteBuf.limit(len); + bb = byteBuf; + } else { + if (offset == 0) { + if (otherBuffer != b) { + // Now wrap this other buffer; with compound + // file, we are repeatedly called with its + // buffer, so we wrap it once and then re-use it + // on subsequent calls + otherBuffer = b; + otherByteBuf = ByteBuffer.wrap(b); + } else + otherByteBuf.clear(); + otherByteBuf.limit(len); + bb = otherByteBuf; + } else + // Always wrap when offset != 0 + bb = ByteBuffer.wrap(b, offset, len); + } + + long pos = getFilePointer(); + while (bb.hasRemaining()) { + int i = channel.read(bb, pos); + if (i == -1) + throw new IOException("read past EOF"); + pos += i; + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/NativeFSLockFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/NativeFSLockFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/NativeFSLockFactory.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,332 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.io.File; +import java.io.RandomAccessFile; +import java.io.IOException; +import java.util.HashSet; +import java.util.Random; + +/** + *

Implements {@link LockFactory} using native OS file + * locks. Note that because this LockFactory relies on + * java.nio.* APIs for locking, any problems with those APIs + * will cause locking to fail. Specifically, on certain NFS + * environments the java.nio.* locks will fail (the lock can + * incorrectly be double acquired) whereas {@link + * SimpleFSLockFactory} worked perfectly in those same + * environments. For NFS based access to an index, it's + * recommended that you try {@link SimpleFSLockFactory} + * first and work around the one limitation that a lock file + * could be left when the JVM exits abnormally.

+ * + *

The primary benefit of {@link NativeFSLockFactory} is + * that lock files will be properly removed (by the OS) if + * the JVM has an abnormal exit.

+ * + *

Note that, unlike {@link SimpleFSLockFactory}, the existence of + * leftover lock files in the filesystem on exiting the JVM + * is fine because the OS will free the locks held against + * these files even though the files still remain.

+ * + *

If you suspect that this or any other LockFactory is + * not working properly in your environment, you can easily + * test it by using {@link VerifyingLockFactory}, {@link + * LockVerifyServer} and {@link LockStressTest}.

+ * + * @see LockFactory + */ + +public class NativeFSLockFactory extends LockFactory { + + /** + * Directory specified by org.apache.lucene.lockDir + * system property. If that is not set, then java.io.tmpdir + * system property is used. + */ + + private File lockDir; + + // Simple test to verify locking system is "working". On + // NFS, if it's misconfigured, you can hit long (35 + // second) timeouts which cause Lock.obtain to take far + // too long (it assumes the obtain() call takes zero + // time). Since it's a configuration problem, we test up + // front once on creating the LockFactory: + private void acquireTestLock() throws IOException { + String randomLockName = "lucene-" + Long.toString(new Random().nextInt(), Character.MAX_RADIX) + "-test.lock"; + + Lock l = makeLock(randomLockName); + try { + l.obtain(); + } catch (IOException e) { + IOException e2 = new IOException("Failed to acquire random test lock; please verify filesystem for lock directory '" + lockDir + "' supports locking"); + e2.initCause(e); + throw e2; + } + + l.release(); + } + + /** + * Create a NativeFSLockFactory instance, with null (unset) + * lock directory. This is package-private and is only + * used by FSDirectory when creating this LockFactory via + * the System property + * org.apache.lucene.store.FSDirectoryLockFactoryClass. + */ + NativeFSLockFactory() throws IOException { + this((File) null); + } + + /** + * Create a NativeFSLockFactory instance, storing lock + * files into the specified lockDirName: + * + * @param lockDirName where lock files are created. + */ + public NativeFSLockFactory(String lockDirName) throws IOException { + this(new File(lockDirName)); + } + + /** + * Create a NativeFSLockFactory instance, storing lock + * files into the specified lockDir: + * + * @param lockDir where lock files are created. + */ + public NativeFSLockFactory(File lockDir) throws IOException { + setLockDir(lockDir); + } + + /** + * Set the lock directory. This is package-private and is + * only used externally by FSDirectory when creating this + * LockFactory via the System property + * org.apache.lucene.store.FSDirectoryLockFactoryClass. + */ + void setLockDir(File lockDir) throws IOException { + this.lockDir = lockDir; + if (lockDir != null) { + // Ensure that lockDir exists and is a directory. + if (!lockDir.exists()) { + if (!lockDir.mkdirs()) + throw new IOException("Cannot create directory: " + + lockDir.getAbsolutePath()); + } else if (!lockDir.isDirectory()) { + throw new IOException("Found regular file where directory expected: " + + lockDir.getAbsolutePath()); + } + + acquireTestLock(); + } + } + + public synchronized Lock makeLock(String lockName) { + if (lockPrefix != null) + lockName = lockPrefix + "-n-" + lockName; + return new NativeFSLock(lockDir, lockName); + } + + public void clearLock(String lockName) throws IOException { + // Note that this isn't strictly required anymore + // because the existence of these files does not mean + // they are locked, but, still do this in case people + // really want to see the files go away: + if (lockDir.exists()) { + if (lockPrefix != null) { + lockName = lockPrefix + "-n-" + lockName; + } + File lockFile = new File(lockDir, lockName); + if (lockFile.exists() && !lockFile.delete()) { + throw new IOException("Cannot delete " + lockFile); + } + } + } +}; + +class NativeFSLock extends Lock { + + private RandomAccessFile f; + private FileChannel channel; + private FileLock lock; + private File path; + private File lockDir; + + /* + * The javadocs for FileChannel state that you should have + * a single instance of a FileChannel (per JVM) for all + * locking against a given file. To ensure this, we have + * a single (static) HashSet that contains the file paths + * of all currently locked locks. This protects against + * possible cases where different Directory instances in + * one JVM (each with their own NativeFSLockFactory + * instance) have set the same lock dir and lock prefix. + */ + private static HashSet LOCK_HELD = new HashSet(); + + public NativeFSLock(File lockDir, String lockFileName) { + this.lockDir = lockDir; + path = new File(lockDir, lockFileName); + } + + public synchronized boolean obtain() throws IOException { + + if (isLocked()) { + // Our instance is already locked: + return false; + } + + // Ensure that lockDir exists and is a directory. + if (!lockDir.exists()) { + if (!lockDir.mkdirs()) + throw new IOException("Cannot create directory: " + + lockDir.getAbsolutePath()); + } else if (!lockDir.isDirectory()) { + throw new IOException("Found regular file where directory expected: " + + lockDir.getAbsolutePath()); + } + + String canonicalPath = path.getCanonicalPath(); + + boolean markedHeld = false; + + try { + + // Make sure nobody else in-process has this lock held + // already, and, mark it held if not: + + synchronized(LOCK_HELD) { + if (LOCK_HELD.contains(canonicalPath)) { + // Someone else in this JVM already has the lock: + return false; + } else { + // This "reserves" the fact that we are the one + // thread trying to obtain this lock, so we own + // the only instance of a channel against this + // file: + LOCK_HELD.add(canonicalPath); + markedHeld = true; + } + } + + try { + f = new RandomAccessFile(path, "rw"); + } catch (IOException e) { + // On Windows, we can get intermittant "Access + // Denied" here. So, we treat this as failure to + // acquire the lock, but, store the reason in case + // there is in fact a real error case. + failureReason = e; + f = null; + } + + if (f != null) { + try { + channel = f.getChannel(); + try { + lock = channel.tryLock(); + } catch (IOException e) { + // At least on OS X, we will sometimes get an + // intermittant "Permission Denied" IOException, + // which seems to simply mean "you failed to get + // the lock". But other IOExceptions could be + // "permanent" (eg, locking is not supported via + // the filesystem). So, we record the failure + // reason here; the timeout obtain (usually the + // one calling us) will use this as "root cause" + // if it fails to get the lock. + failureReason = e; + } finally { + if (lock == null) { + try { + channel.close(); + } finally { + channel = null; + } + } + } + } finally { + if (channel == null) { + try { + f.close(); + } finally { + f = null; + } + } + } + } + + } finally { + if (markedHeld && !isLocked()) { + synchronized(LOCK_HELD) { + if (LOCK_HELD.contains(canonicalPath)) { + LOCK_HELD.remove(canonicalPath); + } + } + } + } + return isLocked(); + } + + public synchronized void release() throws IOException { + if (isLocked()) { + try { + lock.release(); + } finally { + lock = null; + try { + channel.close(); + } finally { + channel = null; + try { + f.close(); + } finally { + f = null; + synchronized(LOCK_HELD) { + LOCK_HELD.remove(path.getCanonicalPath()); + } + } + } + } + if (!path.delete()) + throw new LockReleaseFailedException("failed to delete " + path); + } + } + + public synchronized boolean isLocked() { + return lock != null; + } + + public String toString() { + return "NativeFSLock@" + path; + } + + public void finalize() throws Throwable { + try { + if (isLocked()) { + release(); + } + } finally { + super.finalize(); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/NoLockFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/NoLockFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/NoLockFactory.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,63 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + * Use this {@link LockFactory} to disable locking entirely. + * This LockFactory is used when you call {@link FSDirectory#setDisableLocks}. + * Only one instance of this lock is created. You should call {@link + * #getNoLockFactory()} to get the instance. + * + * @see LockFactory + */ + +public class NoLockFactory extends LockFactory { + + // Single instance returned whenever makeLock is called. + private static NoLock singletonLock = new NoLock(); + private static NoLockFactory singleton = new NoLockFactory(); + + public static NoLockFactory getNoLockFactory() { + return singleton; + } + + public Lock makeLock(String lockName) { + return singletonLock; + } + + public void clearLock(String lockName) {}; +}; + +class NoLock extends Lock { + public boolean obtain() throws IOException { + return true; + } + + public void release() { + } + + public boolean isLocked() { + return false; + } + + public String toString() { + return "NoLock"; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/RAMDirectory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/RAMDirectory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/RAMDirectory.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,243 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.io.FileNotFoundException; +import java.io.File; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; + +/** + * A memory-resident {@link Directory} implementation. Locking + * implementation is by default the {@link SingleInstanceLockFactory} + * but can be changed with {@link #setLockFactory}. + * + * @version $Id: RAMDirectory.java,v 1.1 2012/08/17 14:55:05 marcin Exp $ + */ +public class RAMDirectory extends Directory implements Serializable { + + private static final long serialVersionUID = 1l; + + HashMap fileMap = new HashMap(); + long sizeInBytes = 0; + + // ***** + // Lock acquisition sequence: RAMDirectory, then RAMFile + // ***** + + /** Constructs an empty {@link Directory}. */ + public RAMDirectory() { + setLockFactory(new SingleInstanceLockFactory()); + } + + /** + * Creates a new RAMDirectory instance from a different + * Directory implementation. This can be used to load + * a disk-based index into memory. + *

+ * This should be used only with indices that can fit into memory. + *

+ * Note that the resulting RAMDirectory instance is fully + * independent from the original Directory (it is a + * complete copy). Any subsequent changes to the + * original Directory will not be visible in the + * RAMDirectory instance. + * + * @param dir a Directory value + * @exception IOException if an error occurs + */ + public RAMDirectory(Directory dir) throws IOException { + this(dir, false); + } + + private RAMDirectory(Directory dir, boolean closeDir) throws IOException { + this(); + Directory.copy(dir, this, closeDir); + } + + /** + * Creates a new RAMDirectory instance from the {@link FSDirectory}. + * + * @param dir a File specifying the index directory + * + * @see #RAMDirectory(Directory) + */ + public RAMDirectory(File dir) throws IOException { + this(FSDirectory.getDirectory(dir), true); + } + + /** + * Creates a new RAMDirectory instance from the {@link FSDirectory}. + * + * @param dir a String specifying the full index directory path + * + * @see #RAMDirectory(Directory) + */ + public RAMDirectory(String dir) throws IOException { + this(FSDirectory.getDirectory(dir), true); + } + + /** Returns an array of strings, one for each file in the directory. */ + public synchronized final String[] list() { + ensureOpen(); + Set fileNames = fileMap.keySet(); + String[] result = new String[fileNames.size()]; + int i = 0; + Iterator it = fileNames.iterator(); + while (it.hasNext()) + result[i++] = (String)it.next(); + return result; + } + + /** Returns true iff the named file exists in this directory. */ + public final boolean fileExists(String name) { + ensureOpen(); + RAMFile file; + synchronized (this) { + file = (RAMFile)fileMap.get(name); + } + return file != null; + } + + /** Returns the time the named file was last modified. + * @throws IOException if the file does not exist + */ + public final long fileModified(String name) throws IOException { + ensureOpen(); + RAMFile file; + synchronized (this) { + file = (RAMFile)fileMap.get(name); + } + if (file==null) + throw new FileNotFoundException(name); + return file.getLastModified(); + } + + /** Set the modified time of an existing file to now. + * @throws IOException if the file does not exist + */ + public void touchFile(String name) throws IOException { + ensureOpen(); + RAMFile file; + synchronized (this) { + file = (RAMFile)fileMap.get(name); + } + if (file==null) + throw new FileNotFoundException(name); + + long ts2, ts1 = System.currentTimeMillis(); + do { + try { + Thread.sleep(0, 1); + } catch (InterruptedException e) {} + ts2 = System.currentTimeMillis(); + } while(ts1 == ts2); + + file.setLastModified(ts2); + } + + /** Returns the length in bytes of a file in the directory. + * @throws IOException if the file does not exist + */ + public final long fileLength(String name) throws IOException { + ensureOpen(); + RAMFile file; + synchronized (this) { + file = (RAMFile)fileMap.get(name); + } + if (file==null) + throw new FileNotFoundException(name); + return file.getLength(); + } + + /** Return total size in bytes of all files in this + * directory. This is currently quantized to + * RAMOutputStream.BUFFER_SIZE. */ + public synchronized final long sizeInBytes() { + ensureOpen(); + return sizeInBytes; + } + + /** Removes an existing file in the directory. + * @throws IOException if the file does not exist + */ + public synchronized void deleteFile(String name) throws IOException { + ensureOpen(); + RAMFile file = (RAMFile)fileMap.get(name); + if (file!=null) { + fileMap.remove(name); + file.directory = null; + sizeInBytes -= file.sizeInBytes; // updates to RAMFile.sizeInBytes synchronized on directory + } else + throw new FileNotFoundException(name); + } + + /** Renames an existing file in the directory. + * @throws FileNotFoundException if from does not exist + * @deprecated + */ + public synchronized final void renameFile(String from, String to) throws IOException { + ensureOpen(); + RAMFile fromFile = (RAMFile)fileMap.get(from); + if (fromFile==null) + throw new FileNotFoundException(from); + RAMFile toFile = (RAMFile)fileMap.get(to); + if (toFile!=null) { + sizeInBytes -= toFile.sizeInBytes; // updates to RAMFile.sizeInBytes synchronized on directory + toFile.directory = null; + } + fileMap.remove(from); + fileMap.put(to, fromFile); + } + + /** Creates a new, empty file in the directory with the given name. Returns a stream writing this file. */ + public IndexOutput createOutput(String name) throws IOException { + ensureOpen(); + RAMFile file = new RAMFile(this); + synchronized (this) { + RAMFile existing = (RAMFile)fileMap.get(name); + if (existing!=null) { + sizeInBytes -= existing.sizeInBytes; + existing.directory = null; + } + fileMap.put(name, file); + } + return new RAMOutputStream(file); + } + + /** Returns a stream reading an existing file. */ + public IndexInput openInput(String name) throws IOException { + ensureOpen(); + RAMFile file; + synchronized (this) { + file = (RAMFile)fileMap.get(name); + } + if (file == null) + throw new FileNotFoundException(name); + return new RAMInputStream(file); + } + + /** Closes the store to future operations, releasing associated memory. */ + public void close() { + isOpen = false; + fileMap = null; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/RAMFile.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/RAMFile.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/RAMFile.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,98 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.io.Serializable; + +class RAMFile implements Serializable { + + private static final long serialVersionUID = 1l; + + private ArrayList buffers = new ArrayList(); + long length; + RAMDirectory directory; + long sizeInBytes; // Only maintained if in a directory; updates synchronized on directory + + // This is publicly modifiable via Directory.touchFile(), so direct access not supported + private long lastModified = System.currentTimeMillis(); + + // File used as buffer, in no RAMDirectory + RAMFile() {} + + RAMFile(RAMDirectory directory) { + this.directory = directory; + } + + // For non-stream access from thread that might be concurrent with writing + synchronized long getLength() { + return length; + } + + synchronized void setLength(long length) { + this.length = length; + } + + // For non-stream access from thread that might be concurrent with writing + synchronized long getLastModified() { + return lastModified; + } + + synchronized void setLastModified(long lastModified) { + this.lastModified = lastModified; + } + + final synchronized byte[] addBuffer(int size) { + byte[] buffer = newBuffer(size); + if (directory!=null) + synchronized (directory) { // Ensure addition of buffer and adjustment to directory size are atomic wrt directory + buffers.add(buffer); + directory.sizeInBytes += size; + sizeInBytes += size; + } + else + buffers.add(buffer); + return buffer; + } + + final synchronized byte[] getBuffer(int index) { + return (byte[]) buffers.get(index); + } + + final synchronized int numBuffers() { + return buffers.size(); + } + + /** + * Expert: allocate a new buffer. + * Subclasses can allocate differently. + * @param size size of allocated buffer. + * @return allocated buffer. + */ + byte[] newBuffer(int size) { + return new byte[size]; + } + + // Only valid if in a directory + long getSizeInBytes() { + synchronized (directory) { + return sizeInBytes; + } + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/RAMInputStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/RAMInputStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/RAMInputStream.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,116 @@ +package org.apache.lucene.store; + +import java.io.IOException; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A memory-resident {@link IndexInput} implementation. + * + * @version $Id: RAMInputStream.java,v 1.1 2012/08/17 14:55:05 marcin Exp $ + */ + +class RAMInputStream extends IndexInput implements Cloneable { + static final int BUFFER_SIZE = RAMOutputStream.BUFFER_SIZE; + + private RAMFile file; + private long length; + + private byte[] currentBuffer; + private int currentBufferIndex; + + private int bufferPosition; + private long bufferStart; + private int bufferLength; + + RAMInputStream(RAMFile f) throws IOException { + file = f; + length = file.length; + if (length/BUFFER_SIZE >= Integer.MAX_VALUE) { + throw new IOException("Too large RAMFile! "+length); + } + + // make sure that we switch to the + // first needed buffer lazily + currentBufferIndex = -1; + currentBuffer = null; + } + + public void close() { + // nothing to do here + } + + public long length() { + return length; + } + + public byte readByte() throws IOException { + if (bufferPosition >= bufferLength) { + currentBufferIndex++; + switchCurrentBuffer(true); + } + return currentBuffer[bufferPosition++]; + } + + public void readBytes(byte[] b, int offset, int len) throws IOException { + while (len > 0) { + if (bufferPosition >= bufferLength) { + currentBufferIndex++; + switchCurrentBuffer(true); + } + + int remainInBuffer = bufferLength - bufferPosition; + int bytesToCopy = len < remainInBuffer ? len : remainInBuffer; + System.arraycopy(currentBuffer, bufferPosition, b, offset, bytesToCopy); + offset += bytesToCopy; + len -= bytesToCopy; + bufferPosition += bytesToCopy; + } + } + + private final void switchCurrentBuffer(boolean enforceEOF) throws IOException { + if (currentBufferIndex >= file.numBuffers()) { + // end of file reached, no more buffers left + if (enforceEOF) + throw new IOException("Read past EOF"); + else { + // Force EOF if a read takes place at this position + currentBufferIndex--; + bufferPosition = BUFFER_SIZE; + } + } else { + currentBuffer = (byte[]) file.getBuffer(currentBufferIndex); + bufferPosition = 0; + bufferStart = (long) BUFFER_SIZE * (long) currentBufferIndex; + long buflen = length - bufferStart; + bufferLength = buflen > BUFFER_SIZE ? BUFFER_SIZE : (int) buflen; + } + } + + public long getFilePointer() { + return currentBufferIndex < 0 ? 0 : bufferStart + bufferPosition; + } + + public void seek(long pos) throws IOException { + if (currentBuffer==null || pos < bufferStart || pos >= bufferStart + BUFFER_SIZE) { + currentBufferIndex = (int) (pos / BUFFER_SIZE); + switchCurrentBuffer(false); + } + bufferPosition = (int) (pos % BUFFER_SIZE); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/RAMOutputStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/RAMOutputStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/RAMOutputStream.java 17 Aug 2012 14:55:05 -0000 1.1 @@ -0,0 +1,158 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +/** + * A memory-resident {@link IndexOutput} implementation. + * + * @version $Id: RAMOutputStream.java,v 1.1 2012/08/17 14:55:05 marcin Exp $ + */ + +public class RAMOutputStream extends IndexOutput { + static final int BUFFER_SIZE = 1024; + + private RAMFile file; + + private byte[] currentBuffer; + private int currentBufferIndex; + + private int bufferPosition; + private long bufferStart; + private int bufferLength; + + /** Construct an empty output buffer. */ + public RAMOutputStream() { + this(new RAMFile()); + } + + RAMOutputStream(RAMFile f) { + file = f; + + // make sure that we switch to the + // first needed buffer lazily + currentBufferIndex = -1; + currentBuffer = null; + } + + /** Copy the current contents of this buffer to the named output. */ + public void writeTo(IndexOutput out) throws IOException { + flush(); + final long end = file.length; + long pos = 0; + int buffer = 0; + while (pos < end) { + int length = BUFFER_SIZE; + long nextPos = pos + length; + if (nextPos > end) { // at the last buffer + length = (int)(end - pos); + } + out.writeBytes((byte[])file.getBuffer(buffer++), length); + pos = nextPos; + } + } + + /** Resets this to an empty buffer. */ + public void reset() { + try { + seek(0); + } catch (IOException e) { // should never happen + throw new RuntimeException(e.toString()); + } + + file.setLength(0); + } + + public void close() throws IOException { + flush(); + } + + public void seek(long pos) throws IOException { + // set the file length in case we seek back + // and flush() has not been called yet + setFileLength(); + if (pos < bufferStart || pos >= bufferStart + bufferLength) { + currentBufferIndex = (int) (pos / BUFFER_SIZE); + switchCurrentBuffer(); + } + + bufferPosition = (int) (pos % BUFFER_SIZE); + } + + public long length() { + return file.length; + } + + public void writeByte(byte b) throws IOException { + if (bufferPosition == bufferLength) { + currentBufferIndex++; + switchCurrentBuffer(); + } + currentBuffer[bufferPosition++] = b; + } + + public void writeBytes(byte[] b, int offset, int len) throws IOException { + assert b != null; + while (len > 0) { + if (bufferPosition == bufferLength) { + currentBufferIndex++; + switchCurrentBuffer(); + } + + int remainInBuffer = currentBuffer.length - bufferPosition; + int bytesToCopy = len < remainInBuffer ? len : remainInBuffer; + System.arraycopy(b, offset, currentBuffer, bufferPosition, bytesToCopy); + offset += bytesToCopy; + len -= bytesToCopy; + bufferPosition += bytesToCopy; + } + } + + private final void switchCurrentBuffer() throws IOException { + if (currentBufferIndex == file.numBuffers()) { + currentBuffer = file.addBuffer(BUFFER_SIZE); + } else { + currentBuffer = (byte[]) file.getBuffer(currentBufferIndex); + } + bufferPosition = 0; + bufferStart = (long) BUFFER_SIZE * (long) currentBufferIndex; + bufferLength = currentBuffer.length; + } + + private void setFileLength() { + long pointer = bufferStart + bufferPosition; + if (pointer > file.length) { + file.setLength(pointer); + } + } + + public void flush() throws IOException { + file.setLastModified(System.currentTimeMillis()); + setFileLength(); + } + + public long getFilePointer() { + return currentBufferIndex < 0 ? 0 : bufferStart + bufferPosition; + } + + /** Returns byte usage of all buffers. */ + public long sizeInBytes() { + return file.numBuffers() * BUFFER_SIZE; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/SimpleFSLockFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/SimpleFSLockFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/SimpleFSLockFactory.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,159 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.io.IOException; + +/** + *

Implements {@link LockFactory} using {@link + * File#createNewFile()}. This is the default LockFactory + * for {@link FSDirectory}.

+ * + *

NOTE: the javadocs + * for File.createNewFile contain a vague + * yet spooky warning about not using the API for file + * locking. This warning was added due to this + * bug, and in fact the only known problem with using + * this API for locking is that the Lucene write lock may + * not be released when the JVM exits abnormally.

+ + *

When this happens, a {@link LockObtainFailedException} + * is hit when trying to create a writer, in which case you + * need to explicitly clear the lock file first. You can + * either manually remove the file, or use the {@link + * org.apache.lucene.index.IndexReader#unlock(Directory)} + * API. But, first be certain that no writer is in fact + * writing to the index otherwise you can easily corrupt + * your index.

+ * + *

If you suspect that this or any other LockFactory is + * not working properly in your environment, you can easily + * test it by using {@link VerifyingLockFactory}, {@link + * LockVerifyServer} and {@link LockStressTest}.

+ * + * @see LockFactory + */ + +public class SimpleFSLockFactory extends LockFactory { + + /** + * Directory specified by org.apache.lucene.lockDir + * system property. If that is not set, then java.io.tmpdir + * system property is used. + */ + + private File lockDir; + + /** + * Create a SimpleFSLockFactory instance, with null (unset) + * lock directory. This is package-private and is only + * used by FSDirectory when creating this LockFactory via + * the System property + * org.apache.lucene.store.FSDirectoryLockFactoryClass. + */ + SimpleFSLockFactory() throws IOException { + this((File) null); + } + + /** + * Instantiate using the provided directory (as a File instance). + * @param lockDir where lock files should be created. + */ + public SimpleFSLockFactory(File lockDir) throws IOException { + setLockDir(lockDir); + } + + /** + * Instantiate using the provided directory name (String). + * @param lockDirName where lock files should be created. + */ + public SimpleFSLockFactory(String lockDirName) throws IOException { + lockDir = new File(lockDirName); + setLockDir(lockDir); + } + + /** + * Set the lock directory. This is package-private and is + * only used externally by FSDirectory when creating this + * LockFactory via the System property + * org.apache.lucene.store.FSDirectoryLockFactoryClass. + */ + void setLockDir(File lockDir) throws IOException { + this.lockDir = lockDir; + } + + public Lock makeLock(String lockName) { + if (lockPrefix != null) { + lockName = lockPrefix + "-" + lockName; + } + return new SimpleFSLock(lockDir, lockName); + } + + public void clearLock(String lockName) throws IOException { + if (lockDir.exists()) { + if (lockPrefix != null) { + lockName = lockPrefix + "-" + lockName; + } + File lockFile = new File(lockDir, lockName); + if (lockFile.exists() && !lockFile.delete()) { + throw new IOException("Cannot delete " + lockFile); + } + } + } +}; + +class SimpleFSLock extends Lock { + + File lockFile; + File lockDir; + + public SimpleFSLock(File lockDir, String lockFileName) { + this.lockDir = lockDir; + lockFile = new File(lockDir, lockFileName); + } + + public boolean obtain() throws IOException { + + // Ensure that lockDir exists and is a directory: + if (!lockDir.exists()) { + if (!lockDir.mkdirs()) + throw new IOException("Cannot create directory: " + + lockDir.getAbsolutePath()); + } else if (!lockDir.isDirectory()) { + throw new IOException("Found regular file where directory expected: " + + lockDir.getAbsolutePath()); + } + return lockFile.createNewFile(); + } + + public void release() throws LockReleaseFailedException { + if (lockFile.exists() && !lockFile.delete()) + throw new LockReleaseFailedException("failed to delete " + lockFile); + } + + public boolean isLocked() { + return lockFile.exists(); + } + + public String toString() { + return "SimpleFSLock@" + lockFile; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/SingleInstanceLockFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/SingleInstanceLockFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/SingleInstanceLockFactory.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,85 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.HashSet; + +/** + * Implements {@link LockFactory} for a single in-process instance, + * meaning all locking will take place through this one instance. + * Only use this {@link LockFactory} when you are certain all + * IndexReaders and IndexWriters for a given index are running + * against a single shared in-process Directory instance. This is + * currently the default locking for RAMDirectory. + * + * @see LockFactory + */ + +public class SingleInstanceLockFactory extends LockFactory { + + private HashSet locks = new HashSet(); + + public Lock makeLock(String lockName) { + // We do not use the LockPrefix at all, because the private + // HashSet instance effectively scopes the locking to this + // single Directory instance. + return new SingleInstanceLock(locks, lockName); + } + + public void clearLock(String lockName) throws IOException { + synchronized(locks) { + if (locks.contains(lockName)) { + locks.remove(lockName); + } + } + } +}; + +class SingleInstanceLock extends Lock { + + String lockName; + private HashSet locks; + + public SingleInstanceLock(HashSet locks, String lockName) { + this.locks = locks; + this.lockName = lockName; + } + + public boolean obtain() throws IOException { + synchronized(locks) { + return locks.add(lockName); + } + } + + public void release() { + synchronized(locks) { + locks.remove(lockName); + } + } + + public boolean isLocked() { + synchronized(locks) { + return locks.contains(lockName); + } + } + + public String toString() { + return "SingleInstanceLock: " + lockName; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/VerifyingLockFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/VerifyingLockFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/VerifyingLockFactory.java 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,119 @@ +package org.apache.lucene.store; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.net.Socket; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * A {@link LockFactory} that wraps another {@link + * LockFactory} and verifies that each lock obtain/release + * is "correct" (never results in two processes holding the + * lock at the same time). It does this by contacting an + * external server ({@link LockVerifyServer}) to assert that + * at most one process holds the lock at a time. To use + * this, you should also run {@link LockVerifyServer} on the + * host & port matching what you pass to the constructor. + * + * @see LockVerifyServer + * @see LockStressTest + */ + +public class VerifyingLockFactory extends LockFactory { + + LockFactory lf; + byte id; + String host; + int port; + + private class CheckedLock extends Lock { + private Lock lock; + + public CheckedLock(Lock lock) { + this.lock = lock; + } + + private void verify(byte message) { + try { + Socket s = new Socket(host, port); + OutputStream out = s.getOutputStream(); + out.write(id); + out.write(message); + InputStream in = s.getInputStream(); + int result = in.read(); + in.close(); + out.close(); + s.close(); + if (result != 0) + throw new RuntimeException("lock was double acquired"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public synchronized boolean obtain(long lockWaitTimeout) + throws LockObtainFailedException, IOException { + boolean obtained = lock.obtain(lockWaitTimeout); + if (obtained) + verify((byte) 1); + return obtained; + } + + public synchronized boolean obtain() + throws LockObtainFailedException, IOException { + return lock.obtain(); + } + + public synchronized boolean isLocked() { + return lock.isLocked(); + } + + public synchronized void release() throws IOException { + if (isLocked()) { + verify((byte) 0); + lock.release(); + } + } + } + + /** + * @param id should be a unique id across all clients + * @param lf the LockFactory that we are testing + * @param host host or IP where {@link LockVerifyServer} + is running + * @param port the port {@link LockVerifyServer} is + listening on + */ + public VerifyingLockFactory(byte id, LockFactory lf, String host, int port) throws IOException { + this.id = id; + this.lf = lf; + this.host = host; + this.port = port; + } + + public synchronized Lock makeLock(String lockName) { + return new CheckedLock(lf.makeLock(lockName)); + } + + public synchronized void clearLock(String lockName) + throws IOException { + lf.clearLock(lockName); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/store/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/store/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/store/package.html 17 Aug 2012 14:55:06 -0000 1.1 @@ -0,0 +1,26 @@ + + + + + + + + +Binary i/o API, used for all index data. + + Index: 3rdParty_sources/lucene/org/apache/lucene/util/ArrayUtil.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/ArrayUtil.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/ArrayUtil.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,130 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +public final class ArrayUtil { + + public static int getNextSize(int targetSize) { + /* This over-allocates proportional to the list size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... + */ + return (targetSize >> 3) + (targetSize < 9 ? 3 : 6) + targetSize; + } + + public static int getShrinkSize(int currentSize, int targetSize) { + final int newSize = getNextSize(targetSize); + // Only reallocate if we are "substantially" smaller. + // This saves us from "running hot" (constantly making a + // bit bigger then a bit smaller, over and over): + if (newSize < currentSize/2) + return newSize; + else + return currentSize; + } + + public static int[] grow(int[] array, int minSize) { + if (array.length < minSize) { + int[] newArray = new int[getNextSize(minSize)]; + System.arraycopy(array, 0, newArray, 0, array.length); + return newArray; + } else + return array; + } + + public static int[] grow(int[] array) { + return grow(array, 1+array.length); + } + + public static int[] shrink(int[] array, int targetSize) { + final int newSize = getShrinkSize(array.length, targetSize); + if (newSize != array.length) { + int[] newArray = new int[newSize]; + System.arraycopy(array, 0, newArray, 0, newSize); + return newArray; + } else + return array; + } + + public static long[] grow(long[] array, int minSize) { + if (array.length < minSize) { + long[] newArray = new long[getNextSize(minSize)]; + System.arraycopy(array, 0, newArray, 0, array.length); + return newArray; + } else + return array; + } + + public static long[] grow(long[] array) { + return grow(array, 1+array.length); + } + + public static long[] shrink(long[] array, int targetSize) { + final int newSize = getShrinkSize(array.length, targetSize); + if (newSize != array.length) { + long[] newArray = new long[newSize]; + System.arraycopy(array, 0, newArray, 0, newSize); + return newArray; + } else + return array; + } + + public static byte[] grow(byte[] array, int minSize) { + if (array.length < minSize) { + byte[] newArray = new byte[getNextSize(minSize)]; + System.arraycopy(array, 0, newArray, 0, array.length); + return newArray; + } else + return array; + } + + public static byte[] grow(byte[] array) { + return grow(array, 1+array.length); + } + + public static byte[] shrink(byte[] array, int targetSize) { + final int newSize = getShrinkSize(array.length, targetSize); + if (newSize != array.length) { + byte[] newArray = new byte[newSize]; + System.arraycopy(array, 0, newArray, 0, newSize); + return newArray; + } else + return array; + } + + /** Returns hash of chars in range start (inclusive) to + * end (inclusive) */ + public static int hashCode(char[] array, int start, int end) { + int code = 0; + for(int i=end-1;i>=start;i--) + code = code*31 + array[i]; + return code; + } + + /** Returns hash of chars in range start (inclusive) to + * end (inclusive) */ + public static int hashCode(byte[] array, int start, int end) { + int code = 0; + for(int i=end-1;i>=start;i--) + code = code*31 + array[i]; + return code; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/BitUtil.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/BitUtil.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/BitUtil.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,799 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.util; // from org.apache.solr.util rev 555343 + +/** A variety of high efficiencly bit twiddling routines. + * + * @version $Id: BitUtil.java,v 1.1 2012/08/17 14:54:53 marcin Exp $ + */ +public class BitUtil { + + /** Returns the number of bits set in the long */ + public static int pop(long x) { + /* Hacker's Delight 32 bit pop function: + * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc + * + int pop(unsigned x) { + x = x - ((x >> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + x = (x + (x >> 4)) & 0x0F0F0F0F; + x = x + (x >> 8); + x = x + (x >> 16); + return x & 0x0000003F; + } + ***/ + + // 64 bit java version of the C function from above + x = x - ((x >>> 1) & 0x5555555555555555L); + x = (x & 0x3333333333333333L) + ((x >>>2 ) & 0x3333333333333333L); + x = (x + (x >>> 4)) & 0x0F0F0F0F0F0F0F0FL; + x = x + (x >>> 8); + x = x + (x >>> 16); + x = x + (x >>> 32); + return ((int)x) & 0x7F; + } + + /*** Returns the number of set bits in an array of longs. */ + public static long pop_array(long A[], int wordOffset, int numWords) { + /* + * Robert Harley and David Seal's bit counting algorithm, as documented + * in the revisions of Hacker's Delight + * http://www.hackersdelight.org/revisions.pdf + * http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.cc + * + * This function was adapted to Java, and extended to use 64 bit words. + * if only we had access to wider registers like SSE from java... + * + * This function can be transformed to compute the popcount of other functions + * on bitsets via something like this: + * sed 's/A\[\([^]]*\)\]/\(A[\1] \& B[\1]\)/g' + * + */ + int n = wordOffset+numWords; + long tot=0, tot8=0; + long ones=0, twos=0, fours=0; + + int i; + for (i = wordOffset; i <= n - 8; i+=8) { + /*** C macro from Hacker's Delight + #define CSA(h,l, a,b,c) \ + {unsigned u = a ^ b; unsigned v = c; \ + h = (a & b) | (u & v); l = u ^ v;} + ***/ + + long twosA,twosB,foursA,foursB,eights; + + // CSA(twosA, ones, ones, A[i], A[i+1]) + { + long b=A[i], c=A[i+1]; + long u=ones ^ b; + twosA=(ones & b)|( u & c); + ones=u^c; + } + // CSA(twosB, ones, ones, A[i+2], A[i+3]) + { + long b=A[i+2], c=A[i+3]; + long u=ones^b; + twosB =(ones&b)|(u&c); + ones=u^c; + } + //CSA(foursA, twos, twos, twosA, twosB) + { + long u=twos^twosA; + foursA=(twos&twosA)|(u&twosB); + twos=u^twosB; + } + //CSA(twosA, ones, ones, A[i+4], A[i+5]) + { + long b=A[i+4], c=A[i+5]; + long u=ones^b; + twosA=(ones&b)|(u&c); + ones=u^c; + } + // CSA(twosB, ones, ones, A[i+6], A[i+7]) + { + long b=A[i+6], c=A[i+7]; + long u=ones^b; + twosB=(ones&b)|(u&c); + ones=u^c; + } + //CSA(foursB, twos, twos, twosA, twosB) + { + long u=twos^twosA; + foursB=(twos&twosA)|(u&twosB); + twos=u^twosB; + } + + //CSA(eights, fours, fours, foursA, foursB) + { + long u=fours^foursA; + eights=(fours&foursA)|(u&foursB); + fours=u^foursB; + } + tot8 += pop(eights); + } + + // handle trailing words in a binary-search manner... + // derived from the loop above by setting specific elements to 0. + // the original method in Hackers Delight used a simple for loop: + // for (i = i; i < n; i++) // Add in the last elements + // tot = tot + pop(A[i]); + + if (i<=n-4) { + long twosA, twosB, foursA, eights; + { + long b=A[i], c=A[i+1]; + long u=ones ^ b; + twosA=(ones & b)|( u & c); + ones=u^c; + } + { + long b=A[i+2], c=A[i+3]; + long u=ones^b; + twosB =(ones&b)|(u&c); + ones=u^c; + } + { + long u=twos^twosA; + foursA=(twos&twosA)|(u&twosB); + twos=u^twosB; + } + eights=fours&foursA; + fours=fours^foursA; + + tot8 += pop(eights); + i+=4; + } + + if (i<=n-2) { + long b=A[i], c=A[i+1]; + long u=ones ^ b; + long twosA=(ones & b)|( u & c); + ones=u^c; + + long foursA=twos&twosA; + twos=twos^twosA; + + long eights=fours&foursA; + fours=fours^foursA; + + tot8 += pop(eights); + i+=2; + } + + if (i>= 1 + return i + print ','.join([ str(ntz(i)) for i in range(256) ]) + ***/ + /** table of number of trailing zeros in a byte */ + public static final byte[] ntzTable = {8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0}; + + + /** Returns number of trailing zeros in the 64 bit long value. */ + public static int ntz(long val) { + // A full binary search to determine the low byte was slower than + // a linear search for nextSetBit(). This is most likely because + // the implementation of nextSetBit() shifts bits to the right, increasing + // the probability that the first non-zero byte is in the rhs. + // + // This implementation does a single binary search at the top level only + // so that all other bit shifting can be done on ints instead of longs to + // remain friendly to 32 bit architectures. In addition, the case of a + // non-zero first byte is checked for first because it is the most common + // in dense bit arrays. + + int lower = (int)val; + int lowByte = lower & 0xff; + if (lowByte != 0) return ntzTable[lowByte]; + + if (lower!=0) { + lowByte = (lower>>>8) & 0xff; + if (lowByte != 0) return ntzTable[lowByte] + 8; + lowByte = (lower>>>16) & 0xff; + if (lowByte != 0) return ntzTable[lowByte] + 16; + // no need to mask off low byte for the last byte in the 32 bit word + // no need to check for zero on the last byte either. + return ntzTable[lower>>>24] + 24; + } else { + // grab upper 32 bits + int upper=(int)(val>>32); + lowByte = upper & 0xff; + if (lowByte != 0) return ntzTable[lowByte] + 32; + lowByte = (upper>>>8) & 0xff; + if (lowByte != 0) return ntzTable[lowByte] + 40; + lowByte = (upper>>>16) & 0xff; + if (lowByte != 0) return ntzTable[lowByte] + 48; + // no need to mask off low byte for the last byte in the 32 bit word + // no need to check for zero on the last byte either. + return ntzTable[upper>>>24] + 56; + } + } + + /** returns 0 based index of first set bit + * (only works for x!=0) + *
This is an alternate implementation of ntz() + */ + public static int ntz2(long x) { + int n = 0; + int y = (int)x; + if (y==0) {n+=32; y = (int)(x>>>32); } // the only 64 bit shift necessary + if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } + if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } + return (ntzTable[ y & 0xff ]) + n; + } + + /** returns 0 based index of first set bit + *
This is an alternate implementation of ntz() + */ + public static int ntz3(long x) { + // another implementation taken from Hackers Delight, extended to 64 bits + // and converted to Java. + // Many 32 bit ntz algorithms are at http://www.hackersdelight.org/HDcode/ntz.cc + int n = 1; + + // do the first step as a long, all others as ints. + int y = (int)x; + if (y==0) {n+=32; y = (int)(x>>>32); } + if ((y & 0x0000FFFF) == 0) { n+=16; y>>>=16; } + if ((y & 0x000000FF) == 0) { n+=8; y>>>=8; } + if ((y & 0x0000000F) == 0) { n+=4; y>>>=4; } + if ((y & 0x00000003) == 0) { n+=2; y>>>=2; } + return n - (y & 1); + } + + + /** returns true if v is a power of two or zero*/ + public static boolean isPowerOfTwo(int v) { + return ((v & (v-1)) == 0); + } + + /** returns true if v is a power of two or zero*/ + public static boolean isPowerOfTwo(long v) { + return ((v & (v-1)) == 0); + } + + /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ + public static int nextHighestPowerOfTwo(int v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + + /** returns the next highest power of two, or the current value if it's already a power of two or zero*/ + public static long nextHighestPowerOfTwo(long v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v |= v >> 32; + v++; + return v; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/BitVector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/BitVector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/BitVector.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,233 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; + +import org.apache.lucene.store.Directory; +import org.apache.lucene.store.IndexInput; +import org.apache.lucene.store.IndexOutput; + +/** Optimized implementation of a vector of bits. This is more-or-less like + java.util.BitSet, but also includes the following: +
    +
  • a count() method, which efficiently computes the number of one bits;
  • +
  • optimized read from and write to disk;
  • +
  • inlinable get() method;
  • +
  • store and load, as bit set or d-gaps, depending on sparseness;
  • +
+ + + @version $Id: BitVector.java,v 1.1 2012/08/17 14:54:54 marcin Exp $ + */ +public final class BitVector { + + private byte[] bits; + private int size; + private int count = -1; + + /** Constructs a vector capable of holding n bits. */ + public BitVector(int n) { + size = n; + bits = new byte[(size >> 3) + 1]; + } + + /** Sets the value of bit to one. */ + public final void set(int bit) { + if (bit >= size) { + throw new ArrayIndexOutOfBoundsException(bit); + } + bits[bit >> 3] |= 1 << (bit & 7); + count = -1; + } + + /** Sets the value of bit to true, and + * returns true if bit was already set */ + public final boolean getAndSet(int bit) { + if (bit >= size) { + throw new ArrayIndexOutOfBoundsException(bit); + } + final int pos = bit >> 3; + final int v = bits[pos]; + final int flag = 1 << (bit & 7); + if ((flag & v) != 0) + return true; + else { + bits[pos] = (byte) (v | flag); + if (count != -1) + count++; + return false; + } + } + + /** Sets the value of bit to zero. */ + public final void clear(int bit) { + if (bit >= size) { + throw new ArrayIndexOutOfBoundsException(bit); + } + bits[bit >> 3] &= ~(1 << (bit & 7)); + count = -1; + } + + /** Returns true if bit is one and + false if it is zero. */ + public final boolean get(int bit) { + if (bit >= size) { + throw new ArrayIndexOutOfBoundsException(bit); + } + return (bits[bit >> 3] & (1 << (bit & 7))) != 0; + } + + /** Returns the number of bits in this vector. This is also one greater than + the number of the largest valid bit number. */ + public final int size() { + return size; + } + + /** Returns the total number of one bits in this vector. This is efficiently + computed and cached, so that, if the vector is not changed, no + recomputation is done for repeated calls. */ + public final int count() { + // if the vector has been modified + if (count == -1) { + int c = 0; + int end = bits.length; + for (int i = 0; i < end; i++) + c += BYTE_COUNTS[bits[i] & 0xFF]; // sum bits per byte + count = c; + } + return count; + } + + private static final byte[] BYTE_COUNTS = { // table of bits/byte + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 + }; + + + /** Writes this vector to the file name in Directory + d, in a format that can be read by the constructor {@link + #BitVector(Directory, String)}. */ + public final void write(Directory d, String name) throws IOException { + IndexOutput output = d.createOutput(name); + try { + if (isSparse()) { + writeDgaps(output); // sparse bit-set more efficiently saved as d-gaps. + } else { + writeBits(output); + } + } finally { + output.close(); + } + } + + /** Write as a bit set */ + private void writeBits(IndexOutput output) throws IOException { + output.writeInt(size()); // write size + output.writeInt(count()); // write count + output.writeBytes(bits, bits.length); + } + + /** Write as a d-gaps list */ + private void writeDgaps(IndexOutput output) throws IOException { + output.writeInt(-1); // mark using d-gaps + output.writeInt(size()); // write size + output.writeInt(count()); // write count + int last=0; + int n = count(); + int m = bits.length; + for (int i=0; i0; i++) { + if (bits[i]!=0) { + output.writeVInt(i-last); + output.writeByte(bits[i]); + last = i; + n -= BYTE_COUNTS[bits[i] & 0xFF]; + } + } + } + + /** Indicates if the bit vector is sparse and should be saved as a d-gaps list, or dense, and should be saved as a bit set. */ + private boolean isSparse() { + // note: order of comparisons below set to favor smaller values (no binary range search.) + // note: adding 4 because we start with ((int) -1) to indicate d-gaps format. + // note: we write the d-gap for the byte number, and the byte (bits[i]) itself, therefore + // multiplying count by (8+8) or (8+16) or (8+24) etc.: + // - first 8 for writing bits[i] (1 byte vs. 1 bit), and + // - second part for writing the byte-number d-gap as vint. + // note: factor is for read/write of byte-arrays being faster than vints. + int factor = 10; + if (bits.length < (1<< 7)) return factor * (4 + (8+ 8)*count()) < size(); + if (bits.length < (1<<14)) return factor * (4 + (8+16)*count()) < size(); + if (bits.length < (1<<21)) return factor * (4 + (8+24)*count()) < size(); + if (bits.length < (1<<28)) return factor * (4 + (8+32)*count()) < size(); + return factor * (4 + (8+40)*count()) < size(); + } + + /** Constructs a bit vector from the file name in Directory + d, as written by the {@link #write} method. + */ + public BitVector(Directory d, String name) throws IOException { + IndexInput input = d.openInput(name); + try { + size = input.readInt(); // read size + if (size == -1) { + readDgaps(input); + } else { + readBits(input); + } + } finally { + input.close(); + } + } + + /** Read as a bit set */ + private void readBits(IndexInput input) throws IOException { + count = input.readInt(); // read count + bits = new byte[(size >> 3) + 1]; // allocate bits + input.readBytes(bits, 0, bits.length); + } + + /** read as a d-gaps list */ + private void readDgaps(IndexInput input) throws IOException { + size = input.readInt(); // (re)read size + count = input.readInt(); // read count + bits = new byte[(size >> 3) + 1]; // allocate bits + int last=0; + int n = count(); + while (n>0) { + last += input.readVInt(); + bits[last] = input.readByte(); + n -= BYTE_COUNTS[bits[last] & 0xFF]; + } + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/CloseableThreadLocal.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/CloseableThreadLocal.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/CloseableThreadLocal.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,97 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Map; +import java.util.HashMap; +import java.util.Iterator; +import java.lang.ref.WeakReference; + +/** Java's builtin ThreadLocal has a serious flaw: + * it can take an arbitrarily long amount of time to + * dereference the things you had stored in it, even once the + * ThreadLocal instance itself is no longer referenced. + * This is because there is single, master map stored for + * each thread, which all ThreadLocals share, and that + * master map only periodically purges "stale" entries. + * + * While not technically a memory leak, because eventually + * the memory will be reclaimed, it can take a long time + * and you can easily hit OutOfMemoryError because from the + * GC's standpoint the stale entries are not reclaimaible. + * + * This class works around that, by only enrolling + * WeakReference values into the ThreadLocal, and + * separately holding a hard reference to each stored + * value. When you call {@link #close}, these hard + * references are cleared and then GC is freely able to + * reclaim space by objects stored in it. */ + +public class CloseableThreadLocal { + + private ThreadLocal t = new ThreadLocal(); + + private Map hardRefs = new HashMap(); + + protected Object initialValue() { + return null; + } + + public Object get() { + WeakReference weakRef = (WeakReference) t.get(); + if (weakRef == null) { + Object iv = initialValue(); + if (iv != null) { + set(iv); + return iv; + } else + return null; + } else { + Object v = weakRef.get(); + // This can never be null, because we hold a hard + // reference to the underlying object: + assert v != null; + return v; + } + } + + public void set(Object object) { + + t.set(new WeakReference(object)); + + synchronized(hardRefs) { + hardRefs.put(Thread.currentThread(), object); + + // Purge dead threads + Iterator it = hardRefs.keySet().iterator(); + while(it.hasNext()) { + Thread t = (Thread) it.next(); + if (!t.isAlive()) + it.remove(); + } + } + } + + public void close() { + // Clear the hard refs; then, the only remaining refs to + // all values we were storing are weak (unless somewhere + // else is still using them) and so GC may reclaim them: + hardRefs = null; + t = null; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/Constants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/Constants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/Constants.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,47 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Some useful constants. + * + * + * @version $Id: Constants.java,v 1.1 2012/08/17 14:54:53 marcin Exp $ + **/ + +public final class Constants { + private Constants() {} // can't construct + + /** The value of System.getProperty("java.version"). **/ + public static final String JAVA_VERSION = System.getProperty("java.version"); + /** True iff this is Java version 1.1. */ + public static final boolean JAVA_1_1 = JAVA_VERSION.startsWith("1.1."); + /** True iff this is Java version 1.2. */ + public static final boolean JAVA_1_2 = JAVA_VERSION.startsWith("1.2."); + /** True iff this is Java version 1.3. */ + public static final boolean JAVA_1_3 = JAVA_VERSION.startsWith("1.3."); + + /** The value of System.getProperty("os.name"). **/ + public static final String OS_NAME = System.getProperty("os.name"); + /** True iff running on Linux. */ + public static final boolean LINUX = OS_NAME.startsWith("Linux"); + /** True iff running on Windows. */ + public static final boolean WINDOWS = OS_NAME.startsWith("Windows"); + /** True iff running on SunOS. */ + public static final boolean SUN_OS = OS_NAME.startsWith("SunOS"); +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/DocIdBitSet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/DocIdBitSet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/DocIdBitSet.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,77 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.BitSet; +import org.apache.lucene.search.DocIdSet; +import org.apache.lucene.search.DocIdSetIterator; + + +/** Simple DocIdSet and DocIdSetIterator backed by a BitSet */ +public class DocIdBitSet extends DocIdSet { + private BitSet bitSet; + + public DocIdBitSet(BitSet bitSet) { + this.bitSet = bitSet; + } + + public DocIdSetIterator iterator() { + return new DocIdBitSetIterator(bitSet); + } + + /** + * Returns the underlying BitSet. + */ + public BitSet getBitSet() { + return this.bitSet; + } + + private static class DocIdBitSetIterator extends DocIdSetIterator { + private int docId; + private BitSet bitSet; + + DocIdBitSetIterator(BitSet bitSet) { + this.bitSet = bitSet; + this.docId = -1; + } + + public int doc() { + assert docId != -1; + return docId; + } + + public boolean next() { + // (docId + 1) on next line requires -1 initial value for docNr: + return checkNextDocId(bitSet.nextSetBit(docId + 1)); + } + + public boolean skipTo(int skipDocNr) { + return checkNextDocId( bitSet.nextSetBit(skipDocNr)); + } + + private boolean checkNextDocId(int d) { + if (d == -1) { // -1 returned by BitSet.nextSetBit() when exhausted + docId = Integer.MAX_VALUE; + return false; + } else { + docId = d; + return true; + } + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSet.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,773 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.util; + +import java.util.Arrays; +import java.io.Serializable; + +import org.apache.lucene.search.DocIdSet; +import org.apache.lucene.search.DocIdSetIterator; + +/** An "open" BitSet implementation that allows direct access to the array of words + * storing the bits. + *

+ * Unlike java.util.bitset, the fact that bits are packed into an array of longs + * is part of the interface. This allows efficient implementation of other algorithms + * by someone other than the author. It also allows one to efficiently implement + * alternate serialization or interchange formats. + *

+ * OpenBitSet is faster than java.util.BitSet in most operations + * and *much* faster at calculating cardinality of sets and results of set operations. + * It can also handle sets of larger cardinality (up to 64 * 2**32-1) + *

+ * The goals of OpenBitSet are the fastest implementation possible, and + * maximum code reuse. Extra safety and encapsulation + * may always be built on top, but if that's built in, the cost can never be removed (and + * hence people re-implement their own version in order to get better performance). + * If you want a "safe", totally encapsulated (and slower and limited) BitSet + * class, use java.util.BitSet. + *

+ *

Performance Results

+ * + Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M +
BitSet size = 1,000,000 +
Results are java.util.BitSet time divided by OpenBitSet time. + + + + + + + + + + +
cardinality intersect_count union nextSetBit get iterator
50% full 3.36 3.96 1.44 1.46 1.99 1.58
1% full 3.31 3.90   1.04   0.99
+
+Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M +
BitSet size = 1,000,000 +
Results are java.util.BitSet time divided by OpenBitSet time. + + + + + + + + + + +
cardinality intersect_count union nextSetBit get iterator
50% full 2.50 3.50 1.00 1.03 1.12 1.25
1% full 2.51 3.49   1.00   1.02
+ + * @version $Id: OpenBitSet.java,v 1.1 2012/08/17 14:54:53 marcin Exp $ + */ + +public class OpenBitSet extends DocIdSet implements Cloneable, Serializable { + protected long[] bits; + protected int wlen; // number of words (elements) used in the array + + /** Constructs an OpenBitSet large enough to hold numBits. + * + * @param numBits + */ + public OpenBitSet(long numBits) { + bits = new long[bits2words(numBits)]; + wlen = bits.length; + } + + public OpenBitSet() { + this(64); + } + + /** Constructs an OpenBitSet from an existing long[]. + *
+ * The first 64 bits are in long[0], + * with bit index 0 at the least significant bit, and bit index 63 at the most significant. + * Given a bit index, + * the word containing it is long[index/64], and it is at bit number index%64 within that word. + *

+ * numWords are the number of elements in the array that contain + * set bits (non-zero longs). + * numWords should be <= bits.length, and + * any existing words in the array at position >= numWords should be zero. + * + */ + public OpenBitSet(long[] bits, int numWords) { + this.bits = bits; + this.wlen = numWords; + } + + public DocIdSetIterator iterator() { + return new OpenBitSetIterator(bits, wlen); + } + + /** Returns the current capacity in bits (1 greater than the index of the last bit) */ + public long capacity() { return bits.length << 6; } + + /** + * Returns the current capacity of this set. Included for + * compatibility. This is *not* equal to {@link #cardinality} + */ + public long size() { + return capacity(); + } + + /** Returns true if there are no set bits */ + public boolean isEmpty() { return cardinality()==0; } + + /** Expert: returns the long[] storing the bits */ + public long[] getBits() { return bits; } + + /** Expert: sets a new long[] to use as the bit storage */ + public void setBits(long[] bits) { this.bits = bits; } + + /** Expert: gets the number of longs in the array that are in use */ + public int getNumWords() { return wlen; } + + /** Expert: sets the number of longs in the array that are in use */ + public void setNumWords(int nWords) { this.wlen=nWords; } + + + + /** Returns true or false for the specified bit index. */ + public boolean get(int index) { + int i = index >> 6; // div 64 + // signed shift will keep a negative index and force an + // array-index-out-of-bounds-exception, removing the need for an explicit check. + if (i>=bits.length) return false; + + int bit = index & 0x3f; // mod 64 + long bitmask = 1L << bit; + return (bits[i] & bitmask) != 0; + } + + + /** Returns true or false for the specified bit index. + * The index should be less than the OpenBitSet size + */ + public boolean fastGet(int index) { + int i = index >> 6; // div 64 + // signed shift will keep a negative index and force an + // array-index-out-of-bounds-exception, removing the need for an explicit check. + int bit = index & 0x3f; // mod 64 + long bitmask = 1L << bit; + return (bits[i] & bitmask) != 0; + } + + + + /** Returns true or false for the specified bit index + */ + public boolean get(long index) { + int i = (int)(index >> 6); // div 64 + if (i>=bits.length) return false; + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + return (bits[i] & bitmask) != 0; + } + + /** Returns true or false for the specified bit index. + * The index should be less than the OpenBitSet size. + */ + public boolean fastGet(long index) { + int i = (int)(index >> 6); // div 64 + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + return (bits[i] & bitmask) != 0; + } + + /* + // alternate implementation of get() + public boolean get1(int index) { + int i = index >> 6; // div 64 + int bit = index & 0x3f; // mod 64 + return ((bits[i]>>>bit) & 0x01) != 0; + // this does a long shift and a bittest (on x86) vs + // a long shift, and a long AND, (the test for zero is prob a no-op) + // testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0; + } + */ + + + /** returns 1 if the bit is set, 0 if not. + * The index should be less than the OpenBitSet size + */ + public int getBit(int index) { + int i = index >> 6; // div 64 + int bit = index & 0x3f; // mod 64 + return ((int)(bits[i]>>>bit)) & 0x01; + } + + + /* + public boolean get2(int index) { + int word = index >> 6; // div 64 + int bit = index & 0x0000003f; // mod 64 + return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed + // we could right shift and check for parity bit, if it was available to us. + } + */ + + /** sets a bit, expanding the set size if necessary */ + public void set(long index) { + int wordNum = expandingWordNum(index); + int bit = (int)index & 0x3f; + long bitmask = 1L << bit; + bits[wordNum] |= bitmask; + } + + + /** Sets the bit at the specified index. + * The index should be less than the OpenBitSet size. + */ + public void fastSet(int index) { + int wordNum = index >> 6; // div 64 + int bit = index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] |= bitmask; + } + + /** Sets the bit at the specified index. + * The index should be less than the OpenBitSet size. + */ + public void fastSet(long index) { + int wordNum = (int)(index >> 6); + int bit = (int)index & 0x3f; + long bitmask = 1L << bit; + bits[wordNum] |= bitmask; + } + + /** Sets a range of bits, expanding the set size if necessary + * + * @param startIndex lower index + * @param endIndex one-past the last bit to set + */ + public void set(long startIndex, long endIndex) { + if (endIndex <= startIndex) return; + + int startWord = (int)(startIndex>>6); + + // since endIndex is one past the end, this is index of the last + // word to be changed. + int endWord = expandingWordNum(endIndex-1); + + long startmask = -1L << startIndex; + long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap + + if (startWord == endWord) { + bits[startWord] |= (startmask & endmask); + return; + } + + bits[startWord] |= startmask; + Arrays.fill(bits, startWord+1, endWord, -1L); + bits[endWord] |= endmask; + } + + + + protected int expandingWordNum(long index) { + int wordNum = (int)(index >> 6); + if (wordNum>=wlen) { + ensureCapacity(index+1); + wlen = wordNum+1; + } + return wordNum; + } + + + /** clears a bit. + * The index should be less than the OpenBitSet size. + */ + public void fastClear(int index) { + int wordNum = index >> 6; + int bit = index & 0x03f; + long bitmask = 1L << bit; + bits[wordNum] &= ~bitmask; + // hmmm, it takes one more instruction to clear than it does to set... any + // way to work around this? If there were only 63 bits per word, we could + // use a right shift of 10111111...111 in binary to position the 0 in the + // correct place (using sign extension). + // Could also use Long.rotateRight() or rotateLeft() *if* they were converted + // by the JVM into a native instruction. + // bits[word] &= Long.rotateLeft(0xfffffffe,bit); + } + + /** clears a bit. + * The index should be less than the OpenBitSet size. + */ + public void fastClear(long index) { + int wordNum = (int)(index >> 6); // div 64 + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] &= ~bitmask; + } + + /** clears a bit, allowing access beyond the current set size without changing the size.*/ + public void clear(long index) { + int wordNum = (int)(index >> 6); // div 64 + if (wordNum>=wlen) return; + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] &= ~bitmask; + } + + /** Clears a range of bits. Clearing past the end does not change the size of the set. + * + * @param startIndex lower index + * @param endIndex one-past the last bit to clear + */ + public void clear(long startIndex, long endIndex) { + if (endIndex <= startIndex) return; + + int startWord = (int)(startIndex>>6); + if (startWord >= wlen) return; + + // since endIndex is one past the end, this is index of the last + // word to be changed. + int endWord = (int)((endIndex-1)>>6); + + long startmask = -1L << startIndex; + long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap + + // invert masks since we are clearing + startmask = ~startmask; + endmask = ~endmask; + + if (startWord == endWord) { + bits[startWord] &= (startmask | endmask); + return; + } + + bits[startWord] &= startmask; + + int middle = Math.min(wlen, endWord); + Arrays.fill(bits, startWord+1, middle, 0L); + if (endWord < wlen) { + bits[endWord] &= endmask; + } + } + + + + /** Sets a bit and returns the previous value. + * The index should be less than the OpenBitSet size. + */ + public boolean getAndSet(int index) { + int wordNum = index >> 6; // div 64 + int bit = index & 0x3f; // mod 64 + long bitmask = 1L << bit; + boolean val = (bits[wordNum] & bitmask) != 0; + bits[wordNum] |= bitmask; + return val; + } + + /** Sets a bit and returns the previous value. + * The index should be less than the OpenBitSet size. + */ + public boolean getAndSet(long index) { + int wordNum = (int)(index >> 6); // div 64 + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + boolean val = (bits[wordNum] & bitmask) != 0; + bits[wordNum] |= bitmask; + return val; + } + + /** flips a bit. + * The index should be less than the OpenBitSet size. + */ + public void fastFlip(int index) { + int wordNum = index >> 6; // div 64 + int bit = index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] ^= bitmask; + } + + /** flips a bit. + * The index should be less than the OpenBitSet size. + */ + public void fastFlip(long index) { + int wordNum = (int)(index >> 6); // div 64 + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] ^= bitmask; + } + + /** flips a bit, expanding the set size if necessary */ + public void flip(long index) { + int wordNum = expandingWordNum(index); + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] ^= bitmask; + } + + /** flips a bit and returns the resulting bit value. + * The index should be less than the OpenBitSet size. + */ + public boolean flipAndGet(int index) { + int wordNum = index >> 6; // div 64 + int bit = index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] ^= bitmask; + return (bits[wordNum] & bitmask) != 0; + } + + /** flips a bit and returns the resulting bit value. + * The index should be less than the OpenBitSet size. + */ + public boolean flipAndGet(long index) { + int wordNum = (int)(index >> 6); // div 64 + int bit = (int)index & 0x3f; // mod 64 + long bitmask = 1L << bit; + bits[wordNum] ^= bitmask; + return (bits[wordNum] & bitmask) != 0; + } + + /** Flips a range of bits, expanding the set size if necessary + * + * @param startIndex lower index + * @param endIndex one-past the last bit to flip + */ + public void flip(long startIndex, long endIndex) { + if (endIndex <= startIndex) return; + int oldlen = wlen; + int startWord = (int)(startIndex>>6); + + // since endIndex is one past the end, this is index of the last + // word to be changed. + int endWord = expandingWordNum(endIndex-1); + + /*** Grrr, java shifting wraps around so -1L>>>64 == -1 + * for that reason, make sure not to use endmask if the bits to flip will + * be zero in the last word (redefine endWord to be the last changed...) + long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000 + long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111 + ***/ + + long startmask = -1L << startIndex; + long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap + + if (startWord == endWord) { + bits[startWord] ^= (startmask & endmask); + return; + } + + bits[startWord] ^= startmask; + + for (int i=startWord+1; i b.wlen) { + tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); + } + return tot; + } + + /** Returns the popcount or cardinality of "a and not b" + * or "intersection(a, not(b))". + * Neither set is modified. + */ + public static long andNotCount(OpenBitSet a, OpenBitSet b) { + long tot = BitUtil.pop_andnot(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); + if (a.wlen > b.wlen) { + tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); + } + return tot; + } + + /** Returns the popcount or cardinality of the exclusive-or of the two sets. + * Neither set is modified. + */ + public static long xorCount(OpenBitSet a, OpenBitSet b) { + long tot = BitUtil.pop_xor(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen)); + if (a.wlen < b.wlen) { + tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen); + } else if (a.wlen > b.wlen) { + tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen); + } + return tot; + } + + + /** Returns the index of the first set bit starting at the index specified. + * -1 is returned if there are no more set bits. + */ + public int nextSetBit(int index) { + int i = index>>6; + if (i>=wlen) return -1; + int subIndex = index & 0x3f; // index within the word + long word = bits[i] >> subIndex; // skip all the bits to the right of index + + if (word!=0) { + return (i<<6) + subIndex + BitUtil.ntz(word); + } + + while(++i < wlen) { + word = bits[i]; + if (word!=0) return (i<<6) + BitUtil.ntz(word); + } + + return -1; + } + + /** Returns the index of the first set bit starting at the index specified. + * -1 is returned if there are no more set bits. + */ + public long nextSetBit(long index) { + int i = (int)(index>>>6); + if (i>=wlen) return -1; + int subIndex = (int)index & 0x3f; // index within the word + long word = bits[i] >>> subIndex; // skip all the bits to the right of index + + if (word!=0) { + return (((long)i)<<6) + (subIndex + BitUtil.ntz(word)); + } + + while(++i < wlen) { + word = bits[i]; + if (word!=0) return (((long)i)<<6) + BitUtil.ntz(word); + } + + return -1; + } + + + + + public Object clone() { + try { + OpenBitSet obs = (OpenBitSet)super.clone(); + obs.bits = (long[]) obs.bits.clone(); // hopefully an array clone is as fast(er) than arraycopy + return obs; + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); + } + } + + /** this = this AND other */ + public void intersect(OpenBitSet other) { + int newLen= Math.min(this.wlen,other.wlen); + long[] thisArr = this.bits; + long[] otherArr = other.bits; + // testing against zero can be more efficient + int pos=newLen; + while(--pos>=0) { + thisArr[pos] &= otherArr[pos]; + } + if (this.wlen > newLen) { + // fill zeros from the new shorter length to the old length + Arrays.fill(bits,newLen,this.wlen,0); + } + this.wlen = newLen; + } + + /** this = this OR other */ + public void union(OpenBitSet other) { + int newLen = Math.max(wlen,other.wlen); + ensureCapacityWords(newLen); + + long[] thisArr = this.bits; + long[] otherArr = other.bits; + int pos=Math.min(wlen,other.wlen); + while(--pos>=0) { + thisArr[pos] |= otherArr[pos]; + } + if (this.wlen < newLen) { + System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen); + } + this.wlen = newLen; + } + + + /** Remove all elements set in other. this = this AND_NOT other */ + public void remove(OpenBitSet other) { + int idx = Math.min(wlen,other.wlen); + long[] thisArr = this.bits; + long[] otherArr = other.bits; + while(--idx>=0) { + thisArr[idx] &= ~otherArr[idx]; + } + } + + /** this = this XOR other */ + public void xor(OpenBitSet other) { + int newLen = Math.max(wlen,other.wlen); + ensureCapacityWords(newLen); + + long[] thisArr = this.bits; + long[] otherArr = other.bits; + int pos=Math.min(wlen,other.wlen); + while(--pos>=0) { + thisArr[pos] ^= otherArr[pos]; + } + if (this.wlen < newLen) { + System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen); + } + this.wlen = newLen; + } + + + // some BitSet compatability methods + + //** see {@link intersect} */ + public void and(OpenBitSet other) { + intersect(other); + } + + //** see {@link union} */ + public void or(OpenBitSet other) { + union(other); + } + + //** see {@link andNot} */ + public void andNot(OpenBitSet other) { + remove(other); + } + + /** returns true if the sets have any elements in common */ + public boolean intersects(OpenBitSet other) { + int pos = Math.min(this.wlen, other.wlen); + long[] thisArr = this.bits; + long[] otherArr = other.bits; + while (--pos>=0) { + if ((thisArr[pos] & otherArr[pos])!=0) return true; + } + return false; + } + + + + /** Expand the long[] with the size given as a number of words (64 bit longs). + * getNumWords() is unchanged by this call. + */ + public void ensureCapacityWords(int numWords) { + if (bits.length < numWords) { + long[] newBits = new long[numWords]; + System.arraycopy(bits,0,newBits,0,wlen); + bits = newBits; + } + } + + /** Ensure that the long[] is big enough to hold numBits, expanding it if necessary. + * getNumWords() is unchanged by this call. + */ + public void ensureCapacity(long numBits) { + ensureCapacityWords(bits2words(numBits)); + } + + /** Lowers numWords, the number of words in use, + * by checking for trailing zero words. + */ + public void trimTrailingZeros() { + int idx = wlen-1; + while (idx>=0 && bits[idx]==0) idx--; + wlen = idx+1; + } + + /** returns the number of 64 bit words it would take to hold numBits */ + public static int bits2words(long numBits) { + return (int)(((numBits-1)>>>6)+1); + } + + + /** returns true if both sets have the same bits set */ + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof OpenBitSet)) return false; + OpenBitSet a; + OpenBitSet b = (OpenBitSet)o; + // make a the larger set. + if (b.wlen > this.wlen) { + a = b; b=this; + } else { + a=this; + } + + // check for any set bits out of the range of b + for (int i=a.wlen-1; i>=b.wlen; i--) { + if (a.bits[i]!=0) return false; + } + + for (int i=b.wlen-1; i>=0; i--) { + if (a.bits[i] != b.bits[i]) return false; + } + + return true; + } + + + public int hashCode() { + long h = 0x98761234; // something non-zero for length==0 + for (int i = bits.length; --i>=0;) { + h ^= bits[i]; + h = (h << 1) | (h >>> 63); // rotate left + } + return (int)((h>>32) ^ h); // fold leftmost bits into right + } + +} + + Index: 3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSetDISI.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSetDISI.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSetDISI.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,101 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import org.apache.lucene.search.DocIdSetIterator; + +public class OpenBitSetDISI extends OpenBitSet { + + /** Construct an OpenBitSetDISI with its bits set + * from the doc ids of the given DocIdSetIterator. + * Also give a maximum size one larger than the largest doc id for which a + * bit may ever be set on this OpenBitSetDISI. + */ + public OpenBitSetDISI(DocIdSetIterator disi, int maxSize) throws IOException { + super(maxSize); + inPlaceOr(disi); + } + + /** Construct an OpenBitSetDISI with no bits set, and a given maximum size + * one larger than the largest doc id for which a bit may ever be set + * on this OpenBitSetDISI. + */ + public OpenBitSetDISI(int maxSize) { + super(maxSize); + } + + /** + * Perform an inplace OR with the doc ids from a given DocIdSetIterator, + * setting the bit for each such doc id. + * These doc ids should be smaller than the maximum size passed to the + * constructor. + */ + public void inPlaceOr(DocIdSetIterator disi) throws IOException { + while (disi.next() && (disi.doc() < size())) { + fastSet(disi.doc()); + } + } + + /** + * Perform an inplace AND with the doc ids from a given DocIdSetIterator, + * leaving only the bits set for which the doc ids are in common. + * These doc ids should be smaller than the maximum size passed to the + * constructor. + */ + public void inPlaceAnd(DocIdSetIterator disi) throws IOException { + int index = nextSetBit(0); + int lastNotCleared = -1; + while ((index != -1) && disi.skipTo(index)) { + while ((index != -1) && (index < disi.doc())) { + fastClear(index); + index = nextSetBit(index + 1); + } + if (index == disi.doc()) { + lastNotCleared = index; + index++; + } + assert (index == -1) || (index > disi.doc()); + } + clear(lastNotCleared+1, size()); + } + + /** + * Perform an inplace NOT with the doc ids from a given DocIdSetIterator, + * clearing all the bits for each such doc id. + * These doc ids should be smaller than the maximum size passed to the + * constructor. + */ + public void inPlaceNot(DocIdSetIterator disi) throws IOException { + while (disi.next() && (disi.doc() < size())) { + fastClear(disi.doc()); + } + } + + /** + * Perform an inplace XOR with the doc ids from a given DocIdSetIterator, + * flipping all the bits for each such doc id. + * These doc ids should be smaller than the maximum size passed to the + * constructor. + */ + public void inPlaceXor(DocIdSetIterator disi) throws IOException { + while (disi.next() && (disi.doc() < size())) { + fastFlip(disi.doc()); + } + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSetIterator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSetIterator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/OpenBitSetIterator.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,173 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.lucene.util; + +import java.io.IOException; + +import org.apache.lucene.search.DocIdSetIterator; + +/** An iterator to iterate over set bits in an OpenBitSet. + * This is faster than nextSetBit() for iterating over the complete set of bits, + * especially when the density of the bits set is high. + * + * @version $Id: OpenBitSetIterator.java,v 1.1 2012/08/17 14:54:53 marcin Exp $ + */ +public class OpenBitSetIterator extends DocIdSetIterator { + + // The General Idea: instead of having an array per byte that has + // the offsets of the next set bit, that array could be + // packed inside a 32 bit integer (8 4 bit numbers). That + // should be faster than accessing an array for each index, and + // the total array size is kept smaller (256*sizeof(int))=1K + protected final static int[] bitlist={ + 0x0,0x1,0x2,0x21,0x3,0x31,0x32,0x321,0x4,0x41,0x42,0x421,0x43,0x431,0x432,0x4321,0x5,0x51,0x52,0x521,0x53,0x531,0x532,0x5321,0x54,0x541,0x542,0x5421,0x543,0x5431,0x5432,0x54321,0x6,0x61,0x62,0x621,0x63,0x631,0x632,0x6321,0x64,0x641,0x642,0x6421,0x643,0x6431,0x6432,0x64321,0x65,0x651,0x652,0x6521,0x653,0x6531,0x6532,0x65321,0x654,0x6541,0x6542,0x65421,0x6543,0x65431,0x65432,0x654321,0x7,0x71,0x72,0x721,0x73,0x731,0x732,0x7321,0x74,0x741,0x742,0x7421,0x743,0x7431,0x7432,0x74321,0x75,0x751,0x752,0x7521,0x753,0x7531,0x7532,0x75321,0x754,0x7541,0x7542,0x75421,0x7543,0x75431,0x75432,0x754321,0x76,0x761,0x762,0x7621,0x763,0x7631,0x7632,0x76321,0x764,0x7641,0x7642,0x76421,0x7643,0x76431,0x76432,0x764321,0x765,0x7651,0x7652,0x76521,0x7653,0x76531,0x76532,0x765321,0x7654,0x76541,0x76542,0x765421,0x76543,0x765431,0x765432,0x7654321,0x8,0x81,0x82,0x821,0x83,0x831,0x832,0x8321,0x84,0x841,0x842,0x8421,0x843,0x8431,0x8432,0x84321,0x85,0x851,0x852,0x8521,0x853,0x8531,0x8532,0x85321,0x854,0x8541,0x8542,0x85421,0x8543,0x85431,0x85432,0x854321,0x86,0x861,0x862,0x8621,0x863,0x8631,0x8632,0x86321,0x864,0x8641,0x8642,0x86421,0x8643,0x86431,0x86432,0x864321,0x865,0x8651,0x8652,0x86521,0x8653,0x86531,0x86532,0x865321,0x8654,0x86541,0x86542,0x865421,0x86543,0x865431,0x865432,0x8654321,0x87,0x871,0x872,0x8721,0x873,0x8731,0x8732,0x87321,0x874,0x8741,0x8742,0x87421,0x8743,0x87431,0x87432,0x874321,0x875,0x8751,0x8752,0x87521,0x8753,0x87531,0x87532,0x875321,0x8754,0x87541,0x87542,0x875421,0x87543,0x875431,0x875432,0x8754321,0x876,0x8761,0x8762,0x87621,0x8763,0x87631,0x87632,0x876321,0x8764,0x87641,0x87642,0x876421,0x87643,0x876431,0x876432,0x8764321,0x8765,0x87651,0x87652,0x876521,0x87653,0x876531,0x876532,0x8765321,0x87654,0x876541,0x876542,0x8765421,0x876543,0x8765431,0x8765432,0x87654321 + }; + /***** the python code that generated bitlist + def bits2int(val): + arr=0 + for shift in range(8,0,-1): + if val & 0x80: + arr = (arr << 4) | shift + val = val << 1 + return arr + + def int_table(): + tbl = [ hex(bits2int(val)).strip('L') for val in range(256) ] + return ','.join(tbl) + ******/ + + // hmmm, what about an iterator that finds zeros though, + // or a reverse iterator... should they be separate classes + // for efficiency, or have a common root interface? (or + // maybe both? could ask for a SetBitsIterator, etc... + + + private final long[] arr; + private final int words; + private int i=-1; + private long word; + private int wordShift; + private int indexArray; + private int curDocId; + + public OpenBitSetIterator(OpenBitSet obs) { + this(obs.getBits(), obs.getNumWords()); + } + + public OpenBitSetIterator(long[] bits, int numWords) { + arr = bits; + words = numWords; + } + + // 64 bit shifts + private void shift() { + if ((int)word ==0) {wordShift +=32; word = word >>>32; } + if ((word & 0x0000FFFF) == 0) { wordShift +=16; word >>>=16; } + if ((word & 0x000000FF) == 0) { wordShift +=8; word >>>=8; } + indexArray = bitlist[(int)word & 0xff]; + } + + /***** alternate shift implementations + // 32 bit shifts, but a long shift needed at the end + private void shift2() { + int y = (int)word; + if (y==0) {wordShift +=32; y = (int)(word >>>32); } + if ((y & 0x0000FFFF) == 0) { wordShift +=16; y>>>=16; } + if ((y & 0x000000FF) == 0) { wordShift +=8; y>>>=8; } + indexArray = bitlist[y & 0xff]; + word >>>= (wordShift +1); + } + + private void shift3() { + int lower = (int)word; + int lowByte = lower & 0xff; + if (lowByte != 0) { + indexArray=bitlist[lowByte]; + return; + } + shift(); + } + ******/ + + public boolean next() { + if (indexArray==0) { + if (word!=0) { + word >>>= 8; + wordShift += 8; + } + + while (word==0) { + if (++i >= words) { + curDocId = -1; + return false; + } + word = arr[i]; + wordShift =-1; // loop invariant code motion should move this + } + + // after the first time, should I go with a linear search, or + // stick with the binary search in shift? + shift(); + } + + int bitIndex = (indexArray & 0x0f) + wordShift; + indexArray >>>= 4; + // should i<<6 be cached as a separate variable? + // it would only save one cycle in the best circumstances. + curDocId = (i<<6) + bitIndex; + return true; + } + + public boolean skipTo(int target) { + indexArray=0; + i = target >> 6; + if (i>=words) { + word =0; // setup so next() will also return -1 + curDocId = -1; + return false; + } + wordShift = target & 0x3f; + word = arr[i] >>> wordShift; + if (word !=0) { + wordShift--; // compensate for 1 based arrIndex + } else { + while (word ==0) { + if (++i >= words) { + curDocId = -1; + return false; + } + word = arr[i]; + } + wordShift =-1; + } + + shift(); + + int bitIndex = (indexArray & 0x0f) + wordShift; + indexArray >>>= 4; + // should i<<6 be cached as a separate variable? + // it would only save one cycle in the best circumstances. + curDocId = (i<<6) + bitIndex; + return true; + } + + public int doc() { + return this.curDocId; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/Parameter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/Parameter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/Parameter.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,74 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.ObjectStreamException; +import java.io.Serializable; +import java.io.StreamCorruptedException; +import java.util.HashMap; +import java.util.Map; + +/** + * A serializable Enum class. + */ +public abstract class Parameter implements Serializable +{ + static Map allParameters = new HashMap(); + + private String name; + + private Parameter() { + // typesafe enum pattern, no public constructor + } + + protected Parameter(String name) { + // typesafe enum pattern, no public constructor + this.name = name; + String key = makeKey(name); + + if(allParameters.containsKey(key)) + throw new IllegalArgumentException("Parameter name " + key + " already used!"); + + allParameters.put(key, this); + } + + private String makeKey(String name){ + return getClass() + " " + name; + } + + public String toString() { + return name; + } + + /** + * Resolves the deserialized instance to the local reference for accurate + * equals() and == comparisons. + * + * @return a reference to Parameter as resolved in the local VM + * @throws ObjectStreamException + */ + protected Object readResolve() throws ObjectStreamException { + Object par = allParameters.get(makeKey(name)); + + if(par == null) + throw new StreamCorruptedException("Unknown parameter value: " + name); + + return par; + } + + } Index: 3rdParty_sources/lucene/org/apache/lucene/util/PriorityQueue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/PriorityQueue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/PriorityQueue.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,166 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** A PriorityQueue maintains a partial ordering of its elements such that the + least element can always be found in constant time. Put()'s and pop()'s + require log(size) time. */ +public abstract class PriorityQueue { + private int size; + private int maxSize; + protected Object[] heap; + + /** Determines the ordering of objects in this priority queue. Subclasses + must define this one method. */ + protected abstract boolean lessThan(Object a, Object b); + + /** Subclass constructors must call this. */ + protected final void initialize(int maxSize) { + size = 0; + int heapSize; + if (0 == maxSize) + // We allocate 1 extra to avoid if statement in top() + heapSize = 2; + else + heapSize = maxSize + 1; + heap = new Object[heapSize]; + this.maxSize = maxSize; + } + + /** + * Adds an Object to a PriorityQueue in log(size) time. + * If one tries to add more objects than maxSize from initialize + * a RuntimeException (ArrayIndexOutOfBound) is thrown. + */ + public final void put(Object element) { + size++; + heap[size] = element; + upHeap(); + } + + /** + * Adds element to the PriorityQueue in log(size) time if either + * the PriorityQueue is not full, or not lessThan(element, top()). + * @param element + * @return true if element is added, false otherwise. + */ + public boolean insert(Object element) { + return insertWithOverflow(element) != element; + } + + /** + * insertWithOverflow() is the same as insert() except its + * return value: it returns the object (if any) that was + * dropped off the heap because it was full. This can be + * the given parameter (in case it is smaller than the + * full heap's minimum, and couldn't be added), or another + * object that was previously the smallest value in the + * heap and now has been replaced by a larger one, or null + * if the queue wasn't yet full with maxSize elements. + */ + public Object insertWithOverflow(Object element) { + if (size < maxSize) { + put(element); + return null; + } else if (size > 0 && !lessThan(element, heap[1])) { + Object ret = heap[1]; + heap[1] = element; + adjustTop(); + return ret; + } else { + return element; + } + } + + /** Returns the least element of the PriorityQueue in constant time. */ + public final Object top() { + // We don't need to check size here: if maxSize is 0, + // then heap is length 2 array with both entries null. + // If size is 0 then heap[1] is already null. + return heap[1]; + } + + /** Removes and returns the least element of the PriorityQueue in log(size) + time. */ + public final Object pop() { + if (size > 0) { + Object result = heap[1]; // save first value + heap[1] = heap[size]; // move last to first + heap[size] = null; // permit GC of objects + size--; + downHeap(); // adjust heap + return result; + } else + return null; + } + + /** Should be called when the Object at top changes values. Still log(n) + * worst case, but it's at least twice as fast to

+   *  { pq.top().change(); pq.adjustTop(); }
+   * 
instead of
+   *  { o = pq.pop(); o.change(); pq.push(o); }
+   * 
+ */ + public final void adjustTop() { + downHeap(); + } + + /** Returns the number of elements currently stored in the PriorityQueue. */ + public final int size() { + return size; + } + + /** Removes all entries from the PriorityQueue. */ + public final void clear() { + for (int i = 0; i <= size; i++) + heap[i] = null; + size = 0; + } + + private final void upHeap() { + int i = size; + Object node = heap[i]; // save bottom node + int j = i >>> 1; + while (j > 0 && lessThan(node, heap[j])) { + heap[i] = heap[j]; // shift parents down + i = j; + j = j >>> 1; + } + heap[i] = node; // install saved node + } + + private final void downHeap() { + int i = 1; + Object node = heap[i]; // save top node + int j = i << 1; // find smaller child + int k = j + 1; + if (k <= size && lessThan(heap[k], heap[j])) { + j = k; + } + while (j <= size && lessThan(heap[j], node)) { + heap[i] = heap[j]; // shift up child + i = j; + j = i << 1; + k = j + 1; + if (k <= size && lessThan(heap[k], heap[j])) { + j = k; + } + } + heap[i] = node; // install saved node + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/ScorerDocQueue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/ScorerDocQueue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/ScorerDocQueue.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,215 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* Derived from org.apache.lucene.util.PriorityQueue of March 2005 */ + +import java.io.IOException; +import org.apache.lucene.search.Scorer; + +/** A ScorerDocQueue maintains a partial ordering of its Scorers such that the + least Scorer can always be found in constant time. Put()'s and pop()'s + require log(size) time. The ordering is by Scorer.doc(). + */ +public class ScorerDocQueue { // later: SpansQueue for spans with doc and term positions + private final HeapedScorerDoc[] heap; + private final int maxSize; + private int size; + + private class HeapedScorerDoc { + Scorer scorer; + int doc; + + HeapedScorerDoc(Scorer s) { this(s, s.doc()); } + + HeapedScorerDoc(Scorer scorer, int doc) { + this.scorer = scorer; + this.doc = doc; + } + + void adjust() { doc = scorer.doc(); } + } + + private HeapedScorerDoc topHSD; // same as heap[1], only for speed + + /** Create a ScorerDocQueue with a maximum size. */ + public ScorerDocQueue(int maxSize) { + // assert maxSize >= 0; + size = 0; + int heapSize = maxSize + 1; + heap = new HeapedScorerDoc[heapSize]; + this.maxSize = maxSize; + topHSD = heap[1]; // initially null + } + + /** + * Adds a Scorer to a ScorerDocQueue in log(size) time. + * If one tries to add more Scorers than maxSize + * a RuntimeException (ArrayIndexOutOfBound) is thrown. + */ + public final void put(Scorer scorer) { + size++; + heap[size] = new HeapedScorerDoc(scorer); + upHeap(); + } + + /** + * Adds a Scorer to the ScorerDocQueue in log(size) time if either + * the ScorerDocQueue is not full, or not lessThan(scorer, top()). + * @param scorer + * @return true if scorer is added, false otherwise. + */ + public boolean insert(Scorer scorer){ + if (size < maxSize) { + put(scorer); + return true; + } else { + int docNr = scorer.doc(); + if ((size > 0) && (! (docNr < topHSD.doc))) { // heap[1] is top() + heap[1] = new HeapedScorerDoc(scorer, docNr); + downHeap(); + return true; + } else { + return false; + } + } + } + + /** Returns the least Scorer of the ScorerDocQueue in constant time. + * Should not be used when the queue is empty. + */ + public final Scorer top() { + // assert size > 0; + return topHSD.scorer; + } + + /** Returns document number of the least Scorer of the ScorerDocQueue + * in constant time. + * Should not be used when the queue is empty. + */ + public final int topDoc() { + // assert size > 0; + return topHSD.doc; + } + + public final float topScore() throws IOException { + // assert size > 0; + return topHSD.scorer.score(); + } + + public final boolean topNextAndAdjustElsePop() throws IOException { + return checkAdjustElsePop( topHSD.scorer.next()); + } + + public final boolean topSkipToAndAdjustElsePop(int target) throws IOException { + return checkAdjustElsePop( topHSD.scorer.skipTo(target)); + } + + private boolean checkAdjustElsePop(boolean cond) { + if (cond) { // see also adjustTop + topHSD.doc = topHSD.scorer.doc(); + } else { // see also popNoResult + heap[1] = heap[size]; // move last to first + heap[size] = null; + size--; + } + downHeap(); + return cond; + } + + /** Removes and returns the least scorer of the ScorerDocQueue in log(size) + * time. + * Should not be used when the queue is empty. + */ + public final Scorer pop() { + // assert size > 0; + Scorer result = topHSD.scorer; + popNoResult(); + return result; + } + + /** Removes the least scorer of the ScorerDocQueue in log(size) time. + * Should not be used when the queue is empty. + */ + private final void popNoResult() { + heap[1] = heap[size]; // move last to first + heap[size] = null; + size--; + downHeap(); // adjust heap + } + + /** Should be called when the scorer at top changes doc() value. + * Still log(n) worst case, but it's at least twice as fast to
+   *  { pq.top().change(); pq.adjustTop(); }
+   * 
instead of
+   *  { o = pq.pop(); o.change(); pq.push(o); }
+   * 
+ */ + public final void adjustTop() { + // assert size > 0; + topHSD.adjust(); + downHeap(); + } + + /** Returns the number of scorers currently stored in the ScorerDocQueue. */ + public final int size() { + return size; + } + + /** Removes all entries from the ScorerDocQueue. */ + public final void clear() { + for (int i = 0; i <= size; i++) { + heap[i] = null; + } + size = 0; + } + + private final void upHeap() { + int i = size; + HeapedScorerDoc node = heap[i]; // save bottom node + int j = i >>> 1; + while ((j > 0) && (node.doc < heap[j].doc)) { + heap[i] = heap[j]; // shift parents down + i = j; + j = j >>> 1; + } + heap[i] = node; // install saved node + topHSD = heap[1]; + } + + private final void downHeap() { + int i = 1; + HeapedScorerDoc node = heap[i]; // save top node + int j = i << 1; // find smaller child + int k = j + 1; + if ((k <= size) && (heap[k].doc < heap[j].doc)) { + j = k; + } + while ((j <= size) && (heap[j].doc < node.doc)) { + heap[i] = heap[j]; // shift up child + i = j; + j = i << 1; + k = j + 1; + if (k <= size && (heap[k].doc < heap[j].doc)) { + j = k; + } + } + heap[i] = node; // install saved node + topHSD = heap[1]; + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/SmallFloat.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/SmallFloat.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/SmallFloat.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,124 @@ +package org.apache.lucene.util; +/** + * Copyright 2005 The Apache Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** Floating point numbers smaller than 32 bits. + * + * @version $Id: SmallFloat.java,v 1.1 2012/08/17 14:54:53 marcin Exp $ + */ +public class SmallFloat { + + /** Converts a 32 bit float to an 8 bit float. + *
Values less than zero are all mapped to zero. + *
Values are truncated (rounded down) to the nearest 8 bit value. + *
Values between zero and the smallest representable value + * are rounded up. + * + * @param f the 32 bit float to be converted to an 8 bit float (byte) + * @param numMantissaBits the number of mantissa bits to use in the byte, with the remainder to be used in the exponent + * @param zeroExp the zero-point in the range of exponent values + * @return the 8 bit float representation + */ + public static byte floatToByte(float f, int numMantissaBits, int zeroExp) { + // Adjustment from a float zero exponent to our zero exponent, + // shifted over to our exponent position. + int fzero = (63-zeroExp)<> (24-numMantissaBits); + if (smallfloat < fzero) { + return (bits<=0) ? + (byte)0 // negative numbers and zero both map to 0 byte + :(byte)1; // underflow is mapped to smallest non-zero number. + } else if (smallfloat >= fzero + 0x100) { + return -1; // overflow maps to largest number + } else { + return (byte)(smallfloat - fzero); + } + } + + /** Converts an 8 bit float to a 32 bit float. */ + public static float byteToFloat(byte b, int numMantissaBits, int zeroExp) { + // on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup + // is only a little bit faster (anywhere from 0% to 7%) + if (b == 0) return 0.0f; + int bits = (b&0xff) << (24-numMantissaBits); + bits += (63-zeroExp) << 24; + return Float.intBitsToFloat(bits); + } + + + // + // Some specializations of the generic functions follow. + // The generic functions are just as fast with current (1.5) + // -server JVMs, but still slower with client JVMs. + // + + /** floatToByte(b, mantissaBits=3, zeroExponent=15) + *
smallest non-zero value = 5.820766E-10 + *
largest value = 7.5161928E9 + *
epsilon = 0.125 + */ + public static byte floatToByte315(float f) { + int bits = Float.floatToRawIntBits(f); + int smallfloat = bits >> (24-3); + if (smallfloat < (63-15)<<3) { + return (bits<=0) ? (byte)0 : (byte)1; + } + if (smallfloat >= ((63-15)<<3) + 0x100) { + return -1; + } + return (byte)(smallfloat - ((63-15)<<3)); + } + + /** byteToFloat(b, mantissaBits=3, zeroExponent=15) */ + public static float byte315ToFloat(byte b) { + // on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup + // is only a little bit faster (anywhere from 0% to 7%) + if (b == 0) return 0.0f; + int bits = (b&0xff) << (24-3); + bits += (63-15) << 24; + return Float.intBitsToFloat(bits); + } + + + /** floatToByte(b, mantissaBits=5, zeroExponent=2) + *
smallest nonzero value = 0.033203125 + *
largest value = 1984.0 + *
epsilon = 0.03125 + */ + public static byte floatToByte52(float f) { + int bits = Float.floatToRawIntBits(f); + int smallfloat = bits >> (24-5); + if (smallfloat < (63-2)<<5) { + return (bits<=0) ? (byte)0 : (byte)1; + } + if (smallfloat >= ((63-2)<<5) + 0x100) { + return -1; + } + return (byte)(smallfloat - ((63-2)<<5)); + } + + /** byteToFloat(b, mantissaBits=5, zeroExponent=2) */ + public static float byte52ToFloat(byte b) { + // on Java1.5 & 1.6 JVMs, prebuilding a decoding array and doing a lookup + // is only a little bit faster (anywhere from 0% to 7%) + if (b == 0) return 0.0f; + int bits = (b&0xff) << (24-5); + bits += (63-2) << 24; + return Float.intBitsToFloat(bits); + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/SortedVIntList.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/SortedVIntList.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/SortedVIntList.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,218 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.util.BitSet; + +import org.apache.lucene.search.DocIdSet; +import org.apache.lucene.search.DocIdSetIterator; + +/** + * Store and iterate sorted integers in compressed form in RAM. + *
The code for compressing the differences between ascending integers was + * borrowed from {@link org.apache.lucene.store.IndexInput} and + * {@link org.apache.lucene.store.IndexOutput}. + */ +public class SortedVIntList extends DocIdSet { + /** When a BitSet has fewer than 1 in BITS2VINTLIST_SIZE bits set, + * a SortedVIntList representing the index numbers of the set bits + * will be smaller than that BitSet. + */ + final static int BITS2VINTLIST_SIZE = 8; + + private int size; + private byte[] bytes; + private int lastBytePos; + + /** + * Create a SortedVIntList from all elements of an array of integers. + * + * @param sortedInts A sorted array of non negative integers. + */ + public SortedVIntList(int[] sortedInts) { + this(sortedInts, sortedInts.length); + } + + /** + * Create a SortedVIntList from an array of integers. + * @param sortedInts An array of sorted non negative integers. + * @param inputSize The number of integers to be used from the array. + */ + public SortedVIntList(int[] sortedInts, int inputSize) { + SortedVIntListBuilder builder = new SortedVIntListBuilder(); + for (int i = 0; i < inputSize; i++) { + builder.addInt(sortedInts[i]); + } + builder.done(); + } + + /** + * Create a SortedVIntList from a BitSet. + * @param bits A bit set representing a set of integers. + */ + public SortedVIntList(BitSet bits) { + SortedVIntListBuilder builder = new SortedVIntListBuilder(); + int nextInt = bits.nextSetBit(0); + while (nextInt != -1) { + builder.addInt(nextInt); + nextInt = bits.nextSetBit(nextInt + 1); + } + builder.done(); + } + + /** + * Create a SortedVIntList from an OpenBitSet. + * @param bits A bit set representing a set of integers. + */ + public SortedVIntList(OpenBitSet bits) { + SortedVIntListBuilder builder = new SortedVIntListBuilder(); + int nextInt = bits.nextSetBit(0); + while (nextInt != -1) { + builder.addInt(nextInt); + nextInt = bits.nextSetBit(nextInt + 1); + } + builder.done(); + } + + /** + * Create a SortedVIntList. + * @param docIdSetIterator An iterator providing document numbers as a set of integers. + * This DocIdSetIterator is iterated completely when this constructor + * is called and it must provide the integers in non + * decreasing order. + */ + public SortedVIntList(DocIdSetIterator docIdSetIterator) throws IOException { + SortedVIntListBuilder builder = new SortedVIntListBuilder(); + while (docIdSetIterator.next()) { + builder.addInt(docIdSetIterator.doc()); + } + builder.done(); + } + + + private class SortedVIntListBuilder { + private int lastInt = 0; + + SortedVIntListBuilder() { + initBytes(); + lastInt = 0; + } + + void addInt(int nextInt) { + int diff = nextInt - lastInt; + if (diff < 0) { + throw new IllegalArgumentException( + "Input not sorted or first element negative."); + } + + if ((lastBytePos + MAX_BYTES_PER_INT) > bytes.length) { + // biggest possible int does not fit + resizeBytes((bytes.length * 2) + MAX_BYTES_PER_INT); + } + + // See org.apache.lucene.store.IndexOutput.writeVInt() + while ((diff & ~VB1) != 0) { // The high bit of the next byte needs to be set. + bytes[lastBytePos++] = (byte) ((diff & VB1) | ~VB1); + diff >>>= BIT_SHIFT; + } + bytes[lastBytePos++] = (byte) diff; // Last byte, high bit not set. + size++; + lastInt = nextInt; + } + + void done() { + resizeBytes(lastBytePos); + } + } + + + private void initBytes() { + size = 0; + bytes = new byte[128]; // initial byte size + lastBytePos = 0; + } + + private void resizeBytes(int newSize) { + if (newSize != bytes.length) { + byte[] newBytes = new byte[newSize]; + System.arraycopy(bytes, 0, newBytes, 0, lastBytePos); + bytes = newBytes; + } + } + + private static final int VB1 = 0x7F; + private static final int BIT_SHIFT = 7; + private final int MAX_BYTES_PER_INT = (31 / BIT_SHIFT) + 1; + + /** + * @return The total number of sorted integers. + */ + public int size() { + return size; + } + + /** + * @return The size of the byte array storing the compressed sorted integers. + */ + public int getByteSize() { + return bytes.length; + } + + /** + * @return An iterator over the sorted integers. + */ + public DocIdSetIterator iterator() { + return new DocIdSetIterator() { + int bytePos = 0; + int lastInt = 0; + + private void advance() { + // See org.apache.lucene.store.IndexInput.readVInt() + byte b = bytes[bytePos++]; + lastInt += b & VB1; + for (int s = BIT_SHIFT; (b & ~VB1) != 0; s += BIT_SHIFT) { + b = bytes[bytePos++]; + lastInt += (b & VB1) << s; + } + } + + public int doc() {return lastInt;} + + public boolean next() { + if (bytePos >= lastBytePos) { + return false; + } else { + advance(); + return true; + } + } + + public boolean skipTo(int docNr) { + while (bytePos < lastBytePos) { + advance(); + if (lastInt >= docNr) { // No skipping to docNr available. + return true; + } + } + return false; + } + }; + } +} + Index: 3rdParty_sources/lucene/org/apache/lucene/util/StringHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/StringHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/StringHelper.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,66 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Methods for manipulating strings. + * + * $Id: StringHelper.java,v 1.1 2012/08/17 14:54:53 marcin Exp $ + */ +public abstract class StringHelper { + + /** + * Compares two byte[] arrays, element by element, and returns the + * number of elements common to both arrays. + * + * @param bytes1 The first byte[] to compare + * @param bytes2 The second byte[] to compare + * @return The number of common elements. + */ + public static final int bytesDifference(byte[] bytes1, int len1, byte[] bytes2, int len2) { + int len = len1 < len2 ? len1 : len2; + for (int i = 0; i < len; i++) + if (bytes1[i] != bytes2[i]) + return i; + return len; + } + + /** + * Compares two strings, character by character, and returns the + * first position where the two strings differ from one another. + * + * @param s1 The first string to compare + * @param s2 The second string to compare + * @return The first position where the two strings differ. + */ + public static final int stringDifference(String s1, String s2) { + int len1 = s1.length(); + int len2 = s2.length(); + int len = len1 < len2 ? len1 : len2; + for (int i = 0; i < len; i++) { + if (s1.charAt(i) != s2.charAt(i)) { + return i; + } + } + return len; + } + + private StringHelper() { + } +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/ToStringUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/ToStringUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/ToStringUtils.java 17 Aug 2012 14:54:54 -0000 1.1 @@ -0,0 +1,28 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +public class ToStringUtils { + /** for printing boost only if not 1.0 */ + public static String boost(float boost) { + if (boost != 1.0f) { + return "^" + Float.toString(boost); + } else return ""; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/UnicodeUtil.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/UnicodeUtil.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/UnicodeUtil.java 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,447 @@ +package org.apache.lucene.util; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* + * Some of this code came from the excellent Unicode + * conversion examples from: + * + * http://www.unicode.org/Public/PROGRAMS/CVTUTF + * + * Full Copyright for that code follows: +*/ + +/* + * Copyright 2001-2004 Unicode, Inc. + * + * Disclaimer + * + * This source code is provided as is by Unicode, Inc. No claims are + * made as to fitness for any particular purpose. No warranties of any + * kind are expressed or implied. The recipient agrees to determine + * applicability of information provided. If this file has been + * purchased on magnetic or optical media from Unicode, Inc., the + * sole remedy for any claim will be exchange of defective media + * within 90 days of receipt. + * + * Limitations on Rights to Redistribute This Code + * + * Unicode, Inc. hereby grants the right to freely use the information + * supplied in this file in the creation of products supporting the + * Unicode Standard, and to make copies of this file in any form + * for internal or external distribution as long as this notice + * remains attached. + */ + +/** + * Class to encode java's UTF16 char[] into UTF8 byte[] + * without always allocating a new byte[] as + * String.getBytes("UTF-8") does. + * + *

WARNING: This API is a new and experimental and + * may suddenly change.

+ */ + +final public class UnicodeUtil { + + public static final int UNI_SUR_HIGH_START = 0xD800; + public static final int UNI_SUR_HIGH_END = 0xDBFF; + public static final int UNI_SUR_LOW_START = 0xDC00; + public static final int UNI_SUR_LOW_END = 0xDFFF; + public static final int UNI_REPLACEMENT_CHAR = 0xFFFD; + + private static final long UNI_MAX_BMP = 0x0000FFFF; + + private static final int HALF_BASE = 0x0010000; + private static final long HALF_SHIFT = 10; + private static final long HALF_MASK = 0x3FFL; + + public static final class UTF8Result { + public byte[] result = new byte[10]; + public int length; + + public void setLength(int newLength) { + if (result.length < newLength) { + byte[] newArray = new byte[(int) (1.5*newLength)]; + System.arraycopy(result, 0, newArray, 0, length); + result = newArray; + } + length = newLength; + } + } + + public static final class UTF16Result { + public char[] result = new char[10]; + public int[] offsets = new int[10]; + public int length; + + public void setLength(int newLength) { + if (result.length < newLength) { + char[] newArray = new char[(int) (1.5*newLength)]; + System.arraycopy(result, 0, newArray, 0, length); + result = newArray; + } + length = newLength; + } + + public void copyText(UTF16Result other) { + setLength(other.length); + System.arraycopy(other.result, 0, result, 0, length); + } + } + + /** Encode characters from a char[] source, starting at + * offset and stopping when the character 0xffff is seen. + * Returns the number of bytes written to bytesOut. */ + public static void UTF16toUTF8(final char[] source, final int offset, UTF8Result result) { + + int upto = 0; + int i = offset; + byte[] out = result.result; + + while(true) { + + final int code = (int) source[i++]; + + if (upto+4 > out.length) { + byte[] newOut = new byte[2*out.length]; + assert newOut.length >= upto+4; + System.arraycopy(out, 0, newOut, 0, upto); + result.result = out = newOut; + } + if (code < 0x80) + out[upto++] = (byte) code; + else if (code < 0x800) { + out[upto++] = (byte) (0xC0 | (code >> 6)); + out[upto++] = (byte)(0x80 | (code & 0x3F)); + } else if (code < 0xD800 || code > 0xDFFF) { + if (code == 0xffff) + // END + break; + out[upto++] = (byte)(0xE0 | (code >> 12)); + out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); + out[upto++] = (byte)(0x80 | (code & 0x3F)); + } else { + // surrogate pair + // confirm valid high surrogate + if (code < 0xDC00 && source[i] != 0xffff) { + int utf32 = (int) source[i]; + // confirm valid low surrogate and write pair + if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { + utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); + i++; + out[upto++] = (byte)(0xF0 | (utf32 >> 18)); + out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); + out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); + out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); + continue; + } + } + // replace unpaired surrogate or out-of-order low surrogate + // with substitution character + out[upto++] = (byte) 0xEF; + out[upto++] = (byte) 0xBF; + out[upto++] = (byte) 0xBD; + } + } + //assert matches(source, offset, i-offset-1, out, upto); + result.length = upto; + } + + /** Encode characters from a char[] source, starting at + * offset for length chars. Returns the number of bytes + * written to bytesOut. */ + public static void UTF16toUTF8(final char[] source, final int offset, final int length, UTF8Result result) { + + int upto = 0; + int i = offset; + final int end = offset + length; + byte[] out = result.result; + + while(i < end) { + + final int code = (int) source[i++]; + + if (upto+4 > out.length) { + byte[] newOut = new byte[2*out.length]; + assert newOut.length >= upto+4; + System.arraycopy(out, 0, newOut, 0, upto); + result.result = out = newOut; + } + if (code < 0x80) + out[upto++] = (byte) code; + else if (code < 0x800) { + out[upto++] = (byte) (0xC0 | (code >> 6)); + out[upto++] = (byte)(0x80 | (code & 0x3F)); + } else if (code < 0xD800 || code > 0xDFFF) { + out[upto++] = (byte)(0xE0 | (code >> 12)); + out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); + out[upto++] = (byte)(0x80 | (code & 0x3F)); + } else { + // surrogate pair + // confirm valid high surrogate + if (code < 0xDC00 && i < end && source[i] != 0xffff) { + int utf32 = (int) source[i]; + // confirm valid low surrogate and write pair + if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { + utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); + i++; + out[upto++] = (byte)(0xF0 | (utf32 >> 18)); + out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); + out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); + out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); + continue; + } + } + // replace unpaired surrogate or out-of-order low surrogate + // with substitution character + out[upto++] = (byte) 0xEF; + out[upto++] = (byte) 0xBF; + out[upto++] = (byte) 0xBD; + } + } + //assert matches(source, offset, length, out, upto); + result.length = upto; + } + + /** Encode characters from this String, starting at offset + * for length characters. Returns the number of bytes + * written to bytesOut. */ + public static void UTF16toUTF8(final String s, final int offset, final int length, UTF8Result result) { + final int end = offset + length; + + byte[] out = result.result; + + int upto = 0; + for(int i=offset;i out.length) { + byte[] newOut = new byte[2*out.length]; + assert newOut.length >= upto+4; + System.arraycopy(out, 0, newOut, 0, upto); + result.result = out = newOut; + } + if (code < 0x80) + out[upto++] = (byte) code; + else if (code < 0x800) { + out[upto++] = (byte) (0xC0 | (code >> 6)); + out[upto++] = (byte)(0x80 | (code & 0x3F)); + } else if (code < 0xD800 || code > 0xDFFF) { + out[upto++] = (byte)(0xE0 | (code >> 12)); + out[upto++] = (byte)(0x80 | ((code >> 6) & 0x3F)); + out[upto++] = (byte)(0x80 | (code & 0x3F)); + } else { + // surrogate pair + // confirm valid high surrogate + if (code < 0xDC00 && (i < end-1)) { + int utf32 = (int) s.charAt(i+1); + // confirm valid low surrogate and write pair + if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) { + utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); + i++; + out[upto++] = (byte)(0xF0 | (utf32 >> 18)); + out[upto++] = (byte)(0x80 | ((utf32 >> 12) & 0x3F)); + out[upto++] = (byte)(0x80 | ((utf32 >> 6) & 0x3F)); + out[upto++] = (byte)(0x80 | (utf32 & 0x3F)); + continue; + } + } + // replace unpaired surrogate or out-of-order low surrogate + // with substitution character + out[upto++] = (byte) 0xEF; + out[upto++] = (byte) 0xBF; + out[upto++] = (byte) 0xBD; + } + } + //assert matches(s, offset, length, out, upto); + result.length = upto; + } + + /** Convert UTF8 bytes into UTF16 characters. If offset + * is non-zero, conversion starts at that starting point + * in utf8, re-using the results from the previous call + * up until offset. */ + public static void UTF8toUTF16(final byte[] utf8, final int offset, final int length, final UTF16Result result) { + + final int end = offset + length; + char[] out = result.result; + if (result.offsets.length <= end) { + int[] newOffsets = new int[2*end]; + System.arraycopy(result.offsets, 0, newOffsets, 0, result.offsets.length); + result.offsets = newOffsets; + } + final int[] offsets = result.offsets; + + // If incremental decoding fell in the middle of a + // single unicode character, rollback to its start: + int upto = offset; + while(offsets[upto] == -1) + upto--; + + int outUpto = offsets[upto]; + + // Pre-allocate for worst case 1-for-1 + if (outUpto+length >= out.length) { + char[] newOut = new char[2*(outUpto+length)]; + System.arraycopy(out, 0, newOut, 0, outUpto); + result.result = out = newOut; + } + + while (upto < end) { + + final int b = utf8[upto]&0xff; + final int ch; + + offsets[upto++] = outUpto; + + if (b < 0xc0) { + assert b < 0x80; + ch = b; + } else if (b < 0xe0) { + ch = ((b&0x1f)<<6) + (utf8[upto]&0x3f); + offsets[upto++] = -1; + } else if (b < 0xf0) { + ch = ((b&0xf)<<12) + ((utf8[upto]&0x3f)<<6) + (utf8[upto+1]&0x3f); + offsets[upto++] = -1; + offsets[upto++] = -1; + } else { + assert b < 0xf8; + ch = ((b&0x7)<<18) + ((utf8[upto]&0x3f)<<12) + ((utf8[upto+1]&0x3f)<<6) + (utf8[upto+2]&0x3f); + offsets[upto++] = -1; + offsets[upto++] = -1; + offsets[upto++] = -1; + } + + if (ch <= UNI_MAX_BMP) { + // target is a character <= 0xFFFF + out[outUpto++] = (char) ch; + } else { + // target is a character in range 0xFFFF - 0x10FFFF + final int chHalf = ch - HALF_BASE; + out[outUpto++] = (char) ((chHalf >> HALF_SHIFT) + UNI_SUR_HIGH_START); + out[outUpto++] = (char) ((chHalf & HALF_MASK) + UNI_SUR_LOW_START); + } + } + + offsets[upto] = outUpto; + result.length = outUpto; + } + + // Only called from assert + /* + private static boolean matches(char[] source, int offset, int length, byte[] result, int upto) { + try { + String s1 = new String(source, offset, length); + String s2 = new String(result, 0, upto, "UTF-8"); + if (!s1.equals(s2)) { + //System.out.println("DIFF: s1 len=" + s1.length()); + //for(int i=0;i= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { + if (i < size-1) { + i++; + char nextCH = s.charAt(i); + if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { + // Valid surrogate pair + } else + // Unmatched hight surrogate + return false; + } else + // Unmatched hight surrogate + return false; + } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) + // Unmatched low surrogate + return false; + } + + return true; + } + + public static final boolean validUTF16String(char[] s, int size) { + for(int i=0;i= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { + if (i < size-1) { + i++; + char nextCH = s[i]; + if (nextCH >= UNI_SUR_LOW_START && nextCH <= UNI_SUR_LOW_END) { + // Valid surrogate pair + } else + return false; + } else + return false; + } else if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) + // Unmatched low surrogate + return false; + } + + return true; + } + */ +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/package.html 17 Aug 2012 14:54:53 -0000 1.1 @@ -0,0 +1,26 @@ + + + + + + + + +Some utility classes. + + Index: 3rdParty_sources/lucene/org/apache/lucene/util/cache/Cache.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/cache/Cache.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/cache/Cache.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,105 @@ +package org.apache.lucene.util.cache; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/** + * Base class for cache implementations. + */ +public abstract class Cache { + + /** + * Simple Cache wrapper that synchronizes all + * calls that access the cache. + */ + static class SynchronizedCache extends Cache { + Object mutex; + Cache cache; + + SynchronizedCache(Cache cache) { + this.cache = cache; + this.mutex = this; + } + + SynchronizedCache(Cache cache, Object mutex) { + this.cache = cache; + this.mutex = mutex; + } + + public void put(Object key, Object value) { + synchronized(mutex) {cache.put(key, value);} + } + + public Object get(Object key) { + synchronized(mutex) {return cache.get(key);} + } + + public boolean containsKey(Object key) { + synchronized(mutex) {return cache.containsKey(key);} + } + + public void close() { + synchronized(mutex) {cache.close();} + } + + Cache getSynchronizedCache() { + return this; + } + } + + /** + * Returns a thread-safe cache backed by the specified cache. + * In order to guarantee thread-safety, all access to the backed cache must + * be accomplished through the returned cache. + */ + public static Cache synchronizedCache(Cache cache) { + return cache.getSynchronizedCache(); + } + + /** + * Called by {@link #synchronizedCache(Cache)}. This method + * returns a {@link SynchronizedCache} instance that wraps + * this instance by default and can be overridden to return + * e. g. subclasses of {@link SynchronizedCache} or this + * in case this cache is already synchronized. + */ + Cache getSynchronizedCache() { + return new SynchronizedCache(this); + } + + /** + * Puts a (key, value)-pair into the cache. + */ + public abstract void put(Object key, Object value); + + /** + * Returns the value for the given key. + */ + public abstract Object get(Object key); + + /** + * Returns whether the given key is in this cache. + */ + public abstract boolean containsKey(Object key); + + /** + * Closes the cache. + */ + public abstract void close(); + +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/cache/SimpleLRUCache.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/cache/SimpleLRUCache.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/cache/SimpleLRUCache.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,49 @@ +package org.apache.lucene.util.cache; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Simple LRU cache implementation that uses a LinkedHashMap. + * This cache is not synchronized, use {@link Cache#synchronizedCache(Cache)} + * if needed. + * + */ +public class SimpleLRUCache extends SimpleMapCache { + private final static float LOADFACTOR = 0.75f; + + private int cacheSize; + + /** + * Creates a last-recently-used cache with the specified size. + */ + public SimpleLRUCache(int cacheSize) { + super(null); + this.cacheSize = cacheSize; + int capacity = (int) Math.ceil(cacheSize / LOADFACTOR) + 1; + + super.map = new LinkedHashMap(capacity, LOADFACTOR, true) { + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > SimpleLRUCache.this.cacheSize; + } + }; + } + +} Index: 3rdParty_sources/lucene/org/apache/lucene/util/cache/SimpleMapCache.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/apache/lucene/util/cache/SimpleMapCache.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/apache/lucene/util/cache/SimpleMapCache.java 17 Aug 2012 14:55:10 -0000 1.1 @@ -0,0 +1,100 @@ +package org.apache.lucene.util.cache; + +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Simple cache implementation that uses a HashMap to store (key, value) pairs. + * This cache is not synchronized, use {@link Cache#synchronizedCache(Cache)} + * if needed. + */ +public class SimpleMapCache extends Cache { + Map map; + + public SimpleMapCache() { + this(new HashMap()); + } + + public SimpleMapCache(Map map) { + this.map = map; + } + + public Object get(Object key) { + return map.get(key); + } + + public void put(Object key, Object value) { + map.put(key, value); + } + + public void close() { + // NOOP + } + + public boolean containsKey(Object key) { + return map.containsKey(key); + } + + /** + * Returns a Set containing all keys in this cache. + */ + public Set keySet() { + return map.keySet(); + } + + Cache getSynchronizedCache() { + return new SynchronizedSimpleMapCache(this); + } + + private static class SynchronizedSimpleMapCache extends SimpleMapCache { + Object mutex; + SimpleMapCache cache; + + SynchronizedSimpleMapCache(SimpleMapCache cache) { + this.cache = cache; + this.mutex = this; + } + + public void put(Object key, Object value) { + synchronized(mutex) {cache.put(key, value);} + } + + public Object get(Object key) { + synchronized(mutex) {return cache.get(key);} + } + + public boolean containsKey(Object key) { + synchronized(mutex) {return cache.containsKey(key);} + } + + public void close() { + synchronized(mutex) {cache.close();} + } + + public Set keySet() { + synchronized(mutex) {return cache.keySet();} + } + + Cache getSynchronizedCache() { + return this; + } + } +} Index: 3rdParty_sources/lucene/org/tartarus/snowball/Among.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/Among.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/Among.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,34 @@ + +package org.tartarus.snowball; + +import java.lang.reflect.Method; + +public class Among { + public Among (String s, int substring_i, int result, + String methodname, SnowballProgram methodobject) { + this.s_size = s.length(); + this.s = s; + this.substring_i = substring_i; + this.result = result; + this.methodobject = methodobject; + if (methodname.length() == 0) { + this.method = null; + } else { + try { + this.method = methodobject.getClass(). + getDeclaredMethod(methodname, new Class[0]); + } catch (NoSuchMethodException e) { + // FIXME - debug message + this.method = null; + } + } + } + + public int s_size; /* search string */ + public String s; /* search string */ + public int substring_i; /* index to longest matching substring */ + public int result; /* result of the lookup */ + public Method method; /* method to use if substring matches */ + public SnowballProgram methodobject; /* object to invoke method on */ + +}; Index: 3rdParty_sources/lucene/org/tartarus/snowball/SnowballProgram.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/SnowballProgram.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/SnowballProgram.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,426 @@ + +package org.tartarus.snowball; +import java.lang.reflect.InvocationTargetException; + +/** + * This is the rev 500 of the Snowball SVN trunk, + * but modified: + * made abstract and introduced abstract method stem + * to avoid expensive + */ +public abstract class SnowballProgram { + protected SnowballProgram() + { + current = new StringBuffer(); + setCurrent(""); + } + + public abstract boolean stem(); + + /** + * Set the current string. + */ + public void setCurrent(String value) + { + current.replace(0, current.length(), value); + cursor = 0; + limit = current.length(); + limit_backward = 0; + bra = cursor; + ket = limit; + } + + /** + * Get the current string. + */ + public String getCurrent() + { + String result = current.toString(); + // Make a new StringBuffer. If we reuse the old one, and a user of + // the library keeps a reference to the buffer returned (for example, + // by converting it to a String in a way which doesn't force a copy), + // the buffer size will not decrease, and we will risk wasting a large + // amount of memory. + // Thanks to Wolfram Esser for spotting this problem. + current = new StringBuffer(); + return result; + } + + // current string + protected StringBuffer current; + + protected int cursor; + protected int limit; + protected int limit_backward; + protected int bra; + protected int ket; + + protected void copy_from(SnowballProgram other) + { + current = other.current; + cursor = other.cursor; + limit = other.limit; + limit_backward = other.limit_backward; + bra = other.bra; + ket = other.ket; + } + + protected boolean in_grouping(char [] s, int min, int max) + { + if (cursor >= limit) return false; + char ch = current.charAt(cursor); + if (ch > max || ch < min) return false; + ch -= min; + if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return false; + cursor++; + return true; + } + + protected boolean in_grouping_b(char [] s, int min, int max) + { + if (cursor <= limit_backward) return false; + char ch = current.charAt(cursor - 1); + if (ch > max || ch < min) return false; + ch -= min; + if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return false; + cursor--; + return true; + } + + protected boolean out_grouping(char [] s, int min, int max) + { + if (cursor >= limit) return false; + char ch = current.charAt(cursor); + if (ch > max || ch < min) { + cursor++; + return true; + } + ch -= min; + if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) { + cursor ++; + return true; + } + return false; + } + + protected boolean out_grouping_b(char [] s, int min, int max) + { + if (cursor <= limit_backward) return false; + char ch = current.charAt(cursor - 1); + if (ch > max || ch < min) { + cursor--; + return true; + } + ch -= min; + if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) { + cursor--; + return true; + } + return false; + } + + protected boolean in_range(int min, int max) + { + if (cursor >= limit) return false; + char ch = current.charAt(cursor); + if (ch > max || ch < min) return false; + cursor++; + return true; + } + + protected boolean in_range_b(int min, int max) + { + if (cursor <= limit_backward) return false; + char ch = current.charAt(cursor - 1); + if (ch > max || ch < min) return false; + cursor--; + return true; + } + + protected boolean out_range(int min, int max) + { + if (cursor >= limit) return false; + char ch = current.charAt(cursor); + if (!(ch > max || ch < min)) return false; + cursor++; + return true; + } + + protected boolean out_range_b(int min, int max) + { + if (cursor <= limit_backward) return false; + char ch = current.charAt(cursor - 1); + if(!(ch > max || ch < min)) return false; + cursor--; + return true; + } + + protected boolean eq_s(int s_size, String s) + { + if (limit - cursor < s_size) return false; + int i; + for (i = 0; i != s_size; i++) { + if (current.charAt(cursor + i) != s.charAt(i)) return false; + } + cursor += s_size; + return true; + } + + protected boolean eq_s_b(int s_size, String s) + { + if (cursor - limit_backward < s_size) return false; + int i; + for (i = 0; i != s_size; i++) { + if (current.charAt(cursor - s_size + i) != s.charAt(i)) return false; + } + cursor -= s_size; + return true; + } + + protected boolean eq_v(StringBuffer s) + { + return eq_s(s.length(), s.toString()); + } + + protected boolean eq_v_b(StringBuffer s) + { return eq_s_b(s.length(), s.toString()); + } + + protected int find_among(Among v[], int v_size) + { + int i = 0; + int j = v_size; + + int c = cursor; + int l = limit; + + int common_i = 0; + int common_j = 0; + + boolean first_key_inspected = false; + + while(true) { + int k = i + ((j - i) >> 1); + int diff = 0; + int common = common_i < common_j ? common_i : common_j; // smaller + Among w = v[k]; + int i2; + for (i2 = common; i2 < w.s_size; i2++) { + if (c + common == l) { + diff = -1; + break; + } + diff = current.charAt(c + common) - w.s.charAt(i2); + if (diff != 0) break; + common++; + } + if (diff < 0) { + j = k; + common_j = common; + } else { + i = k; + common_i = common; + } + if (j - i <= 1) { + if (i > 0) break; // v->s has been inspected + if (j == i) break; // only one item in v + + // - but now we need to go round once more to get + // v->s inspected. This looks messy, but is actually + // the optimal approach. + + if (first_key_inspected) break; + first_key_inspected = true; + } + } + while(true) { + Among w = v[i]; + if (common_i >= w.s_size) { + cursor = c + w.s_size; + if (w.method == null) return w.result; + boolean res; + try { + Object resobj = w.method.invoke(w.methodobject, + new Object[0]); + res = resobj.toString().equals("true"); + } catch (InvocationTargetException e) { + res = false; + // FIXME - debug message + } catch (IllegalAccessException e) { + res = false; + // FIXME - debug message + } + cursor = c + w.s_size; + if (res) return w.result; + } + i = w.substring_i; + if (i < 0) return 0; + } + } + + // find_among_b is for backwards processing. Same comments apply + protected int find_among_b(Among v[], int v_size) + { + int i = 0; + int j = v_size; + + int c = cursor; + int lb = limit_backward; + + int common_i = 0; + int common_j = 0; + + boolean first_key_inspected = false; + + while(true) { + int k = i + ((j - i) >> 1); + int diff = 0; + int common = common_i < common_j ? common_i : common_j; + Among w = v[k]; + int i2; + for (i2 = w.s_size - 1 - common; i2 >= 0; i2--) { + if (c - common == lb) { + diff = -1; + break; + } + diff = current.charAt(c - 1 - common) - w.s.charAt(i2); + if (diff != 0) break; + common++; + } + if (diff < 0) { + j = k; + common_j = common; + } else { + i = k; + common_i = common; + } + if (j - i <= 1) { + if (i > 0) break; + if (j == i) break; + if (first_key_inspected) break; + first_key_inspected = true; + } + } + while(true) { + Among w = v[i]; + if (common_i >= w.s_size) { + cursor = c - w.s_size; + if (w.method == null) return w.result; + + boolean res; + try { + Object resobj = w.method.invoke(w.methodobject, + new Object[0]); + res = resobj.toString().equals("true"); + } catch (InvocationTargetException e) { + res = false; + // FIXME - debug message + } catch (IllegalAccessException e) { + res = false; + // FIXME - debug message + } + cursor = c - w.s_size; + if (res) return w.result; + } + i = w.substring_i; + if (i < 0) return 0; + } + } + + /* to replace chars between c_bra and c_ket in current by the + * chars in s. + */ + protected int replace_s(int c_bra, int c_ket, String s) + { + int adjustment = s.length() - (c_ket - c_bra); + current.replace(c_bra, c_ket, s); + limit += adjustment; + if (cursor >= c_ket) cursor += adjustment; + else if (cursor > c_bra) cursor = c_bra; + return adjustment; + } + + protected void slice_check() + { + if (bra < 0 || + bra > ket || + ket > limit || + limit > current.length()) // this line could be removed + { + System.err.println("faulty slice operation"); + // FIXME: report error somehow. + /* + fprintf(stderr, "faulty slice operation:\n"); + debug(z, -1, 0); + exit(1); + */ + } + } + + protected void slice_from(String s) + { + slice_check(); + replace_s(bra, ket, s); + } + + protected void slice_from(StringBuffer s) + { + slice_from(s.toString()); + } + + protected void slice_del() + { + slice_from(""); + } + + protected void insert(int c_bra, int c_ket, String s) + { + int adjustment = replace_s(c_bra, c_ket, s); + if (c_bra <= bra) bra += adjustment; + if (c_bra <= ket) ket += adjustment; + } + + protected void insert(int c_bra, int c_ket, StringBuffer s) + { + insert(c_bra, c_ket, s.toString()); + } + + /* Copy the slice into the supplied StringBuffer */ + protected StringBuffer slice_to(StringBuffer s) + { + slice_check(); + int len = ket - bra; + s.replace(0, s.length(), current.substring(bra, ket)); + return s; + } + + protected StringBuffer assign_to(StringBuffer s) + { + s.replace(0, s.length(), current.substring(0, limit)); + return s; + } + +/* +extern void debug(struct SN_env * z, int number, int line_count) +{ int i; + int limit = SIZE(z->p); + //if (number >= 0) printf("%3d (line %4d): '", number, line_count); + if (number >= 0) printf("%3d (line %4d): [%d]'", number, line_count,limit); + for (i = 0; i <= limit; i++) + { if (z->lb == i) printf("{"); + if (z->bra == i) printf("["); + if (z->c == i) printf("|"); + if (z->ket == i) printf("]"); + if (z->l == i) printf("}"); + if (i < limit) + { int ch = z->p[i]; + if (ch == 0) ch = '#'; + printf("%c", ch); + } + } + printf("'\n"); +} +*/ + +}; + Index: 3rdParty_sources/lucene/org/tartarus/snowball/TestApp.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/TestApp.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/TestApp.java 17 Aug 2012 14:55:14 -0000 1.1 @@ -0,0 +1,78 @@ + +package org.tartarus.snowball; + +import java.lang.reflect.Method; +import java.io.Reader; +import java.io.Writer; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.OutputStream; +import java.io.FileOutputStream; + +public class TestApp { + private static void usage() + { + System.err.println("Usage: TestApp [-o ]"); + } + + public static void main(String [] args) throws Throwable { + if (args.length < 2) { + usage(); + return; + } + + Class stemClass = Class.forName("org.tartarus.snowball.ext." + + args[0] + "Stemmer"); + SnowballProgram stemmer = (SnowballProgram) stemClass.newInstance(); + Method stemMethod = stemClass.getMethod("stem", new Class[0]); + + Reader reader; + reader = new InputStreamReader(new FileInputStream(args[1])); + reader = new BufferedReader(reader); + + StringBuffer input = new StringBuffer(); + + OutputStream outstream; + + if (args.length > 2) { + if (args.length == 4 && args[2].equals("-o")) { + outstream = new FileOutputStream(args[3]); + } else { + usage(); + return; + } + } else { + outstream = System.out; + } + Writer output = new OutputStreamWriter(outstream); + output = new BufferedWriter(output); + + int repeat = 1; + if (args.length > 4) { + repeat = Integer.parseInt(args[4]); + } + + Object [] emptyArgs = new Object[0]; + int character; + while ((character = reader.read()) != -1) { + char ch = (char) character; + if (Character.isWhitespace((char) ch)) { + if (input.length() > 0) { + stemmer.setCurrent(input.toString()); + for (int i = repeat; i != 0; i--) { + stemMethod.invoke(stemmer, emptyArgs); + } + output.write(stemmer.getCurrent()); + output.write('\n'); + input.delete(0, input.length()); + } + } else { + input.append(Character.toLowerCase(ch)); + } + } + output.flush(); + } +} Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/DanishStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/DanishStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/DanishStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,423 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class DanishStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "hed", -1, 1, "", this), + new Among ( "ethed", 0, 1, "", this), + new Among ( "ered", -1, 1, "", this), + new Among ( "e", -1, 1, "", this), + new Among ( "erede", 3, 1, "", this), + new Among ( "ende", 3, 1, "", this), + new Among ( "erende", 5, 1, "", this), + new Among ( "ene", 3, 1, "", this), + new Among ( "erne", 3, 1, "", this), + new Among ( "ere", 3, 1, "", this), + new Among ( "en", -1, 1, "", this), + new Among ( "heden", 10, 1, "", this), + new Among ( "eren", 10, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "heder", 13, 1, "", this), + new Among ( "erer", 13, 1, "", this), + new Among ( "s", -1, 2, "", this), + new Among ( "heds", 16, 1, "", this), + new Among ( "es", 16, 1, "", this), + new Among ( "endes", 18, 1, "", this), + new Among ( "erendes", 19, 1, "", this), + new Among ( "enes", 18, 1, "", this), + new Among ( "ernes", 18, 1, "", this), + new Among ( "eres", 18, 1, "", this), + new Among ( "ens", 16, 1, "", this), + new Among ( "hedens", 24, 1, "", this), + new Among ( "erens", 24, 1, "", this), + new Among ( "ers", 16, 1, "", this), + new Among ( "ets", 16, 1, "", this), + new Among ( "erets", 28, 1, "", this), + new Among ( "et", -1, 1, "", this), + new Among ( "eret", 30, 1, "", this) + }; + + private Among a_1[] = { + new Among ( "gd", -1, -1, "", this), + new Among ( "dt", -1, -1, "", this), + new Among ( "gt", -1, -1, "", this), + new Among ( "kt", -1, -1, "", this) + }; + + private Among a_2[] = { + new Among ( "ig", -1, 1, "", this), + new Among ( "lig", 0, 1, "", this), + new Among ( "elig", 1, 1, "", this), + new Among ( "els", -1, 1, "", this), + new Among ( "l\u00F8st", -1, 2, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 128 }; + + private static final char g_s_ending[] = {239, 254, 42, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 }; + + private int I_x; + private int I_p1; + private StringBuffer S_ch = new StringBuffer(); + + private void copy_from(DanishStemmer other) { + I_x = other.I_x; + I_p1 = other.I_p1; + S_ch = other.S_ch; + super.copy_from(other); + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + // (, line 29 + I_p1 = limit; + // test, line 33 + v_1 = cursor; + // (, line 33 + // hop, line 33 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + return false; + } + cursor = c; + } + // setmark x, line 33 + I_x = cursor; + cursor = v_1; + // goto, line 34 + golab0: while(true) + { + v_2 = cursor; + lab1: do { + if (!(in_grouping(g_v, 97, 248))) + { + break lab1; + } + cursor = v_2; + break golab0; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 34 + golab2: while(true) + { + lab3: do { + if (!(out_grouping(g_v, 97, 248))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 34 + I_p1 = cursor; + // try, line 35 + lab4: do { + // (, line 35 + if (!(I_p1 < I_x)) + { + break lab4; + } + I_p1 = I_x; + } while (false); + return true; + } + + private boolean r_main_suffix() { + int among_var; + int v_1; + int v_2; + // (, line 40 + // setlimit, line 41 + v_1 = limit - cursor; + // tomark, line 41 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 41 + // [, line 41 + ket = cursor; + // substring, line 41 + among_var = find_among_b(a_0, 32); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 41 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 48 + // delete, line 48 + slice_del(); + break; + case 2: + // (, line 50 + if (!(in_grouping_b(g_s_ending, 97, 229))) + { + return false; + } + // delete, line 50 + slice_del(); + break; + } + return true; + } + + private boolean r_consonant_pair() { + int v_1; + int v_2; + int v_3; + // (, line 54 + // test, line 55 + v_1 = limit - cursor; + // (, line 55 + // setlimit, line 56 + v_2 = limit - cursor; + // tomark, line 56 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_3 = limit_backward; + limit_backward = cursor; + cursor = limit - v_2; + // (, line 56 + // [, line 56 + ket = cursor; + // substring, line 56 + if (find_among_b(a_1, 4) == 0) + { + limit_backward = v_3; + return false; + } + // ], line 56 + bra = cursor; + limit_backward = v_3; + cursor = limit - v_1; + // next, line 62 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 62 + bra = cursor; + // delete, line 62 + slice_del(); + return true; + } + + private boolean r_other_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 65 + // do, line 66 + v_1 = limit - cursor; + lab0: do { + // (, line 66 + // [, line 66 + ket = cursor; + // literal, line 66 + if (!(eq_s_b(2, "st"))) + { + break lab0; + } + // ], line 66 + bra = cursor; + // literal, line 66 + if (!(eq_s_b(2, "ig"))) + { + break lab0; + } + // delete, line 66 + slice_del(); + } while (false); + cursor = limit - v_1; + // setlimit, line 67 + v_2 = limit - cursor; + // tomark, line 67 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_3 = limit_backward; + limit_backward = cursor; + cursor = limit - v_2; + // (, line 67 + // [, line 67 + ket = cursor; + // substring, line 67 + among_var = find_among_b(a_2, 5); + if (among_var == 0) + { + limit_backward = v_3; + return false; + } + // ], line 67 + bra = cursor; + limit_backward = v_3; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 70 + // delete, line 70 + slice_del(); + // do, line 70 + v_4 = limit - cursor; + lab1: do { + // call consonant_pair, line 70 + if (!r_consonant_pair()) + { + break lab1; + } + } while (false); + cursor = limit - v_4; + break; + case 2: + // (, line 72 + // <-, line 72 + slice_from("l\u00F8s"); + break; + } + return true; + } + + private boolean r_undouble() { + int v_1; + int v_2; + // (, line 75 + // setlimit, line 76 + v_1 = limit - cursor; + // tomark, line 76 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 76 + // [, line 76 + ket = cursor; + if (!(out_grouping_b(g_v, 97, 248))) + { + limit_backward = v_2; + return false; + } + // ], line 76 + bra = cursor; + // -> ch, line 76 + S_ch = slice_to(S_ch); + limit_backward = v_2; + // name ch, line 77 + if (!(eq_v_b(S_ch))) + { + return false; + } + // delete, line 78 + slice_del(); + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 82 + // do, line 84 + v_1 = cursor; + lab0: do { + // call mark_regions, line 84 + if (!r_mark_regions()) + { + break lab0; + } + } while (false); + cursor = v_1; + // backwards, line 85 + limit_backward = cursor; cursor = limit; + // (, line 85 + // do, line 86 + v_2 = limit - cursor; + lab1: do { + // call main_suffix, line 86 + if (!r_main_suffix()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 87 + v_3 = limit - cursor; + lab2: do { + // call consonant_pair, line 87 + if (!r_consonant_pair()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 88 + v_4 = limit - cursor; + lab3: do { + // call other_suffix, line 88 + if (!r_other_suffix()) + { + break lab3; + } + } while (false); + cursor = limit - v_4; + // do, line 89 + v_5 = limit - cursor; + lab4: do { + // call undouble, line 89 + if (!r_undouble()) + { + break lab4; + } + } while (false); + cursor = limit - v_5; + cursor = limit_backward; return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/DutchStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/DutchStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/DutchStemmer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,837 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class DutchStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "", -1, 6, "", this), + new Among ( "\u00E1", 0, 1, "", this), + new Among ( "\u00E4", 0, 1, "", this), + new Among ( "\u00E9", 0, 2, "", this), + new Among ( "\u00EB", 0, 2, "", this), + new Among ( "\u00ED", 0, 3, "", this), + new Among ( "\u00EF", 0, 3, "", this), + new Among ( "\u00F3", 0, 4, "", this), + new Among ( "\u00F6", 0, 4, "", this), + new Among ( "\u00FA", 0, 5, "", this), + new Among ( "\u00FC", 0, 5, "", this) + }; + + private Among a_1[] = { + new Among ( "", -1, 3, "", this), + new Among ( "I", 0, 2, "", this), + new Among ( "Y", 0, 1, "", this) + }; + + private Among a_2[] = { + new Among ( "dd", -1, -1, "", this), + new Among ( "kk", -1, -1, "", this), + new Among ( "tt", -1, -1, "", this) + }; + + private Among a_3[] = { + new Among ( "ene", -1, 2, "", this), + new Among ( "se", -1, 3, "", this), + new Among ( "en", -1, 2, "", this), + new Among ( "heden", 2, 1, "", this), + new Among ( "s", -1, 3, "", this) + }; + + private Among a_4[] = { + new Among ( "end", -1, 1, "", this), + new Among ( "ig", -1, 2, "", this), + new Among ( "ing", -1, 1, "", this), + new Among ( "lijk", -1, 3, "", this), + new Among ( "baar", -1, 4, "", this), + new Among ( "bar", -1, 5, "", this) + }; + + private Among a_5[] = { + new Among ( "aa", -1, -1, "", this), + new Among ( "ee", -1, -1, "", this), + new Among ( "oo", -1, -1, "", this), + new Among ( "uu", -1, -1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 }; + + private static final char g_v_I[] = {1, 0, 0, 17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 }; + + private static final char g_v_j[] = {17, 67, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 }; + + private int I_p2; + private int I_p1; + private boolean B_e_found; + + private void copy_from(DutchStemmer other) { + I_p2 = other.I_p2; + I_p1 = other.I_p1; + B_e_found = other.B_e_found; + super.copy_from(other); + } + + private boolean r_prelude() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + // (, line 41 + // test, line 42 + v_1 = cursor; + // repeat, line 42 + replab0: while(true) + { + v_2 = cursor; + lab1: do { + // (, line 42 + // [, line 43 + bra = cursor; + // substring, line 43 + among_var = find_among(a_0, 11); + if (among_var == 0) + { + break lab1; + } + // ], line 43 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 45 + // <-, line 45 + slice_from("a"); + break; + case 2: + // (, line 47 + // <-, line 47 + slice_from("e"); + break; + case 3: + // (, line 49 + // <-, line 49 + slice_from("i"); + break; + case 4: + // (, line 51 + // <-, line 51 + slice_from("o"); + break; + case 5: + // (, line 53 + // <-, line 53 + slice_from("u"); + break; + case 6: + // (, line 54 + // next, line 54 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_2; + break replab0; + } + cursor = v_1; + // try, line 57 + v_3 = cursor; + lab2: do { + // (, line 57 + // [, line 57 + bra = cursor; + // literal, line 57 + if (!(eq_s(1, "y"))) + { + cursor = v_3; + break lab2; + } + // ], line 57 + ket = cursor; + // <-, line 57 + slice_from("Y"); + } while (false); + // repeat, line 58 + replab3: while(true) + { + v_4 = cursor; + lab4: do { + // goto, line 58 + golab5: while(true) + { + v_5 = cursor; + lab6: do { + // (, line 58 + if (!(in_grouping(g_v, 97, 232))) + { + break lab6; + } + // [, line 59 + bra = cursor; + // or, line 59 + lab7: do { + v_6 = cursor; + lab8: do { + // (, line 59 + // literal, line 59 + if (!(eq_s(1, "i"))) + { + break lab8; + } + // ], line 59 + ket = cursor; + if (!(in_grouping(g_v, 97, 232))) + { + break lab8; + } + // <-, line 59 + slice_from("I"); + break lab7; + } while (false); + cursor = v_6; + // (, line 60 + // literal, line 60 + if (!(eq_s(1, "y"))) + { + break lab6; + } + // ], line 60 + ket = cursor; + // <-, line 60 + slice_from("Y"); + } while (false); + cursor = v_5; + break golab5; + } while (false); + cursor = v_5; + if (cursor >= limit) + { + break lab4; + } + cursor++; + } + continue replab3; + } while (false); + cursor = v_4; + break replab3; + } + return true; + } + + private boolean r_mark_regions() { + // (, line 64 + I_p1 = limit; + I_p2 = limit; + // gopast, line 69 + golab0: while(true) + { + lab1: do { + if (!(in_grouping(g_v, 97, 232))) + { + break lab1; + } + break golab0; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 69 + golab2: while(true) + { + lab3: do { + if (!(out_grouping(g_v, 97, 232))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 69 + I_p1 = cursor; + // try, line 70 + lab4: do { + // (, line 70 + if (!(I_p1 < 3)) + { + break lab4; + } + I_p1 = 3; + } while (false); + // gopast, line 71 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 97, 232))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 71 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 97, 232))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p2, line 71 + I_p2 = cursor; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 75 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 75 + // [, line 77 + bra = cursor; + // substring, line 77 + among_var = find_among(a_1, 3); + if (among_var == 0) + { + break lab1; + } + // ], line 77 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 78 + // <-, line 78 + slice_from("y"); + break; + case 2: + // (, line 79 + // <-, line 79 + slice_from("i"); + break; + case 3: + // (, line 80 + // next, line 80 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_undouble() { + int v_1; + // (, line 90 + // test, line 91 + v_1 = limit - cursor; + // among, line 91 + if (find_among_b(a_2, 3) == 0) + { + return false; + } + cursor = limit - v_1; + // [, line 91 + ket = cursor; + // next, line 91 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 91 + bra = cursor; + // delete, line 91 + slice_del(); + return true; + } + + private boolean r_e_ending() { + int v_1; + // (, line 94 + // unset e_found, line 95 + B_e_found = false; + // [, line 96 + ket = cursor; + // literal, line 96 + if (!(eq_s_b(1, "e"))) + { + return false; + } + // ], line 96 + bra = cursor; + // call R1, line 96 + if (!r_R1()) + { + return false; + } + // test, line 96 + v_1 = limit - cursor; + if (!(out_grouping_b(g_v, 97, 232))) + { + return false; + } + cursor = limit - v_1; + // delete, line 96 + slice_del(); + // set e_found, line 97 + B_e_found = true; + // call undouble, line 98 + if (!r_undouble()) + { + return false; + } + return true; + } + + private boolean r_en_ending() { + int v_1; + int v_2; + // (, line 101 + // call R1, line 102 + if (!r_R1()) + { + return false; + } + // and, line 102 + v_1 = limit - cursor; + if (!(out_grouping_b(g_v, 97, 232))) + { + return false; + } + cursor = limit - v_1; + // not, line 102 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 102 + if (!(eq_s_b(3, "gem"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + // delete, line 102 + slice_del(); + // call undouble, line 103 + if (!r_undouble()) + { + return false; + } + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + // (, line 106 + // do, line 107 + v_1 = limit - cursor; + lab0: do { + // (, line 107 + // [, line 108 + ket = cursor; + // substring, line 108 + among_var = find_among_b(a_3, 5); + if (among_var == 0) + { + break lab0; + } + // ], line 108 + bra = cursor; + switch(among_var) { + case 0: + break lab0; + case 1: + // (, line 110 + // call R1, line 110 + if (!r_R1()) + { + break lab0; + } + // <-, line 110 + slice_from("heid"); + break; + case 2: + // (, line 113 + // call en_ending, line 113 + if (!r_en_ending()) + { + break lab0; + } + break; + case 3: + // (, line 116 + // call R1, line 116 + if (!r_R1()) + { + break lab0; + } + if (!(out_grouping_b(g_v_j, 97, 232))) + { + break lab0; + } + // delete, line 116 + slice_del(); + break; + } + } while (false); + cursor = limit - v_1; + // do, line 120 + v_2 = limit - cursor; + lab1: do { + // call e_ending, line 120 + if (!r_e_ending()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 122 + v_3 = limit - cursor; + lab2: do { + // (, line 122 + // [, line 122 + ket = cursor; + // literal, line 122 + if (!(eq_s_b(4, "heid"))) + { + break lab2; + } + // ], line 122 + bra = cursor; + // call R2, line 122 + if (!r_R2()) + { + break lab2; + } + // not, line 122 + { + v_4 = limit - cursor; + lab3: do { + // literal, line 122 + if (!(eq_s_b(1, "c"))) + { + break lab3; + } + break lab2; + } while (false); + cursor = limit - v_4; + } + // delete, line 122 + slice_del(); + // [, line 123 + ket = cursor; + // literal, line 123 + if (!(eq_s_b(2, "en"))) + { + break lab2; + } + // ], line 123 + bra = cursor; + // call en_ending, line 123 + if (!r_en_ending()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 126 + v_5 = limit - cursor; + lab4: do { + // (, line 126 + // [, line 127 + ket = cursor; + // substring, line 127 + among_var = find_among_b(a_4, 6); + if (among_var == 0) + { + break lab4; + } + // ], line 127 + bra = cursor; + switch(among_var) { + case 0: + break lab4; + case 1: + // (, line 129 + // call R2, line 129 + if (!r_R2()) + { + break lab4; + } + // delete, line 129 + slice_del(); + // or, line 130 + lab5: do { + v_6 = limit - cursor; + lab6: do { + // (, line 130 + // [, line 130 + ket = cursor; + // literal, line 130 + if (!(eq_s_b(2, "ig"))) + { + break lab6; + } + // ], line 130 + bra = cursor; + // call R2, line 130 + if (!r_R2()) + { + break lab6; + } + // not, line 130 + { + v_7 = limit - cursor; + lab7: do { + // literal, line 130 + if (!(eq_s_b(1, "e"))) + { + break lab7; + } + break lab6; + } while (false); + cursor = limit - v_7; + } + // delete, line 130 + slice_del(); + break lab5; + } while (false); + cursor = limit - v_6; + // call undouble, line 130 + if (!r_undouble()) + { + break lab4; + } + } while (false); + break; + case 2: + // (, line 133 + // call R2, line 133 + if (!r_R2()) + { + break lab4; + } + // not, line 133 + { + v_8 = limit - cursor; + lab8: do { + // literal, line 133 + if (!(eq_s_b(1, "e"))) + { + break lab8; + } + break lab4; + } while (false); + cursor = limit - v_8; + } + // delete, line 133 + slice_del(); + break; + case 3: + // (, line 136 + // call R2, line 136 + if (!r_R2()) + { + break lab4; + } + // delete, line 136 + slice_del(); + // call e_ending, line 136 + if (!r_e_ending()) + { + break lab4; + } + break; + case 4: + // (, line 139 + // call R2, line 139 + if (!r_R2()) + { + break lab4; + } + // delete, line 139 + slice_del(); + break; + case 5: + // (, line 142 + // call R2, line 142 + if (!r_R2()) + { + break lab4; + } + // Boolean test e_found, line 142 + if (!(B_e_found)) + { + break lab4; + } + // delete, line 142 + slice_del(); + break; + } + } while (false); + cursor = limit - v_5; + // do, line 146 + v_9 = limit - cursor; + lab9: do { + // (, line 146 + if (!(out_grouping_b(g_v_I, 73, 232))) + { + break lab9; + } + // test, line 148 + v_10 = limit - cursor; + // (, line 148 + // among, line 149 + if (find_among_b(a_5, 4) == 0) + { + break lab9; + } + if (!(out_grouping_b(g_v, 97, 232))) + { + break lab9; + } + cursor = limit - v_10; + // [, line 152 + ket = cursor; + // next, line 152 + if (cursor <= limit_backward) + { + break lab9; + } + cursor--; + // ], line 152 + bra = cursor; + // delete, line 152 + slice_del(); + } while (false); + cursor = limit - v_9; + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 157 + // do, line 159 + v_1 = cursor; + lab0: do { + // call prelude, line 159 + if (!r_prelude()) + { + break lab0; + } + } while (false); + cursor = v_1; + // do, line 160 + v_2 = cursor; + lab1: do { + // call mark_regions, line 160 + if (!r_mark_regions()) + { + break lab1; + } + } while (false); + cursor = v_2; + // backwards, line 161 + limit_backward = cursor; cursor = limit; + // do, line 162 + v_3 = limit - cursor; + lab2: do { + // call standard_suffix, line 162 + if (!r_standard_suffix()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + cursor = limit_backward; // do, line 163 + v_4 = cursor; + lab3: do { + // call postlude, line 163 + if (!r_postlude()) + { + break lab3; + } + } while (false); + cursor = v_4; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/EnglishStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/EnglishStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/EnglishStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,1314 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class EnglishStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "arsen", -1, -1, "", this), + new Among ( "commun", -1, -1, "", this), + new Among ( "gener", -1, -1, "", this) + }; + + private Among a_1[] = { + new Among ( "'", -1, 1, "", this), + new Among ( "'s'", 0, 1, "", this), + new Among ( "'s", -1, 1, "", this) + }; + + private Among a_2[] = { + new Among ( "ied", -1, 2, "", this), + new Among ( "s", -1, 3, "", this), + new Among ( "ies", 1, 2, "", this), + new Among ( "sses", 1, 1, "", this), + new Among ( "ss", 1, -1, "", this), + new Among ( "us", 1, -1, "", this) + }; + + private Among a_3[] = { + new Among ( "", -1, 3, "", this), + new Among ( "bb", 0, 2, "", this), + new Among ( "dd", 0, 2, "", this), + new Among ( "ff", 0, 2, "", this), + new Among ( "gg", 0, 2, "", this), + new Among ( "bl", 0, 1, "", this), + new Among ( "mm", 0, 2, "", this), + new Among ( "nn", 0, 2, "", this), + new Among ( "pp", 0, 2, "", this), + new Among ( "rr", 0, 2, "", this), + new Among ( "at", 0, 1, "", this), + new Among ( "tt", 0, 2, "", this), + new Among ( "iz", 0, 1, "", this) + }; + + private Among a_4[] = { + new Among ( "ed", -1, 2, "", this), + new Among ( "eed", 0, 1, "", this), + new Among ( "ing", -1, 2, "", this), + new Among ( "edly", -1, 2, "", this), + new Among ( "eedly", 3, 1, "", this), + new Among ( "ingly", -1, 2, "", this) + }; + + private Among a_5[] = { + new Among ( "anci", -1, 3, "", this), + new Among ( "enci", -1, 2, "", this), + new Among ( "ogi", -1, 13, "", this), + new Among ( "li", -1, 16, "", this), + new Among ( "bli", 3, 12, "", this), + new Among ( "abli", 4, 4, "", this), + new Among ( "alli", 3, 8, "", this), + new Among ( "fulli", 3, 14, "", this), + new Among ( "lessli", 3, 15, "", this), + new Among ( "ousli", 3, 10, "", this), + new Among ( "entli", 3, 5, "", this), + new Among ( "aliti", -1, 8, "", this), + new Among ( "biliti", -1, 12, "", this), + new Among ( "iviti", -1, 11, "", this), + new Among ( "tional", -1, 1, "", this), + new Among ( "ational", 14, 7, "", this), + new Among ( "alism", -1, 8, "", this), + new Among ( "ation", -1, 7, "", this), + new Among ( "ization", 17, 6, "", this), + new Among ( "izer", -1, 6, "", this), + new Among ( "ator", -1, 7, "", this), + new Among ( "iveness", -1, 11, "", this), + new Among ( "fulness", -1, 9, "", this), + new Among ( "ousness", -1, 10, "", this) + }; + + private Among a_6[] = { + new Among ( "icate", -1, 4, "", this), + new Among ( "ative", -1, 6, "", this), + new Among ( "alize", -1, 3, "", this), + new Among ( "iciti", -1, 4, "", this), + new Among ( "ical", -1, 4, "", this), + new Among ( "tional", -1, 1, "", this), + new Among ( "ational", 5, 2, "", this), + new Among ( "ful", -1, 5, "", this), + new Among ( "ness", -1, 5, "", this) + }; + + private Among a_7[] = { + new Among ( "ic", -1, 1, "", this), + new Among ( "ance", -1, 1, "", this), + new Among ( "ence", -1, 1, "", this), + new Among ( "able", -1, 1, "", this), + new Among ( "ible", -1, 1, "", this), + new Among ( "ate", -1, 1, "", this), + new Among ( "ive", -1, 1, "", this), + new Among ( "ize", -1, 1, "", this), + new Among ( "iti", -1, 1, "", this), + new Among ( "al", -1, 1, "", this), + new Among ( "ism", -1, 1, "", this), + new Among ( "ion", -1, 2, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "ous", -1, 1, "", this), + new Among ( "ant", -1, 1, "", this), + new Among ( "ent", -1, 1, "", this), + new Among ( "ment", 15, 1, "", this), + new Among ( "ement", 16, 1, "", this) + }; + + private Among a_8[] = { + new Among ( "e", -1, 1, "", this), + new Among ( "l", -1, 2, "", this) + }; + + private Among a_9[] = { + new Among ( "succeed", -1, -1, "", this), + new Among ( "proceed", -1, -1, "", this), + new Among ( "exceed", -1, -1, "", this), + new Among ( "canning", -1, -1, "", this), + new Among ( "inning", -1, -1, "", this), + new Among ( "earring", -1, -1, "", this), + new Among ( "herring", -1, -1, "", this), + new Among ( "outing", -1, -1, "", this) + }; + + private Among a_10[] = { + new Among ( "andes", -1, -1, "", this), + new Among ( "atlas", -1, -1, "", this), + new Among ( "bias", -1, -1, "", this), + new Among ( "cosmos", -1, -1, "", this), + new Among ( "dying", -1, 3, "", this), + new Among ( "early", -1, 9, "", this), + new Among ( "gently", -1, 7, "", this), + new Among ( "howe", -1, -1, "", this), + new Among ( "idly", -1, 6, "", this), + new Among ( "lying", -1, 4, "", this), + new Among ( "news", -1, -1, "", this), + new Among ( "only", -1, 10, "", this), + new Among ( "singly", -1, 11, "", this), + new Among ( "skies", -1, 2, "", this), + new Among ( "skis", -1, 1, "", this), + new Among ( "sky", -1, -1, "", this), + new Among ( "tying", -1, 5, "", this), + new Among ( "ugly", -1, 8, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1 }; + + private static final char g_v_WXY[] = {1, 17, 65, 208, 1 }; + + private static final char g_valid_LI[] = {55, 141, 2 }; + + private boolean B_Y_found; + private int I_p2; + private int I_p1; + + private void copy_from(EnglishStemmer other) { + B_Y_found = other.B_Y_found; + I_p2 = other.I_p2; + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_prelude() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 25 + // unset Y_found, line 26 + B_Y_found = false; + // do, line 27 + v_1 = cursor; + lab0: do { + // (, line 27 + // [, line 27 + bra = cursor; + // literal, line 27 + if (!(eq_s(1, "'"))) + { + break lab0; + } + // ], line 27 + ket = cursor; + // delete, line 27 + slice_del(); + } while (false); + cursor = v_1; + // do, line 28 + v_2 = cursor; + lab1: do { + // (, line 28 + // [, line 28 + bra = cursor; + // literal, line 28 + if (!(eq_s(1, "y"))) + { + break lab1; + } + // ], line 28 + ket = cursor; + // <-, line 28 + slice_from("Y"); + // set Y_found, line 28 + B_Y_found = true; + } while (false); + cursor = v_2; + // do, line 29 + v_3 = cursor; + lab2: do { + // repeat, line 29 + replab3: while(true) + { + v_4 = cursor; + lab4: do { + // (, line 29 + // goto, line 29 + golab5: while(true) + { + v_5 = cursor; + lab6: do { + // (, line 29 + if (!(in_grouping(g_v, 97, 121))) + { + break lab6; + } + // [, line 29 + bra = cursor; + // literal, line 29 + if (!(eq_s(1, "y"))) + { + break lab6; + } + // ], line 29 + ket = cursor; + cursor = v_5; + break golab5; + } while (false); + cursor = v_5; + if (cursor >= limit) + { + break lab4; + } + cursor++; + } + // <-, line 29 + slice_from("Y"); + // set Y_found, line 29 + B_Y_found = true; + continue replab3; + } while (false); + cursor = v_4; + break replab3; + } + } while (false); + cursor = v_3; + return true; + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + // (, line 32 + I_p1 = limit; + I_p2 = limit; + // do, line 35 + v_1 = cursor; + lab0: do { + // (, line 35 + // or, line 41 + lab1: do { + v_2 = cursor; + lab2: do { + // among, line 36 + if (find_among(a_0, 3) == 0) + { + break lab2; + } + break lab1; + } while (false); + cursor = v_2; + // (, line 41 + // gopast, line 41 + golab3: while(true) + { + lab4: do { + if (!(in_grouping(g_v, 97, 121))) + { + break lab4; + } + break golab3; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + // gopast, line 41 + golab5: while(true) + { + lab6: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + } while (false); + // setmark p1, line 42 + I_p1 = cursor; + // gopast, line 43 + golab7: while(true) + { + lab8: do { + if (!(in_grouping(g_v, 97, 121))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + // gopast, line 43 + golab9: while(true) + { + lab10: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab10; + } + break golab9; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + // setmark p2, line 43 + I_p2 = cursor; + } while (false); + cursor = v_1; + return true; + } + + private boolean r_shortv() { + int v_1; + // (, line 49 + // or, line 51 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 50 + if (!(out_grouping_b(g_v_WXY, 89, 121))) + { + break lab1; + } + if (!(in_grouping_b(g_v, 97, 121))) + { + break lab1; + } + if (!(out_grouping_b(g_v, 97, 121))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 52 + if (!(out_grouping_b(g_v, 97, 121))) + { + return false; + } + if (!(in_grouping_b(g_v, 97, 121))) + { + return false; + } + // atlimit, line 52 + if (cursor > limit_backward) + { + return false; + } + } while (false); + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_Step_1a() { + int among_var; + int v_1; + int v_2; + // (, line 58 + // try, line 59 + v_1 = limit - cursor; + lab0: do { + // (, line 59 + // [, line 60 + ket = cursor; + // substring, line 60 + among_var = find_among_b(a_1, 3); + if (among_var == 0) + { + cursor = limit - v_1; + break lab0; + } + // ], line 60 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_1; + break lab0; + case 1: + // (, line 62 + // delete, line 62 + slice_del(); + break; + } + } while (false); + // [, line 65 + ket = cursor; + // substring, line 65 + among_var = find_among_b(a_2, 6); + if (among_var == 0) + { + return false; + } + // ], line 65 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 66 + // <-, line 66 + slice_from("ss"); + break; + case 2: + // (, line 68 + // or, line 68 + lab1: do { + v_2 = limit - cursor; + lab2: do { + // (, line 68 + // hop, line 68 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + break lab2; + } + cursor = c; + } + // <-, line 68 + slice_from("i"); + break lab1; + } while (false); + cursor = limit - v_2; + // <-, line 68 + slice_from("ie"); + } while (false); + break; + case 3: + // (, line 69 + // next, line 69 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // gopast, line 69 + golab3: while(true) + { + lab4: do { + if (!(in_grouping_b(g_v, 97, 121))) + { + break lab4; + } + break golab3; + } while (false); + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + // delete, line 69 + slice_del(); + break; + } + return true; + } + + private boolean r_Step_1b() { + int among_var; + int v_1; + int v_3; + int v_4; + // (, line 74 + // [, line 75 + ket = cursor; + // substring, line 75 + among_var = find_among_b(a_4, 6); + if (among_var == 0) + { + return false; + } + // ], line 75 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 77 + // call R1, line 77 + if (!r_R1()) + { + return false; + } + // <-, line 77 + slice_from("ee"); + break; + case 2: + // (, line 79 + // test, line 80 + v_1 = limit - cursor; + // gopast, line 80 + golab0: while(true) + { + lab1: do { + if (!(in_grouping_b(g_v, 97, 121))) + { + break lab1; + } + break golab0; + } while (false); + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + cursor = limit - v_1; + // delete, line 80 + slice_del(); + // test, line 81 + v_3 = limit - cursor; + // substring, line 81 + among_var = find_among_b(a_3, 13); + if (among_var == 0) + { + return false; + } + cursor = limit - v_3; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 83 + // <+, line 83 + { + int c = cursor; + insert(cursor, cursor, "e"); + cursor = c; + } + break; + case 2: + // (, line 86 + // [, line 86 + ket = cursor; + // next, line 86 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 86 + bra = cursor; + // delete, line 86 + slice_del(); + break; + case 3: + // (, line 87 + // atmark, line 87 + if (cursor != I_p1) + { + return false; + } + // test, line 87 + v_4 = limit - cursor; + // call shortv, line 87 + if (!r_shortv()) + { + return false; + } + cursor = limit - v_4; + // <+, line 87 + { + int c = cursor; + insert(cursor, cursor, "e"); + cursor = c; + } + break; + } + break; + } + return true; + } + + private boolean r_Step_1c() { + int v_1; + int v_2; + // (, line 93 + // [, line 94 + ket = cursor; + // or, line 94 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // literal, line 94 + if (!(eq_s_b(1, "y"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // literal, line 94 + if (!(eq_s_b(1, "Y"))) + { + return false; + } + } while (false); + // ], line 94 + bra = cursor; + if (!(out_grouping_b(g_v, 97, 121))) + { + return false; + } + // not, line 95 + { + v_2 = limit - cursor; + lab2: do { + // atlimit, line 95 + if (cursor > limit_backward) + { + break lab2; + } + return false; + } while (false); + cursor = limit - v_2; + } + // <-, line 96 + slice_from("i"); + return true; + } + + private boolean r_Step_2() { + int among_var; + // (, line 99 + // [, line 100 + ket = cursor; + // substring, line 100 + among_var = find_among_b(a_5, 24); + if (among_var == 0) + { + return false; + } + // ], line 100 + bra = cursor; + // call R1, line 100 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 101 + // <-, line 101 + slice_from("tion"); + break; + case 2: + // (, line 102 + // <-, line 102 + slice_from("ence"); + break; + case 3: + // (, line 103 + // <-, line 103 + slice_from("ance"); + break; + case 4: + // (, line 104 + // <-, line 104 + slice_from("able"); + break; + case 5: + // (, line 105 + // <-, line 105 + slice_from("ent"); + break; + case 6: + // (, line 107 + // <-, line 107 + slice_from("ize"); + break; + case 7: + // (, line 109 + // <-, line 109 + slice_from("ate"); + break; + case 8: + // (, line 111 + // <-, line 111 + slice_from("al"); + break; + case 9: + // (, line 112 + // <-, line 112 + slice_from("ful"); + break; + case 10: + // (, line 114 + // <-, line 114 + slice_from("ous"); + break; + case 11: + // (, line 116 + // <-, line 116 + slice_from("ive"); + break; + case 12: + // (, line 118 + // <-, line 118 + slice_from("ble"); + break; + case 13: + // (, line 119 + // literal, line 119 + if (!(eq_s_b(1, "l"))) + { + return false; + } + // <-, line 119 + slice_from("og"); + break; + case 14: + // (, line 120 + // <-, line 120 + slice_from("ful"); + break; + case 15: + // (, line 121 + // <-, line 121 + slice_from("less"); + break; + case 16: + // (, line 122 + if (!(in_grouping_b(g_valid_LI, 99, 116))) + { + return false; + } + // delete, line 122 + slice_del(); + break; + } + return true; + } + + private boolean r_Step_3() { + int among_var; + // (, line 126 + // [, line 127 + ket = cursor; + // substring, line 127 + among_var = find_among_b(a_6, 9); + if (among_var == 0) + { + return false; + } + // ], line 127 + bra = cursor; + // call R1, line 127 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 128 + // <-, line 128 + slice_from("tion"); + break; + case 2: + // (, line 129 + // <-, line 129 + slice_from("ate"); + break; + case 3: + // (, line 130 + // <-, line 130 + slice_from("al"); + break; + case 4: + // (, line 132 + // <-, line 132 + slice_from("ic"); + break; + case 5: + // (, line 134 + // delete, line 134 + slice_del(); + break; + case 6: + // (, line 136 + // call R2, line 136 + if (!r_R2()) + { + return false; + } + // delete, line 136 + slice_del(); + break; + } + return true; + } + + private boolean r_Step_4() { + int among_var; + int v_1; + // (, line 140 + // [, line 141 + ket = cursor; + // substring, line 141 + among_var = find_among_b(a_7, 18); + if (among_var == 0) + { + return false; + } + // ], line 141 + bra = cursor; + // call R2, line 141 + if (!r_R2()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 144 + // delete, line 144 + slice_del(); + break; + case 2: + // (, line 145 + // or, line 145 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // literal, line 145 + if (!(eq_s_b(1, "s"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // literal, line 145 + if (!(eq_s_b(1, "t"))) + { + return false; + } + } while (false); + // delete, line 145 + slice_del(); + break; + } + return true; + } + + private boolean r_Step_5() { + int among_var; + int v_1; + int v_2; + // (, line 149 + // [, line 150 + ket = cursor; + // substring, line 150 + among_var = find_among_b(a_8, 2); + if (among_var == 0) + { + return false; + } + // ], line 150 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 151 + // or, line 151 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // call R2, line 151 + if (!r_R2()) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 151 + // call R1, line 151 + if (!r_R1()) + { + return false; + } + // not, line 151 + { + v_2 = limit - cursor; + lab2: do { + // call shortv, line 151 + if (!r_shortv()) + { + break lab2; + } + return false; + } while (false); + cursor = limit - v_2; + } + } while (false); + // delete, line 151 + slice_del(); + break; + case 2: + // (, line 152 + // call R2, line 152 + if (!r_R2()) + { + return false; + } + // literal, line 152 + if (!(eq_s_b(1, "l"))) + { + return false; + } + // delete, line 152 + slice_del(); + break; + } + return true; + } + + private boolean r_exception2() { + // (, line 156 + // [, line 158 + ket = cursor; + // substring, line 158 + if (find_among_b(a_9, 8) == 0) + { + return false; + } + // ], line 158 + bra = cursor; + // atlimit, line 158 + if (cursor > limit_backward) + { + return false; + } + return true; + } + + private boolean r_exception1() { + int among_var; + // (, line 168 + // [, line 170 + bra = cursor; + // substring, line 170 + among_var = find_among(a_10, 18); + if (among_var == 0) + { + return false; + } + // ], line 170 + ket = cursor; + // atlimit, line 170 + if (cursor < limit) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 174 + // <-, line 174 + slice_from("ski"); + break; + case 2: + // (, line 175 + // <-, line 175 + slice_from("sky"); + break; + case 3: + // (, line 176 + // <-, line 176 + slice_from("die"); + break; + case 4: + // (, line 177 + // <-, line 177 + slice_from("lie"); + break; + case 5: + // (, line 178 + // <-, line 178 + slice_from("tie"); + break; + case 6: + // (, line 182 + // <-, line 182 + slice_from("idl"); + break; + case 7: + // (, line 183 + // <-, line 183 + slice_from("gentl"); + break; + case 8: + // (, line 184 + // <-, line 184 + slice_from("ugli"); + break; + case 9: + // (, line 185 + // <-, line 185 + slice_from("earli"); + break; + case 10: + // (, line 186 + // <-, line 186 + slice_from("onli"); + break; + case 11: + // (, line 187 + // <-, line 187 + slice_from("singl"); + break; + } + return true; + } + + private boolean r_postlude() { + int v_1; + int v_2; + // (, line 203 + // Boolean test Y_found, line 203 + if (!(B_Y_found)) + { + return false; + } + // repeat, line 203 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 203 + // goto, line 203 + golab2: while(true) + { + v_2 = cursor; + lab3: do { + // (, line 203 + // [, line 203 + bra = cursor; + // literal, line 203 + if (!(eq_s(1, "Y"))) + { + break lab3; + } + // ], line 203 + ket = cursor; + cursor = v_2; + break golab2; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + break lab1; + } + cursor++; + } + // <-, line 203 + slice_from("y"); + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + int v_12; + int v_13; + // (, line 205 + // or, line 207 + lab0: do { + v_1 = cursor; + lab1: do { + // call exception1, line 207 + if (!r_exception1()) + { + break lab1; + } + break lab0; + } while (false); + cursor = v_1; + lab2: do { + // not, line 208 + { + v_2 = cursor; + lab3: do { + // hop, line 208 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + break lab3; + } + cursor = c; + } + break lab2; + } while (false); + cursor = v_2; + } + break lab0; + } while (false); + cursor = v_1; + // (, line 208 + // do, line 209 + v_3 = cursor; + lab4: do { + // call prelude, line 209 + if (!r_prelude()) + { + break lab4; + } + } while (false); + cursor = v_3; + // do, line 210 + v_4 = cursor; + lab5: do { + // call mark_regions, line 210 + if (!r_mark_regions()) + { + break lab5; + } + } while (false); + cursor = v_4; + // backwards, line 211 + limit_backward = cursor; cursor = limit; + // (, line 211 + // do, line 213 + v_5 = limit - cursor; + lab6: do { + // call Step_1a, line 213 + if (!r_Step_1a()) + { + break lab6; + } + } while (false); + cursor = limit - v_5; + // or, line 215 + lab7: do { + v_6 = limit - cursor; + lab8: do { + // call exception2, line 215 + if (!r_exception2()) + { + break lab8; + } + break lab7; + } while (false); + cursor = limit - v_6; + // (, line 215 + // do, line 217 + v_7 = limit - cursor; + lab9: do { + // call Step_1b, line 217 + if (!r_Step_1b()) + { + break lab9; + } + } while (false); + cursor = limit - v_7; + // do, line 218 + v_8 = limit - cursor; + lab10: do { + // call Step_1c, line 218 + if (!r_Step_1c()) + { + break lab10; + } + } while (false); + cursor = limit - v_8; + // do, line 220 + v_9 = limit - cursor; + lab11: do { + // call Step_2, line 220 + if (!r_Step_2()) + { + break lab11; + } + } while (false); + cursor = limit - v_9; + // do, line 221 + v_10 = limit - cursor; + lab12: do { + // call Step_3, line 221 + if (!r_Step_3()) + { + break lab12; + } + } while (false); + cursor = limit - v_10; + // do, line 222 + v_11 = limit - cursor; + lab13: do { + // call Step_4, line 222 + if (!r_Step_4()) + { + break lab13; + } + } while (false); + cursor = limit - v_11; + // do, line 224 + v_12 = limit - cursor; + lab14: do { + // call Step_5, line 224 + if (!r_Step_5()) + { + break lab14; + } + } while (false); + cursor = limit - v_12; + } while (false); + cursor = limit_backward; // do, line 227 + v_13 = cursor; + lab15: do { + // call postlude, line 227 + if (!r_postlude()) + { + break lab15; + } + } while (false); + cursor = v_13; + } while (false); + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/FinnishStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/FinnishStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/FinnishStemmer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,1034 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class FinnishStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "pa", -1, 1, "", this), + new Among ( "sti", -1, 2, "", this), + new Among ( "kaan", -1, 1, "", this), + new Among ( "han", -1, 1, "", this), + new Among ( "kin", -1, 1, "", this), + new Among ( "h\u00E4n", -1, 1, "", this), + new Among ( "k\u00E4\u00E4n", -1, 1, "", this), + new Among ( "ko", -1, 1, "", this), + new Among ( "p\u00E4", -1, 1, "", this), + new Among ( "k\u00F6", -1, 1, "", this) + }; + + private Among a_1[] = { + new Among ( "lla", -1, -1, "", this), + new Among ( "na", -1, -1, "", this), + new Among ( "ssa", -1, -1, "", this), + new Among ( "ta", -1, -1, "", this), + new Among ( "lta", 3, -1, "", this), + new Among ( "sta", 3, -1, "", this) + }; + + private Among a_2[] = { + new Among ( "ll\u00E4", -1, -1, "", this), + new Among ( "n\u00E4", -1, -1, "", this), + new Among ( "ss\u00E4", -1, -1, "", this), + new Among ( "t\u00E4", -1, -1, "", this), + new Among ( "lt\u00E4", 3, -1, "", this), + new Among ( "st\u00E4", 3, -1, "", this) + }; + + private Among a_3[] = { + new Among ( "lle", -1, -1, "", this), + new Among ( "ine", -1, -1, "", this) + }; + + private Among a_4[] = { + new Among ( "nsa", -1, 3, "", this), + new Among ( "mme", -1, 3, "", this), + new Among ( "nne", -1, 3, "", this), + new Among ( "ni", -1, 2, "", this), + new Among ( "si", -1, 1, "", this), + new Among ( "an", -1, 4, "", this), + new Among ( "en", -1, 6, "", this), + new Among ( "\u00E4n", -1, 5, "", this), + new Among ( "ns\u00E4", -1, 3, "", this) + }; + + private Among a_5[] = { + new Among ( "aa", -1, -1, "", this), + new Among ( "ee", -1, -1, "", this), + new Among ( "ii", -1, -1, "", this), + new Among ( "oo", -1, -1, "", this), + new Among ( "uu", -1, -1, "", this), + new Among ( "\u00E4\u00E4", -1, -1, "", this), + new Among ( "\u00F6\u00F6", -1, -1, "", this) + }; + + private Among a_6[] = { + new Among ( "a", -1, 8, "", this), + new Among ( "lla", 0, -1, "", this), + new Among ( "na", 0, -1, "", this), + new Among ( "ssa", 0, -1, "", this), + new Among ( "ta", 0, -1, "", this), + new Among ( "lta", 4, -1, "", this), + new Among ( "sta", 4, -1, "", this), + new Among ( "tta", 4, 9, "", this), + new Among ( "lle", -1, -1, "", this), + new Among ( "ine", -1, -1, "", this), + new Among ( "ksi", -1, -1, "", this), + new Among ( "n", -1, 7, "", this), + new Among ( "han", 11, 1, "", this), + new Among ( "den", 11, -1, "r_VI", this), + new Among ( "seen", 11, -1, "r_LONG", this), + new Among ( "hen", 11, 2, "", this), + new Among ( "tten", 11, -1, "r_VI", this), + new Among ( "hin", 11, 3, "", this), + new Among ( "siin", 11, -1, "r_VI", this), + new Among ( "hon", 11, 4, "", this), + new Among ( "h\u00E4n", 11, 5, "", this), + new Among ( "h\u00F6n", 11, 6, "", this), + new Among ( "\u00E4", -1, 8, "", this), + new Among ( "ll\u00E4", 22, -1, "", this), + new Among ( "n\u00E4", 22, -1, "", this), + new Among ( "ss\u00E4", 22, -1, "", this), + new Among ( "t\u00E4", 22, -1, "", this), + new Among ( "lt\u00E4", 26, -1, "", this), + new Among ( "st\u00E4", 26, -1, "", this), + new Among ( "tt\u00E4", 26, 9, "", this) + }; + + private Among a_7[] = { + new Among ( "eja", -1, -1, "", this), + new Among ( "mma", -1, 1, "", this), + new Among ( "imma", 1, -1, "", this), + new Among ( "mpa", -1, 1, "", this), + new Among ( "impa", 3, -1, "", this), + new Among ( "mmi", -1, 1, "", this), + new Among ( "immi", 5, -1, "", this), + new Among ( "mpi", -1, 1, "", this), + new Among ( "impi", 7, -1, "", this), + new Among ( "ej\u00E4", -1, -1, "", this), + new Among ( "mm\u00E4", -1, 1, "", this), + new Among ( "imm\u00E4", 10, -1, "", this), + new Among ( "mp\u00E4", -1, 1, "", this), + new Among ( "imp\u00E4", 12, -1, "", this) + }; + + private Among a_8[] = { + new Among ( "i", -1, -1, "", this), + new Among ( "j", -1, -1, "", this) + }; + + private Among a_9[] = { + new Among ( "mma", -1, 1, "", this), + new Among ( "imma", 0, -1, "", this) + }; + + private static final char g_AEI[] = {17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8 }; + + private static final char g_V1[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32 }; + + private static final char g_V2[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32 }; + + private static final char g_particle_end[] = {17, 97, 24, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32 }; + + private boolean B_ending_removed; + private StringBuffer S_x = new StringBuffer(); + private int I_p2; + private int I_p1; + + private void copy_from(FinnishStemmer other) { + B_ending_removed = other.B_ending_removed; + S_x = other.S_x; + I_p2 = other.I_p2; + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_mark_regions() { + int v_1; + int v_3; + // (, line 41 + I_p1 = limit; + I_p2 = limit; + // goto, line 46 + golab0: while(true) + { + v_1 = cursor; + lab1: do { + if (!(in_grouping(g_V1, 97, 246))) + { + break lab1; + } + cursor = v_1; + break golab0; + } while (false); + cursor = v_1; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 46 + golab2: while(true) + { + lab3: do { + if (!(out_grouping(g_V1, 97, 246))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 46 + I_p1 = cursor; + // goto, line 47 + golab4: while(true) + { + v_3 = cursor; + lab5: do { + if (!(in_grouping(g_V1, 97, 246))) + { + break lab5; + } + cursor = v_3; + break golab4; + } while (false); + cursor = v_3; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 47 + golab6: while(true) + { + lab7: do { + if (!(out_grouping(g_V1, 97, 246))) + { + break lab7; + } + break golab6; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p2, line 47 + I_p2 = cursor; + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_particle_etc() { + int among_var; + int v_1; + int v_2; + // (, line 54 + // setlimit, line 55 + v_1 = limit - cursor; + // tomark, line 55 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 55 + // [, line 55 + ket = cursor; + // substring, line 55 + among_var = find_among_b(a_0, 10); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 55 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 62 + if (!(in_grouping_b(g_particle_end, 97, 246))) + { + return false; + } + break; + case 2: + // (, line 64 + // call R2, line 64 + if (!r_R2()) + { + return false; + } + break; + } + // delete, line 66 + slice_del(); + return true; + } + + private boolean r_possessive() { + int among_var; + int v_1; + int v_2; + int v_3; + // (, line 68 + // setlimit, line 69 + v_1 = limit - cursor; + // tomark, line 69 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 69 + // [, line 69 + ket = cursor; + // substring, line 69 + among_var = find_among_b(a_4, 9); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 69 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 72 + // not, line 72 + { + v_3 = limit - cursor; + lab0: do { + // literal, line 72 + if (!(eq_s_b(1, "k"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_3; + } + // delete, line 72 + slice_del(); + break; + case 2: + // (, line 74 + // delete, line 74 + slice_del(); + // [, line 74 + ket = cursor; + // literal, line 74 + if (!(eq_s_b(3, "kse"))) + { + return false; + } + // ], line 74 + bra = cursor; + // <-, line 74 + slice_from("ksi"); + break; + case 3: + // (, line 78 + // delete, line 78 + slice_del(); + break; + case 4: + // (, line 81 + // among, line 81 + if (find_among_b(a_1, 6) == 0) + { + return false; + } + // delete, line 81 + slice_del(); + break; + case 5: + // (, line 83 + // among, line 83 + if (find_among_b(a_2, 6) == 0) + { + return false; + } + // delete, line 84 + slice_del(); + break; + case 6: + // (, line 86 + // among, line 86 + if (find_among_b(a_3, 2) == 0) + { + return false; + } + // delete, line 86 + slice_del(); + break; + } + return true; + } + + private boolean r_LONG() { + // among, line 91 + if (find_among_b(a_5, 7) == 0) + { + return false; + } + return true; + } + + private boolean r_VI() { + // (, line 93 + // literal, line 93 + if (!(eq_s_b(1, "i"))) + { + return false; + } + if (!(in_grouping_b(g_V2, 97, 246))) + { + return false; + } + return true; + } + + private boolean r_case_ending() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 95 + // setlimit, line 96 + v_1 = limit - cursor; + // tomark, line 96 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 96 + // [, line 96 + ket = cursor; + // substring, line 96 + among_var = find_among_b(a_6, 30); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 96 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 98 + // literal, line 98 + if (!(eq_s_b(1, "a"))) + { + return false; + } + break; + case 2: + // (, line 99 + // literal, line 99 + if (!(eq_s_b(1, "e"))) + { + return false; + } + break; + case 3: + // (, line 100 + // literal, line 100 + if (!(eq_s_b(1, "i"))) + { + return false; + } + break; + case 4: + // (, line 101 + // literal, line 101 + if (!(eq_s_b(1, "o"))) + { + return false; + } + break; + case 5: + // (, line 102 + // literal, line 102 + if (!(eq_s_b(1, "\u00E4"))) + { + return false; + } + break; + case 6: + // (, line 103 + // literal, line 103 + if (!(eq_s_b(1, "\u00F6"))) + { + return false; + } + break; + case 7: + // (, line 111 + // try, line 111 + v_3 = limit - cursor; + lab0: do { + // (, line 111 + // and, line 113 + v_4 = limit - cursor; + // or, line 112 + lab1: do { + v_5 = limit - cursor; + lab2: do { + // call LONG, line 111 + if (!r_LONG()) + { + break lab2; + } + break lab1; + } while (false); + cursor = limit - v_5; + // literal, line 112 + if (!(eq_s_b(2, "ie"))) + { + cursor = limit - v_3; + break lab0; + } + } while (false); + cursor = limit - v_4; + // next, line 113 + if (cursor <= limit_backward) + { + cursor = limit - v_3; + break lab0; + } + cursor--; + // ], line 113 + bra = cursor; + } while (false); + break; + case 8: + // (, line 119 + if (!(in_grouping_b(g_V1, 97, 246))) + { + return false; + } + if (!(out_grouping_b(g_V1, 97, 246))) + { + return false; + } + break; + case 9: + // (, line 121 + // literal, line 121 + if (!(eq_s_b(1, "e"))) + { + return false; + } + break; + } + // delete, line 138 + slice_del(); + // set ending_removed, line 139 + B_ending_removed = true; + return true; + } + + private boolean r_other_endings() { + int among_var; + int v_1; + int v_2; + int v_3; + // (, line 141 + // setlimit, line 142 + v_1 = limit - cursor; + // tomark, line 142 + if (cursor < I_p2) + { + return false; + } + cursor = I_p2; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 142 + // [, line 142 + ket = cursor; + // substring, line 142 + among_var = find_among_b(a_7, 14); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 142 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 146 + // not, line 146 + { + v_3 = limit - cursor; + lab0: do { + // literal, line 146 + if (!(eq_s_b(2, "po"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_3; + } + break; + } + // delete, line 151 + slice_del(); + return true; + } + + private boolean r_i_plural() { + int v_1; + int v_2; + // (, line 153 + // setlimit, line 154 + v_1 = limit - cursor; + // tomark, line 154 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 154 + // [, line 154 + ket = cursor; + // substring, line 154 + if (find_among_b(a_8, 2) == 0) + { + limit_backward = v_2; + return false; + } + // ], line 154 + bra = cursor; + limit_backward = v_2; + // delete, line 158 + slice_del(); + return true; + } + + private boolean r_t_plural() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + // (, line 160 + // setlimit, line 161 + v_1 = limit - cursor; + // tomark, line 161 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 161 + // [, line 162 + ket = cursor; + // literal, line 162 + if (!(eq_s_b(1, "t"))) + { + limit_backward = v_2; + return false; + } + // ], line 162 + bra = cursor; + // test, line 162 + v_3 = limit - cursor; + if (!(in_grouping_b(g_V1, 97, 246))) + { + limit_backward = v_2; + return false; + } + cursor = limit - v_3; + // delete, line 163 + slice_del(); + limit_backward = v_2; + // setlimit, line 165 + v_4 = limit - cursor; + // tomark, line 165 + if (cursor < I_p2) + { + return false; + } + cursor = I_p2; + v_5 = limit_backward; + limit_backward = cursor; + cursor = limit - v_4; + // (, line 165 + // [, line 165 + ket = cursor; + // substring, line 165 + among_var = find_among_b(a_9, 2); + if (among_var == 0) + { + limit_backward = v_5; + return false; + } + // ], line 165 + bra = cursor; + limit_backward = v_5; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 167 + // not, line 167 + { + v_6 = limit - cursor; + lab0: do { + // literal, line 167 + if (!(eq_s_b(2, "po"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_6; + } + break; + } + // delete, line 170 + slice_del(); + return true; + } + + private boolean r_tidy() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + // (, line 172 + // setlimit, line 173 + v_1 = limit - cursor; + // tomark, line 173 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 173 + // do, line 174 + v_3 = limit - cursor; + lab0: do { + // (, line 174 + // and, line 174 + v_4 = limit - cursor; + // call LONG, line 174 + if (!r_LONG()) + { + break lab0; + } + cursor = limit - v_4; + // (, line 174 + // [, line 174 + ket = cursor; + // next, line 174 + if (cursor <= limit_backward) + { + break lab0; + } + cursor--; + // ], line 174 + bra = cursor; + // delete, line 174 + slice_del(); + } while (false); + cursor = limit - v_3; + // do, line 175 + v_5 = limit - cursor; + lab1: do { + // (, line 175 + // [, line 175 + ket = cursor; + if (!(in_grouping_b(g_AEI, 97, 228))) + { + break lab1; + } + // ], line 175 + bra = cursor; + if (!(out_grouping_b(g_V1, 97, 246))) + { + break lab1; + } + // delete, line 175 + slice_del(); + } while (false); + cursor = limit - v_5; + // do, line 176 + v_6 = limit - cursor; + lab2: do { + // (, line 176 + // [, line 176 + ket = cursor; + // literal, line 176 + if (!(eq_s_b(1, "j"))) + { + break lab2; + } + // ], line 176 + bra = cursor; + // or, line 176 + lab3: do { + v_7 = limit - cursor; + lab4: do { + // literal, line 176 + if (!(eq_s_b(1, "o"))) + { + break lab4; + } + break lab3; + } while (false); + cursor = limit - v_7; + // literal, line 176 + if (!(eq_s_b(1, "u"))) + { + break lab2; + } + } while (false); + // delete, line 176 + slice_del(); + } while (false); + cursor = limit - v_6; + // do, line 177 + v_8 = limit - cursor; + lab5: do { + // (, line 177 + // [, line 177 + ket = cursor; + // literal, line 177 + if (!(eq_s_b(1, "o"))) + { + break lab5; + } + // ], line 177 + bra = cursor; + // literal, line 177 + if (!(eq_s_b(1, "j"))) + { + break lab5; + } + // delete, line 177 + slice_del(); + } while (false); + cursor = limit - v_8; + limit_backward = v_2; + // goto, line 179 + golab6: while(true) + { + v_9 = limit - cursor; + lab7: do { + if (!(out_grouping_b(g_V1, 97, 246))) + { + break lab7; + } + cursor = limit - v_9; + break golab6; + } while (false); + cursor = limit - v_9; + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + // [, line 179 + ket = cursor; + // next, line 179 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 179 + bra = cursor; + // -> x, line 179 + S_x = slice_to(S_x); + // name x, line 179 + if (!(eq_v_b(S_x))) + { + return false; + } + // delete, line 179 + slice_del(); + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + // (, line 183 + // do, line 185 + v_1 = cursor; + lab0: do { + // call mark_regions, line 185 + if (!r_mark_regions()) + { + break lab0; + } + } while (false); + cursor = v_1; + // unset ending_removed, line 186 + B_ending_removed = false; + // backwards, line 187 + limit_backward = cursor; cursor = limit; + // (, line 187 + // do, line 188 + v_2 = limit - cursor; + lab1: do { + // call particle_etc, line 188 + if (!r_particle_etc()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 189 + v_3 = limit - cursor; + lab2: do { + // call possessive, line 189 + if (!r_possessive()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 190 + v_4 = limit - cursor; + lab3: do { + // call case_ending, line 190 + if (!r_case_ending()) + { + break lab3; + } + } while (false); + cursor = limit - v_4; + // do, line 191 + v_5 = limit - cursor; + lab4: do { + // call other_endings, line 191 + if (!r_other_endings()) + { + break lab4; + } + } while (false); + cursor = limit - v_5; + // or, line 192 + lab5: do { + v_6 = limit - cursor; + lab6: do { + // (, line 192 + // Boolean test ending_removed, line 192 + if (!(B_ending_removed)) + { + break lab6; + } + // do, line 192 + v_7 = limit - cursor; + lab7: do { + // call i_plural, line 192 + if (!r_i_plural()) + { + break lab7; + } + } while (false); + cursor = limit - v_7; + break lab5; + } while (false); + cursor = limit - v_6; + // do, line 192 + v_8 = limit - cursor; + lab8: do { + // call t_plural, line 192 + if (!r_t_plural()) + { + break lab8; + } + } while (false); + cursor = limit - v_8; + } while (false); + // do, line 193 + v_9 = limit - cursor; + lab9: do { + // call tidy, line 193 + if (!r_tidy()) + { + break lab9; + } + } while (false); + cursor = limit - v_9; + cursor = limit_backward; return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/FrenchStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/FrenchStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/FrenchStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,1501 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class FrenchStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "col", -1, -1, "", this), + new Among ( "par", -1, -1, "", this), + new Among ( "tap", -1, -1, "", this) + }; + + private Among a_1[] = { + new Among ( "", -1, 4, "", this), + new Among ( "I", 0, 1, "", this), + new Among ( "U", 0, 2, "", this), + new Among ( "Y", 0, 3, "", this) + }; + + private Among a_2[] = { + new Among ( "iqU", -1, 3, "", this), + new Among ( "abl", -1, 3, "", this), + new Among ( "I\u00E8r", -1, 4, "", this), + new Among ( "i\u00E8r", -1, 4, "", this), + new Among ( "eus", -1, 2, "", this), + new Among ( "iv", -1, 1, "", this) + }; + + private Among a_3[] = { + new Among ( "ic", -1, 2, "", this), + new Among ( "abil", -1, 1, "", this), + new Among ( "iv", -1, 3, "", this) + }; + + private Among a_4[] = { + new Among ( "iqUe", -1, 1, "", this), + new Among ( "atrice", -1, 2, "", this), + new Among ( "ance", -1, 1, "", this), + new Among ( "ence", -1, 5, "", this), + new Among ( "logie", -1, 3, "", this), + new Among ( "able", -1, 1, "", this), + new Among ( "isme", -1, 1, "", this), + new Among ( "euse", -1, 11, "", this), + new Among ( "iste", -1, 1, "", this), + new Among ( "ive", -1, 8, "", this), + new Among ( "if", -1, 8, "", this), + new Among ( "usion", -1, 4, "", this), + new Among ( "ation", -1, 2, "", this), + new Among ( "ution", -1, 4, "", this), + new Among ( "ateur", -1, 2, "", this), + new Among ( "iqUes", -1, 1, "", this), + new Among ( "atrices", -1, 2, "", this), + new Among ( "ances", -1, 1, "", this), + new Among ( "ences", -1, 5, "", this), + new Among ( "logies", -1, 3, "", this), + new Among ( "ables", -1, 1, "", this), + new Among ( "ismes", -1, 1, "", this), + new Among ( "euses", -1, 11, "", this), + new Among ( "istes", -1, 1, "", this), + new Among ( "ives", -1, 8, "", this), + new Among ( "ifs", -1, 8, "", this), + new Among ( "usions", -1, 4, "", this), + new Among ( "ations", -1, 2, "", this), + new Among ( "utions", -1, 4, "", this), + new Among ( "ateurs", -1, 2, "", this), + new Among ( "ments", -1, 15, "", this), + new Among ( "ements", 30, 6, "", this), + new Among ( "issements", 31, 12, "", this), + new Among ( "it\u00E9s", -1, 7, "", this), + new Among ( "ment", -1, 15, "", this), + new Among ( "ement", 34, 6, "", this), + new Among ( "issement", 35, 12, "", this), + new Among ( "amment", 34, 13, "", this), + new Among ( "emment", 34, 14, "", this), + new Among ( "aux", -1, 10, "", this), + new Among ( "eaux", 39, 9, "", this), + new Among ( "eux", -1, 1, "", this), + new Among ( "it\u00E9", -1, 7, "", this) + }; + + private Among a_5[] = { + new Among ( "ira", -1, 1, "", this), + new Among ( "ie", -1, 1, "", this), + new Among ( "isse", -1, 1, "", this), + new Among ( "issante", -1, 1, "", this), + new Among ( "i", -1, 1, "", this), + new Among ( "irai", 4, 1, "", this), + new Among ( "ir", -1, 1, "", this), + new Among ( "iras", -1, 1, "", this), + new Among ( "ies", -1, 1, "", this), + new Among ( "\u00EEmes", -1, 1, "", this), + new Among ( "isses", -1, 1, "", this), + new Among ( "issantes", -1, 1, "", this), + new Among ( "\u00EEtes", -1, 1, "", this), + new Among ( "is", -1, 1, "", this), + new Among ( "irais", 13, 1, "", this), + new Among ( "issais", 13, 1, "", this), + new Among ( "irions", -1, 1, "", this), + new Among ( "issions", -1, 1, "", this), + new Among ( "irons", -1, 1, "", this), + new Among ( "issons", -1, 1, "", this), + new Among ( "issants", -1, 1, "", this), + new Among ( "it", -1, 1, "", this), + new Among ( "irait", 21, 1, "", this), + new Among ( "issait", 21, 1, "", this), + new Among ( "issant", -1, 1, "", this), + new Among ( "iraIent", -1, 1, "", this), + new Among ( "issaIent", -1, 1, "", this), + new Among ( "irent", -1, 1, "", this), + new Among ( "issent", -1, 1, "", this), + new Among ( "iront", -1, 1, "", this), + new Among ( "\u00EEt", -1, 1, "", this), + new Among ( "iriez", -1, 1, "", this), + new Among ( "issiez", -1, 1, "", this), + new Among ( "irez", -1, 1, "", this), + new Among ( "issez", -1, 1, "", this) + }; + + private Among a_6[] = { + new Among ( "a", -1, 3, "", this), + new Among ( "era", 0, 2, "", this), + new Among ( "asse", -1, 3, "", this), + new Among ( "ante", -1, 3, "", this), + new Among ( "\u00E9e", -1, 2, "", this), + new Among ( "ai", -1, 3, "", this), + new Among ( "erai", 5, 2, "", this), + new Among ( "er", -1, 2, "", this), + new Among ( "as", -1, 3, "", this), + new Among ( "eras", 8, 2, "", this), + new Among ( "\u00E2mes", -1, 3, "", this), + new Among ( "asses", -1, 3, "", this), + new Among ( "antes", -1, 3, "", this), + new Among ( "\u00E2tes", -1, 3, "", this), + new Among ( "\u00E9es", -1, 2, "", this), + new Among ( "ais", -1, 3, "", this), + new Among ( "erais", 15, 2, "", this), + new Among ( "ions", -1, 1, "", this), + new Among ( "erions", 17, 2, "", this), + new Among ( "assions", 17, 3, "", this), + new Among ( "erons", -1, 2, "", this), + new Among ( "ants", -1, 3, "", this), + new Among ( "\u00E9s", -1, 2, "", this), + new Among ( "ait", -1, 3, "", this), + new Among ( "erait", 23, 2, "", this), + new Among ( "ant", -1, 3, "", this), + new Among ( "aIent", -1, 3, "", this), + new Among ( "eraIent", 26, 2, "", this), + new Among ( "\u00E8rent", -1, 2, "", this), + new Among ( "assent", -1, 3, "", this), + new Among ( "eront", -1, 2, "", this), + new Among ( "\u00E2t", -1, 3, "", this), + new Among ( "ez", -1, 2, "", this), + new Among ( "iez", 32, 2, "", this), + new Among ( "eriez", 33, 2, "", this), + new Among ( "assiez", 33, 3, "", this), + new Among ( "erez", 32, 2, "", this), + new Among ( "\u00E9", -1, 2, "", this) + }; + + private Among a_7[] = { + new Among ( "e", -1, 3, "", this), + new Among ( "I\u00E8re", 0, 2, "", this), + new Among ( "i\u00E8re", 0, 2, "", this), + new Among ( "ion", -1, 1, "", this), + new Among ( "Ier", -1, 2, "", this), + new Among ( "ier", -1, 2, "", this), + new Among ( "\u00EB", -1, 4, "", this) + }; + + private Among a_8[] = { + new Among ( "ell", -1, -1, "", this), + new Among ( "eill", -1, -1, "", this), + new Among ( "enn", -1, -1, "", this), + new Among ( "onn", -1, -1, "", this), + new Among ( "ett", -1, -1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 130, 103, 8, 5 }; + + private static final char g_keep_with_s[] = {1, 65, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 }; + + private int I_p2; + private int I_p1; + private int I_pV; + + private void copy_from(FrenchStemmer other) { + I_p2 = other.I_p2; + I_p1 = other.I_p1; + I_pV = other.I_pV; + super.copy_from(other); + } + + private boolean r_prelude() { + int v_1; + int v_2; + int v_3; + int v_4; + // repeat, line 38 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // goto, line 38 + golab2: while(true) + { + v_2 = cursor; + lab3: do { + // (, line 38 + // or, line 44 + lab4: do { + v_3 = cursor; + lab5: do { + // (, line 40 + if (!(in_grouping(g_v, 97, 251))) + { + break lab5; + } + // [, line 40 + bra = cursor; + // or, line 40 + lab6: do { + v_4 = cursor; + lab7: do { + // (, line 40 + // literal, line 40 + if (!(eq_s(1, "u"))) + { + break lab7; + } + // ], line 40 + ket = cursor; + if (!(in_grouping(g_v, 97, 251))) + { + break lab7; + } + // <-, line 40 + slice_from("U"); + break lab6; + } while (false); + cursor = v_4; + lab8: do { + // (, line 41 + // literal, line 41 + if (!(eq_s(1, "i"))) + { + break lab8; + } + // ], line 41 + ket = cursor; + if (!(in_grouping(g_v, 97, 251))) + { + break lab8; + } + // <-, line 41 + slice_from("I"); + break lab6; + } while (false); + cursor = v_4; + // (, line 42 + // literal, line 42 + if (!(eq_s(1, "y"))) + { + break lab5; + } + // ], line 42 + ket = cursor; + // <-, line 42 + slice_from("Y"); + } while (false); + break lab4; + } while (false); + cursor = v_3; + lab9: do { + // (, line 45 + // [, line 45 + bra = cursor; + // literal, line 45 + if (!(eq_s(1, "y"))) + { + break lab9; + } + // ], line 45 + ket = cursor; + if (!(in_grouping(g_v, 97, 251))) + { + break lab9; + } + // <-, line 45 + slice_from("Y"); + break lab4; + } while (false); + cursor = v_3; + // (, line 47 + // literal, line 47 + if (!(eq_s(1, "q"))) + { + break lab3; + } + // [, line 47 + bra = cursor; + // literal, line 47 + if (!(eq_s(1, "u"))) + { + break lab3; + } + // ], line 47 + ket = cursor; + // <-, line 47 + slice_from("U"); + } while (false); + cursor = v_2; + break golab2; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + break lab1; + } + cursor++; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + int v_4; + // (, line 50 + I_pV = limit; + I_p1 = limit; + I_p2 = limit; + // do, line 56 + v_1 = cursor; + lab0: do { + // (, line 56 + // or, line 58 + lab1: do { + v_2 = cursor; + lab2: do { + // (, line 57 + if (!(in_grouping(g_v, 97, 251))) + { + break lab2; + } + if (!(in_grouping(g_v, 97, 251))) + { + break lab2; + } + // next, line 57 + if (cursor >= limit) + { + break lab2; + } + cursor++; + break lab1; + } while (false); + cursor = v_2; + lab3: do { + // among, line 59 + if (find_among(a_0, 3) == 0) + { + break lab3; + } + break lab1; + } while (false); + cursor = v_2; + // (, line 66 + // next, line 66 + if (cursor >= limit) + { + break lab0; + } + cursor++; + // gopast, line 66 + golab4: while(true) + { + lab5: do { + if (!(in_grouping(g_v, 97, 251))) + { + break lab5; + } + break golab4; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + } while (false); + // setmark pV, line 67 + I_pV = cursor; + } while (false); + cursor = v_1; + // do, line 69 + v_4 = cursor; + lab6: do { + // (, line 69 + // gopast, line 70 + golab7: while(true) + { + lab8: do { + if (!(in_grouping(g_v, 97, 251))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // gopast, line 70 + golab9: while(true) + { + lab10: do { + if (!(out_grouping(g_v, 97, 251))) + { + break lab10; + } + break golab9; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // setmark p1, line 70 + I_p1 = cursor; + // gopast, line 71 + golab11: while(true) + { + lab12: do { + if (!(in_grouping(g_v, 97, 251))) + { + break lab12; + } + break golab11; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // gopast, line 71 + golab13: while(true) + { + lab14: do { + if (!(out_grouping(g_v, 97, 251))) + { + break lab14; + } + break golab13; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // setmark p2, line 71 + I_p2 = cursor; + } while (false); + cursor = v_4; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 75 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 75 + // [, line 77 + bra = cursor; + // substring, line 77 + among_var = find_among(a_1, 4); + if (among_var == 0) + { + break lab1; + } + // ], line 77 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 78 + // <-, line 78 + slice_from("i"); + break; + case 2: + // (, line 79 + // <-, line 79 + slice_from("u"); + break; + case 3: + // (, line 80 + // <-, line 80 + slice_from("y"); + break; + case 4: + // (, line 81 + // next, line 81 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_RV() { + if (!(I_pV <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + // (, line 91 + // [, line 92 + ket = cursor; + // substring, line 92 + among_var = find_among_b(a_4, 43); + if (among_var == 0) + { + return false; + } + // ], line 92 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 96 + // call R2, line 96 + if (!r_R2()) + { + return false; + } + // delete, line 96 + slice_del(); + break; + case 2: + // (, line 99 + // call R2, line 99 + if (!r_R2()) + { + return false; + } + // delete, line 99 + slice_del(); + // try, line 100 + v_1 = limit - cursor; + lab0: do { + // (, line 100 + // [, line 100 + ket = cursor; + // literal, line 100 + if (!(eq_s_b(2, "ic"))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 100 + bra = cursor; + // or, line 100 + lab1: do { + v_2 = limit - cursor; + lab2: do { + // (, line 100 + // call R2, line 100 + if (!r_R2()) + { + break lab2; + } + // delete, line 100 + slice_del(); + break lab1; + } while (false); + cursor = limit - v_2; + // <-, line 100 + slice_from("iqU"); + } while (false); + } while (false); + break; + case 3: + // (, line 104 + // call R2, line 104 + if (!r_R2()) + { + return false; + } + // <-, line 104 + slice_from("log"); + break; + case 4: + // (, line 107 + // call R2, line 107 + if (!r_R2()) + { + return false; + } + // <-, line 107 + slice_from("u"); + break; + case 5: + // (, line 110 + // call R2, line 110 + if (!r_R2()) + { + return false; + } + // <-, line 110 + slice_from("ent"); + break; + case 6: + // (, line 113 + // call RV, line 114 + if (!r_RV()) + { + return false; + } + // delete, line 114 + slice_del(); + // try, line 115 + v_3 = limit - cursor; + lab3: do { + // (, line 115 + // [, line 116 + ket = cursor; + // substring, line 116 + among_var = find_among_b(a_2, 6); + if (among_var == 0) + { + cursor = limit - v_3; + break lab3; + } + // ], line 116 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_3; + break lab3; + case 1: + // (, line 117 + // call R2, line 117 + if (!r_R2()) + { + cursor = limit - v_3; + break lab3; + } + // delete, line 117 + slice_del(); + // [, line 117 + ket = cursor; + // literal, line 117 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_3; + break lab3; + } + // ], line 117 + bra = cursor; + // call R2, line 117 + if (!r_R2()) + { + cursor = limit - v_3; + break lab3; + } + // delete, line 117 + slice_del(); + break; + case 2: + // (, line 118 + // or, line 118 + lab4: do { + v_4 = limit - cursor; + lab5: do { + // (, line 118 + // call R2, line 118 + if (!r_R2()) + { + break lab5; + } + // delete, line 118 + slice_del(); + break lab4; + } while (false); + cursor = limit - v_4; + // (, line 118 + // call R1, line 118 + if (!r_R1()) + { + cursor = limit - v_3; + break lab3; + } + // <-, line 118 + slice_from("eux"); + } while (false); + break; + case 3: + // (, line 120 + // call R2, line 120 + if (!r_R2()) + { + cursor = limit - v_3; + break lab3; + } + // delete, line 120 + slice_del(); + break; + case 4: + // (, line 122 + // call RV, line 122 + if (!r_RV()) + { + cursor = limit - v_3; + break lab3; + } + // <-, line 122 + slice_from("i"); + break; + } + } while (false); + break; + case 7: + // (, line 128 + // call R2, line 129 + if (!r_R2()) + { + return false; + } + // delete, line 129 + slice_del(); + // try, line 130 + v_5 = limit - cursor; + lab6: do { + // (, line 130 + // [, line 131 + ket = cursor; + // substring, line 131 + among_var = find_among_b(a_3, 3); + if (among_var == 0) + { + cursor = limit - v_5; + break lab6; + } + // ], line 131 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_5; + break lab6; + case 1: + // (, line 132 + // or, line 132 + lab7: do { + v_6 = limit - cursor; + lab8: do { + // (, line 132 + // call R2, line 132 + if (!r_R2()) + { + break lab8; + } + // delete, line 132 + slice_del(); + break lab7; + } while (false); + cursor = limit - v_6; + // <-, line 132 + slice_from("abl"); + } while (false); + break; + case 2: + // (, line 133 + // or, line 133 + lab9: do { + v_7 = limit - cursor; + lab10: do { + // (, line 133 + // call R2, line 133 + if (!r_R2()) + { + break lab10; + } + // delete, line 133 + slice_del(); + break lab9; + } while (false); + cursor = limit - v_7; + // <-, line 133 + slice_from("iqU"); + } while (false); + break; + case 3: + // (, line 134 + // call R2, line 134 + if (!r_R2()) + { + cursor = limit - v_5; + break lab6; + } + // delete, line 134 + slice_del(); + break; + } + } while (false); + break; + case 8: + // (, line 140 + // call R2, line 141 + if (!r_R2()) + { + return false; + } + // delete, line 141 + slice_del(); + // try, line 142 + v_8 = limit - cursor; + lab11: do { + // (, line 142 + // [, line 142 + ket = cursor; + // literal, line 142 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_8; + break lab11; + } + // ], line 142 + bra = cursor; + // call R2, line 142 + if (!r_R2()) + { + cursor = limit - v_8; + break lab11; + } + // delete, line 142 + slice_del(); + // [, line 142 + ket = cursor; + // literal, line 142 + if (!(eq_s_b(2, "ic"))) + { + cursor = limit - v_8; + break lab11; + } + // ], line 142 + bra = cursor; + // or, line 142 + lab12: do { + v_9 = limit - cursor; + lab13: do { + // (, line 142 + // call R2, line 142 + if (!r_R2()) + { + break lab13; + } + // delete, line 142 + slice_del(); + break lab12; + } while (false); + cursor = limit - v_9; + // <-, line 142 + slice_from("iqU"); + } while (false); + } while (false); + break; + case 9: + // (, line 144 + // <-, line 144 + slice_from("eau"); + break; + case 10: + // (, line 145 + // call R1, line 145 + if (!r_R1()) + { + return false; + } + // <-, line 145 + slice_from("al"); + break; + case 11: + // (, line 147 + // or, line 147 + lab14: do { + v_10 = limit - cursor; + lab15: do { + // (, line 147 + // call R2, line 147 + if (!r_R2()) + { + break lab15; + } + // delete, line 147 + slice_del(); + break lab14; + } while (false); + cursor = limit - v_10; + // (, line 147 + // call R1, line 147 + if (!r_R1()) + { + return false; + } + // <-, line 147 + slice_from("eux"); + } while (false); + break; + case 12: + // (, line 150 + // call R1, line 150 + if (!r_R1()) + { + return false; + } + if (!(out_grouping_b(g_v, 97, 251))) + { + return false; + } + // delete, line 150 + slice_del(); + break; + case 13: + // (, line 155 + // call RV, line 155 + if (!r_RV()) + { + return false; + } + // fail, line 155 + // (, line 155 + // <-, line 155 + slice_from("ant"); + return false; + case 14: + // (, line 156 + // call RV, line 156 + if (!r_RV()) + { + return false; + } + // fail, line 156 + // (, line 156 + // <-, line 156 + slice_from("ent"); + return false; + case 15: + // (, line 158 + // test, line 158 + v_11 = limit - cursor; + // (, line 158 + if (!(in_grouping_b(g_v, 97, 251))) + { + return false; + } + // call RV, line 158 + if (!r_RV()) + { + return false; + } + cursor = limit - v_11; + // fail, line 158 + // (, line 158 + // delete, line 158 + slice_del(); + return false; + } + return true; + } + + private boolean r_i_verb_suffix() { + int among_var; + int v_1; + int v_2; + // setlimit, line 163 + v_1 = limit - cursor; + // tomark, line 163 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 163 + // [, line 164 + ket = cursor; + // substring, line 164 + among_var = find_among_b(a_5, 35); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 164 + bra = cursor; + switch(among_var) { + case 0: + limit_backward = v_2; + return false; + case 1: + // (, line 170 + if (!(out_grouping_b(g_v, 97, 251))) + { + limit_backward = v_2; + return false; + } + // delete, line 170 + slice_del(); + break; + } + limit_backward = v_2; + return true; + } + + private boolean r_verb_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + // setlimit, line 174 + v_1 = limit - cursor; + // tomark, line 174 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 174 + // [, line 175 + ket = cursor; + // substring, line 175 + among_var = find_among_b(a_6, 38); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 175 + bra = cursor; + switch(among_var) { + case 0: + limit_backward = v_2; + return false; + case 1: + // (, line 177 + // call R2, line 177 + if (!r_R2()) + { + limit_backward = v_2; + return false; + } + // delete, line 177 + slice_del(); + break; + case 2: + // (, line 185 + // delete, line 185 + slice_del(); + break; + case 3: + // (, line 190 + // delete, line 190 + slice_del(); + // try, line 191 + v_3 = limit - cursor; + lab0: do { + // (, line 191 + // [, line 191 + ket = cursor; + // literal, line 191 + if (!(eq_s_b(1, "e"))) + { + cursor = limit - v_3; + break lab0; + } + // ], line 191 + bra = cursor; + // delete, line 191 + slice_del(); + } while (false); + break; + } + limit_backward = v_2; + return true; + } + + private boolean r_residual_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 198 + // try, line 199 + v_1 = limit - cursor; + lab0: do { + // (, line 199 + // [, line 199 + ket = cursor; + // literal, line 199 + if (!(eq_s_b(1, "s"))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 199 + bra = cursor; + // test, line 199 + v_2 = limit - cursor; + if (!(out_grouping_b(g_keep_with_s, 97, 232))) + { + cursor = limit - v_1; + break lab0; + } + cursor = limit - v_2; + // delete, line 199 + slice_del(); + } while (false); + // setlimit, line 200 + v_3 = limit - cursor; + // tomark, line 200 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_4 = limit_backward; + limit_backward = cursor; + cursor = limit - v_3; + // (, line 200 + // [, line 201 + ket = cursor; + // substring, line 201 + among_var = find_among_b(a_7, 7); + if (among_var == 0) + { + limit_backward = v_4; + return false; + } + // ], line 201 + bra = cursor; + switch(among_var) { + case 0: + limit_backward = v_4; + return false; + case 1: + // (, line 202 + // call R2, line 202 + if (!r_R2()) + { + limit_backward = v_4; + return false; + } + // or, line 202 + lab1: do { + v_5 = limit - cursor; + lab2: do { + // literal, line 202 + if (!(eq_s_b(1, "s"))) + { + break lab2; + } + break lab1; + } while (false); + cursor = limit - v_5; + // literal, line 202 + if (!(eq_s_b(1, "t"))) + { + limit_backward = v_4; + return false; + } + } while (false); + // delete, line 202 + slice_del(); + break; + case 2: + // (, line 204 + // <-, line 204 + slice_from("i"); + break; + case 3: + // (, line 205 + // delete, line 205 + slice_del(); + break; + case 4: + // (, line 206 + // literal, line 206 + if (!(eq_s_b(2, "gu"))) + { + limit_backward = v_4; + return false; + } + // delete, line 206 + slice_del(); + break; + } + limit_backward = v_4; + return true; + } + + private boolean r_un_double() { + int v_1; + // (, line 211 + // test, line 212 + v_1 = limit - cursor; + // among, line 212 + if (find_among_b(a_8, 5) == 0) + { + return false; + } + cursor = limit - v_1; + // [, line 212 + ket = cursor; + // next, line 212 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 212 + bra = cursor; + // delete, line 212 + slice_del(); + return true; + } + + private boolean r_un_accent() { + int v_3; + // (, line 215 + // atleast, line 216 + { + int v_1 = 1; + // atleast, line 216 + replab0: while(true) + { + lab1: do { + if (!(out_grouping_b(g_v, 97, 251))) + { + break lab1; + } + v_1--; + continue replab0; + } while (false); + break replab0; + } + if (v_1 > 0) + { + return false; + } + } + // [, line 217 + ket = cursor; + // or, line 217 + lab2: do { + v_3 = limit - cursor; + lab3: do { + // literal, line 217 + if (!(eq_s_b(1, "\u00E9"))) + { + break lab3; + } + break lab2; + } while (false); + cursor = limit - v_3; + // literal, line 217 + if (!(eq_s_b(1, "\u00E8"))) + { + return false; + } + } while (false); + // ], line 217 + bra = cursor; + // <-, line 217 + slice_from("e"); + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + // (, line 221 + // do, line 223 + v_1 = cursor; + lab0: do { + // call prelude, line 223 + if (!r_prelude()) + { + break lab0; + } + } while (false); + cursor = v_1; + // do, line 224 + v_2 = cursor; + lab1: do { + // call mark_regions, line 224 + if (!r_mark_regions()) + { + break lab1; + } + } while (false); + cursor = v_2; + // backwards, line 225 + limit_backward = cursor; cursor = limit; + // (, line 225 + // do, line 227 + v_3 = limit - cursor; + lab2: do { + // (, line 227 + // or, line 237 + lab3: do { + v_4 = limit - cursor; + lab4: do { + // (, line 228 + // and, line 233 + v_5 = limit - cursor; + // (, line 229 + // or, line 229 + lab5: do { + v_6 = limit - cursor; + lab6: do { + // call standard_suffix, line 229 + if (!r_standard_suffix()) + { + break lab6; + } + break lab5; + } while (false); + cursor = limit - v_6; + lab7: do { + // call i_verb_suffix, line 230 + if (!r_i_verb_suffix()) + { + break lab7; + } + break lab5; + } while (false); + cursor = limit - v_6; + // call verb_suffix, line 231 + if (!r_verb_suffix()) + { + break lab4; + } + } while (false); + cursor = limit - v_5; + // try, line 234 + v_7 = limit - cursor; + lab8: do { + // (, line 234 + // [, line 234 + ket = cursor; + // or, line 234 + lab9: do { + v_8 = limit - cursor; + lab10: do { + // (, line 234 + // literal, line 234 + if (!(eq_s_b(1, "Y"))) + { + break lab10; + } + // ], line 234 + bra = cursor; + // <-, line 234 + slice_from("i"); + break lab9; + } while (false); + cursor = limit - v_8; + // (, line 235 + // literal, line 235 + if (!(eq_s_b(1, "\u00E7"))) + { + cursor = limit - v_7; + break lab8; + } + // ], line 235 + bra = cursor; + // <-, line 235 + slice_from("c"); + } while (false); + } while (false); + break lab3; + } while (false); + cursor = limit - v_4; + // call residual_suffix, line 238 + if (!r_residual_suffix()) + { + break lab2; + } + } while (false); + } while (false); + cursor = limit - v_3; + // do, line 243 + v_9 = limit - cursor; + lab11: do { + // call un_double, line 243 + if (!r_un_double()) + { + break lab11; + } + } while (false); + cursor = limit - v_9; + // do, line 244 + v_10 = limit - cursor; + lab12: do { + // call un_accent, line 244 + if (!r_un_accent()) + { + break lab12; + } + } while (false); + cursor = limit - v_10; + cursor = limit_backward; // do, line 246 + v_11 = cursor; + lab13: do { + // call postlude, line 246 + if (!r_postlude()) + { + break lab13; + } + } while (false); + cursor = v_11; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/German2Stemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/German2Stemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/German2Stemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,726 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class German2Stemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "", -1, 6, "", this), + new Among ( "ae", 0, 2, "", this), + new Among ( "oe", 0, 3, "", this), + new Among ( "qu", 0, 5, "", this), + new Among ( "ue", 0, 4, "", this), + new Among ( "\u00DF", 0, 1, "", this) + }; + + private Among a_1[] = { + new Among ( "", -1, 6, "", this), + new Among ( "U", 0, 2, "", this), + new Among ( "Y", 0, 1, "", this), + new Among ( "\u00E4", 0, 3, "", this), + new Among ( "\u00F6", 0, 4, "", this), + new Among ( "\u00FC", 0, 5, "", this) + }; + + private Among a_2[] = { + new Among ( "e", -1, 1, "", this), + new Among ( "em", -1, 1, "", this), + new Among ( "en", -1, 1, "", this), + new Among ( "ern", -1, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "s", -1, 2, "", this), + new Among ( "es", 5, 1, "", this) + }; + + private Among a_3[] = { + new Among ( "en", -1, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "st", -1, 2, "", this), + new Among ( "est", 2, 1, "", this) + }; + + private Among a_4[] = { + new Among ( "ig", -1, 1, "", this), + new Among ( "lich", -1, 1, "", this) + }; + + private Among a_5[] = { + new Among ( "end", -1, 1, "", this), + new Among ( "ig", -1, 2, "", this), + new Among ( "ung", -1, 1, "", this), + new Among ( "lich", -1, 3, "", this), + new Among ( "isch", -1, 2, "", this), + new Among ( "ik", -1, 2, "", this), + new Among ( "heit", -1, 3, "", this), + new Among ( "keit", -1, 4, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32, 8 }; + + private static final char g_s_ending[] = {117, 30, 5 }; + + private static final char g_st_ending[] = {117, 30, 4 }; + + private int I_x; + private int I_p2; + private int I_p1; + + private void copy_from(German2Stemmer other) { + I_x = other.I_x; + I_p2 = other.I_p2; + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_prelude() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 28 + // test, line 30 + v_1 = cursor; + // repeat, line 30 + replab0: while(true) + { + v_2 = cursor; + lab1: do { + // goto, line 30 + golab2: while(true) + { + v_3 = cursor; + lab3: do { + // (, line 30 + if (!(in_grouping(g_v, 97, 252))) + { + break lab3; + } + // [, line 31 + bra = cursor; + // or, line 31 + lab4: do { + v_4 = cursor; + lab5: do { + // (, line 31 + // literal, line 31 + if (!(eq_s(1, "u"))) + { + break lab5; + } + // ], line 31 + ket = cursor; + if (!(in_grouping(g_v, 97, 252))) + { + break lab5; + } + // <-, line 31 + slice_from("U"); + break lab4; + } while (false); + cursor = v_4; + // (, line 32 + // literal, line 32 + if (!(eq_s(1, "y"))) + { + break lab3; + } + // ], line 32 + ket = cursor; + if (!(in_grouping(g_v, 97, 252))) + { + break lab3; + } + // <-, line 32 + slice_from("Y"); + } while (false); + cursor = v_3; + break golab2; + } while (false); + cursor = v_3; + if (cursor >= limit) + { + break lab1; + } + cursor++; + } + continue replab0; + } while (false); + cursor = v_2; + break replab0; + } + cursor = v_1; + // repeat, line 35 + replab6: while(true) + { + v_5 = cursor; + lab7: do { + // (, line 35 + // [, line 36 + bra = cursor; + // substring, line 36 + among_var = find_among(a_0, 6); + if (among_var == 0) + { + break lab7; + } + // ], line 36 + ket = cursor; + switch(among_var) { + case 0: + break lab7; + case 1: + // (, line 37 + // <-, line 37 + slice_from("ss"); + break; + case 2: + // (, line 38 + // <-, line 38 + slice_from("\u00E4"); + break; + case 3: + // (, line 39 + // <-, line 39 + slice_from("\u00F6"); + break; + case 4: + // (, line 40 + // <-, line 40 + slice_from("\u00FC"); + break; + case 5: + // (, line 41 + // hop, line 41 + { + int c = cursor + 2; + if (0 > c || c > limit) + { + break lab7; + } + cursor = c; + } + break; + case 6: + // (, line 42 + // next, line 42 + if (cursor >= limit) + { + break lab7; + } + cursor++; + break; + } + continue replab6; + } while (false); + cursor = v_5; + break replab6; + } + return true; + } + + private boolean r_mark_regions() { + int v_1; + // (, line 48 + I_p1 = limit; + I_p2 = limit; + // test, line 53 + v_1 = cursor; + // (, line 53 + // hop, line 53 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + return false; + } + cursor = c; + } + // setmark x, line 53 + I_x = cursor; + cursor = v_1; + // gopast, line 55 + golab0: while(true) + { + lab1: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab1; + } + break golab0; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 55 + golab2: while(true) + { + lab3: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 55 + I_p1 = cursor; + // try, line 56 + lab4: do { + // (, line 56 + if (!(I_p1 < I_x)) + { + break lab4; + } + I_p1 = I_x; + } while (false); + // gopast, line 57 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 57 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p2, line 57 + I_p2 = cursor; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 61 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 61 + // [, line 63 + bra = cursor; + // substring, line 63 + among_var = find_among(a_1, 6); + if (among_var == 0) + { + break lab1; + } + // ], line 63 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 64 + // <-, line 64 + slice_from("y"); + break; + case 2: + // (, line 65 + // <-, line 65 + slice_from("u"); + break; + case 3: + // (, line 66 + // <-, line 66 + slice_from("a"); + break; + case 4: + // (, line 67 + // <-, line 67 + slice_from("o"); + break; + case 5: + // (, line 68 + // <-, line 68 + slice_from("u"); + break; + case 6: + // (, line 69 + // next, line 69 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + // (, line 79 + // do, line 80 + v_1 = limit - cursor; + lab0: do { + // (, line 80 + // [, line 81 + ket = cursor; + // substring, line 81 + among_var = find_among_b(a_2, 7); + if (among_var == 0) + { + break lab0; + } + // ], line 81 + bra = cursor; + // call R1, line 81 + if (!r_R1()) + { + break lab0; + } + switch(among_var) { + case 0: + break lab0; + case 1: + // (, line 83 + // delete, line 83 + slice_del(); + break; + case 2: + // (, line 86 + if (!(in_grouping_b(g_s_ending, 98, 116))) + { + break lab0; + } + // delete, line 86 + slice_del(); + break; + } + } while (false); + cursor = limit - v_1; + // do, line 90 + v_2 = limit - cursor; + lab1: do { + // (, line 90 + // [, line 91 + ket = cursor; + // substring, line 91 + among_var = find_among_b(a_3, 4); + if (among_var == 0) + { + break lab1; + } + // ], line 91 + bra = cursor; + // call R1, line 91 + if (!r_R1()) + { + break lab1; + } + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 93 + // delete, line 93 + slice_del(); + break; + case 2: + // (, line 96 + if (!(in_grouping_b(g_st_ending, 98, 116))) + { + break lab1; + } + // hop, line 96 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + break lab1; + } + cursor = c; + } + // delete, line 96 + slice_del(); + break; + } + } while (false); + cursor = limit - v_2; + // do, line 100 + v_3 = limit - cursor; + lab2: do { + // (, line 100 + // [, line 101 + ket = cursor; + // substring, line 101 + among_var = find_among_b(a_5, 8); + if (among_var == 0) + { + break lab2; + } + // ], line 101 + bra = cursor; + // call R2, line 101 + if (!r_R2()) + { + break lab2; + } + switch(among_var) { + case 0: + break lab2; + case 1: + // (, line 103 + // delete, line 103 + slice_del(); + // try, line 104 + v_4 = limit - cursor; + lab3: do { + // (, line 104 + // [, line 104 + ket = cursor; + // literal, line 104 + if (!(eq_s_b(2, "ig"))) + { + cursor = limit - v_4; + break lab3; + } + // ], line 104 + bra = cursor; + // not, line 104 + { + v_5 = limit - cursor; + lab4: do { + // literal, line 104 + if (!(eq_s_b(1, "e"))) + { + break lab4; + } + cursor = limit - v_4; + break lab3; + } while (false); + cursor = limit - v_5; + } + // call R2, line 104 + if (!r_R2()) + { + cursor = limit - v_4; + break lab3; + } + // delete, line 104 + slice_del(); + } while (false); + break; + case 2: + // (, line 107 + // not, line 107 + { + v_6 = limit - cursor; + lab5: do { + // literal, line 107 + if (!(eq_s_b(1, "e"))) + { + break lab5; + } + break lab2; + } while (false); + cursor = limit - v_6; + } + // delete, line 107 + slice_del(); + break; + case 3: + // (, line 110 + // delete, line 110 + slice_del(); + // try, line 111 + v_7 = limit - cursor; + lab6: do { + // (, line 111 + // [, line 112 + ket = cursor; + // or, line 112 + lab7: do { + v_8 = limit - cursor; + lab8: do { + // literal, line 112 + if (!(eq_s_b(2, "er"))) + { + break lab8; + } + break lab7; + } while (false); + cursor = limit - v_8; + // literal, line 112 + if (!(eq_s_b(2, "en"))) + { + cursor = limit - v_7; + break lab6; + } + } while (false); + // ], line 112 + bra = cursor; + // call R1, line 112 + if (!r_R1()) + { + cursor = limit - v_7; + break lab6; + } + // delete, line 112 + slice_del(); + } while (false); + break; + case 4: + // (, line 116 + // delete, line 116 + slice_del(); + // try, line 117 + v_9 = limit - cursor; + lab9: do { + // (, line 117 + // [, line 118 + ket = cursor; + // substring, line 118 + among_var = find_among_b(a_4, 2); + if (among_var == 0) + { + cursor = limit - v_9; + break lab9; + } + // ], line 118 + bra = cursor; + // call R2, line 118 + if (!r_R2()) + { + cursor = limit - v_9; + break lab9; + } + switch(among_var) { + case 0: + cursor = limit - v_9; + break lab9; + case 1: + // (, line 120 + // delete, line 120 + slice_del(); + break; + } + } while (false); + break; + } + } while (false); + cursor = limit - v_3; + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 130 + // do, line 131 + v_1 = cursor; + lab0: do { + // call prelude, line 131 + if (!r_prelude()) + { + break lab0; + } + } while (false); + cursor = v_1; + // do, line 132 + v_2 = cursor; + lab1: do { + // call mark_regions, line 132 + if (!r_mark_regions()) + { + break lab1; + } + } while (false); + cursor = v_2; + // backwards, line 133 + limit_backward = cursor; cursor = limit; + // do, line 134 + v_3 = limit - cursor; + lab2: do { + // call standard_suffix, line 134 + if (!r_standard_suffix()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + cursor = limit_backward; // do, line 135 + v_4 = cursor; + lab3: do { + // call postlude, line 135 + if (!r_postlude()) + { + break lab3; + } + } while (false); + cursor = v_4; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/GermanStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/GermanStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/GermanStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,688 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class GermanStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "", -1, 6, "", this), + new Among ( "U", 0, 2, "", this), + new Among ( "Y", 0, 1, "", this), + new Among ( "\u00E4", 0, 3, "", this), + new Among ( "\u00F6", 0, 4, "", this), + new Among ( "\u00FC", 0, 5, "", this) + }; + + private Among a_1[] = { + new Among ( "e", -1, 1, "", this), + new Among ( "em", -1, 1, "", this), + new Among ( "en", -1, 1, "", this), + new Among ( "ern", -1, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "s", -1, 2, "", this), + new Among ( "es", 5, 1, "", this) + }; + + private Among a_2[] = { + new Among ( "en", -1, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "st", -1, 2, "", this), + new Among ( "est", 2, 1, "", this) + }; + + private Among a_3[] = { + new Among ( "ig", -1, 1, "", this), + new Among ( "lich", -1, 1, "", this) + }; + + private Among a_4[] = { + new Among ( "end", -1, 1, "", this), + new Among ( "ig", -1, 2, "", this), + new Among ( "ung", -1, 1, "", this), + new Among ( "lich", -1, 3, "", this), + new Among ( "isch", -1, 2, "", this), + new Among ( "ik", -1, 2, "", this), + new Among ( "heit", -1, 3, "", this), + new Among ( "keit", -1, 4, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32, 8 }; + + private static final char g_s_ending[] = {117, 30, 5 }; + + private static final char g_st_ending[] = {117, 30, 4 }; + + private int I_x; + private int I_p2; + private int I_p1; + + private void copy_from(GermanStemmer other) { + I_x = other.I_x; + I_p2 = other.I_p2; + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_prelude() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + // (, line 28 + // test, line 30 + v_1 = cursor; + // repeat, line 30 + replab0: while(true) + { + v_2 = cursor; + lab1: do { + // (, line 30 + // or, line 33 + lab2: do { + v_3 = cursor; + lab3: do { + // (, line 31 + // [, line 32 + bra = cursor; + // literal, line 32 + if (!(eq_s(1, "\u00DF"))) + { + break lab3; + } + // ], line 32 + ket = cursor; + // <-, line 32 + slice_from("ss"); + break lab2; + } while (false); + cursor = v_3; + // next, line 33 + if (cursor >= limit) + { + break lab1; + } + cursor++; + } while (false); + continue replab0; + } while (false); + cursor = v_2; + break replab0; + } + cursor = v_1; + // repeat, line 36 + replab4: while(true) + { + v_4 = cursor; + lab5: do { + // goto, line 36 + golab6: while(true) + { + v_5 = cursor; + lab7: do { + // (, line 36 + if (!(in_grouping(g_v, 97, 252))) + { + break lab7; + } + // [, line 37 + bra = cursor; + // or, line 37 + lab8: do { + v_6 = cursor; + lab9: do { + // (, line 37 + // literal, line 37 + if (!(eq_s(1, "u"))) + { + break lab9; + } + // ], line 37 + ket = cursor; + if (!(in_grouping(g_v, 97, 252))) + { + break lab9; + } + // <-, line 37 + slice_from("U"); + break lab8; + } while (false); + cursor = v_6; + // (, line 38 + // literal, line 38 + if (!(eq_s(1, "y"))) + { + break lab7; + } + // ], line 38 + ket = cursor; + if (!(in_grouping(g_v, 97, 252))) + { + break lab7; + } + // <-, line 38 + slice_from("Y"); + } while (false); + cursor = v_5; + break golab6; + } while (false); + cursor = v_5; + if (cursor >= limit) + { + break lab5; + } + cursor++; + } + continue replab4; + } while (false); + cursor = v_4; + break replab4; + } + return true; + } + + private boolean r_mark_regions() { + int v_1; + // (, line 42 + I_p1 = limit; + I_p2 = limit; + // test, line 47 + v_1 = cursor; + // (, line 47 + // hop, line 47 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + return false; + } + cursor = c; + } + // setmark x, line 47 + I_x = cursor; + cursor = v_1; + // gopast, line 49 + golab0: while(true) + { + lab1: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab1; + } + break golab0; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 49 + golab2: while(true) + { + lab3: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 49 + I_p1 = cursor; + // try, line 50 + lab4: do { + // (, line 50 + if (!(I_p1 < I_x)) + { + break lab4; + } + I_p1 = I_x; + } while (false); + // gopast, line 51 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 51 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p2, line 51 + I_p2 = cursor; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 55 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 55 + // [, line 57 + bra = cursor; + // substring, line 57 + among_var = find_among(a_0, 6); + if (among_var == 0) + { + break lab1; + } + // ], line 57 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 58 + // <-, line 58 + slice_from("y"); + break; + case 2: + // (, line 59 + // <-, line 59 + slice_from("u"); + break; + case 3: + // (, line 60 + // <-, line 60 + slice_from("a"); + break; + case 4: + // (, line 61 + // <-, line 61 + slice_from("o"); + break; + case 5: + // (, line 62 + // <-, line 62 + slice_from("u"); + break; + case 6: + // (, line 63 + // next, line 63 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + // (, line 73 + // do, line 74 + v_1 = limit - cursor; + lab0: do { + // (, line 74 + // [, line 75 + ket = cursor; + // substring, line 75 + among_var = find_among_b(a_1, 7); + if (among_var == 0) + { + break lab0; + } + // ], line 75 + bra = cursor; + // call R1, line 75 + if (!r_R1()) + { + break lab0; + } + switch(among_var) { + case 0: + break lab0; + case 1: + // (, line 77 + // delete, line 77 + slice_del(); + break; + case 2: + // (, line 80 + if (!(in_grouping_b(g_s_ending, 98, 116))) + { + break lab0; + } + // delete, line 80 + slice_del(); + break; + } + } while (false); + cursor = limit - v_1; + // do, line 84 + v_2 = limit - cursor; + lab1: do { + // (, line 84 + // [, line 85 + ket = cursor; + // substring, line 85 + among_var = find_among_b(a_2, 4); + if (among_var == 0) + { + break lab1; + } + // ], line 85 + bra = cursor; + // call R1, line 85 + if (!r_R1()) + { + break lab1; + } + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 87 + // delete, line 87 + slice_del(); + break; + case 2: + // (, line 90 + if (!(in_grouping_b(g_st_ending, 98, 116))) + { + break lab1; + } + // hop, line 90 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + break lab1; + } + cursor = c; + } + // delete, line 90 + slice_del(); + break; + } + } while (false); + cursor = limit - v_2; + // do, line 94 + v_3 = limit - cursor; + lab2: do { + // (, line 94 + // [, line 95 + ket = cursor; + // substring, line 95 + among_var = find_among_b(a_4, 8); + if (among_var == 0) + { + break lab2; + } + // ], line 95 + bra = cursor; + // call R2, line 95 + if (!r_R2()) + { + break lab2; + } + switch(among_var) { + case 0: + break lab2; + case 1: + // (, line 97 + // delete, line 97 + slice_del(); + // try, line 98 + v_4 = limit - cursor; + lab3: do { + // (, line 98 + // [, line 98 + ket = cursor; + // literal, line 98 + if (!(eq_s_b(2, "ig"))) + { + cursor = limit - v_4; + break lab3; + } + // ], line 98 + bra = cursor; + // not, line 98 + { + v_5 = limit - cursor; + lab4: do { + // literal, line 98 + if (!(eq_s_b(1, "e"))) + { + break lab4; + } + cursor = limit - v_4; + break lab3; + } while (false); + cursor = limit - v_5; + } + // call R2, line 98 + if (!r_R2()) + { + cursor = limit - v_4; + break lab3; + } + // delete, line 98 + slice_del(); + } while (false); + break; + case 2: + // (, line 101 + // not, line 101 + { + v_6 = limit - cursor; + lab5: do { + // literal, line 101 + if (!(eq_s_b(1, "e"))) + { + break lab5; + } + break lab2; + } while (false); + cursor = limit - v_6; + } + // delete, line 101 + slice_del(); + break; + case 3: + // (, line 104 + // delete, line 104 + slice_del(); + // try, line 105 + v_7 = limit - cursor; + lab6: do { + // (, line 105 + // [, line 106 + ket = cursor; + // or, line 106 + lab7: do { + v_8 = limit - cursor; + lab8: do { + // literal, line 106 + if (!(eq_s_b(2, "er"))) + { + break lab8; + } + break lab7; + } while (false); + cursor = limit - v_8; + // literal, line 106 + if (!(eq_s_b(2, "en"))) + { + cursor = limit - v_7; + break lab6; + } + } while (false); + // ], line 106 + bra = cursor; + // call R1, line 106 + if (!r_R1()) + { + cursor = limit - v_7; + break lab6; + } + // delete, line 106 + slice_del(); + } while (false); + break; + case 4: + // (, line 110 + // delete, line 110 + slice_del(); + // try, line 111 + v_9 = limit - cursor; + lab9: do { + // (, line 111 + // [, line 112 + ket = cursor; + // substring, line 112 + among_var = find_among_b(a_3, 2); + if (among_var == 0) + { + cursor = limit - v_9; + break lab9; + } + // ], line 112 + bra = cursor; + // call R2, line 112 + if (!r_R2()) + { + cursor = limit - v_9; + break lab9; + } + switch(among_var) { + case 0: + cursor = limit - v_9; + break lab9; + case 1: + // (, line 114 + // delete, line 114 + slice_del(); + break; + } + } while (false); + break; + } + } while (false); + cursor = limit - v_3; + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 124 + // do, line 125 + v_1 = cursor; + lab0: do { + // call prelude, line 125 + if (!r_prelude()) + { + break lab0; + } + } while (false); + cursor = v_1; + // do, line 126 + v_2 = cursor; + lab1: do { + // call mark_regions, line 126 + if (!r_mark_regions()) + { + break lab1; + } + } while (false); + cursor = v_2; + // backwards, line 127 + limit_backward = cursor; cursor = limit; + // do, line 128 + v_3 = limit - cursor; + lab2: do { + // call standard_suffix, line 128 + if (!r_standard_suffix()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + cursor = limit_backward; // do, line 129 + v_4 = cursor; + lab3: do { + // call postlude, line 129 + if (!r_postlude()) + { + break lab3; + } + } while (false); + cursor = v_4; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/HungarianStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/HungarianStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/HungarianStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,1158 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class HungarianStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "cs", -1, -1, "", this), + new Among ( "dzs", -1, -1, "", this), + new Among ( "gy", -1, -1, "", this), + new Among ( "ly", -1, -1, "", this), + new Among ( "ny", -1, -1, "", this), + new Among ( "sz", -1, -1, "", this), + new Among ( "ty", -1, -1, "", this), + new Among ( "zs", -1, -1, "", this) + }; + + private Among a_1[] = { + new Among ( "\u00E1", -1, 1, "", this), + new Among ( "\u00E9", -1, 2, "", this) + }; + + private Among a_2[] = { + new Among ( "bb", -1, -1, "", this), + new Among ( "cc", -1, -1, "", this), + new Among ( "dd", -1, -1, "", this), + new Among ( "ff", -1, -1, "", this), + new Among ( "gg", -1, -1, "", this), + new Among ( "jj", -1, -1, "", this), + new Among ( "kk", -1, -1, "", this), + new Among ( "ll", -1, -1, "", this), + new Among ( "mm", -1, -1, "", this), + new Among ( "nn", -1, -1, "", this), + new Among ( "pp", -1, -1, "", this), + new Among ( "rr", -1, -1, "", this), + new Among ( "ccs", -1, -1, "", this), + new Among ( "ss", -1, -1, "", this), + new Among ( "zzs", -1, -1, "", this), + new Among ( "tt", -1, -1, "", this), + new Among ( "vv", -1, -1, "", this), + new Among ( "ggy", -1, -1, "", this), + new Among ( "lly", -1, -1, "", this), + new Among ( "nny", -1, -1, "", this), + new Among ( "tty", -1, -1, "", this), + new Among ( "ssz", -1, -1, "", this), + new Among ( "zz", -1, -1, "", this) + }; + + private Among a_3[] = { + new Among ( "al", -1, 1, "", this), + new Among ( "el", -1, 2, "", this) + }; + + private Among a_4[] = { + new Among ( "ba", -1, -1, "", this), + new Among ( "ra", -1, -1, "", this), + new Among ( "be", -1, -1, "", this), + new Among ( "re", -1, -1, "", this), + new Among ( "ig", -1, -1, "", this), + new Among ( "nak", -1, -1, "", this), + new Among ( "nek", -1, -1, "", this), + new Among ( "val", -1, -1, "", this), + new Among ( "vel", -1, -1, "", this), + new Among ( "ul", -1, -1, "", this), + new Among ( "n\u00E1l", -1, -1, "", this), + new Among ( "n\u00E9l", -1, -1, "", this), + new Among ( "b\u00F3l", -1, -1, "", this), + new Among ( "r\u00F3l", -1, -1, "", this), + new Among ( "t\u00F3l", -1, -1, "", this), + new Among ( "b\u00F5l", -1, -1, "", this), + new Among ( "r\u00F5l", -1, -1, "", this), + new Among ( "t\u00F5l", -1, -1, "", this), + new Among ( "\u00FCl", -1, -1, "", this), + new Among ( "n", -1, -1, "", this), + new Among ( "an", 19, -1, "", this), + new Among ( "ban", 20, -1, "", this), + new Among ( "en", 19, -1, "", this), + new Among ( "ben", 22, -1, "", this), + new Among ( "k\u00E9ppen", 22, -1, "", this), + new Among ( "on", 19, -1, "", this), + new Among ( "\u00F6n", 19, -1, "", this), + new Among ( "k\u00E9pp", -1, -1, "", this), + new Among ( "kor", -1, -1, "", this), + new Among ( "t", -1, -1, "", this), + new Among ( "at", 29, -1, "", this), + new Among ( "et", 29, -1, "", this), + new Among ( "k\u00E9nt", 29, -1, "", this), + new Among ( "ank\u00E9nt", 32, -1, "", this), + new Among ( "enk\u00E9nt", 32, -1, "", this), + new Among ( "onk\u00E9nt", 32, -1, "", this), + new Among ( "ot", 29, -1, "", this), + new Among ( "\u00E9rt", 29, -1, "", this), + new Among ( "\u00F6t", 29, -1, "", this), + new Among ( "hez", -1, -1, "", this), + new Among ( "hoz", -1, -1, "", this), + new Among ( "h\u00F6z", -1, -1, "", this), + new Among ( "v\u00E1", -1, -1, "", this), + new Among ( "v\u00E9", -1, -1, "", this) + }; + + private Among a_5[] = { + new Among ( "\u00E1n", -1, 2, "", this), + new Among ( "\u00E9n", -1, 1, "", this), + new Among ( "\u00E1nk\u00E9nt", -1, 3, "", this) + }; + + private Among a_6[] = { + new Among ( "stul", -1, 2, "", this), + new Among ( "astul", 0, 1, "", this), + new Among ( "\u00E1stul", 0, 3, "", this), + new Among ( "st\u00FCl", -1, 2, "", this), + new Among ( "est\u00FCl", 3, 1, "", this), + new Among ( "\u00E9st\u00FCl", 3, 4, "", this) + }; + + private Among a_7[] = { + new Among ( "\u00E1", -1, 1, "", this), + new Among ( "\u00E9", -1, 2, "", this) + }; + + private Among a_8[] = { + new Among ( "k", -1, 7, "", this), + new Among ( "ak", 0, 4, "", this), + new Among ( "ek", 0, 6, "", this), + new Among ( "ok", 0, 5, "", this), + new Among ( "\u00E1k", 0, 1, "", this), + new Among ( "\u00E9k", 0, 2, "", this), + new Among ( "\u00F6k", 0, 3, "", this) + }; + + private Among a_9[] = { + new Among ( "\u00E9i", -1, 7, "", this), + new Among ( "\u00E1\u00E9i", 0, 6, "", this), + new Among ( "\u00E9\u00E9i", 0, 5, "", this), + new Among ( "\u00E9", -1, 9, "", this), + new Among ( "k\u00E9", 3, 4, "", this), + new Among ( "ak\u00E9", 4, 1, "", this), + new Among ( "ek\u00E9", 4, 1, "", this), + new Among ( "ok\u00E9", 4, 1, "", this), + new Among ( "\u00E1k\u00E9", 4, 3, "", this), + new Among ( "\u00E9k\u00E9", 4, 2, "", this), + new Among ( "\u00F6k\u00E9", 4, 1, "", this), + new Among ( "\u00E9\u00E9", 3, 8, "", this) + }; + + private Among a_10[] = { + new Among ( "a", -1, 18, "", this), + new Among ( "ja", 0, 17, "", this), + new Among ( "d", -1, 16, "", this), + new Among ( "ad", 2, 13, "", this), + new Among ( "ed", 2, 13, "", this), + new Among ( "od", 2, 13, "", this), + new Among ( "\u00E1d", 2, 14, "", this), + new Among ( "\u00E9d", 2, 15, "", this), + new Among ( "\u00F6d", 2, 13, "", this), + new Among ( "e", -1, 18, "", this), + new Among ( "je", 9, 17, "", this), + new Among ( "nk", -1, 4, "", this), + new Among ( "unk", 11, 1, "", this), + new Among ( "\u00E1nk", 11, 2, "", this), + new Among ( "\u00E9nk", 11, 3, "", this), + new Among ( "\u00FCnk", 11, 1, "", this), + new Among ( "uk", -1, 8, "", this), + new Among ( "juk", 16, 7, "", this), + new Among ( "\u00E1juk", 17, 5, "", this), + new Among ( "\u00FCk", -1, 8, "", this), + new Among ( "j\u00FCk", 19, 7, "", this), + new Among ( "\u00E9j\u00FCk", 20, 6, "", this), + new Among ( "m", -1, 12, "", this), + new Among ( "am", 22, 9, "", this), + new Among ( "em", 22, 9, "", this), + new Among ( "om", 22, 9, "", this), + new Among ( "\u00E1m", 22, 10, "", this), + new Among ( "\u00E9m", 22, 11, "", this), + new Among ( "o", -1, 18, "", this), + new Among ( "\u00E1", -1, 19, "", this), + new Among ( "\u00E9", -1, 20, "", this) + }; + + private Among a_11[] = { + new Among ( "id", -1, 10, "", this), + new Among ( "aid", 0, 9, "", this), + new Among ( "jaid", 1, 6, "", this), + new Among ( "eid", 0, 9, "", this), + new Among ( "jeid", 3, 6, "", this), + new Among ( "\u00E1id", 0, 7, "", this), + new Among ( "\u00E9id", 0, 8, "", this), + new Among ( "i", -1, 15, "", this), + new Among ( "ai", 7, 14, "", this), + new Among ( "jai", 8, 11, "", this), + new Among ( "ei", 7, 14, "", this), + new Among ( "jei", 10, 11, "", this), + new Among ( "\u00E1i", 7, 12, "", this), + new Among ( "\u00E9i", 7, 13, "", this), + new Among ( "itek", -1, 24, "", this), + new Among ( "eitek", 14, 21, "", this), + new Among ( "jeitek", 15, 20, "", this), + new Among ( "\u00E9itek", 14, 23, "", this), + new Among ( "ik", -1, 29, "", this), + new Among ( "aik", 18, 26, "", this), + new Among ( "jaik", 19, 25, "", this), + new Among ( "eik", 18, 26, "", this), + new Among ( "jeik", 21, 25, "", this), + new Among ( "\u00E1ik", 18, 27, "", this), + new Among ( "\u00E9ik", 18, 28, "", this), + new Among ( "ink", -1, 20, "", this), + new Among ( "aink", 25, 17, "", this), + new Among ( "jaink", 26, 16, "", this), + new Among ( "eink", 25, 17, "", this), + new Among ( "jeink", 28, 16, "", this), + new Among ( "\u00E1ink", 25, 18, "", this), + new Among ( "\u00E9ink", 25, 19, "", this), + new Among ( "aitok", -1, 21, "", this), + new Among ( "jaitok", 32, 20, "", this), + new Among ( "\u00E1itok", -1, 22, "", this), + new Among ( "im", -1, 5, "", this), + new Among ( "aim", 35, 4, "", this), + new Among ( "jaim", 36, 1, "", this), + new Among ( "eim", 35, 4, "", this), + new Among ( "jeim", 38, 1, "", this), + new Among ( "\u00E1im", 35, 2, "", this), + new Among ( "\u00E9im", 35, 3, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 52, 14 }; + + private int I_p1; + + private void copy_from(HungarianStemmer other) { + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + int v_3; + // (, line 44 + I_p1 = limit; + // or, line 51 + lab0: do { + v_1 = cursor; + lab1: do { + // (, line 48 + if (!(in_grouping(g_v, 97, 252))) + { + break lab1; + } + // goto, line 48 + golab2: while(true) + { + v_2 = cursor; + lab3: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab3; + } + cursor = v_2; + break golab2; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + break lab1; + } + cursor++; + } + // or, line 49 + lab4: do { + v_3 = cursor; + lab5: do { + // among, line 49 + if (find_among(a_0, 8) == 0) + { + break lab5; + } + break lab4; + } while (false); + cursor = v_3; + // next, line 49 + if (cursor >= limit) + { + break lab1; + } + cursor++; + } while (false); + // setmark p1, line 50 + I_p1 = cursor; + break lab0; + } while (false); + cursor = v_1; + // (, line 53 + if (!(out_grouping(g_v, 97, 252))) + { + return false; + } + // gopast, line 53 + golab6: while(true) + { + lab7: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab7; + } + break golab6; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 53 + I_p1 = cursor; + } while (false); + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_v_ending() { + int among_var; + // (, line 60 + // [, line 61 + ket = cursor; + // substring, line 61 + among_var = find_among_b(a_1, 2); + if (among_var == 0) + { + return false; + } + // ], line 61 + bra = cursor; + // call R1, line 61 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 62 + // <-, line 62 + slice_from("a"); + break; + case 2: + // (, line 63 + // <-, line 63 + slice_from("e"); + break; + } + return true; + } + + private boolean r_double() { + int v_1; + // (, line 67 + // test, line 68 + v_1 = limit - cursor; + // among, line 68 + if (find_among_b(a_2, 23) == 0) + { + return false; + } + cursor = limit - v_1; + return true; + } + + private boolean r_undouble() { + // (, line 72 + // next, line 73 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // [, line 73 + ket = cursor; + // hop, line 73 + { + int c = cursor - 1; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + // ], line 73 + bra = cursor; + // delete, line 73 + slice_del(); + return true; + } + + private boolean r_instrum() { + int among_var; + // (, line 76 + // [, line 77 + ket = cursor; + // substring, line 77 + among_var = find_among_b(a_3, 2); + if (among_var == 0) + { + return false; + } + // ], line 77 + bra = cursor; + // call R1, line 77 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 78 + // call double, line 78 + if (!r_double()) + { + return false; + } + break; + case 2: + // (, line 79 + // call double, line 79 + if (!r_double()) + { + return false; + } + break; + } + // delete, line 81 + slice_del(); + // call undouble, line 82 + if (!r_undouble()) + { + return false; + } + return true; + } + + private boolean r_case() { + // (, line 86 + // [, line 87 + ket = cursor; + // substring, line 87 + if (find_among_b(a_4, 44) == 0) + { + return false; + } + // ], line 87 + bra = cursor; + // call R1, line 87 + if (!r_R1()) + { + return false; + } + // delete, line 111 + slice_del(); + // call v_ending, line 112 + if (!r_v_ending()) + { + return false; + } + return true; + } + + private boolean r_case_special() { + int among_var; + // (, line 115 + // [, line 116 + ket = cursor; + // substring, line 116 + among_var = find_among_b(a_5, 3); + if (among_var == 0) + { + return false; + } + // ], line 116 + bra = cursor; + // call R1, line 116 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 117 + // <-, line 117 + slice_from("e"); + break; + case 2: + // (, line 118 + // <-, line 118 + slice_from("a"); + break; + case 3: + // (, line 119 + // <-, line 119 + slice_from("a"); + break; + } + return true; + } + + private boolean r_case_other() { + int among_var; + // (, line 123 + // [, line 124 + ket = cursor; + // substring, line 124 + among_var = find_among_b(a_6, 6); + if (among_var == 0) + { + return false; + } + // ], line 124 + bra = cursor; + // call R1, line 124 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 125 + // delete, line 125 + slice_del(); + break; + case 2: + // (, line 126 + // delete, line 126 + slice_del(); + break; + case 3: + // (, line 127 + // <-, line 127 + slice_from("a"); + break; + case 4: + // (, line 128 + // <-, line 128 + slice_from("e"); + break; + } + return true; + } + + private boolean r_factive() { + int among_var; + // (, line 132 + // [, line 133 + ket = cursor; + // substring, line 133 + among_var = find_among_b(a_7, 2); + if (among_var == 0) + { + return false; + } + // ], line 133 + bra = cursor; + // call R1, line 133 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 134 + // call double, line 134 + if (!r_double()) + { + return false; + } + break; + case 2: + // (, line 135 + // call double, line 135 + if (!r_double()) + { + return false; + } + break; + } + // delete, line 137 + slice_del(); + // call undouble, line 138 + if (!r_undouble()) + { + return false; + } + return true; + } + + private boolean r_plural() { + int among_var; + // (, line 141 + // [, line 142 + ket = cursor; + // substring, line 142 + among_var = find_among_b(a_8, 7); + if (among_var == 0) + { + return false; + } + // ], line 142 + bra = cursor; + // call R1, line 142 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 143 + // <-, line 143 + slice_from("a"); + break; + case 2: + // (, line 144 + // <-, line 144 + slice_from("e"); + break; + case 3: + // (, line 145 + // delete, line 145 + slice_del(); + break; + case 4: + // (, line 146 + // delete, line 146 + slice_del(); + break; + case 5: + // (, line 147 + // delete, line 147 + slice_del(); + break; + case 6: + // (, line 148 + // delete, line 148 + slice_del(); + break; + case 7: + // (, line 149 + // delete, line 149 + slice_del(); + break; + } + return true; + } + + private boolean r_owned() { + int among_var; + // (, line 153 + // [, line 154 + ket = cursor; + // substring, line 154 + among_var = find_among_b(a_9, 12); + if (among_var == 0) + { + return false; + } + // ], line 154 + bra = cursor; + // call R1, line 154 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 155 + // delete, line 155 + slice_del(); + break; + case 2: + // (, line 156 + // <-, line 156 + slice_from("e"); + break; + case 3: + // (, line 157 + // <-, line 157 + slice_from("a"); + break; + case 4: + // (, line 158 + // delete, line 158 + slice_del(); + break; + case 5: + // (, line 159 + // <-, line 159 + slice_from("e"); + break; + case 6: + // (, line 160 + // <-, line 160 + slice_from("a"); + break; + case 7: + // (, line 161 + // delete, line 161 + slice_del(); + break; + case 8: + // (, line 162 + // <-, line 162 + slice_from("e"); + break; + case 9: + // (, line 163 + // delete, line 163 + slice_del(); + break; + } + return true; + } + + private boolean r_sing_owner() { + int among_var; + // (, line 167 + // [, line 168 + ket = cursor; + // substring, line 168 + among_var = find_among_b(a_10, 31); + if (among_var == 0) + { + return false; + } + // ], line 168 + bra = cursor; + // call R1, line 168 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 169 + // delete, line 169 + slice_del(); + break; + case 2: + // (, line 170 + // <-, line 170 + slice_from("a"); + break; + case 3: + // (, line 171 + // <-, line 171 + slice_from("e"); + break; + case 4: + // (, line 172 + // delete, line 172 + slice_del(); + break; + case 5: + // (, line 173 + // <-, line 173 + slice_from("a"); + break; + case 6: + // (, line 174 + // <-, line 174 + slice_from("e"); + break; + case 7: + // (, line 175 + // delete, line 175 + slice_del(); + break; + case 8: + // (, line 176 + // delete, line 176 + slice_del(); + break; + case 9: + // (, line 177 + // delete, line 177 + slice_del(); + break; + case 10: + // (, line 178 + // <-, line 178 + slice_from("a"); + break; + case 11: + // (, line 179 + // <-, line 179 + slice_from("e"); + break; + case 12: + // (, line 180 + // delete, line 180 + slice_del(); + break; + case 13: + // (, line 181 + // delete, line 181 + slice_del(); + break; + case 14: + // (, line 182 + // <-, line 182 + slice_from("a"); + break; + case 15: + // (, line 183 + // <-, line 183 + slice_from("e"); + break; + case 16: + // (, line 184 + // delete, line 184 + slice_del(); + break; + case 17: + // (, line 185 + // delete, line 185 + slice_del(); + break; + case 18: + // (, line 186 + // delete, line 186 + slice_del(); + break; + case 19: + // (, line 187 + // <-, line 187 + slice_from("a"); + break; + case 20: + // (, line 188 + // <-, line 188 + slice_from("e"); + break; + } + return true; + } + + private boolean r_plur_owner() { + int among_var; + // (, line 192 + // [, line 193 + ket = cursor; + // substring, line 193 + among_var = find_among_b(a_11, 42); + if (among_var == 0) + { + return false; + } + // ], line 193 + bra = cursor; + // call R1, line 193 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 194 + // delete, line 194 + slice_del(); + break; + case 2: + // (, line 195 + // <-, line 195 + slice_from("a"); + break; + case 3: + // (, line 196 + // <-, line 196 + slice_from("e"); + break; + case 4: + // (, line 197 + // delete, line 197 + slice_del(); + break; + case 5: + // (, line 198 + // delete, line 198 + slice_del(); + break; + case 6: + // (, line 199 + // delete, line 199 + slice_del(); + break; + case 7: + // (, line 200 + // <-, line 200 + slice_from("a"); + break; + case 8: + // (, line 201 + // <-, line 201 + slice_from("e"); + break; + case 9: + // (, line 202 + // delete, line 202 + slice_del(); + break; + case 10: + // (, line 203 + // delete, line 203 + slice_del(); + break; + case 11: + // (, line 204 + // delete, line 204 + slice_del(); + break; + case 12: + // (, line 205 + // <-, line 205 + slice_from("a"); + break; + case 13: + // (, line 206 + // <-, line 206 + slice_from("e"); + break; + case 14: + // (, line 207 + // delete, line 207 + slice_del(); + break; + case 15: + // (, line 208 + // delete, line 208 + slice_del(); + break; + case 16: + // (, line 209 + // delete, line 209 + slice_del(); + break; + case 17: + // (, line 210 + // delete, line 210 + slice_del(); + break; + case 18: + // (, line 211 + // <-, line 211 + slice_from("a"); + break; + case 19: + // (, line 212 + // <-, line 212 + slice_from("e"); + break; + case 20: + // (, line 214 + // delete, line 214 + slice_del(); + break; + case 21: + // (, line 215 + // delete, line 215 + slice_del(); + break; + case 22: + // (, line 216 + // <-, line 216 + slice_from("a"); + break; + case 23: + // (, line 217 + // <-, line 217 + slice_from("e"); + break; + case 24: + // (, line 218 + // delete, line 218 + slice_del(); + break; + case 25: + // (, line 219 + // delete, line 219 + slice_del(); + break; + case 26: + // (, line 220 + // delete, line 220 + slice_del(); + break; + case 27: + // (, line 221 + // <-, line 221 + slice_from("a"); + break; + case 28: + // (, line 222 + // <-, line 222 + slice_from("e"); + break; + case 29: + // (, line 223 + // delete, line 223 + slice_del(); + break; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + // (, line 228 + // do, line 229 + v_1 = cursor; + lab0: do { + // call mark_regions, line 229 + if (!r_mark_regions()) + { + break lab0; + } + } while (false); + cursor = v_1; + // backwards, line 230 + limit_backward = cursor; cursor = limit; + // (, line 230 + // do, line 231 + v_2 = limit - cursor; + lab1: do { + // call instrum, line 231 + if (!r_instrum()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 232 + v_3 = limit - cursor; + lab2: do { + // call case, line 232 + if (!r_case()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 233 + v_4 = limit - cursor; + lab3: do { + // call case_special, line 233 + if (!r_case_special()) + { + break lab3; + } + } while (false); + cursor = limit - v_4; + // do, line 234 + v_5 = limit - cursor; + lab4: do { + // call case_other, line 234 + if (!r_case_other()) + { + break lab4; + } + } while (false); + cursor = limit - v_5; + // do, line 235 + v_6 = limit - cursor; + lab5: do { + // call factive, line 235 + if (!r_factive()) + { + break lab5; + } + } while (false); + cursor = limit - v_6; + // do, line 236 + v_7 = limit - cursor; + lab6: do { + // call owned, line 236 + if (!r_owned()) + { + break lab6; + } + } while (false); + cursor = limit - v_7; + // do, line 237 + v_8 = limit - cursor; + lab7: do { + // call sing_owner, line 237 + if (!r_sing_owner()) + { + break lab7; + } + } while (false); + cursor = limit - v_8; + // do, line 238 + v_9 = limit - cursor; + lab8: do { + // call plur_owner, line 238 + if (!r_plur_owner()) + { + break lab8; + } + } while (false); + cursor = limit - v_9; + // do, line 239 + v_10 = limit - cursor; + lab9: do { + // call plural, line 239 + if (!r_plural()) + { + break lab9; + } + } while (false); + cursor = limit - v_10; + cursor = limit_backward; return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/ItalianStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/ItalianStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/ItalianStemmer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,1180 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class ItalianStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "", -1, 7, "", this), + new Among ( "qu", 0, 6, "", this), + new Among ( "\u00E1", 0, 1, "", this), + new Among ( "\u00E9", 0, 2, "", this), + new Among ( "\u00ED", 0, 3, "", this), + new Among ( "\u00F3", 0, 4, "", this), + new Among ( "\u00FA", 0, 5, "", this) + }; + + private Among a_1[] = { + new Among ( "", -1, 3, "", this), + new Among ( "I", 0, 1, "", this), + new Among ( "U", 0, 2, "", this) + }; + + private Among a_2[] = { + new Among ( "la", -1, -1, "", this), + new Among ( "cela", 0, -1, "", this), + new Among ( "gliela", 0, -1, "", this), + new Among ( "mela", 0, -1, "", this), + new Among ( "tela", 0, -1, "", this), + new Among ( "vela", 0, -1, "", this), + new Among ( "le", -1, -1, "", this), + new Among ( "cele", 6, -1, "", this), + new Among ( "gliele", 6, -1, "", this), + new Among ( "mele", 6, -1, "", this), + new Among ( "tele", 6, -1, "", this), + new Among ( "vele", 6, -1, "", this), + new Among ( "ne", -1, -1, "", this), + new Among ( "cene", 12, -1, "", this), + new Among ( "gliene", 12, -1, "", this), + new Among ( "mene", 12, -1, "", this), + new Among ( "sene", 12, -1, "", this), + new Among ( "tene", 12, -1, "", this), + new Among ( "vene", 12, -1, "", this), + new Among ( "ci", -1, -1, "", this), + new Among ( "li", -1, -1, "", this), + new Among ( "celi", 20, -1, "", this), + new Among ( "glieli", 20, -1, "", this), + new Among ( "meli", 20, -1, "", this), + new Among ( "teli", 20, -1, "", this), + new Among ( "veli", 20, -1, "", this), + new Among ( "gli", 20, -1, "", this), + new Among ( "mi", -1, -1, "", this), + new Among ( "si", -1, -1, "", this), + new Among ( "ti", -1, -1, "", this), + new Among ( "vi", -1, -1, "", this), + new Among ( "lo", -1, -1, "", this), + new Among ( "celo", 31, -1, "", this), + new Among ( "glielo", 31, -1, "", this), + new Among ( "melo", 31, -1, "", this), + new Among ( "telo", 31, -1, "", this), + new Among ( "velo", 31, -1, "", this) + }; + + private Among a_3[] = { + new Among ( "ando", -1, 1, "", this), + new Among ( "endo", -1, 1, "", this), + new Among ( "ar", -1, 2, "", this), + new Among ( "er", -1, 2, "", this), + new Among ( "ir", -1, 2, "", this) + }; + + private Among a_4[] = { + new Among ( "ic", -1, -1, "", this), + new Among ( "abil", -1, -1, "", this), + new Among ( "os", -1, -1, "", this), + new Among ( "iv", -1, 1, "", this) + }; + + private Among a_5[] = { + new Among ( "ic", -1, 1, "", this), + new Among ( "abil", -1, 1, "", this), + new Among ( "iv", -1, 1, "", this) + }; + + private Among a_6[] = { + new Among ( "ica", -1, 1, "", this), + new Among ( "logia", -1, 3, "", this), + new Among ( "osa", -1, 1, "", this), + new Among ( "ista", -1, 1, "", this), + new Among ( "iva", -1, 9, "", this), + new Among ( "anza", -1, 1, "", this), + new Among ( "enza", -1, 5, "", this), + new Among ( "ice", -1, 1, "", this), + new Among ( "atrice", 7, 1, "", this), + new Among ( "iche", -1, 1, "", this), + new Among ( "logie", -1, 3, "", this), + new Among ( "abile", -1, 1, "", this), + new Among ( "ibile", -1, 1, "", this), + new Among ( "usione", -1, 4, "", this), + new Among ( "azione", -1, 2, "", this), + new Among ( "uzione", -1, 4, "", this), + new Among ( "atore", -1, 2, "", this), + new Among ( "ose", -1, 1, "", this), + new Among ( "ante", -1, 1, "", this), + new Among ( "mente", -1, 1, "", this), + new Among ( "amente", 19, 7, "", this), + new Among ( "iste", -1, 1, "", this), + new Among ( "ive", -1, 9, "", this), + new Among ( "anze", -1, 1, "", this), + new Among ( "enze", -1, 5, "", this), + new Among ( "ici", -1, 1, "", this), + new Among ( "atrici", 25, 1, "", this), + new Among ( "ichi", -1, 1, "", this), + new Among ( "abili", -1, 1, "", this), + new Among ( "ibili", -1, 1, "", this), + new Among ( "ismi", -1, 1, "", this), + new Among ( "usioni", -1, 4, "", this), + new Among ( "azioni", -1, 2, "", this), + new Among ( "uzioni", -1, 4, "", this), + new Among ( "atori", -1, 2, "", this), + new Among ( "osi", -1, 1, "", this), + new Among ( "anti", -1, 1, "", this), + new Among ( "amenti", -1, 6, "", this), + new Among ( "imenti", -1, 6, "", this), + new Among ( "isti", -1, 1, "", this), + new Among ( "ivi", -1, 9, "", this), + new Among ( "ico", -1, 1, "", this), + new Among ( "ismo", -1, 1, "", this), + new Among ( "oso", -1, 1, "", this), + new Among ( "amento", -1, 6, "", this), + new Among ( "imento", -1, 6, "", this), + new Among ( "ivo", -1, 9, "", this), + new Among ( "it\u00E0", -1, 8, "", this), + new Among ( "ist\u00E0", -1, 1, "", this), + new Among ( "ist\u00E8", -1, 1, "", this), + new Among ( "ist\u00EC", -1, 1, "", this) + }; + + private Among a_7[] = { + new Among ( "isca", -1, 1, "", this), + new Among ( "enda", -1, 1, "", this), + new Among ( "ata", -1, 1, "", this), + new Among ( "ita", -1, 1, "", this), + new Among ( "uta", -1, 1, "", this), + new Among ( "ava", -1, 1, "", this), + new Among ( "eva", -1, 1, "", this), + new Among ( "iva", -1, 1, "", this), + new Among ( "erebbe", -1, 1, "", this), + new Among ( "irebbe", -1, 1, "", this), + new Among ( "isce", -1, 1, "", this), + new Among ( "ende", -1, 1, "", this), + new Among ( "are", -1, 1, "", this), + new Among ( "ere", -1, 1, "", this), + new Among ( "ire", -1, 1, "", this), + new Among ( "asse", -1, 1, "", this), + new Among ( "ate", -1, 1, "", this), + new Among ( "avate", 16, 1, "", this), + new Among ( "evate", 16, 1, "", this), + new Among ( "ivate", 16, 1, "", this), + new Among ( "ete", -1, 1, "", this), + new Among ( "erete", 20, 1, "", this), + new Among ( "irete", 20, 1, "", this), + new Among ( "ite", -1, 1, "", this), + new Among ( "ereste", -1, 1, "", this), + new Among ( "ireste", -1, 1, "", this), + new Among ( "ute", -1, 1, "", this), + new Among ( "erai", -1, 1, "", this), + new Among ( "irai", -1, 1, "", this), + new Among ( "isci", -1, 1, "", this), + new Among ( "endi", -1, 1, "", this), + new Among ( "erei", -1, 1, "", this), + new Among ( "irei", -1, 1, "", this), + new Among ( "assi", -1, 1, "", this), + new Among ( "ati", -1, 1, "", this), + new Among ( "iti", -1, 1, "", this), + new Among ( "eresti", -1, 1, "", this), + new Among ( "iresti", -1, 1, "", this), + new Among ( "uti", -1, 1, "", this), + new Among ( "avi", -1, 1, "", this), + new Among ( "evi", -1, 1, "", this), + new Among ( "ivi", -1, 1, "", this), + new Among ( "isco", -1, 1, "", this), + new Among ( "ando", -1, 1, "", this), + new Among ( "endo", -1, 1, "", this), + new Among ( "Yamo", -1, 1, "", this), + new Among ( "iamo", -1, 1, "", this), + new Among ( "avamo", -1, 1, "", this), + new Among ( "evamo", -1, 1, "", this), + new Among ( "ivamo", -1, 1, "", this), + new Among ( "eremo", -1, 1, "", this), + new Among ( "iremo", -1, 1, "", this), + new Among ( "assimo", -1, 1, "", this), + new Among ( "ammo", -1, 1, "", this), + new Among ( "emmo", -1, 1, "", this), + new Among ( "eremmo", 54, 1, "", this), + new Among ( "iremmo", 54, 1, "", this), + new Among ( "immo", -1, 1, "", this), + new Among ( "ano", -1, 1, "", this), + new Among ( "iscano", 58, 1, "", this), + new Among ( "avano", 58, 1, "", this), + new Among ( "evano", 58, 1, "", this), + new Among ( "ivano", 58, 1, "", this), + new Among ( "eranno", -1, 1, "", this), + new Among ( "iranno", -1, 1, "", this), + new Among ( "ono", -1, 1, "", this), + new Among ( "iscono", 65, 1, "", this), + new Among ( "arono", 65, 1, "", this), + new Among ( "erono", 65, 1, "", this), + new Among ( "irono", 65, 1, "", this), + new Among ( "erebbero", -1, 1, "", this), + new Among ( "irebbero", -1, 1, "", this), + new Among ( "assero", -1, 1, "", this), + new Among ( "essero", -1, 1, "", this), + new Among ( "issero", -1, 1, "", this), + new Among ( "ato", -1, 1, "", this), + new Among ( "ito", -1, 1, "", this), + new Among ( "uto", -1, 1, "", this), + new Among ( "avo", -1, 1, "", this), + new Among ( "evo", -1, 1, "", this), + new Among ( "ivo", -1, 1, "", this), + new Among ( "ar", -1, 1, "", this), + new Among ( "ir", -1, 1, "", this), + new Among ( "er\u00E0", -1, 1, "", this), + new Among ( "ir\u00E0", -1, 1, "", this), + new Among ( "er\u00F2", -1, 1, "", this), + new Among ( "ir\u00F2", -1, 1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 8, 2, 1 }; + + private static final char g_AEIO[] = {17, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 8, 2 }; + + private static final char g_CG[] = {17 }; + + private int I_p2; + private int I_p1; + private int I_pV; + + private void copy_from(ItalianStemmer other) { + I_p2 = other.I_p2; + I_p1 = other.I_p1; + I_pV = other.I_pV; + super.copy_from(other); + } + + private boolean r_prelude() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 34 + // test, line 35 + v_1 = cursor; + // repeat, line 35 + replab0: while(true) + { + v_2 = cursor; + lab1: do { + // (, line 35 + // [, line 36 + bra = cursor; + // substring, line 36 + among_var = find_among(a_0, 7); + if (among_var == 0) + { + break lab1; + } + // ], line 36 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 37 + // <-, line 37 + slice_from("\u00E0"); + break; + case 2: + // (, line 38 + // <-, line 38 + slice_from("\u00E8"); + break; + case 3: + // (, line 39 + // <-, line 39 + slice_from("\u00EC"); + break; + case 4: + // (, line 40 + // <-, line 40 + slice_from("\u00F2"); + break; + case 5: + // (, line 41 + // <-, line 41 + slice_from("\u00F9"); + break; + case 6: + // (, line 42 + // <-, line 42 + slice_from("qU"); + break; + case 7: + // (, line 43 + // next, line 43 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_2; + break replab0; + } + cursor = v_1; + // repeat, line 46 + replab2: while(true) + { + v_3 = cursor; + lab3: do { + // goto, line 46 + golab4: while(true) + { + v_4 = cursor; + lab5: do { + // (, line 46 + if (!(in_grouping(g_v, 97, 249))) + { + break lab5; + } + // [, line 47 + bra = cursor; + // or, line 47 + lab6: do { + v_5 = cursor; + lab7: do { + // (, line 47 + // literal, line 47 + if (!(eq_s(1, "u"))) + { + break lab7; + } + // ], line 47 + ket = cursor; + if (!(in_grouping(g_v, 97, 249))) + { + break lab7; + } + // <-, line 47 + slice_from("U"); + break lab6; + } while (false); + cursor = v_5; + // (, line 48 + // literal, line 48 + if (!(eq_s(1, "i"))) + { + break lab5; + } + // ], line 48 + ket = cursor; + if (!(in_grouping(g_v, 97, 249))) + { + break lab5; + } + // <-, line 48 + slice_from("I"); + } while (false); + cursor = v_4; + break golab4; + } while (false); + cursor = v_4; + if (cursor >= limit) + { + break lab3; + } + cursor++; + } + continue replab2; + } while (false); + cursor = v_3; + break replab2; + } + return true; + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + int v_3; + int v_6; + int v_8; + // (, line 52 + I_pV = limit; + I_p1 = limit; + I_p2 = limit; + // do, line 58 + v_1 = cursor; + lab0: do { + // (, line 58 + // or, line 60 + lab1: do { + v_2 = cursor; + lab2: do { + // (, line 59 + if (!(in_grouping(g_v, 97, 249))) + { + break lab2; + } + // or, line 59 + lab3: do { + v_3 = cursor; + lab4: do { + // (, line 59 + if (!(out_grouping(g_v, 97, 249))) + { + break lab4; + } + // gopast, line 59 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 97, 249))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + break lab4; + } + cursor++; + } + break lab3; + } while (false); + cursor = v_3; + // (, line 59 + if (!(in_grouping(g_v, 97, 249))) + { + break lab2; + } + // gopast, line 59 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 97, 249))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab2; + } + cursor++; + } + } while (false); + break lab1; + } while (false); + cursor = v_2; + // (, line 61 + if (!(out_grouping(g_v, 97, 249))) + { + break lab0; + } + // or, line 61 + lab9: do { + v_6 = cursor; + lab10: do { + // (, line 61 + if (!(out_grouping(g_v, 97, 249))) + { + break lab10; + } + // gopast, line 61 + golab11: while(true) + { + lab12: do { + if (!(in_grouping(g_v, 97, 249))) + { + break lab12; + } + break golab11; + } while (false); + if (cursor >= limit) + { + break lab10; + } + cursor++; + } + break lab9; + } while (false); + cursor = v_6; + // (, line 61 + if (!(in_grouping(g_v, 97, 249))) + { + break lab0; + } + // next, line 61 + if (cursor >= limit) + { + break lab0; + } + cursor++; + } while (false); + } while (false); + // setmark pV, line 62 + I_pV = cursor; + } while (false); + cursor = v_1; + // do, line 64 + v_8 = cursor; + lab13: do { + // (, line 64 + // gopast, line 65 + golab14: while(true) + { + lab15: do { + if (!(in_grouping(g_v, 97, 249))) + { + break lab15; + } + break golab14; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 65 + golab16: while(true) + { + lab17: do { + if (!(out_grouping(g_v, 97, 249))) + { + break lab17; + } + break golab16; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p1, line 65 + I_p1 = cursor; + // gopast, line 66 + golab18: while(true) + { + lab19: do { + if (!(in_grouping(g_v, 97, 249))) + { + break lab19; + } + break golab18; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 66 + golab20: while(true) + { + lab21: do { + if (!(out_grouping(g_v, 97, 249))) + { + break lab21; + } + break golab20; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p2, line 66 + I_p2 = cursor; + } while (false); + cursor = v_8; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 70 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 70 + // [, line 72 + bra = cursor; + // substring, line 72 + among_var = find_among(a_1, 3); + if (among_var == 0) + { + break lab1; + } + // ], line 72 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 73 + // <-, line 73 + slice_from("i"); + break; + case 2: + // (, line 74 + // <-, line 74 + slice_from("u"); + break; + case 3: + // (, line 75 + // next, line 75 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_RV() { + if (!(I_pV <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_attached_pronoun() { + int among_var; + // (, line 86 + // [, line 87 + ket = cursor; + // substring, line 87 + if (find_among_b(a_2, 37) == 0) + { + return false; + } + // ], line 87 + bra = cursor; + // among, line 97 + among_var = find_among_b(a_3, 5); + if (among_var == 0) + { + return false; + } + // (, line 97 + // call RV, line 97 + if (!r_RV()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 98 + // delete, line 98 + slice_del(); + break; + case 2: + // (, line 99 + // <-, line 99 + slice_from("e"); + break; + } + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 103 + // [, line 104 + ket = cursor; + // substring, line 104 + among_var = find_among_b(a_6, 51); + if (among_var == 0) + { + return false; + } + // ], line 104 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 111 + // call R2, line 111 + if (!r_R2()) + { + return false; + } + // delete, line 111 + slice_del(); + break; + case 2: + // (, line 113 + // call R2, line 113 + if (!r_R2()) + { + return false; + } + // delete, line 113 + slice_del(); + // try, line 114 + v_1 = limit - cursor; + lab0: do { + // (, line 114 + // [, line 114 + ket = cursor; + // literal, line 114 + if (!(eq_s_b(2, "ic"))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 114 + bra = cursor; + // call R2, line 114 + if (!r_R2()) + { + cursor = limit - v_1; + break lab0; + } + // delete, line 114 + slice_del(); + } while (false); + break; + case 3: + // (, line 117 + // call R2, line 117 + if (!r_R2()) + { + return false; + } + // <-, line 117 + slice_from("log"); + break; + case 4: + // (, line 119 + // call R2, line 119 + if (!r_R2()) + { + return false; + } + // <-, line 119 + slice_from("u"); + break; + case 5: + // (, line 121 + // call R2, line 121 + if (!r_R2()) + { + return false; + } + // <-, line 121 + slice_from("ente"); + break; + case 6: + // (, line 123 + // call RV, line 123 + if (!r_RV()) + { + return false; + } + // delete, line 123 + slice_del(); + break; + case 7: + // (, line 124 + // call R1, line 125 + if (!r_R1()) + { + return false; + } + // delete, line 125 + slice_del(); + // try, line 126 + v_2 = limit - cursor; + lab1: do { + // (, line 126 + // [, line 127 + ket = cursor; + // substring, line 127 + among_var = find_among_b(a_4, 4); + if (among_var == 0) + { + cursor = limit - v_2; + break lab1; + } + // ], line 127 + bra = cursor; + // call R2, line 127 + if (!r_R2()) + { + cursor = limit - v_2; + break lab1; + } + // delete, line 127 + slice_del(); + switch(among_var) { + case 0: + cursor = limit - v_2; + break lab1; + case 1: + // (, line 128 + // [, line 128 + ket = cursor; + // literal, line 128 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_2; + break lab1; + } + // ], line 128 + bra = cursor; + // call R2, line 128 + if (!r_R2()) + { + cursor = limit - v_2; + break lab1; + } + // delete, line 128 + slice_del(); + break; + } + } while (false); + break; + case 8: + // (, line 133 + // call R2, line 134 + if (!r_R2()) + { + return false; + } + // delete, line 134 + slice_del(); + // try, line 135 + v_3 = limit - cursor; + lab2: do { + // (, line 135 + // [, line 136 + ket = cursor; + // substring, line 136 + among_var = find_among_b(a_5, 3); + if (among_var == 0) + { + cursor = limit - v_3; + break lab2; + } + // ], line 136 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_3; + break lab2; + case 1: + // (, line 137 + // call R2, line 137 + if (!r_R2()) + { + cursor = limit - v_3; + break lab2; + } + // delete, line 137 + slice_del(); + break; + } + } while (false); + break; + case 9: + // (, line 141 + // call R2, line 142 + if (!r_R2()) + { + return false; + } + // delete, line 142 + slice_del(); + // try, line 143 + v_4 = limit - cursor; + lab3: do { + // (, line 143 + // [, line 143 + ket = cursor; + // literal, line 143 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_4; + break lab3; + } + // ], line 143 + bra = cursor; + // call R2, line 143 + if (!r_R2()) + { + cursor = limit - v_4; + break lab3; + } + // delete, line 143 + slice_del(); + // [, line 143 + ket = cursor; + // literal, line 143 + if (!(eq_s_b(2, "ic"))) + { + cursor = limit - v_4; + break lab3; + } + // ], line 143 + bra = cursor; + // call R2, line 143 + if (!r_R2()) + { + cursor = limit - v_4; + break lab3; + } + // delete, line 143 + slice_del(); + } while (false); + break; + } + return true; + } + + private boolean r_verb_suffix() { + int among_var; + int v_1; + int v_2; + // setlimit, line 148 + v_1 = limit - cursor; + // tomark, line 148 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 148 + // [, line 149 + ket = cursor; + // substring, line 149 + among_var = find_among_b(a_7, 87); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 149 + bra = cursor; + switch(among_var) { + case 0: + limit_backward = v_2; + return false; + case 1: + // (, line 163 + // delete, line 163 + slice_del(); + break; + } + limit_backward = v_2; + return true; + } + + private boolean r_vowel_suffix() { + int v_1; + int v_2; + // (, line 170 + // try, line 171 + v_1 = limit - cursor; + lab0: do { + // (, line 171 + // [, line 172 + ket = cursor; + if (!(in_grouping_b(g_AEIO, 97, 242))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 172 + bra = cursor; + // call RV, line 172 + if (!r_RV()) + { + cursor = limit - v_1; + break lab0; + } + // delete, line 172 + slice_del(); + // [, line 173 + ket = cursor; + // literal, line 173 + if (!(eq_s_b(1, "i"))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 173 + bra = cursor; + // call RV, line 173 + if (!r_RV()) + { + cursor = limit - v_1; + break lab0; + } + // delete, line 173 + slice_del(); + } while (false); + // try, line 175 + v_2 = limit - cursor; + lab1: do { + // (, line 175 + // [, line 176 + ket = cursor; + // literal, line 176 + if (!(eq_s_b(1, "h"))) + { + cursor = limit - v_2; + break lab1; + } + // ], line 176 + bra = cursor; + if (!(in_grouping_b(g_CG, 99, 103))) + { + cursor = limit - v_2; + break lab1; + } + // call RV, line 176 + if (!r_RV()) + { + cursor = limit - v_2; + break lab1; + } + // delete, line 176 + slice_del(); + } while (false); + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + // (, line 181 + // do, line 182 + v_1 = cursor; + lab0: do { + // call prelude, line 182 + if (!r_prelude()) + { + break lab0; + } + } while (false); + cursor = v_1; + // do, line 183 + v_2 = cursor; + lab1: do { + // call mark_regions, line 183 + if (!r_mark_regions()) + { + break lab1; + } + } while (false); + cursor = v_2; + // backwards, line 184 + limit_backward = cursor; cursor = limit; + // (, line 184 + // do, line 185 + v_3 = limit - cursor; + lab2: do { + // call attached_pronoun, line 185 + if (!r_attached_pronoun()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 186 + v_4 = limit - cursor; + lab3: do { + // (, line 186 + // or, line 186 + lab4: do { + v_5 = limit - cursor; + lab5: do { + // call standard_suffix, line 186 + if (!r_standard_suffix()) + { + break lab5; + } + break lab4; + } while (false); + cursor = limit - v_5; + // call verb_suffix, line 186 + if (!r_verb_suffix()) + { + break lab3; + } + } while (false); + } while (false); + cursor = limit - v_4; + // do, line 187 + v_6 = limit - cursor; + lab6: do { + // call vowel_suffix, line 187 + if (!r_vowel_suffix()) + { + break lab6; + } + } while (false); + cursor = limit - v_6; + cursor = limit_backward; // do, line 189 + v_7 = cursor; + lab7: do { + // call postlude, line 189 + if (!r_postlude()) + { + break lab7; + } + } while (false); + cursor = v_7; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/KpStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/KpStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/KpStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,2181 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class KpStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "nde", -1, 7, "", this), + new Among ( "en", -1, 6, "", this), + new Among ( "s", -1, 2, "", this), + new Among ( "'s", 2, 1, "", this), + new Among ( "es", 2, 4, "", this), + new Among ( "ies", 4, 3, "", this), + new Among ( "aus", 2, 5, "", this) + }; + + private Among a_1[] = { + new Among ( "de", -1, 5, "", this), + new Among ( "ge", -1, 2, "", this), + new Among ( "ische", -1, 4, "", this), + new Among ( "je", -1, 1, "", this), + new Among ( "lijke", -1, 3, "", this), + new Among ( "le", -1, 9, "", this), + new Among ( "ene", -1, 10, "", this), + new Among ( "re", -1, 8, "", this), + new Among ( "se", -1, 7, "", this), + new Among ( "te", -1, 6, "", this), + new Among ( "ieve", -1, 11, "", this) + }; + + private Among a_2[] = { + new Among ( "heid", -1, 3, "", this), + new Among ( "fie", -1, 7, "", this), + new Among ( "gie", -1, 8, "", this), + new Among ( "atie", -1, 1, "", this), + new Among ( "isme", -1, 5, "", this), + new Among ( "ing", -1, 5, "", this), + new Among ( "arij", -1, 6, "", this), + new Among ( "erij", -1, 5, "", this), + new Among ( "sel", -1, 3, "", this), + new Among ( "rder", -1, 4, "", this), + new Among ( "ster", -1, 3, "", this), + new Among ( "iteit", -1, 2, "", this), + new Among ( "dst", -1, 10, "", this), + new Among ( "tst", -1, 9, "", this) + }; + + private Among a_3[] = { + new Among ( "end", -1, 10, "", this), + new Among ( "atief", -1, 2, "", this), + new Among ( "erig", -1, 10, "", this), + new Among ( "achtig", -1, 9, "", this), + new Among ( "ioneel", -1, 1, "", this), + new Among ( "baar", -1, 3, "", this), + new Among ( "laar", -1, 5, "", this), + new Among ( "naar", -1, 4, "", this), + new Among ( "raar", -1, 6, "", this), + new Among ( "eriger", -1, 10, "", this), + new Among ( "achtiger", -1, 9, "", this), + new Among ( "lijker", -1, 8, "", this), + new Among ( "tant", -1, 7, "", this), + new Among ( "erigst", -1, 10, "", this), + new Among ( "achtigst", -1, 9, "", this), + new Among ( "lijkst", -1, 8, "", this) + }; + + private Among a_4[] = { + new Among ( "ig", -1, 1, "", this), + new Among ( "iger", -1, 1, "", this), + new Among ( "igst", -1, 1, "", this) + }; + + private Among a_5[] = { + new Among ( "ft", -1, 2, "", this), + new Among ( "kt", -1, 1, "", this), + new Among ( "pt", -1, 3, "", this) + }; + + private Among a_6[] = { + new Among ( "bb", -1, 1, "", this), + new Among ( "cc", -1, 2, "", this), + new Among ( "dd", -1, 3, "", this), + new Among ( "ff", -1, 4, "", this), + new Among ( "gg", -1, 5, "", this), + new Among ( "hh", -1, 6, "", this), + new Among ( "jj", -1, 7, "", this), + new Among ( "kk", -1, 8, "", this), + new Among ( "ll", -1, 9, "", this), + new Among ( "mm", -1, 10, "", this), + new Among ( "nn", -1, 11, "", this), + new Among ( "pp", -1, 12, "", this), + new Among ( "qq", -1, 13, "", this), + new Among ( "rr", -1, 14, "", this), + new Among ( "ss", -1, 15, "", this), + new Among ( "tt", -1, 16, "", this), + new Among ( "v", -1, 21, "", this), + new Among ( "vv", 16, 17, "", this), + new Among ( "ww", -1, 18, "", this), + new Among ( "xx", -1, 19, "", this), + new Among ( "z", -1, 22, "", this), + new Among ( "zz", 20, 20, "", this) + }; + + private Among a_7[] = { + new Among ( "d", -1, 1, "", this), + new Among ( "t", -1, 2, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1 }; + + private static final char g_v_WX[] = {17, 65, 208, 1 }; + + private static final char g_AOU[] = {1, 64, 16 }; + + private static final char g_AIOU[] = {1, 65, 16 }; + + private boolean B_GE_removed; + private boolean B_stemmed; + private boolean B_Y_found; + private int I_p2; + private int I_p1; + private int I_x; + private StringBuffer S_ch = new StringBuffer(); + + private void copy_from(KpStemmer other) { + B_GE_removed = other.B_GE_removed; + B_stemmed = other.B_stemmed; + B_Y_found = other.B_Y_found; + I_p2 = other.I_p2; + I_p1 = other.I_p1; + I_x = other.I_x; + S_ch = other.S_ch; + super.copy_from(other); + } + + private boolean r_R1() { + // (, line 32 + // setmark x, line 32 + I_x = cursor; + if (!(I_x >= I_p1)) + { + return false; + } + return true; + } + + private boolean r_R2() { + // (, line 33 + // setmark x, line 33 + I_x = cursor; + if (!(I_x >= I_p2)) + { + return false; + } + return true; + } + + private boolean r_V() { + int v_1; + int v_2; + // test, line 35 + v_1 = limit - cursor; + // (, line 35 + // or, line 35 + lab0: do { + v_2 = limit - cursor; + lab1: do { + if (!(in_grouping_b(g_v, 97, 121))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // literal, line 35 + if (!(eq_s_b(2, "ij"))) + { + return false; + } + } while (false); + cursor = limit - v_1; + return true; + } + + private boolean r_VX() { + int v_1; + int v_2; + // test, line 36 + v_1 = limit - cursor; + // (, line 36 + // next, line 36 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // or, line 36 + lab0: do { + v_2 = limit - cursor; + lab1: do { + if (!(in_grouping_b(g_v, 97, 121))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // literal, line 36 + if (!(eq_s_b(2, "ij"))) + { + return false; + } + } while (false); + cursor = limit - v_1; + return true; + } + + private boolean r_C() { + int v_1; + int v_2; + // test, line 37 + v_1 = limit - cursor; + // (, line 37 + // not, line 37 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 37 + if (!(eq_s_b(2, "ij"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + if (!(out_grouping_b(g_v, 97, 121))) + { + return false; + } + cursor = limit - v_1; + return true; + } + + private boolean r_lengthen_V() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + // do, line 39 + v_1 = limit - cursor; + lab0: do { + // (, line 39 + if (!(out_grouping_b(g_v_WX, 97, 121))) + { + break lab0; + } + // [, line 40 + ket = cursor; + // or, line 40 + lab1: do { + v_2 = limit - cursor; + lab2: do { + // (, line 40 + if (!(in_grouping_b(g_AOU, 97, 117))) + { + break lab2; + } + // ], line 40 + bra = cursor; + // test, line 40 + v_3 = limit - cursor; + // (, line 40 + // or, line 40 + lab3: do { + v_4 = limit - cursor; + lab4: do { + if (!(out_grouping_b(g_v, 97, 121))) + { + break lab4; + } + break lab3; + } while (false); + cursor = limit - v_4; + // atlimit, line 40 + if (cursor > limit_backward) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + break lab1; + } while (false); + cursor = limit - v_2; + // (, line 41 + // literal, line 41 + if (!(eq_s_b(1, "e"))) + { + break lab0; + } + // ], line 41 + bra = cursor; + // test, line 41 + v_5 = limit - cursor; + // (, line 41 + // or, line 41 + lab5: do { + v_6 = limit - cursor; + lab6: do { + if (!(out_grouping_b(g_v, 97, 121))) + { + break lab6; + } + break lab5; + } while (false); + cursor = limit - v_6; + // atlimit, line 41 + if (cursor > limit_backward) + { + break lab0; + } + } while (false); + // not, line 42 + { + v_7 = limit - cursor; + lab7: do { + if (!(in_grouping_b(g_AIOU, 97, 117))) + { + break lab7; + } + break lab0; + } while (false); + cursor = limit - v_7; + } + // not, line 43 + { + v_8 = limit - cursor; + lab8: do { + // (, line 43 + // next, line 43 + if (cursor <= limit_backward) + { + break lab8; + } + cursor--; + if (!(in_grouping_b(g_AIOU, 97, 117))) + { + break lab8; + } + if (!(out_grouping_b(g_v, 97, 121))) + { + break lab8; + } + break lab0; + } while (false); + cursor = limit - v_8; + } + cursor = limit - v_5; + } while (false); + // -> ch, line 44 + S_ch = slice_to(S_ch); + // <+ ch, line 44 + { + int c = cursor; + insert(cursor, cursor, S_ch); + cursor = c; + } + } while (false); + cursor = limit - v_1; + return true; + } + + private boolean r_Step_1() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 48 + // [, line 49 + ket = cursor; + // among, line 49 + among_var = find_among_b(a_0, 7); + if (among_var == 0) + { + return false; + } + // (, line 49 + // ], line 49 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 51 + // delete, line 51 + slice_del(); + break; + case 2: + // (, line 52 + // call R1, line 52 + if (!r_R1()) + { + return false; + } + // not, line 52 + { + v_1 = limit - cursor; + lab0: do { + // (, line 52 + // literal, line 52 + if (!(eq_s_b(1, "t"))) + { + break lab0; + } + // call R1, line 52 + if (!r_R1()) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_1; + } + // call C, line 52 + if (!r_C()) + { + return false; + } + // delete, line 52 + slice_del(); + break; + case 3: + // (, line 53 + // call R1, line 53 + if (!r_R1()) + { + return false; + } + // <-, line 53 + slice_from("ie"); + break; + case 4: + // (, line 55 + // or, line 55 + lab1: do { + v_2 = limit - cursor; + lab2: do { + // (, line 55 + // literal, line 55 + if (!(eq_s_b(2, "ar"))) + { + break lab2; + } + // call R1, line 55 + if (!r_R1()) + { + break lab2; + } + // call C, line 55 + if (!r_C()) + { + break lab2; + } + // ], line 55 + bra = cursor; + // delete, line 55 + slice_del(); + // call lengthen_V, line 55 + if (!r_lengthen_V()) + { + break lab2; + } + break lab1; + } while (false); + cursor = limit - v_2; + lab3: do { + // (, line 56 + // literal, line 56 + if (!(eq_s_b(2, "er"))) + { + break lab3; + } + // call R1, line 56 + if (!r_R1()) + { + break lab3; + } + // call C, line 56 + if (!r_C()) + { + break lab3; + } + // ], line 56 + bra = cursor; + // delete, line 56 + slice_del(); + break lab1; + } while (false); + cursor = limit - v_2; + // (, line 57 + // call R1, line 57 + if (!r_R1()) + { + return false; + } + // call C, line 57 + if (!r_C()) + { + return false; + } + // <-, line 57 + slice_from("e"); + } while (false); + break; + case 5: + // (, line 59 + // call R1, line 59 + if (!r_R1()) + { + return false; + } + // call V, line 59 + if (!r_V()) + { + return false; + } + // <-, line 59 + slice_from("au"); + break; + case 6: + // (, line 60 + // or, line 60 + lab4: do { + v_3 = limit - cursor; + lab5: do { + // (, line 60 + // literal, line 60 + if (!(eq_s_b(3, "hed"))) + { + break lab5; + } + // call R1, line 60 + if (!r_R1()) + { + break lab5; + } + // ], line 60 + bra = cursor; + // <-, line 60 + slice_from("heid"); + break lab4; + } while (false); + cursor = limit - v_3; + lab6: do { + // (, line 61 + // literal, line 61 + if (!(eq_s_b(2, "nd"))) + { + break lab6; + } + // delete, line 61 + slice_del(); + break lab4; + } while (false); + cursor = limit - v_3; + lab7: do { + // (, line 62 + // literal, line 62 + if (!(eq_s_b(1, "d"))) + { + break lab7; + } + // call R1, line 62 + if (!r_R1()) + { + break lab7; + } + // call C, line 62 + if (!r_C()) + { + break lab7; + } + // ], line 62 + bra = cursor; + // delete, line 62 + slice_del(); + break lab4; + } while (false); + cursor = limit - v_3; + lab8: do { + // (, line 63 + // or, line 63 + lab9: do { + v_4 = limit - cursor; + lab10: do { + // literal, line 63 + if (!(eq_s_b(1, "i"))) + { + break lab10; + } + break lab9; + } while (false); + cursor = limit - v_4; + // literal, line 63 + if (!(eq_s_b(1, "j"))) + { + break lab8; + } + } while (false); + // call V, line 63 + if (!r_V()) + { + break lab8; + } + // delete, line 63 + slice_del(); + break lab4; + } while (false); + cursor = limit - v_3; + // (, line 64 + // call R1, line 64 + if (!r_R1()) + { + return false; + } + // call C, line 64 + if (!r_C()) + { + return false; + } + // delete, line 64 + slice_del(); + // call lengthen_V, line 64 + if (!r_lengthen_V()) + { + return false; + } + } while (false); + break; + case 7: + // (, line 65 + // <-, line 65 + slice_from("nd"); + break; + } + return true; + } + + private boolean r_Step_2() { + int among_var; + int v_1; + // (, line 70 + // [, line 71 + ket = cursor; + // among, line 71 + among_var = find_among_b(a_1, 11); + if (among_var == 0) + { + return false; + } + // (, line 71 + // ], line 71 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 72 + // or, line 72 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 72 + // literal, line 72 + if (!(eq_s_b(2, "'t"))) + { + break lab1; + } + // ], line 72 + bra = cursor; + // delete, line 72 + slice_del(); + break lab0; + } while (false); + cursor = limit - v_1; + lab2: do { + // (, line 73 + // literal, line 73 + if (!(eq_s_b(2, "et"))) + { + break lab2; + } + // ], line 73 + bra = cursor; + // call R1, line 73 + if (!r_R1()) + { + break lab2; + } + // call C, line 73 + if (!r_C()) + { + break lab2; + } + // delete, line 73 + slice_del(); + break lab0; + } while (false); + cursor = limit - v_1; + lab3: do { + // (, line 74 + // literal, line 74 + if (!(eq_s_b(3, "rnt"))) + { + break lab3; + } + // ], line 74 + bra = cursor; + // <-, line 74 + slice_from("rn"); + break lab0; + } while (false); + cursor = limit - v_1; + lab4: do { + // (, line 75 + // literal, line 75 + if (!(eq_s_b(1, "t"))) + { + break lab4; + } + // ], line 75 + bra = cursor; + // call R1, line 75 + if (!r_R1()) + { + break lab4; + } + // call VX, line 75 + if (!r_VX()) + { + break lab4; + } + // delete, line 75 + slice_del(); + break lab0; + } while (false); + cursor = limit - v_1; + lab5: do { + // (, line 76 + // literal, line 76 + if (!(eq_s_b(3, "ink"))) + { + break lab5; + } + // ], line 76 + bra = cursor; + // <-, line 76 + slice_from("ing"); + break lab0; + } while (false); + cursor = limit - v_1; + lab6: do { + // (, line 77 + // literal, line 77 + if (!(eq_s_b(2, "mp"))) + { + break lab6; + } + // ], line 77 + bra = cursor; + // <-, line 77 + slice_from("m"); + break lab0; + } while (false); + cursor = limit - v_1; + lab7: do { + // (, line 78 + // literal, line 78 + if (!(eq_s_b(1, "'"))) + { + break lab7; + } + // ], line 78 + bra = cursor; + // call R1, line 78 + if (!r_R1()) + { + break lab7; + } + // delete, line 78 + slice_del(); + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 79 + // ], line 79 + bra = cursor; + // call R1, line 79 + if (!r_R1()) + { + return false; + } + // call C, line 79 + if (!r_C()) + { + return false; + } + // delete, line 79 + slice_del(); + } while (false); + break; + case 2: + // (, line 80 + // call R1, line 80 + if (!r_R1()) + { + return false; + } + // <-, line 80 + slice_from("g"); + break; + case 3: + // (, line 81 + // call R1, line 81 + if (!r_R1()) + { + return false; + } + // <-, line 81 + slice_from("lijk"); + break; + case 4: + // (, line 82 + // call R1, line 82 + if (!r_R1()) + { + return false; + } + // <-, line 82 + slice_from("isch"); + break; + case 5: + // (, line 83 + // call R1, line 83 + if (!r_R1()) + { + return false; + } + // call C, line 83 + if (!r_C()) + { + return false; + } + // delete, line 83 + slice_del(); + break; + case 6: + // (, line 84 + // call R1, line 84 + if (!r_R1()) + { + return false; + } + // <-, line 84 + slice_from("t"); + break; + case 7: + // (, line 85 + // call R1, line 85 + if (!r_R1()) + { + return false; + } + // <-, line 85 + slice_from("s"); + break; + case 8: + // (, line 86 + // call R1, line 86 + if (!r_R1()) + { + return false; + } + // <-, line 86 + slice_from("r"); + break; + case 9: + // (, line 87 + // call R1, line 87 + if (!r_R1()) + { + return false; + } + // delete, line 87 + slice_del(); + // attach, line 87 + insert(cursor, cursor, "l"); + // call lengthen_V, line 87 + if (!r_lengthen_V()) + { + return false; + } + break; + case 10: + // (, line 88 + // call R1, line 88 + if (!r_R1()) + { + return false; + } + // call C, line 88 + if (!r_C()) + { + return false; + } + // delete, line 88 + slice_del(); + // attach, line 88 + insert(cursor, cursor, "en"); + // call lengthen_V, line 88 + if (!r_lengthen_V()) + { + return false; + } + break; + case 11: + // (, line 89 + // call R1, line 89 + if (!r_R1()) + { + return false; + } + // call C, line 89 + if (!r_C()) + { + return false; + } + // <-, line 89 + slice_from("ief"); + break; + } + return true; + } + + private boolean r_Step_3() { + int among_var; + // (, line 94 + // [, line 95 + ket = cursor; + // among, line 95 + among_var = find_among_b(a_2, 14); + if (among_var == 0) + { + return false; + } + // (, line 95 + // ], line 95 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 96 + // call R1, line 96 + if (!r_R1()) + { + return false; + } + // <-, line 96 + slice_from("eer"); + break; + case 2: + // (, line 97 + // call R1, line 97 + if (!r_R1()) + { + return false; + } + // delete, line 97 + slice_del(); + // call lengthen_V, line 97 + if (!r_lengthen_V()) + { + return false; + } + break; + case 3: + // (, line 100 + // call R1, line 100 + if (!r_R1()) + { + return false; + } + // delete, line 100 + slice_del(); + break; + case 4: + // (, line 101 + // <-, line 101 + slice_from("r"); + break; + case 5: + // (, line 104 + // call R1, line 104 + if (!r_R1()) + { + return false; + } + // delete, line 104 + slice_del(); + // call lengthen_V, line 104 + if (!r_lengthen_V()) + { + return false; + } + break; + case 6: + // (, line 105 + // call R1, line 105 + if (!r_R1()) + { + return false; + } + // call C, line 105 + if (!r_C()) + { + return false; + } + // <-, line 105 + slice_from("aar"); + break; + case 7: + // (, line 106 + // call R2, line 106 + if (!r_R2()) + { + return false; + } + // delete, line 106 + slice_del(); + // attach, line 106 + insert(cursor, cursor, "f"); + // call lengthen_V, line 106 + if (!r_lengthen_V()) + { + return false; + } + break; + case 8: + // (, line 107 + // call R2, line 107 + if (!r_R2()) + { + return false; + } + // delete, line 107 + slice_del(); + // attach, line 107 + insert(cursor, cursor, "g"); + // call lengthen_V, line 107 + if (!r_lengthen_V()) + { + return false; + } + break; + case 9: + // (, line 108 + // call R1, line 108 + if (!r_R1()) + { + return false; + } + // call C, line 108 + if (!r_C()) + { + return false; + } + // <-, line 108 + slice_from("t"); + break; + case 10: + // (, line 109 + // call R1, line 109 + if (!r_R1()) + { + return false; + } + // call C, line 109 + if (!r_C()) + { + return false; + } + // <-, line 109 + slice_from("d"); + break; + } + return true; + } + + private boolean r_Step_4() { + int among_var; + int v_1; + // (, line 114 + // or, line 134 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 115 + // [, line 115 + ket = cursor; + // among, line 115 + among_var = find_among_b(a_3, 16); + if (among_var == 0) + { + break lab1; + } + // (, line 115 + // ], line 115 + bra = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 116 + // call R1, line 116 + if (!r_R1()) + { + break lab1; + } + // <-, line 116 + slice_from("ie"); + break; + case 2: + // (, line 117 + // call R1, line 117 + if (!r_R1()) + { + break lab1; + } + // <-, line 117 + slice_from("eer"); + break; + case 3: + // (, line 118 + // call R1, line 118 + if (!r_R1()) + { + break lab1; + } + // delete, line 118 + slice_del(); + break; + case 4: + // (, line 119 + // call R1, line 119 + if (!r_R1()) + { + break lab1; + } + // call V, line 119 + if (!r_V()) + { + break lab1; + } + // <-, line 119 + slice_from("n"); + break; + case 5: + // (, line 120 + // call R1, line 120 + if (!r_R1()) + { + break lab1; + } + // call V, line 120 + if (!r_V()) + { + break lab1; + } + // <-, line 120 + slice_from("l"); + break; + case 6: + // (, line 121 + // call R1, line 121 + if (!r_R1()) + { + break lab1; + } + // call V, line 121 + if (!r_V()) + { + break lab1; + } + // <-, line 121 + slice_from("r"); + break; + case 7: + // (, line 122 + // call R1, line 122 + if (!r_R1()) + { + break lab1; + } + // <-, line 122 + slice_from("teer"); + break; + case 8: + // (, line 124 + // call R1, line 124 + if (!r_R1()) + { + break lab1; + } + // <-, line 124 + slice_from("lijk"); + break; + case 9: + // (, line 127 + // call R1, line 127 + if (!r_R1()) + { + break lab1; + } + // delete, line 127 + slice_del(); + break; + case 10: + // (, line 131 + // call R1, line 131 + if (!r_R1()) + { + break lab1; + } + // call C, line 131 + if (!r_C()) + { + break lab1; + } + // delete, line 131 + slice_del(); + // call lengthen_V, line 131 + if (!r_lengthen_V()) + { + break lab1; + } + break; + } + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 135 + // [, line 135 + ket = cursor; + // among, line 135 + among_var = find_among_b(a_4, 3); + if (among_var == 0) + { + return false; + } + // (, line 135 + // ], line 135 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 138 + // call R1, line 138 + if (!r_R1()) + { + return false; + } + // call C, line 138 + if (!r_C()) + { + return false; + } + // delete, line 138 + slice_del(); + // call lengthen_V, line 138 + if (!r_lengthen_V()) + { + return false; + } + break; + } + } while (false); + return true; + } + + private boolean r_Step_7() { + int among_var; + // (, line 144 + // [, line 145 + ket = cursor; + // among, line 145 + among_var = find_among_b(a_5, 3); + if (among_var == 0) + { + return false; + } + // (, line 145 + // ], line 145 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 146 + // <-, line 146 + slice_from("k"); + break; + case 2: + // (, line 147 + // <-, line 147 + slice_from("f"); + break; + case 3: + // (, line 148 + // <-, line 148 + slice_from("p"); + break; + } + return true; + } + + private boolean r_Step_6() { + int among_var; + // (, line 153 + // [, line 154 + ket = cursor; + // among, line 154 + among_var = find_among_b(a_6, 22); + if (among_var == 0) + { + return false; + } + // (, line 154 + // ], line 154 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 155 + // <-, line 155 + slice_from("b"); + break; + case 2: + // (, line 156 + // <-, line 156 + slice_from("c"); + break; + case 3: + // (, line 157 + // <-, line 157 + slice_from("d"); + break; + case 4: + // (, line 158 + // <-, line 158 + slice_from("f"); + break; + case 5: + // (, line 159 + // <-, line 159 + slice_from("g"); + break; + case 6: + // (, line 160 + // <-, line 160 + slice_from("h"); + break; + case 7: + // (, line 161 + // <-, line 161 + slice_from("j"); + break; + case 8: + // (, line 162 + // <-, line 162 + slice_from("k"); + break; + case 9: + // (, line 163 + // <-, line 163 + slice_from("l"); + break; + case 10: + // (, line 164 + // <-, line 164 + slice_from("m"); + break; + case 11: + // (, line 165 + // <-, line 165 + slice_from("n"); + break; + case 12: + // (, line 166 + // <-, line 166 + slice_from("p"); + break; + case 13: + // (, line 167 + // <-, line 167 + slice_from("q"); + break; + case 14: + // (, line 168 + // <-, line 168 + slice_from("r"); + break; + case 15: + // (, line 169 + // <-, line 169 + slice_from("s"); + break; + case 16: + // (, line 170 + // <-, line 170 + slice_from("t"); + break; + case 17: + // (, line 171 + // <-, line 171 + slice_from("v"); + break; + case 18: + // (, line 172 + // <-, line 172 + slice_from("w"); + break; + case 19: + // (, line 173 + // <-, line 173 + slice_from("x"); + break; + case 20: + // (, line 174 + // <-, line 174 + slice_from("z"); + break; + case 21: + // (, line 175 + // <-, line 175 + slice_from("f"); + break; + case 22: + // (, line 176 + // <-, line 176 + slice_from("s"); + break; + } + return true; + } + + private boolean r_Step_1c() { + int among_var; + int v_1; + int v_2; + // (, line 181 + // [, line 182 + ket = cursor; + // among, line 182 + among_var = find_among_b(a_7, 2); + if (among_var == 0) + { + return false; + } + // (, line 182 + // ], line 182 + bra = cursor; + // call R1, line 182 + if (!r_R1()) + { + return false; + } + // call C, line 182 + if (!r_C()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 183 + // not, line 183 + { + v_1 = limit - cursor; + lab0: do { + // (, line 183 + // literal, line 183 + if (!(eq_s_b(1, "n"))) + { + break lab0; + } + // call R1, line 183 + if (!r_R1()) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_1; + } + // delete, line 183 + slice_del(); + break; + case 2: + // (, line 184 + // not, line 184 + { + v_2 = limit - cursor; + lab1: do { + // (, line 184 + // literal, line 184 + if (!(eq_s_b(1, "h"))) + { + break lab1; + } + // call R1, line 184 + if (!r_R1()) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_2; + } + // delete, line 184 + slice_del(); + break; + } + return true; + } + + private boolean r_Lose_prefix() { + int v_1; + int v_2; + int v_3; + // (, line 189 + // [, line 190 + bra = cursor; + // literal, line 190 + if (!(eq_s(2, "ge"))) + { + return false; + } + // ], line 190 + ket = cursor; + // test, line 190 + v_1 = cursor; + // hop, line 190 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = v_1; + // (, line 190 + // goto, line 190 + golab0: while(true) + { + v_2 = cursor; + lab1: do { + if (!(in_grouping(g_v, 97, 121))) + { + break lab1; + } + cursor = v_2; + break golab0; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // goto, line 190 + golab2: while(true) + { + v_3 = cursor; + lab3: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab3; + } + cursor = v_3; + break golab2; + } while (false); + cursor = v_3; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // set GE_removed, line 191 + B_GE_removed = true; + // delete, line 192 + slice_del(); + return true; + } + + private boolean r_Lose_infix() { + int v_2; + int v_3; + int v_4; + // (, line 195 + // next, line 196 + if (cursor >= limit) + { + return false; + } + cursor++; + // gopast, line 197 + golab0: while(true) + { + lab1: do { + // (, line 197 + // [, line 197 + bra = cursor; + // literal, line 197 + if (!(eq_s(2, "ge"))) + { + break lab1; + } + // ], line 197 + ket = cursor; + break golab0; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // test, line 197 + v_2 = cursor; + // hop, line 197 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = v_2; + // (, line 197 + // goto, line 197 + golab2: while(true) + { + v_3 = cursor; + lab3: do { + if (!(in_grouping(g_v, 97, 121))) + { + break lab3; + } + cursor = v_3; + break golab2; + } while (false); + cursor = v_3; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // goto, line 197 + golab4: while(true) + { + v_4 = cursor; + lab5: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab5; + } + cursor = v_4; + break golab4; + } while (false); + cursor = v_4; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // set GE_removed, line 198 + B_GE_removed = true; + // delete, line 199 + slice_del(); + return true; + } + + private boolean r_measure() { + int v_1; + int v_2; + int v_5; + int v_6; + int v_9; + int v_10; + // (, line 202 + // do, line 203 + v_1 = cursor; + lab0: do { + // (, line 203 + // tolimit, line 204 + cursor = limit; + // setmark p1, line 205 + I_p1 = cursor; + // setmark p2, line 206 + I_p2 = cursor; + } while (false); + cursor = v_1; + // do, line 208 + v_2 = cursor; + lab1: do { + // (, line 208 + // repeat, line 209 + replab2: while(true) + { + lab3: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab3; + } + continue replab2; + } while (false); + break replab2; + } + // atleast, line 209 + { + int v_4 = 1; + // atleast, line 209 + replab4: while(true) + { + v_5 = cursor; + lab5: do { + // (, line 209 + // or, line 209 + lab6: do { + v_6 = cursor; + lab7: do { + // literal, line 209 + if (!(eq_s(2, "ij"))) + { + break lab7; + } + break lab6; + } while (false); + cursor = v_6; + if (!(in_grouping(g_v, 97, 121))) + { + break lab5; + } + } while (false); + v_4--; + continue replab4; + } while (false); + cursor = v_5; + break replab4; + } + if (v_4 > 0) + { + break lab1; + } + } + if (!(out_grouping(g_v, 97, 121))) + { + break lab1; + } + // setmark p1, line 209 + I_p1 = cursor; + // repeat, line 210 + replab8: while(true) + { + lab9: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab9; + } + continue replab8; + } while (false); + break replab8; + } + // atleast, line 210 + { + int v_8 = 1; + // atleast, line 210 + replab10: while(true) + { + v_9 = cursor; + lab11: do { + // (, line 210 + // or, line 210 + lab12: do { + v_10 = cursor; + lab13: do { + // literal, line 210 + if (!(eq_s(2, "ij"))) + { + break lab13; + } + break lab12; + } while (false); + cursor = v_10; + if (!(in_grouping(g_v, 97, 121))) + { + break lab11; + } + } while (false); + v_8--; + continue replab10; + } while (false); + cursor = v_9; + break replab10; + } + if (v_8 > 0) + { + break lab1; + } + } + if (!(out_grouping(g_v, 97, 121))) + { + break lab1; + } + // setmark p2, line 210 + I_p2 = cursor; + } while (false); + cursor = v_2; + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + int v_12; + int v_13; + int v_14; + int v_15; + int v_16; + int v_18; + int v_19; + int v_20; + // (, line 214 + // unset Y_found, line 216 + B_Y_found = false; + // unset stemmed, line 217 + B_stemmed = false; + // do, line 218 + v_1 = cursor; + lab0: do { + // (, line 218 + // [, line 218 + bra = cursor; + // literal, line 218 + if (!(eq_s(1, "y"))) + { + break lab0; + } + // ], line 218 + ket = cursor; + // <-, line 218 + slice_from("Y"); + // set Y_found, line 218 + B_Y_found = true; + } while (false); + cursor = v_1; + // do, line 219 + v_2 = cursor; + lab1: do { + // repeat, line 219 + replab2: while(true) + { + v_3 = cursor; + lab3: do { + // (, line 219 + // goto, line 219 + golab4: while(true) + { + v_4 = cursor; + lab5: do { + // (, line 219 + if (!(in_grouping(g_v, 97, 121))) + { + break lab5; + } + // [, line 219 + bra = cursor; + // literal, line 219 + if (!(eq_s(1, "y"))) + { + break lab5; + } + // ], line 219 + ket = cursor; + cursor = v_4; + break golab4; + } while (false); + cursor = v_4; + if (cursor >= limit) + { + break lab3; + } + cursor++; + } + // <-, line 219 + slice_from("Y"); + // set Y_found, line 219 + B_Y_found = true; + continue replab2; + } while (false); + cursor = v_3; + break replab2; + } + } while (false); + cursor = v_2; + // call measure, line 221 + if (!r_measure()) + { + return false; + } + // backwards, line 223 + limit_backward = cursor; cursor = limit; + // (, line 223 + // do, line 224 + v_5 = limit - cursor; + lab6: do { + // (, line 224 + // call Step_1, line 224 + if (!r_Step_1()) + { + break lab6; + } + // set stemmed, line 224 + B_stemmed = true; + } while (false); + cursor = limit - v_5; + // do, line 225 + v_6 = limit - cursor; + lab7: do { + // (, line 225 + // call Step_2, line 225 + if (!r_Step_2()) + { + break lab7; + } + // set stemmed, line 225 + B_stemmed = true; + } while (false); + cursor = limit - v_6; + // do, line 226 + v_7 = limit - cursor; + lab8: do { + // (, line 226 + // call Step_3, line 226 + if (!r_Step_3()) + { + break lab8; + } + // set stemmed, line 226 + B_stemmed = true; + } while (false); + cursor = limit - v_7; + // do, line 227 + v_8 = limit - cursor; + lab9: do { + // (, line 227 + // call Step_4, line 227 + if (!r_Step_4()) + { + break lab9; + } + // set stemmed, line 227 + B_stemmed = true; + } while (false); + cursor = limit - v_8; + cursor = limit_backward; // unset GE_removed, line 229 + B_GE_removed = false; + // do, line 230 + v_9 = cursor; + lab10: do { + // (, line 230 + // and, line 230 + v_10 = cursor; + // call Lose_prefix, line 230 + if (!r_Lose_prefix()) + { + break lab10; + } + cursor = v_10; + // call measure, line 230 + if (!r_measure()) + { + break lab10; + } + } while (false); + cursor = v_9; + // backwards, line 231 + limit_backward = cursor; cursor = limit; + // (, line 231 + // do, line 232 + v_11 = limit - cursor; + lab11: do { + // (, line 232 + // Boolean test GE_removed, line 232 + if (!(B_GE_removed)) + { + break lab11; + } + // call Step_1c, line 232 + if (!r_Step_1c()) + { + break lab11; + } + } while (false); + cursor = limit - v_11; + cursor = limit_backward; // unset GE_removed, line 234 + B_GE_removed = false; + // do, line 235 + v_12 = cursor; + lab12: do { + // (, line 235 + // and, line 235 + v_13 = cursor; + // call Lose_infix, line 235 + if (!r_Lose_infix()) + { + break lab12; + } + cursor = v_13; + // call measure, line 235 + if (!r_measure()) + { + break lab12; + } + } while (false); + cursor = v_12; + // backwards, line 236 + limit_backward = cursor; cursor = limit; + // (, line 236 + // do, line 237 + v_14 = limit - cursor; + lab13: do { + // (, line 237 + // Boolean test GE_removed, line 237 + if (!(B_GE_removed)) + { + break lab13; + } + // call Step_1c, line 237 + if (!r_Step_1c()) + { + break lab13; + } + } while (false); + cursor = limit - v_14; + cursor = limit_backward; // backwards, line 239 + limit_backward = cursor; cursor = limit; + // (, line 239 + // do, line 240 + v_15 = limit - cursor; + lab14: do { + // (, line 240 + // call Step_7, line 240 + if (!r_Step_7()) + { + break lab14; + } + // set stemmed, line 240 + B_stemmed = true; + } while (false); + cursor = limit - v_15; + // do, line 241 + v_16 = limit - cursor; + lab15: do { + // (, line 241 + // or, line 241 + lab16: do { + lab17: do { + // Boolean test stemmed, line 241 + if (!(B_stemmed)) + { + break lab17; + } + break lab16; + } while (false); + // Boolean test GE_removed, line 241 + if (!(B_GE_removed)) + { + break lab15; + } + } while (false); + // call Step_6, line 241 + if (!r_Step_6()) + { + break lab15; + } + } while (false); + cursor = limit - v_16; + cursor = limit_backward; // do, line 243 + v_18 = cursor; + lab18: do { + // (, line 243 + // Boolean test Y_found, line 243 + if (!(B_Y_found)) + { + break lab18; + } + // repeat, line 243 + replab19: while(true) + { + v_19 = cursor; + lab20: do { + // (, line 243 + // goto, line 243 + golab21: while(true) + { + v_20 = cursor; + lab22: do { + // (, line 243 + // [, line 243 + bra = cursor; + // literal, line 243 + if (!(eq_s(1, "Y"))) + { + break lab22; + } + // ], line 243 + ket = cursor; + cursor = v_20; + break golab21; + } while (false); + cursor = v_20; + if (cursor >= limit) + { + break lab20; + } + cursor++; + } + // <-, line 243 + slice_from("y"); + continue replab19; + } while (false); + cursor = v_19; + break replab19; + } + } while (false); + cursor = v_18; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/LovinsStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/LovinsStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/LovinsStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,1908 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class LovinsStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "d", -1, -1, "", this), + new Among ( "f", -1, -1, "", this), + new Among ( "ph", -1, -1, "", this), + new Among ( "th", -1, -1, "", this), + new Among ( "l", -1, -1, "", this), + new Among ( "er", -1, -1, "", this), + new Among ( "or", -1, -1, "", this), + new Among ( "es", -1, -1, "", this), + new Among ( "t", -1, -1, "", this) + }; + + private Among a_1[] = { + new Among ( "s'", -1, 1, "r_A", this), + new Among ( "a", -1, 1, "r_A", this), + new Among ( "ia", 1, 1, "r_A", this), + new Among ( "ata", 1, 1, "r_A", this), + new Among ( "ic", -1, 1, "r_A", this), + new Among ( "aic", 4, 1, "r_A", this), + new Among ( "allic", 4, 1, "r_BB", this), + new Among ( "aric", 4, 1, "r_A", this), + new Among ( "atic", 4, 1, "r_B", this), + new Among ( "itic", 4, 1, "r_H", this), + new Among ( "antic", 4, 1, "r_C", this), + new Among ( "istic", 4, 1, "r_A", this), + new Among ( "alistic", 11, 1, "r_B", this), + new Among ( "aristic", 11, 1, "r_A", this), + new Among ( "ivistic", 11, 1, "r_A", this), + new Among ( "ed", -1, 1, "r_E", this), + new Among ( "anced", 15, 1, "r_B", this), + new Among ( "enced", 15, 1, "r_A", this), + new Among ( "ished", 15, 1, "r_A", this), + new Among ( "ied", 15, 1, "r_A", this), + new Among ( "ened", 15, 1, "r_E", this), + new Among ( "ioned", 15, 1, "r_A", this), + new Among ( "ated", 15, 1, "r_I", this), + new Among ( "ented", 15, 1, "r_C", this), + new Among ( "ized", 15, 1, "r_F", this), + new Among ( "arized", 24, 1, "r_A", this), + new Among ( "oid", -1, 1, "r_A", this), + new Among ( "aroid", 26, 1, "r_A", this), + new Among ( "hood", -1, 1, "r_A", this), + new Among ( "ehood", 28, 1, "r_A", this), + new Among ( "ihood", 28, 1, "r_A", this), + new Among ( "elihood", 30, 1, "r_E", this), + new Among ( "ward", -1, 1, "r_A", this), + new Among ( "e", -1, 1, "r_A", this), + new Among ( "ae", 33, 1, "r_A", this), + new Among ( "ance", 33, 1, "r_B", this), + new Among ( "icance", 35, 1, "r_A", this), + new Among ( "ence", 33, 1, "r_A", this), + new Among ( "ide", 33, 1, "r_L", this), + new Among ( "icide", 38, 1, "r_A", this), + new Among ( "otide", 38, 1, "r_A", this), + new Among ( "age", 33, 1, "r_B", this), + new Among ( "able", 33, 1, "r_A", this), + new Among ( "atable", 42, 1, "r_A", this), + new Among ( "izable", 42, 1, "r_E", this), + new Among ( "arizable", 44, 1, "r_A", this), + new Among ( "ible", 33, 1, "r_A", this), + new Among ( "encible", 46, 1, "r_A", this), + new Among ( "ene", 33, 1, "r_E", this), + new Among ( "ine", 33, 1, "r_M", this), + new Among ( "idine", 49, 1, "r_I", this), + new Among ( "one", 33, 1, "r_R", this), + new Among ( "ature", 33, 1, "r_E", this), + new Among ( "eature", 52, 1, "r_Z", this), + new Among ( "ese", 33, 1, "r_A", this), + new Among ( "wise", 33, 1, "r_A", this), + new Among ( "ate", 33, 1, "r_A", this), + new Among ( "entiate", 56, 1, "r_A", this), + new Among ( "inate", 56, 1, "r_A", this), + new Among ( "ionate", 56, 1, "r_D", this), + new Among ( "ite", 33, 1, "r_AA", this), + new Among ( "ive", 33, 1, "r_A", this), + new Among ( "ative", 61, 1, "r_A", this), + new Among ( "ize", 33, 1, "r_F", this), + new Among ( "alize", 63, 1, "r_A", this), + new Among ( "icalize", 64, 1, "r_A", this), + new Among ( "ialize", 64, 1, "r_A", this), + new Among ( "entialize", 66, 1, "r_A", this), + new Among ( "ionalize", 64, 1, "r_A", this), + new Among ( "arize", 63, 1, "r_A", this), + new Among ( "ing", -1, 1, "r_N", this), + new Among ( "ancing", 70, 1, "r_B", this), + new Among ( "encing", 70, 1, "r_A", this), + new Among ( "aging", 70, 1, "r_B", this), + new Among ( "ening", 70, 1, "r_E", this), + new Among ( "ioning", 70, 1, "r_A", this), + new Among ( "ating", 70, 1, "r_I", this), + new Among ( "enting", 70, 1, "r_C", this), + new Among ( "ying", 70, 1, "r_B", this), + new Among ( "izing", 70, 1, "r_F", this), + new Among ( "arizing", 79, 1, "r_A", this), + new Among ( "ish", -1, 1, "r_C", this), + new Among ( "yish", 81, 1, "r_A", this), + new Among ( "i", -1, 1, "r_A", this), + new Among ( "al", -1, 1, "r_BB", this), + new Among ( "ical", 84, 1, "r_A", this), + new Among ( "aical", 85, 1, "r_A", this), + new Among ( "istical", 85, 1, "r_A", this), + new Among ( "oidal", 84, 1, "r_A", this), + new Among ( "eal", 84, 1, "r_Y", this), + new Among ( "ial", 84, 1, "r_A", this), + new Among ( "ancial", 90, 1, "r_A", this), + new Among ( "arial", 90, 1, "r_A", this), + new Among ( "ential", 90, 1, "r_A", this), + new Among ( "ional", 84, 1, "r_A", this), + new Among ( "ational", 94, 1, "r_B", this), + new Among ( "izational", 95, 1, "r_A", this), + new Among ( "ental", 84, 1, "r_A", this), + new Among ( "ful", -1, 1, "r_A", this), + new Among ( "eful", 98, 1, "r_A", this), + new Among ( "iful", 98, 1, "r_A", this), + new Among ( "yl", -1, 1, "r_R", this), + new Among ( "ism", -1, 1, "r_B", this), + new Among ( "icism", 102, 1, "r_A", this), + new Among ( "oidism", 102, 1, "r_A", this), + new Among ( "alism", 102, 1, "r_B", this), + new Among ( "icalism", 105, 1, "r_A", this), + new Among ( "ionalism", 105, 1, "r_A", this), + new Among ( "inism", 102, 1, "r_J", this), + new Among ( "ativism", 102, 1, "r_A", this), + new Among ( "um", -1, 1, "r_U", this), + new Among ( "ium", 110, 1, "r_A", this), + new Among ( "ian", -1, 1, "r_A", this), + new Among ( "ician", 112, 1, "r_A", this), + new Among ( "en", -1, 1, "r_F", this), + new Among ( "ogen", 114, 1, "r_A", this), + new Among ( "on", -1, 1, "r_S", this), + new Among ( "ion", 116, 1, "r_Q", this), + new Among ( "ation", 117, 1, "r_B", this), + new Among ( "ication", 118, 1, "r_G", this), + new Among ( "entiation", 118, 1, "r_A", this), + new Among ( "ination", 118, 1, "r_A", this), + new Among ( "isation", 118, 1, "r_A", this), + new Among ( "arisation", 122, 1, "r_A", this), + new Among ( "entation", 118, 1, "r_A", this), + new Among ( "ization", 118, 1, "r_F", this), + new Among ( "arization", 125, 1, "r_A", this), + new Among ( "action", 117, 1, "r_G", this), + new Among ( "o", -1, 1, "r_A", this), + new Among ( "ar", -1, 1, "r_X", this), + new Among ( "ear", 129, 1, "r_Y", this), + new Among ( "ier", -1, 1, "r_A", this), + new Among ( "ariser", -1, 1, "r_A", this), + new Among ( "izer", -1, 1, "r_F", this), + new Among ( "arizer", 133, 1, "r_A", this), + new Among ( "or", -1, 1, "r_T", this), + new Among ( "ator", 135, 1, "r_A", this), + new Among ( "s", -1, 1, "r_W", this), + new Among ( "'s", 137, 1, "r_A", this), + new Among ( "as", 137, 1, "r_B", this), + new Among ( "ics", 137, 1, "r_A", this), + new Among ( "istics", 140, 1, "r_A", this), + new Among ( "es", 137, 1, "r_E", this), + new Among ( "ances", 142, 1, "r_B", this), + new Among ( "ences", 142, 1, "r_A", this), + new Among ( "ides", 142, 1, "r_L", this), + new Among ( "oides", 145, 1, "r_A", this), + new Among ( "ages", 142, 1, "r_B", this), + new Among ( "ies", 142, 1, "r_P", this), + new Among ( "acies", 148, 1, "r_A", this), + new Among ( "ancies", 148, 1, "r_A", this), + new Among ( "encies", 148, 1, "r_A", this), + new Among ( "aries", 148, 1, "r_A", this), + new Among ( "ities", 148, 1, "r_A", this), + new Among ( "alities", 153, 1, "r_A", this), + new Among ( "ivities", 153, 1, "r_A", this), + new Among ( "ines", 142, 1, "r_M", this), + new Among ( "nesses", 142, 1, "r_A", this), + new Among ( "ates", 142, 1, "r_A", this), + new Among ( "atives", 142, 1, "r_A", this), + new Among ( "ings", 137, 1, "r_N", this), + new Among ( "is", 137, 1, "r_A", this), + new Among ( "als", 137, 1, "r_BB", this), + new Among ( "ials", 162, 1, "r_A", this), + new Among ( "entials", 163, 1, "r_A", this), + new Among ( "ionals", 162, 1, "r_A", this), + new Among ( "isms", 137, 1, "r_B", this), + new Among ( "ians", 137, 1, "r_A", this), + new Among ( "icians", 167, 1, "r_A", this), + new Among ( "ions", 137, 1, "r_B", this), + new Among ( "ations", 169, 1, "r_B", this), + new Among ( "arisations", 170, 1, "r_A", this), + new Among ( "entations", 170, 1, "r_A", this), + new Among ( "izations", 170, 1, "r_A", this), + new Among ( "arizations", 173, 1, "r_A", this), + new Among ( "ars", 137, 1, "r_O", this), + new Among ( "iers", 137, 1, "r_A", this), + new Among ( "izers", 137, 1, "r_F", this), + new Among ( "ators", 137, 1, "r_A", this), + new Among ( "less", 137, 1, "r_A", this), + new Among ( "eless", 179, 1, "r_A", this), + new Among ( "ness", 137, 1, "r_A", this), + new Among ( "eness", 181, 1, "r_E", this), + new Among ( "ableness", 182, 1, "r_A", this), + new Among ( "eableness", 183, 1, "r_E", this), + new Among ( "ibleness", 182, 1, "r_A", this), + new Among ( "ateness", 182, 1, "r_A", this), + new Among ( "iteness", 182, 1, "r_A", this), + new Among ( "iveness", 182, 1, "r_A", this), + new Among ( "ativeness", 188, 1, "r_A", this), + new Among ( "ingness", 181, 1, "r_A", this), + new Among ( "ishness", 181, 1, "r_A", this), + new Among ( "iness", 181, 1, "r_A", this), + new Among ( "ariness", 192, 1, "r_E", this), + new Among ( "alness", 181, 1, "r_A", this), + new Among ( "icalness", 194, 1, "r_A", this), + new Among ( "antialness", 194, 1, "r_A", this), + new Among ( "entialness", 194, 1, "r_A", this), + new Among ( "ionalness", 194, 1, "r_A", this), + new Among ( "fulness", 181, 1, "r_A", this), + new Among ( "lessness", 181, 1, "r_A", this), + new Among ( "ousness", 181, 1, "r_A", this), + new Among ( "eousness", 201, 1, "r_A", this), + new Among ( "iousness", 201, 1, "r_A", this), + new Among ( "itousness", 201, 1, "r_A", this), + new Among ( "entness", 181, 1, "r_A", this), + new Among ( "ants", 137, 1, "r_B", this), + new Among ( "ists", 137, 1, "r_A", this), + new Among ( "icists", 207, 1, "r_A", this), + new Among ( "us", 137, 1, "r_V", this), + new Among ( "ous", 209, 1, "r_A", this), + new Among ( "eous", 210, 1, "r_A", this), + new Among ( "aceous", 211, 1, "r_A", this), + new Among ( "antaneous", 211, 1, "r_A", this), + new Among ( "ious", 210, 1, "r_A", this), + new Among ( "acious", 214, 1, "r_B", this), + new Among ( "itous", 210, 1, "r_A", this), + new Among ( "ant", -1, 1, "r_B", this), + new Among ( "icant", 217, 1, "r_A", this), + new Among ( "ent", -1, 1, "r_C", this), + new Among ( "ement", 219, 1, "r_A", this), + new Among ( "izement", 220, 1, "r_A", this), + new Among ( "ist", -1, 1, "r_A", this), + new Among ( "icist", 222, 1, "r_A", this), + new Among ( "alist", 222, 1, "r_A", this), + new Among ( "icalist", 224, 1, "r_A", this), + new Among ( "ialist", 224, 1, "r_A", this), + new Among ( "ionist", 222, 1, "r_A", this), + new Among ( "entist", 222, 1, "r_A", this), + new Among ( "y", -1, 1, "r_B", this), + new Among ( "acy", 229, 1, "r_A", this), + new Among ( "ancy", 229, 1, "r_B", this), + new Among ( "ency", 229, 1, "r_A", this), + new Among ( "ly", 229, 1, "r_B", this), + new Among ( "ealy", 233, 1, "r_Y", this), + new Among ( "ably", 233, 1, "r_A", this), + new Among ( "ibly", 233, 1, "r_A", this), + new Among ( "edly", 233, 1, "r_E", this), + new Among ( "iedly", 237, 1, "r_A", this), + new Among ( "ely", 233, 1, "r_E", this), + new Among ( "ately", 239, 1, "r_A", this), + new Among ( "ively", 239, 1, "r_A", this), + new Among ( "atively", 241, 1, "r_A", this), + new Among ( "ingly", 233, 1, "r_B", this), + new Among ( "atingly", 243, 1, "r_A", this), + new Among ( "ily", 233, 1, "r_A", this), + new Among ( "lily", 245, 1, "r_A", this), + new Among ( "arily", 245, 1, "r_A", this), + new Among ( "ally", 233, 1, "r_B", this), + new Among ( "ically", 248, 1, "r_A", this), + new Among ( "aically", 249, 1, "r_A", this), + new Among ( "allically", 249, 1, "r_C", this), + new Among ( "istically", 249, 1, "r_A", this), + new Among ( "alistically", 252, 1, "r_B", this), + new Among ( "oidally", 248, 1, "r_A", this), + new Among ( "ially", 248, 1, "r_A", this), + new Among ( "entially", 255, 1, "r_A", this), + new Among ( "ionally", 248, 1, "r_A", this), + new Among ( "ationally", 257, 1, "r_B", this), + new Among ( "izationally", 258, 1, "r_B", this), + new Among ( "entally", 248, 1, "r_A", this), + new Among ( "fully", 233, 1, "r_A", this), + new Among ( "efully", 261, 1, "r_A", this), + new Among ( "ifully", 261, 1, "r_A", this), + new Among ( "enly", 233, 1, "r_E", this), + new Among ( "arly", 233, 1, "r_K", this), + new Among ( "early", 265, 1, "r_Y", this), + new Among ( "lessly", 233, 1, "r_A", this), + new Among ( "ously", 233, 1, "r_A", this), + new Among ( "eously", 268, 1, "r_A", this), + new Among ( "iously", 268, 1, "r_A", this), + new Among ( "ently", 233, 1, "r_A", this), + new Among ( "ary", 229, 1, "r_F", this), + new Among ( "ery", 229, 1, "r_E", this), + new Among ( "icianry", 229, 1, "r_A", this), + new Among ( "atory", 229, 1, "r_A", this), + new Among ( "ity", 229, 1, "r_A", this), + new Among ( "acity", 276, 1, "r_A", this), + new Among ( "icity", 276, 1, "r_A", this), + new Among ( "eity", 276, 1, "r_A", this), + new Among ( "ality", 276, 1, "r_A", this), + new Among ( "icality", 280, 1, "r_A", this), + new Among ( "iality", 280, 1, "r_A", this), + new Among ( "antiality", 282, 1, "r_A", this), + new Among ( "entiality", 282, 1, "r_A", this), + new Among ( "ionality", 280, 1, "r_A", this), + new Among ( "elity", 276, 1, "r_A", this), + new Among ( "ability", 276, 1, "r_A", this), + new Among ( "izability", 287, 1, "r_A", this), + new Among ( "arizability", 288, 1, "r_A", this), + new Among ( "ibility", 276, 1, "r_A", this), + new Among ( "inity", 276, 1, "r_CC", this), + new Among ( "arity", 276, 1, "r_B", this), + new Among ( "ivity", 276, 1, "r_A", this) + }; + + private Among a_2[] = { + new Among ( "bb", -1, -1, "", this), + new Among ( "dd", -1, -1, "", this), + new Among ( "gg", -1, -1, "", this), + new Among ( "ll", -1, -1, "", this), + new Among ( "mm", -1, -1, "", this), + new Among ( "nn", -1, -1, "", this), + new Among ( "pp", -1, -1, "", this), + new Among ( "rr", -1, -1, "", this), + new Among ( "ss", -1, -1, "", this), + new Among ( "tt", -1, -1, "", this) + }; + + private Among a_3[] = { + new Among ( "uad", -1, 18, "", this), + new Among ( "vad", -1, 19, "", this), + new Among ( "cid", -1, 20, "", this), + new Among ( "lid", -1, 21, "", this), + new Among ( "erid", -1, 22, "", this), + new Among ( "pand", -1, 23, "", this), + new Among ( "end", -1, 24, "", this), + new Among ( "ond", -1, 25, "", this), + new Among ( "lud", -1, 26, "", this), + new Among ( "rud", -1, 27, "", this), + new Among ( "ul", -1, 9, "", this), + new Among ( "her", -1, 28, "", this), + new Among ( "metr", -1, 7, "", this), + new Among ( "istr", -1, 6, "", this), + new Among ( "urs", -1, 5, "", this), + new Among ( "uct", -1, 2, "", this), + new Among ( "et", -1, 32, "", this), + new Among ( "mit", -1, 29, "", this), + new Among ( "ent", -1, 30, "", this), + new Among ( "umpt", -1, 3, "", this), + new Among ( "rpt", -1, 4, "", this), + new Among ( "ert", -1, 31, "", this), + new Among ( "yt", -1, 33, "", this), + new Among ( "iev", -1, 1, "", this), + new Among ( "olv", -1, 8, "", this), + new Among ( "ax", -1, 14, "", this), + new Among ( "ex", -1, 15, "", this), + new Among ( "bex", 26, 10, "", this), + new Among ( "dex", 26, 11, "", this), + new Among ( "pex", 26, 12, "", this), + new Among ( "tex", 26, 13, "", this), + new Among ( "ix", -1, 16, "", this), + new Among ( "lux", -1, 17, "", this), + new Among ( "yz", -1, 34, "", this) + }; + + + private void copy_from(LovinsStemmer other) { + super.copy_from(other); + } + + private boolean r_A() { + // (, line 21 + // hop, line 21 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + return true; + } + + private boolean r_B() { + // (, line 22 + // hop, line 22 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + return true; + } + + private boolean r_C() { + // (, line 23 + // hop, line 23 + { + int c = cursor - 4; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + return true; + } + + private boolean r_D() { + // (, line 24 + // hop, line 24 + { + int c = cursor - 5; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + return true; + } + + private boolean r_E() { + int v_1; + int v_2; + // (, line 25 + // test, line 25 + v_1 = limit - cursor; + // hop, line 25 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 25 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 25 + if (!(eq_s_b(1, "e"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + return true; + } + + private boolean r_F() { + int v_1; + int v_2; + // (, line 26 + // test, line 26 + v_1 = limit - cursor; + // hop, line 26 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 26 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 26 + if (!(eq_s_b(1, "e"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + return true; + } + + private boolean r_G() { + int v_1; + // (, line 27 + // test, line 27 + v_1 = limit - cursor; + // hop, line 27 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // literal, line 27 + if (!(eq_s_b(1, "f"))) + { + return false; + } + return true; + } + + private boolean r_H() { + int v_1; + int v_2; + // (, line 28 + // test, line 28 + v_1 = limit - cursor; + // hop, line 28 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 28 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 28 + if (!(eq_s_b(1, "t"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // literal, line 28 + if (!(eq_s_b(2, "ll"))) + { + return false; + } + } while (false); + return true; + } + + private boolean r_I() { + int v_1; + int v_2; + int v_3; + // (, line 29 + // test, line 29 + v_1 = limit - cursor; + // hop, line 29 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 29 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 29 + if (!(eq_s_b(1, "o"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + // not, line 29 + { + v_3 = limit - cursor; + lab1: do { + // literal, line 29 + if (!(eq_s_b(1, "e"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_3; + } + return true; + } + + private boolean r_J() { + int v_1; + int v_2; + int v_3; + // (, line 30 + // test, line 30 + v_1 = limit - cursor; + // hop, line 30 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 30 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 30 + if (!(eq_s_b(1, "a"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + // not, line 30 + { + v_3 = limit - cursor; + lab1: do { + // literal, line 30 + if (!(eq_s_b(1, "e"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_3; + } + return true; + } + + private boolean r_K() { + int v_1; + int v_2; + // (, line 31 + // test, line 31 + v_1 = limit - cursor; + // hop, line 31 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 31 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 31 + if (!(eq_s_b(1, "l"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + lab2: do { + // literal, line 31 + if (!(eq_s_b(1, "i"))) + { + break lab2; + } + break lab0; + } while (false); + cursor = limit - v_2; + // (, line 31 + // literal, line 31 + if (!(eq_s_b(1, "e"))) + { + return false; + } + // next, line 31 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // literal, line 31 + if (!(eq_s_b(1, "u"))) + { + return false; + } + } while (false); + return true; + } + + private boolean r_L() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 32 + // test, line 32 + v_1 = limit - cursor; + // hop, line 32 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 32 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 32 + if (!(eq_s_b(1, "u"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + // not, line 32 + { + v_3 = limit - cursor; + lab1: do { + // literal, line 32 + if (!(eq_s_b(1, "x"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_3; + } + // not, line 32 + { + v_4 = limit - cursor; + lab2: do { + // (, line 32 + // literal, line 32 + if (!(eq_s_b(1, "s"))) + { + break lab2; + } + // not, line 32 + { + v_5 = limit - cursor; + lab3: do { + // literal, line 32 + if (!(eq_s_b(1, "o"))) + { + break lab3; + } + break lab2; + } while (false); + cursor = limit - v_5; + } + return false; + } while (false); + cursor = limit - v_4; + } + return true; + } + + private boolean r_M() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 33 + // test, line 33 + v_1 = limit - cursor; + // hop, line 33 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 33 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 33 + if (!(eq_s_b(1, "a"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + // not, line 33 + { + v_3 = limit - cursor; + lab1: do { + // literal, line 33 + if (!(eq_s_b(1, "c"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_3; + } + // not, line 33 + { + v_4 = limit - cursor; + lab2: do { + // literal, line 33 + if (!(eq_s_b(1, "e"))) + { + break lab2; + } + return false; + } while (false); + cursor = limit - v_4; + } + // not, line 33 + { + v_5 = limit - cursor; + lab3: do { + // literal, line 33 + if (!(eq_s_b(1, "m"))) + { + break lab3; + } + return false; + } while (false); + cursor = limit - v_5; + } + return true; + } + + private boolean r_N() { + int v_1; + int v_2; + int v_3; + // (, line 34 + // test, line 34 + v_1 = limit - cursor; + // hop, line 34 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // (, line 34 + // hop, line 34 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + // or, line 34 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // not, line 34 + { + v_3 = limit - cursor; + lab2: do { + // literal, line 34 + if (!(eq_s_b(1, "s"))) + { + break lab2; + } + break lab1; + } while (false); + cursor = limit - v_3; + } + break lab0; + } while (false); + cursor = limit - v_2; + // hop, line 34 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + } while (false); + return true; + } + + private boolean r_O() { + int v_1; + int v_2; + // (, line 35 + // test, line 35 + v_1 = limit - cursor; + // hop, line 35 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 35 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 35 + if (!(eq_s_b(1, "l"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // literal, line 35 + if (!(eq_s_b(1, "i"))) + { + return false; + } + } while (false); + return true; + } + + private boolean r_P() { + int v_1; + int v_2; + // (, line 36 + // test, line 36 + v_1 = limit - cursor; + // hop, line 36 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 36 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 36 + if (!(eq_s_b(1, "c"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + return true; + } + + private boolean r_Q() { + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 37 + // test, line 37 + v_1 = limit - cursor; + // hop, line 37 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // test, line 37 + v_2 = limit - cursor; + // hop, line 37 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_2; + // not, line 37 + { + v_3 = limit - cursor; + lab0: do { + // literal, line 37 + if (!(eq_s_b(1, "l"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_3; + } + // not, line 37 + { + v_4 = limit - cursor; + lab1: do { + // literal, line 37 + if (!(eq_s_b(1, "n"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_4; + } + return true; + } + + private boolean r_R() { + int v_1; + int v_2; + // (, line 38 + // test, line 38 + v_1 = limit - cursor; + // hop, line 38 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 38 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 38 + if (!(eq_s_b(1, "n"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // literal, line 38 + if (!(eq_s_b(1, "r"))) + { + return false; + } + } while (false); + return true; + } + + private boolean r_S() { + int v_1; + int v_2; + int v_3; + // (, line 39 + // test, line 39 + v_1 = limit - cursor; + // hop, line 39 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 39 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 39 + if (!(eq_s_b(2, "dr"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // (, line 39 + // literal, line 39 + if (!(eq_s_b(1, "t"))) + { + return false; + } + // not, line 39 + { + v_3 = limit - cursor; + lab2: do { + // literal, line 39 + if (!(eq_s_b(1, "t"))) + { + break lab2; + } + return false; + } while (false); + cursor = limit - v_3; + } + } while (false); + return true; + } + + private boolean r_T() { + int v_1; + int v_2; + int v_3; + // (, line 40 + // test, line 40 + v_1 = limit - cursor; + // hop, line 40 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 40 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 40 + if (!(eq_s_b(1, "s"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // (, line 40 + // literal, line 40 + if (!(eq_s_b(1, "t"))) + { + return false; + } + // not, line 40 + { + v_3 = limit - cursor; + lab2: do { + // literal, line 40 + if (!(eq_s_b(1, "o"))) + { + break lab2; + } + return false; + } while (false); + cursor = limit - v_3; + } + } while (false); + return true; + } + + private boolean r_U() { + int v_1; + int v_2; + // (, line 41 + // test, line 41 + v_1 = limit - cursor; + // hop, line 41 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 41 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 41 + if (!(eq_s_b(1, "l"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + lab2: do { + // literal, line 41 + if (!(eq_s_b(1, "m"))) + { + break lab2; + } + break lab0; + } while (false); + cursor = limit - v_2; + lab3: do { + // literal, line 41 + if (!(eq_s_b(1, "n"))) + { + break lab3; + } + break lab0; + } while (false); + cursor = limit - v_2; + // literal, line 41 + if (!(eq_s_b(1, "r"))) + { + return false; + } + } while (false); + return true; + } + + private boolean r_V() { + int v_1; + // (, line 42 + // test, line 42 + v_1 = limit - cursor; + // hop, line 42 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // literal, line 42 + if (!(eq_s_b(1, "c"))) + { + return false; + } + return true; + } + + private boolean r_W() { + int v_1; + int v_2; + int v_3; + // (, line 43 + // test, line 43 + v_1 = limit - cursor; + // hop, line 43 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 43 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 43 + if (!(eq_s_b(1, "s"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + // not, line 43 + { + v_3 = limit - cursor; + lab1: do { + // literal, line 43 + if (!(eq_s_b(1, "u"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_3; + } + return true; + } + + private boolean r_X() { + int v_1; + int v_2; + // (, line 44 + // test, line 44 + v_1 = limit - cursor; + // hop, line 44 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // or, line 44 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 44 + if (!(eq_s_b(1, "l"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + lab2: do { + // literal, line 44 + if (!(eq_s_b(1, "i"))) + { + break lab2; + } + break lab0; + } while (false); + cursor = limit - v_2; + // (, line 44 + // literal, line 44 + if (!(eq_s_b(1, "e"))) + { + return false; + } + // next, line 44 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // literal, line 44 + if (!(eq_s_b(1, "u"))) + { + return false; + } + } while (false); + return true; + } + + private boolean r_Y() { + int v_1; + // (, line 45 + // test, line 45 + v_1 = limit - cursor; + // hop, line 45 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // literal, line 45 + if (!(eq_s_b(2, "in"))) + { + return false; + } + return true; + } + + private boolean r_Z() { + int v_1; + int v_2; + // (, line 46 + // test, line 46 + v_1 = limit - cursor; + // hop, line 46 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 46 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 46 + if (!(eq_s_b(1, "f"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + return true; + } + + private boolean r_AA() { + int v_1; + // (, line 47 + // test, line 47 + v_1 = limit - cursor; + // hop, line 47 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // among, line 47 + if (find_among_b(a_0, 9) == 0) + { + return false; + } + return true; + } + + private boolean r_BB() { + int v_1; + int v_2; + int v_3; + // (, line 49 + // test, line 49 + v_1 = limit - cursor; + // hop, line 49 + { + int c = cursor - 3; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // not, line 49 + { + v_2 = limit - cursor; + lab0: do { + // literal, line 49 + if (!(eq_s_b(3, "met"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_2; + } + // not, line 49 + { + v_3 = limit - cursor; + lab1: do { + // literal, line 49 + if (!(eq_s_b(4, "ryst"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_3; + } + return true; + } + + private boolean r_CC() { + int v_1; + // (, line 50 + // test, line 50 + v_1 = limit - cursor; + // hop, line 50 + { + int c = cursor - 2; + if (limit_backward > c || c > limit) + { + return false; + } + cursor = c; + } + cursor = limit - v_1; + // literal, line 50 + if (!(eq_s_b(1, "l"))) + { + return false; + } + return true; + } + + private boolean r_endings() { + int among_var; + // (, line 55 + // [, line 56 + ket = cursor; + // substring, line 56 + among_var = find_among_b(a_1, 294); + if (among_var == 0) + { + return false; + } + // ], line 56 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 145 + // delete, line 145 + slice_del(); + break; + } + return true; + } + + private boolean r_undouble() { + int v_1; + // (, line 151 + // test, line 152 + v_1 = limit - cursor; + // substring, line 152 + if (find_among_b(a_2, 10) == 0) + { + return false; + } + cursor = limit - v_1; + // [, line 154 + ket = cursor; + // next, line 154 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 154 + bra = cursor; + // delete, line 154 + slice_del(); + return true; + } + + private boolean r_respell() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + // (, line 159 + // [, line 160 + ket = cursor; + // substring, line 160 + among_var = find_among_b(a_3, 34); + if (among_var == 0) + { + return false; + } + // ], line 160 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 161 + // <-, line 161 + slice_from("ief"); + break; + case 2: + // (, line 162 + // <-, line 162 + slice_from("uc"); + break; + case 3: + // (, line 163 + // <-, line 163 + slice_from("um"); + break; + case 4: + // (, line 164 + // <-, line 164 + slice_from("rb"); + break; + case 5: + // (, line 165 + // <-, line 165 + slice_from("ur"); + break; + case 6: + // (, line 166 + // <-, line 166 + slice_from("ister"); + break; + case 7: + // (, line 167 + // <-, line 167 + slice_from("meter"); + break; + case 8: + // (, line 168 + // <-, line 168 + slice_from("olut"); + break; + case 9: + // (, line 169 + // not, line 169 + { + v_1 = limit - cursor; + lab0: do { + // literal, line 169 + if (!(eq_s_b(1, "a"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_1; + } + // not, line 169 + { + v_2 = limit - cursor; + lab1: do { + // literal, line 169 + if (!(eq_s_b(1, "i"))) + { + break lab1; + } + return false; + } while (false); + cursor = limit - v_2; + } + // not, line 169 + { + v_3 = limit - cursor; + lab2: do { + // literal, line 169 + if (!(eq_s_b(1, "o"))) + { + break lab2; + } + return false; + } while (false); + cursor = limit - v_3; + } + // <-, line 169 + slice_from("l"); + break; + case 10: + // (, line 170 + // <-, line 170 + slice_from("bic"); + break; + case 11: + // (, line 171 + // <-, line 171 + slice_from("dic"); + break; + case 12: + // (, line 172 + // <-, line 172 + slice_from("pic"); + break; + case 13: + // (, line 173 + // <-, line 173 + slice_from("tic"); + break; + case 14: + // (, line 174 + // <-, line 174 + slice_from("ac"); + break; + case 15: + // (, line 175 + // <-, line 175 + slice_from("ec"); + break; + case 16: + // (, line 176 + // <-, line 176 + slice_from("ic"); + break; + case 17: + // (, line 177 + // <-, line 177 + slice_from("luc"); + break; + case 18: + // (, line 178 + // <-, line 178 + slice_from("uas"); + break; + case 19: + // (, line 179 + // <-, line 179 + slice_from("vas"); + break; + case 20: + // (, line 180 + // <-, line 180 + slice_from("cis"); + break; + case 21: + // (, line 181 + // <-, line 181 + slice_from("lis"); + break; + case 22: + // (, line 182 + // <-, line 182 + slice_from("eris"); + break; + case 23: + // (, line 183 + // <-, line 183 + slice_from("pans"); + break; + case 24: + // (, line 184 + // not, line 184 + { + v_4 = limit - cursor; + lab3: do { + // literal, line 184 + if (!(eq_s_b(1, "s"))) + { + break lab3; + } + return false; + } while (false); + cursor = limit - v_4; + } + // <-, line 184 + slice_from("ens"); + break; + case 25: + // (, line 185 + // <-, line 185 + slice_from("ons"); + break; + case 26: + // (, line 186 + // <-, line 186 + slice_from("lus"); + break; + case 27: + // (, line 187 + // <-, line 187 + slice_from("rus"); + break; + case 28: + // (, line 188 + // not, line 188 + { + v_5 = limit - cursor; + lab4: do { + // literal, line 188 + if (!(eq_s_b(1, "p"))) + { + break lab4; + } + return false; + } while (false); + cursor = limit - v_5; + } + // not, line 188 + { + v_6 = limit - cursor; + lab5: do { + // literal, line 188 + if (!(eq_s_b(1, "t"))) + { + break lab5; + } + return false; + } while (false); + cursor = limit - v_6; + } + // <-, line 188 + slice_from("hes"); + break; + case 29: + // (, line 189 + // <-, line 189 + slice_from("mis"); + break; + case 30: + // (, line 190 + // not, line 190 + { + v_7 = limit - cursor; + lab6: do { + // literal, line 190 + if (!(eq_s_b(1, "m"))) + { + break lab6; + } + return false; + } while (false); + cursor = limit - v_7; + } + // <-, line 190 + slice_from("ens"); + break; + case 31: + // (, line 192 + // <-, line 192 + slice_from("ers"); + break; + case 32: + // (, line 193 + // not, line 193 + { + v_8 = limit - cursor; + lab7: do { + // literal, line 193 + if (!(eq_s_b(1, "n"))) + { + break lab7; + } + return false; + } while (false); + cursor = limit - v_8; + } + // <-, line 193 + slice_from("es"); + break; + case 33: + // (, line 194 + // <-, line 194 + slice_from("ys"); + break; + case 34: + // (, line 195 + // <-, line 195 + slice_from("ys"); + break; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + // (, line 200 + // backwards, line 202 + limit_backward = cursor; cursor = limit; + // (, line 202 + // do, line 203 + v_1 = limit - cursor; + lab0: do { + // call endings, line 203 + if (!r_endings()) + { + break lab0; + } + } while (false); + cursor = limit - v_1; + // do, line 204 + v_2 = limit - cursor; + lab1: do { + // call undouble, line 204 + if (!r_undouble()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 205 + v_3 = limit - cursor; + lab2: do { + // call respell, line 205 + if (!r_respell()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + cursor = limit_backward; return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/NorwegianStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/NorwegianStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/NorwegianStemmer.java 17 Aug 2012 14:55:08 -0000 1.1 @@ -0,0 +1,358 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class NorwegianStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "a", -1, 1, "", this), + new Among ( "e", -1, 1, "", this), + new Among ( "ede", 1, 1, "", this), + new Among ( "ande", 1, 1, "", this), + new Among ( "ende", 1, 1, "", this), + new Among ( "ane", 1, 1, "", this), + new Among ( "ene", 1, 1, "", this), + new Among ( "hetene", 6, 1, "", this), + new Among ( "erte", 1, 3, "", this), + new Among ( "en", -1, 1, "", this), + new Among ( "heten", 9, 1, "", this), + new Among ( "ar", -1, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "heter", 12, 1, "", this), + new Among ( "s", -1, 2, "", this), + new Among ( "as", 14, 1, "", this), + new Among ( "es", 14, 1, "", this), + new Among ( "edes", 16, 1, "", this), + new Among ( "endes", 16, 1, "", this), + new Among ( "enes", 16, 1, "", this), + new Among ( "hetenes", 19, 1, "", this), + new Among ( "ens", 14, 1, "", this), + new Among ( "hetens", 21, 1, "", this), + new Among ( "ers", 14, 1, "", this), + new Among ( "ets", 14, 1, "", this), + new Among ( "et", -1, 1, "", this), + new Among ( "het", 25, 1, "", this), + new Among ( "ert", -1, 3, "", this), + new Among ( "ast", -1, 1, "", this) + }; + + private Among a_1[] = { + new Among ( "dt", -1, -1, "", this), + new Among ( "vt", -1, -1, "", this) + }; + + private Among a_2[] = { + new Among ( "leg", -1, 1, "", this), + new Among ( "eleg", 0, 1, "", this), + new Among ( "ig", -1, 1, "", this), + new Among ( "eig", 2, 1, "", this), + new Among ( "lig", 2, 1, "", this), + new Among ( "elig", 4, 1, "", this), + new Among ( "els", -1, 1, "", this), + new Among ( "lov", -1, 1, "", this), + new Among ( "elov", 7, 1, "", this), + new Among ( "slov", 7, 1, "", this), + new Among ( "hetslov", 9, 1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 128 }; + + private static final char g_s_ending[] = {119, 125, 149, 1 }; + + private int I_x; + private int I_p1; + + private void copy_from(NorwegianStemmer other) { + I_x = other.I_x; + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + // (, line 26 + I_p1 = limit; + // test, line 30 + v_1 = cursor; + // (, line 30 + // hop, line 30 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + return false; + } + cursor = c; + } + // setmark x, line 30 + I_x = cursor; + cursor = v_1; + // goto, line 31 + golab0: while(true) + { + v_2 = cursor; + lab1: do { + if (!(in_grouping(g_v, 97, 248))) + { + break lab1; + } + cursor = v_2; + break golab0; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 31 + golab2: while(true) + { + lab3: do { + if (!(out_grouping(g_v, 97, 248))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 31 + I_p1 = cursor; + // try, line 32 + lab4: do { + // (, line 32 + if (!(I_p1 < I_x)) + { + break lab4; + } + I_p1 = I_x; + } while (false); + return true; + } + + private boolean r_main_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + // (, line 37 + // setlimit, line 38 + v_1 = limit - cursor; + // tomark, line 38 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 38 + // [, line 38 + ket = cursor; + // substring, line 38 + among_var = find_among_b(a_0, 29); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 38 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 44 + // delete, line 44 + slice_del(); + break; + case 2: + // (, line 46 + // or, line 46 + lab0: do { + v_3 = limit - cursor; + lab1: do { + if (!(in_grouping_b(g_s_ending, 98, 122))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_3; + // (, line 46 + // literal, line 46 + if (!(eq_s_b(1, "k"))) + { + return false; + } + if (!(out_grouping_b(g_v, 97, 248))) + { + return false; + } + } while (false); + // delete, line 46 + slice_del(); + break; + case 3: + // (, line 48 + // <-, line 48 + slice_from("er"); + break; + } + return true; + } + + private boolean r_consonant_pair() { + int v_1; + int v_2; + int v_3; + // (, line 52 + // test, line 53 + v_1 = limit - cursor; + // (, line 53 + // setlimit, line 54 + v_2 = limit - cursor; + // tomark, line 54 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_3 = limit_backward; + limit_backward = cursor; + cursor = limit - v_2; + // (, line 54 + // [, line 54 + ket = cursor; + // substring, line 54 + if (find_among_b(a_1, 2) == 0) + { + limit_backward = v_3; + return false; + } + // ], line 54 + bra = cursor; + limit_backward = v_3; + cursor = limit - v_1; + // next, line 59 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 59 + bra = cursor; + // delete, line 59 + slice_del(); + return true; + } + + private boolean r_other_suffix() { + int among_var; + int v_1; + int v_2; + // (, line 62 + // setlimit, line 63 + v_1 = limit - cursor; + // tomark, line 63 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 63 + // [, line 63 + ket = cursor; + // substring, line 63 + among_var = find_among_b(a_2, 11); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 63 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 67 + // delete, line 67 + slice_del(); + break; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 72 + // do, line 74 + v_1 = cursor; + lab0: do { + // call mark_regions, line 74 + if (!r_mark_regions()) + { + break lab0; + } + } while (false); + cursor = v_1; + // backwards, line 75 + limit_backward = cursor; cursor = limit; + // (, line 75 + // do, line 76 + v_2 = limit - cursor; + lab1: do { + // call main_suffix, line 76 + if (!r_main_suffix()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 77 + v_3 = limit - cursor; + lab2: do { + // call consonant_pair, line 77 + if (!r_consonant_pair()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 78 + v_4 = limit - cursor; + lab3: do { + // call other_suffix, line 78 + if (!r_other_suffix()) + { + break lab3; + } + } while (false); + cursor = limit - v_4; + cursor = limit_backward; return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/PorterStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/PorterStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/PorterStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,906 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class PorterStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "s", -1, 3, "", this), + new Among ( "ies", 0, 2, "", this), + new Among ( "sses", 0, 1, "", this), + new Among ( "ss", 0, -1, "", this) + }; + + private Among a_1[] = { + new Among ( "", -1, 3, "", this), + new Among ( "bb", 0, 2, "", this), + new Among ( "dd", 0, 2, "", this), + new Among ( "ff", 0, 2, "", this), + new Among ( "gg", 0, 2, "", this), + new Among ( "bl", 0, 1, "", this), + new Among ( "mm", 0, 2, "", this), + new Among ( "nn", 0, 2, "", this), + new Among ( "pp", 0, 2, "", this), + new Among ( "rr", 0, 2, "", this), + new Among ( "at", 0, 1, "", this), + new Among ( "tt", 0, 2, "", this), + new Among ( "iz", 0, 1, "", this) + }; + + private Among a_2[] = { + new Among ( "ed", -1, 2, "", this), + new Among ( "eed", 0, 1, "", this), + new Among ( "ing", -1, 2, "", this) + }; + + private Among a_3[] = { + new Among ( "anci", -1, 3, "", this), + new Among ( "enci", -1, 2, "", this), + new Among ( "abli", -1, 4, "", this), + new Among ( "eli", -1, 6, "", this), + new Among ( "alli", -1, 9, "", this), + new Among ( "ousli", -1, 12, "", this), + new Among ( "entli", -1, 5, "", this), + new Among ( "aliti", -1, 10, "", this), + new Among ( "biliti", -1, 14, "", this), + new Among ( "iviti", -1, 13, "", this), + new Among ( "tional", -1, 1, "", this), + new Among ( "ational", 10, 8, "", this), + new Among ( "alism", -1, 10, "", this), + new Among ( "ation", -1, 8, "", this), + new Among ( "ization", 13, 7, "", this), + new Among ( "izer", -1, 7, "", this), + new Among ( "ator", -1, 8, "", this), + new Among ( "iveness", -1, 13, "", this), + new Among ( "fulness", -1, 11, "", this), + new Among ( "ousness", -1, 12, "", this) + }; + + private Among a_4[] = { + new Among ( "icate", -1, 2, "", this), + new Among ( "ative", -1, 3, "", this), + new Among ( "alize", -1, 1, "", this), + new Among ( "iciti", -1, 2, "", this), + new Among ( "ical", -1, 2, "", this), + new Among ( "ful", -1, 3, "", this), + new Among ( "ness", -1, 3, "", this) + }; + + private Among a_5[] = { + new Among ( "ic", -1, 1, "", this), + new Among ( "ance", -1, 1, "", this), + new Among ( "ence", -1, 1, "", this), + new Among ( "able", -1, 1, "", this), + new Among ( "ible", -1, 1, "", this), + new Among ( "ate", -1, 1, "", this), + new Among ( "ive", -1, 1, "", this), + new Among ( "ize", -1, 1, "", this), + new Among ( "iti", -1, 1, "", this), + new Among ( "al", -1, 1, "", this), + new Among ( "ism", -1, 1, "", this), + new Among ( "ion", -1, 2, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "ous", -1, 1, "", this), + new Among ( "ant", -1, 1, "", this), + new Among ( "ent", -1, 1, "", this), + new Among ( "ment", 15, 1, "", this), + new Among ( "ement", 16, 1, "", this), + new Among ( "ou", -1, 1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1 }; + + private static final char g_v_WXY[] = {1, 17, 65, 208, 1 }; + + private boolean B_Y_found; + private int I_p2; + private int I_p1; + + private void copy_from(PorterStemmer other) { + B_Y_found = other.B_Y_found; + I_p2 = other.I_p2; + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_shortv() { + // (, line 19 + if (!(out_grouping_b(g_v_WXY, 89, 121))) + { + return false; + } + if (!(in_grouping_b(g_v, 97, 121))) + { + return false; + } + if (!(out_grouping_b(g_v, 97, 121))) + { + return false; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_Step_1a() { + int among_var; + // (, line 24 + // [, line 25 + ket = cursor; + // substring, line 25 + among_var = find_among_b(a_0, 4); + if (among_var == 0) + { + return false; + } + // ], line 25 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 26 + // <-, line 26 + slice_from("ss"); + break; + case 2: + // (, line 27 + // <-, line 27 + slice_from("i"); + break; + case 3: + // (, line 29 + // delete, line 29 + slice_del(); + break; + } + return true; + } + + private boolean r_Step_1b() { + int among_var; + int v_1; + int v_3; + int v_4; + // (, line 33 + // [, line 34 + ket = cursor; + // substring, line 34 + among_var = find_among_b(a_2, 3); + if (among_var == 0) + { + return false; + } + // ], line 34 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 35 + // call R1, line 35 + if (!r_R1()) + { + return false; + } + // <-, line 35 + slice_from("ee"); + break; + case 2: + // (, line 37 + // test, line 38 + v_1 = limit - cursor; + // gopast, line 38 + golab0: while(true) + { + lab1: do { + if (!(in_grouping_b(g_v, 97, 121))) + { + break lab1; + } + break golab0; + } while (false); + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + cursor = limit - v_1; + // delete, line 38 + slice_del(); + // test, line 39 + v_3 = limit - cursor; + // substring, line 39 + among_var = find_among_b(a_1, 13); + if (among_var == 0) + { + return false; + } + cursor = limit - v_3; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 41 + // <+, line 41 + { + int c = cursor; + insert(cursor, cursor, "e"); + cursor = c; + } + break; + case 2: + // (, line 44 + // [, line 44 + ket = cursor; + // next, line 44 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // ], line 44 + bra = cursor; + // delete, line 44 + slice_del(); + break; + case 3: + // (, line 45 + // atmark, line 45 + if (cursor != I_p1) + { + return false; + } + // test, line 45 + v_4 = limit - cursor; + // call shortv, line 45 + if (!r_shortv()) + { + return false; + } + cursor = limit - v_4; + // <+, line 45 + { + int c = cursor; + insert(cursor, cursor, "e"); + cursor = c; + } + break; + } + break; + } + return true; + } + + private boolean r_Step_1c() { + int v_1; + // (, line 51 + // [, line 52 + ket = cursor; + // or, line 52 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // literal, line 52 + if (!(eq_s_b(1, "y"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // literal, line 52 + if (!(eq_s_b(1, "Y"))) + { + return false; + } + } while (false); + // ], line 52 + bra = cursor; + // gopast, line 53 + golab2: while(true) + { + lab3: do { + if (!(in_grouping_b(g_v, 97, 121))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + // <-, line 54 + slice_from("i"); + return true; + } + + private boolean r_Step_2() { + int among_var; + // (, line 57 + // [, line 58 + ket = cursor; + // substring, line 58 + among_var = find_among_b(a_3, 20); + if (among_var == 0) + { + return false; + } + // ], line 58 + bra = cursor; + // call R1, line 58 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 59 + // <-, line 59 + slice_from("tion"); + break; + case 2: + // (, line 60 + // <-, line 60 + slice_from("ence"); + break; + case 3: + // (, line 61 + // <-, line 61 + slice_from("ance"); + break; + case 4: + // (, line 62 + // <-, line 62 + slice_from("able"); + break; + case 5: + // (, line 63 + // <-, line 63 + slice_from("ent"); + break; + case 6: + // (, line 64 + // <-, line 64 + slice_from("e"); + break; + case 7: + // (, line 66 + // <-, line 66 + slice_from("ize"); + break; + case 8: + // (, line 68 + // <-, line 68 + slice_from("ate"); + break; + case 9: + // (, line 69 + // <-, line 69 + slice_from("al"); + break; + case 10: + // (, line 71 + // <-, line 71 + slice_from("al"); + break; + case 11: + // (, line 72 + // <-, line 72 + slice_from("ful"); + break; + case 12: + // (, line 74 + // <-, line 74 + slice_from("ous"); + break; + case 13: + // (, line 76 + // <-, line 76 + slice_from("ive"); + break; + case 14: + // (, line 77 + // <-, line 77 + slice_from("ble"); + break; + } + return true; + } + + private boolean r_Step_3() { + int among_var; + // (, line 81 + // [, line 82 + ket = cursor; + // substring, line 82 + among_var = find_among_b(a_4, 7); + if (among_var == 0) + { + return false; + } + // ], line 82 + bra = cursor; + // call R1, line 82 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 83 + // <-, line 83 + slice_from("al"); + break; + case 2: + // (, line 85 + // <-, line 85 + slice_from("ic"); + break; + case 3: + // (, line 87 + // delete, line 87 + slice_del(); + break; + } + return true; + } + + private boolean r_Step_4() { + int among_var; + int v_1; + // (, line 91 + // [, line 92 + ket = cursor; + // substring, line 92 + among_var = find_among_b(a_5, 19); + if (among_var == 0) + { + return false; + } + // ], line 92 + bra = cursor; + // call R2, line 92 + if (!r_R2()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 95 + // delete, line 95 + slice_del(); + break; + case 2: + // (, line 96 + // or, line 96 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // literal, line 96 + if (!(eq_s_b(1, "s"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // literal, line 96 + if (!(eq_s_b(1, "t"))) + { + return false; + } + } while (false); + // delete, line 96 + slice_del(); + break; + } + return true; + } + + private boolean r_Step_5a() { + int v_1; + int v_2; + // (, line 100 + // [, line 101 + ket = cursor; + // literal, line 101 + if (!(eq_s_b(1, "e"))) + { + return false; + } + // ], line 101 + bra = cursor; + // or, line 102 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // call R2, line 102 + if (!r_R2()) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 102 + // call R1, line 102 + if (!r_R1()) + { + return false; + } + // not, line 102 + { + v_2 = limit - cursor; + lab2: do { + // call shortv, line 102 + if (!r_shortv()) + { + break lab2; + } + return false; + } while (false); + cursor = limit - v_2; + } + } while (false); + // delete, line 103 + slice_del(); + return true; + } + + private boolean r_Step_5b() { + // (, line 106 + // [, line 107 + ket = cursor; + // literal, line 107 + if (!(eq_s_b(1, "l"))) + { + return false; + } + // ], line 107 + bra = cursor; + // call R2, line 108 + if (!r_R2()) + { + return false; + } + // literal, line 108 + if (!(eq_s_b(1, "l"))) + { + return false; + } + // delete, line 109 + slice_del(); + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_10; + int v_11; + int v_12; + int v_13; + int v_14; + int v_15; + int v_16; + int v_17; + int v_18; + int v_19; + int v_20; + // (, line 113 + // unset Y_found, line 115 + B_Y_found = false; + // do, line 116 + v_1 = cursor; + lab0: do { + // (, line 116 + // [, line 116 + bra = cursor; + // literal, line 116 + if (!(eq_s(1, "y"))) + { + break lab0; + } + // ], line 116 + ket = cursor; + // <-, line 116 + slice_from("Y"); + // set Y_found, line 116 + B_Y_found = true; + } while (false); + cursor = v_1; + // do, line 117 + v_2 = cursor; + lab1: do { + // repeat, line 117 + replab2: while(true) + { + v_3 = cursor; + lab3: do { + // (, line 117 + // goto, line 117 + golab4: while(true) + { + v_4 = cursor; + lab5: do { + // (, line 117 + if (!(in_grouping(g_v, 97, 121))) + { + break lab5; + } + // [, line 117 + bra = cursor; + // literal, line 117 + if (!(eq_s(1, "y"))) + { + break lab5; + } + // ], line 117 + ket = cursor; + cursor = v_4; + break golab4; + } while (false); + cursor = v_4; + if (cursor >= limit) + { + break lab3; + } + cursor++; + } + // <-, line 117 + slice_from("Y"); + // set Y_found, line 117 + B_Y_found = true; + continue replab2; + } while (false); + cursor = v_3; + break replab2; + } + } while (false); + cursor = v_2; + I_p1 = limit; + I_p2 = limit; + // do, line 121 + v_5 = cursor; + lab6: do { + // (, line 121 + // gopast, line 122 + golab7: while(true) + { + lab8: do { + if (!(in_grouping(g_v, 97, 121))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // gopast, line 122 + golab9: while(true) + { + lab10: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab10; + } + break golab9; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // setmark p1, line 122 + I_p1 = cursor; + // gopast, line 123 + golab11: while(true) + { + lab12: do { + if (!(in_grouping(g_v, 97, 121))) + { + break lab12; + } + break golab11; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // gopast, line 123 + golab13: while(true) + { + lab14: do { + if (!(out_grouping(g_v, 97, 121))) + { + break lab14; + } + break golab13; + } while (false); + if (cursor >= limit) + { + break lab6; + } + cursor++; + } + // setmark p2, line 123 + I_p2 = cursor; + } while (false); + cursor = v_5; + // backwards, line 126 + limit_backward = cursor; cursor = limit; + // (, line 126 + // do, line 127 + v_10 = limit - cursor; + lab15: do { + // call Step_1a, line 127 + if (!r_Step_1a()) + { + break lab15; + } + } while (false); + cursor = limit - v_10; + // do, line 128 + v_11 = limit - cursor; + lab16: do { + // call Step_1b, line 128 + if (!r_Step_1b()) + { + break lab16; + } + } while (false); + cursor = limit - v_11; + // do, line 129 + v_12 = limit - cursor; + lab17: do { + // call Step_1c, line 129 + if (!r_Step_1c()) + { + break lab17; + } + } while (false); + cursor = limit - v_12; + // do, line 130 + v_13 = limit - cursor; + lab18: do { + // call Step_2, line 130 + if (!r_Step_2()) + { + break lab18; + } + } while (false); + cursor = limit - v_13; + // do, line 131 + v_14 = limit - cursor; + lab19: do { + // call Step_3, line 131 + if (!r_Step_3()) + { + break lab19; + } + } while (false); + cursor = limit - v_14; + // do, line 132 + v_15 = limit - cursor; + lab20: do { + // call Step_4, line 132 + if (!r_Step_4()) + { + break lab20; + } + } while (false); + cursor = limit - v_15; + // do, line 133 + v_16 = limit - cursor; + lab21: do { + // call Step_5a, line 133 + if (!r_Step_5a()) + { + break lab21; + } + } while (false); + cursor = limit - v_16; + // do, line 134 + v_17 = limit - cursor; + lab22: do { + // call Step_5b, line 134 + if (!r_Step_5b()) + { + break lab22; + } + } while (false); + cursor = limit - v_17; + cursor = limit_backward; // do, line 137 + v_18 = cursor; + lab23: do { + // (, line 137 + // Boolean test Y_found, line 137 + if (!(B_Y_found)) + { + break lab23; + } + // repeat, line 137 + replab24: while(true) + { + v_19 = cursor; + lab25: do { + // (, line 137 + // goto, line 137 + golab26: while(true) + { + v_20 = cursor; + lab27: do { + // (, line 137 + // [, line 137 + bra = cursor; + // literal, line 137 + if (!(eq_s(1, "Y"))) + { + break lab27; + } + // ], line 137 + ket = cursor; + cursor = v_20; + break golab26; + } while (false); + cursor = v_20; + if (cursor >= limit) + { + break lab25; + } + cursor++; + } + // <-, line 137 + slice_from("y"); + continue replab24; + } while (false); + cursor = v_19; + break replab24; + } + } while (false); + cursor = v_18; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/PortugueseStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/PortugueseStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/PortugueseStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,1116 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class PortugueseStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "", -1, 3, "", this), + new Among ( "\u00E3", 0, 1, "", this), + new Among ( "\u00F5", 0, 2, "", this) + }; + + private Among a_1[] = { + new Among ( "", -1, 3, "", this), + new Among ( "a~", 0, 1, "", this), + new Among ( "o~", 0, 2, "", this) + }; + + private Among a_2[] = { + new Among ( "ic", -1, -1, "", this), + new Among ( "ad", -1, -1, "", this), + new Among ( "os", -1, -1, "", this), + new Among ( "iv", -1, 1, "", this) + }; + + private Among a_3[] = { + new Among ( "ante", -1, 1, "", this), + new Among ( "avel", -1, 1, "", this), + new Among ( "\u00EDvel", -1, 1, "", this) + }; + + private Among a_4[] = { + new Among ( "ic", -1, 1, "", this), + new Among ( "abil", -1, 1, "", this), + new Among ( "iv", -1, 1, "", this) + }; + + private Among a_5[] = { + new Among ( "ica", -1, 1, "", this), + new Among ( "\u00E2ncia", -1, 1, "", this), + new Among ( "\u00EAncia", -1, 4, "", this), + new Among ( "ira", -1, 9, "", this), + new Among ( "adora", -1, 1, "", this), + new Among ( "osa", -1, 1, "", this), + new Among ( "ista", -1, 1, "", this), + new Among ( "iva", -1, 8, "", this), + new Among ( "eza", -1, 1, "", this), + new Among ( "log\u00EDa", -1, 2, "", this), + new Among ( "idade", -1, 7, "", this), + new Among ( "ante", -1, 1, "", this), + new Among ( "mente", -1, 6, "", this), + new Among ( "amente", 12, 5, "", this), + new Among ( "\u00E1vel", -1, 1, "", this), + new Among ( "\u00EDvel", -1, 1, "", this), + new Among ( "uci\u00F3n", -1, 3, "", this), + new Among ( "ico", -1, 1, "", this), + new Among ( "ismo", -1, 1, "", this), + new Among ( "oso", -1, 1, "", this), + new Among ( "amento", -1, 1, "", this), + new Among ( "imento", -1, 1, "", this), + new Among ( "ivo", -1, 8, "", this), + new Among ( "a\u00E7a~o", -1, 1, "", this), + new Among ( "ador", -1, 1, "", this), + new Among ( "icas", -1, 1, "", this), + new Among ( "\u00EAncias", -1, 4, "", this), + new Among ( "iras", -1, 9, "", this), + new Among ( "adoras", -1, 1, "", this), + new Among ( "osas", -1, 1, "", this), + new Among ( "istas", -1, 1, "", this), + new Among ( "ivas", -1, 8, "", this), + new Among ( "ezas", -1, 1, "", this), + new Among ( "log\u00EDas", -1, 2, "", this), + new Among ( "idades", -1, 7, "", this), + new Among ( "uciones", -1, 3, "", this), + new Among ( "adores", -1, 1, "", this), + new Among ( "antes", -1, 1, "", this), + new Among ( "a\u00E7o~es", -1, 1, "", this), + new Among ( "icos", -1, 1, "", this), + new Among ( "ismos", -1, 1, "", this), + new Among ( "osos", -1, 1, "", this), + new Among ( "amentos", -1, 1, "", this), + new Among ( "imentos", -1, 1, "", this), + new Among ( "ivos", -1, 8, "", this) + }; + + private Among a_6[] = { + new Among ( "ada", -1, 1, "", this), + new Among ( "ida", -1, 1, "", this), + new Among ( "ia", -1, 1, "", this), + new Among ( "aria", 2, 1, "", this), + new Among ( "eria", 2, 1, "", this), + new Among ( "iria", 2, 1, "", this), + new Among ( "ara", -1, 1, "", this), + new Among ( "era", -1, 1, "", this), + new Among ( "ira", -1, 1, "", this), + new Among ( "ava", -1, 1, "", this), + new Among ( "asse", -1, 1, "", this), + new Among ( "esse", -1, 1, "", this), + new Among ( "isse", -1, 1, "", this), + new Among ( "aste", -1, 1, "", this), + new Among ( "este", -1, 1, "", this), + new Among ( "iste", -1, 1, "", this), + new Among ( "ei", -1, 1, "", this), + new Among ( "arei", 16, 1, "", this), + new Among ( "erei", 16, 1, "", this), + new Among ( "irei", 16, 1, "", this), + new Among ( "am", -1, 1, "", this), + new Among ( "iam", 20, 1, "", this), + new Among ( "ariam", 21, 1, "", this), + new Among ( "eriam", 21, 1, "", this), + new Among ( "iriam", 21, 1, "", this), + new Among ( "aram", 20, 1, "", this), + new Among ( "eram", 20, 1, "", this), + new Among ( "iram", 20, 1, "", this), + new Among ( "avam", 20, 1, "", this), + new Among ( "em", -1, 1, "", this), + new Among ( "arem", 29, 1, "", this), + new Among ( "erem", 29, 1, "", this), + new Among ( "irem", 29, 1, "", this), + new Among ( "assem", 29, 1, "", this), + new Among ( "essem", 29, 1, "", this), + new Among ( "issem", 29, 1, "", this), + new Among ( "ado", -1, 1, "", this), + new Among ( "ido", -1, 1, "", this), + new Among ( "ando", -1, 1, "", this), + new Among ( "endo", -1, 1, "", this), + new Among ( "indo", -1, 1, "", this), + new Among ( "ara~o", -1, 1, "", this), + new Among ( "era~o", -1, 1, "", this), + new Among ( "ira~o", -1, 1, "", this), + new Among ( "ar", -1, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "ir", -1, 1, "", this), + new Among ( "as", -1, 1, "", this), + new Among ( "adas", 47, 1, "", this), + new Among ( "idas", 47, 1, "", this), + new Among ( "ias", 47, 1, "", this), + new Among ( "arias", 50, 1, "", this), + new Among ( "erias", 50, 1, "", this), + new Among ( "irias", 50, 1, "", this), + new Among ( "aras", 47, 1, "", this), + new Among ( "eras", 47, 1, "", this), + new Among ( "iras", 47, 1, "", this), + new Among ( "avas", 47, 1, "", this), + new Among ( "es", -1, 1, "", this), + new Among ( "ardes", 58, 1, "", this), + new Among ( "erdes", 58, 1, "", this), + new Among ( "irdes", 58, 1, "", this), + new Among ( "ares", 58, 1, "", this), + new Among ( "eres", 58, 1, "", this), + new Among ( "ires", 58, 1, "", this), + new Among ( "asses", 58, 1, "", this), + new Among ( "esses", 58, 1, "", this), + new Among ( "isses", 58, 1, "", this), + new Among ( "astes", 58, 1, "", this), + new Among ( "estes", 58, 1, "", this), + new Among ( "istes", 58, 1, "", this), + new Among ( "is", -1, 1, "", this), + new Among ( "ais", 71, 1, "", this), + new Among ( "eis", 71, 1, "", this), + new Among ( "areis", 73, 1, "", this), + new Among ( "ereis", 73, 1, "", this), + new Among ( "ireis", 73, 1, "", this), + new Among ( "\u00E1reis", 73, 1, "", this), + new Among ( "\u00E9reis", 73, 1, "", this), + new Among ( "\u00EDreis", 73, 1, "", this), + new Among ( "\u00E1sseis", 73, 1, "", this), + new Among ( "\u00E9sseis", 73, 1, "", this), + new Among ( "\u00EDsseis", 73, 1, "", this), + new Among ( "\u00E1veis", 73, 1, "", this), + new Among ( "\u00EDeis", 73, 1, "", this), + new Among ( "ar\u00EDeis", 84, 1, "", this), + new Among ( "er\u00EDeis", 84, 1, "", this), + new Among ( "ir\u00EDeis", 84, 1, "", this), + new Among ( "ados", -1, 1, "", this), + new Among ( "idos", -1, 1, "", this), + new Among ( "amos", -1, 1, "", this), + new Among ( "\u00E1ramos", 90, 1, "", this), + new Among ( "\u00E9ramos", 90, 1, "", this), + new Among ( "\u00EDramos", 90, 1, "", this), + new Among ( "\u00E1vamos", 90, 1, "", this), + new Among ( "\u00EDamos", 90, 1, "", this), + new Among ( "ar\u00EDamos", 95, 1, "", this), + new Among ( "er\u00EDamos", 95, 1, "", this), + new Among ( "ir\u00EDamos", 95, 1, "", this), + new Among ( "emos", -1, 1, "", this), + new Among ( "aremos", 99, 1, "", this), + new Among ( "eremos", 99, 1, "", this), + new Among ( "iremos", 99, 1, "", this), + new Among ( "\u00E1ssemos", 99, 1, "", this), + new Among ( "\u00EAssemos", 99, 1, "", this), + new Among ( "\u00EDssemos", 99, 1, "", this), + new Among ( "imos", -1, 1, "", this), + new Among ( "armos", -1, 1, "", this), + new Among ( "ermos", -1, 1, "", this), + new Among ( "irmos", -1, 1, "", this), + new Among ( "\u00E1mos", -1, 1, "", this), + new Among ( "ar\u00E1s", -1, 1, "", this), + new Among ( "er\u00E1s", -1, 1, "", this), + new Among ( "ir\u00E1s", -1, 1, "", this), + new Among ( "eu", -1, 1, "", this), + new Among ( "iu", -1, 1, "", this), + new Among ( "ou", -1, 1, "", this), + new Among ( "ar\u00E1", -1, 1, "", this), + new Among ( "er\u00E1", -1, 1, "", this), + new Among ( "ir\u00E1", -1, 1, "", this) + }; + + private Among a_7[] = { + new Among ( "a", -1, 1, "", this), + new Among ( "i", -1, 1, "", this), + new Among ( "o", -1, 1, "", this), + new Among ( "os", -1, 1, "", this), + new Among ( "\u00E1", -1, 1, "", this), + new Among ( "\u00ED", -1, 1, "", this), + new Among ( "\u00F3", -1, 1, "", this) + }; + + private Among a_8[] = { + new Among ( "e", -1, 1, "", this), + new Among ( "\u00E7", -1, 2, "", this), + new Among ( "\u00E9", -1, 1, "", this), + new Among ( "\u00EA", -1, 1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 19, 12, 2 }; + + private int I_p2; + private int I_p1; + private int I_pV; + + private void copy_from(PortugueseStemmer other) { + I_p2 = other.I_p2; + I_p1 = other.I_p1; + I_pV = other.I_pV; + super.copy_from(other); + } + + private boolean r_prelude() { + int among_var; + int v_1; + // repeat, line 36 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 36 + // [, line 37 + bra = cursor; + // substring, line 37 + among_var = find_among(a_0, 3); + if (among_var == 0) + { + break lab1; + } + // ], line 37 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 38 + // <-, line 38 + slice_from("a~"); + break; + case 2: + // (, line 39 + // <-, line 39 + slice_from("o~"); + break; + case 3: + // (, line 40 + // next, line 40 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + int v_3; + int v_6; + int v_8; + // (, line 44 + I_pV = limit; + I_p1 = limit; + I_p2 = limit; + // do, line 50 + v_1 = cursor; + lab0: do { + // (, line 50 + // or, line 52 + lab1: do { + v_2 = cursor; + lab2: do { + // (, line 51 + if (!(in_grouping(g_v, 97, 250))) + { + break lab2; + } + // or, line 51 + lab3: do { + v_3 = cursor; + lab4: do { + // (, line 51 + if (!(out_grouping(g_v, 97, 250))) + { + break lab4; + } + // gopast, line 51 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 97, 250))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + break lab4; + } + cursor++; + } + break lab3; + } while (false); + cursor = v_3; + // (, line 51 + if (!(in_grouping(g_v, 97, 250))) + { + break lab2; + } + // gopast, line 51 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 97, 250))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab2; + } + cursor++; + } + } while (false); + break lab1; + } while (false); + cursor = v_2; + // (, line 53 + if (!(out_grouping(g_v, 97, 250))) + { + break lab0; + } + // or, line 53 + lab9: do { + v_6 = cursor; + lab10: do { + // (, line 53 + if (!(out_grouping(g_v, 97, 250))) + { + break lab10; + } + // gopast, line 53 + golab11: while(true) + { + lab12: do { + if (!(in_grouping(g_v, 97, 250))) + { + break lab12; + } + break golab11; + } while (false); + if (cursor >= limit) + { + break lab10; + } + cursor++; + } + break lab9; + } while (false); + cursor = v_6; + // (, line 53 + if (!(in_grouping(g_v, 97, 250))) + { + break lab0; + } + // next, line 53 + if (cursor >= limit) + { + break lab0; + } + cursor++; + } while (false); + } while (false); + // setmark pV, line 54 + I_pV = cursor; + } while (false); + cursor = v_1; + // do, line 56 + v_8 = cursor; + lab13: do { + // (, line 56 + // gopast, line 57 + golab14: while(true) + { + lab15: do { + if (!(in_grouping(g_v, 97, 250))) + { + break lab15; + } + break golab14; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 57 + golab16: while(true) + { + lab17: do { + if (!(out_grouping(g_v, 97, 250))) + { + break lab17; + } + break golab16; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p1, line 57 + I_p1 = cursor; + // gopast, line 58 + golab18: while(true) + { + lab19: do { + if (!(in_grouping(g_v, 97, 250))) + { + break lab19; + } + break golab18; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 58 + golab20: while(true) + { + lab21: do { + if (!(out_grouping(g_v, 97, 250))) + { + break lab21; + } + break golab20; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p2, line 58 + I_p2 = cursor; + } while (false); + cursor = v_8; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 62 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 62 + // [, line 63 + bra = cursor; + // substring, line 63 + among_var = find_among(a_1, 3); + if (among_var == 0) + { + break lab1; + } + // ], line 63 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 64 + // <-, line 64 + slice_from("\u00E3"); + break; + case 2: + // (, line 65 + // <-, line 65 + slice_from("\u00F5"); + break; + case 3: + // (, line 66 + // next, line 66 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_RV() { + if (!(I_pV <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 76 + // [, line 77 + ket = cursor; + // substring, line 77 + among_var = find_among_b(a_5, 45); + if (among_var == 0) + { + return false; + } + // ], line 77 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 92 + // call R2, line 93 + if (!r_R2()) + { + return false; + } + // delete, line 93 + slice_del(); + break; + case 2: + // (, line 97 + // call R2, line 98 + if (!r_R2()) + { + return false; + } + // <-, line 98 + slice_from("log"); + break; + case 3: + // (, line 101 + // call R2, line 102 + if (!r_R2()) + { + return false; + } + // <-, line 102 + slice_from("u"); + break; + case 4: + // (, line 105 + // call R2, line 106 + if (!r_R2()) + { + return false; + } + // <-, line 106 + slice_from("ente"); + break; + case 5: + // (, line 109 + // call R1, line 110 + if (!r_R1()) + { + return false; + } + // delete, line 110 + slice_del(); + // try, line 111 + v_1 = limit - cursor; + lab0: do { + // (, line 111 + // [, line 112 + ket = cursor; + // substring, line 112 + among_var = find_among_b(a_2, 4); + if (among_var == 0) + { + cursor = limit - v_1; + break lab0; + } + // ], line 112 + bra = cursor; + // call R2, line 112 + if (!r_R2()) + { + cursor = limit - v_1; + break lab0; + } + // delete, line 112 + slice_del(); + switch(among_var) { + case 0: + cursor = limit - v_1; + break lab0; + case 1: + // (, line 113 + // [, line 113 + ket = cursor; + // literal, line 113 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 113 + bra = cursor; + // call R2, line 113 + if (!r_R2()) + { + cursor = limit - v_1; + break lab0; + } + // delete, line 113 + slice_del(); + break; + } + } while (false); + break; + case 6: + // (, line 121 + // call R2, line 122 + if (!r_R2()) + { + return false; + } + // delete, line 122 + slice_del(); + // try, line 123 + v_2 = limit - cursor; + lab1: do { + // (, line 123 + // [, line 124 + ket = cursor; + // substring, line 124 + among_var = find_among_b(a_3, 3); + if (among_var == 0) + { + cursor = limit - v_2; + break lab1; + } + // ], line 124 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_2; + break lab1; + case 1: + // (, line 127 + // call R2, line 127 + if (!r_R2()) + { + cursor = limit - v_2; + break lab1; + } + // delete, line 127 + slice_del(); + break; + } + } while (false); + break; + case 7: + // (, line 133 + // call R2, line 134 + if (!r_R2()) + { + return false; + } + // delete, line 134 + slice_del(); + // try, line 135 + v_3 = limit - cursor; + lab2: do { + // (, line 135 + // [, line 136 + ket = cursor; + // substring, line 136 + among_var = find_among_b(a_4, 3); + if (among_var == 0) + { + cursor = limit - v_3; + break lab2; + } + // ], line 136 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_3; + break lab2; + case 1: + // (, line 139 + // call R2, line 139 + if (!r_R2()) + { + cursor = limit - v_3; + break lab2; + } + // delete, line 139 + slice_del(); + break; + } + } while (false); + break; + case 8: + // (, line 145 + // call R2, line 146 + if (!r_R2()) + { + return false; + } + // delete, line 146 + slice_del(); + // try, line 147 + v_4 = limit - cursor; + lab3: do { + // (, line 147 + // [, line 148 + ket = cursor; + // literal, line 148 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_4; + break lab3; + } + // ], line 148 + bra = cursor; + // call R2, line 148 + if (!r_R2()) + { + cursor = limit - v_4; + break lab3; + } + // delete, line 148 + slice_del(); + } while (false); + break; + case 9: + // (, line 152 + // call RV, line 153 + if (!r_RV()) + { + return false; + } + // literal, line 153 + if (!(eq_s_b(1, "e"))) + { + return false; + } + // <-, line 154 + slice_from("ir"); + break; + } + return true; + } + + private boolean r_verb_suffix() { + int among_var; + int v_1; + int v_2; + // setlimit, line 159 + v_1 = limit - cursor; + // tomark, line 159 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 159 + // [, line 160 + ket = cursor; + // substring, line 160 + among_var = find_among_b(a_6, 120); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 160 + bra = cursor; + switch(among_var) { + case 0: + limit_backward = v_2; + return false; + case 1: + // (, line 179 + // delete, line 179 + slice_del(); + break; + } + limit_backward = v_2; + return true; + } + + private boolean r_residual_suffix() { + int among_var; + // (, line 183 + // [, line 184 + ket = cursor; + // substring, line 184 + among_var = find_among_b(a_7, 7); + if (among_var == 0) + { + return false; + } + // ], line 184 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 187 + // call RV, line 187 + if (!r_RV()) + { + return false; + } + // delete, line 187 + slice_del(); + break; + } + return true; + } + + private boolean r_residual_form() { + int among_var; + int v_1; + int v_2; + int v_3; + // (, line 191 + // [, line 192 + ket = cursor; + // substring, line 192 + among_var = find_among_b(a_8, 4); + if (among_var == 0) + { + return false; + } + // ], line 192 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 194 + // call RV, line 194 + if (!r_RV()) + { + return false; + } + // delete, line 194 + slice_del(); + // [, line 194 + ket = cursor; + // or, line 194 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 194 + // literal, line 194 + if (!(eq_s_b(1, "u"))) + { + break lab1; + } + // ], line 194 + bra = cursor; + // test, line 194 + v_2 = limit - cursor; + // literal, line 194 + if (!(eq_s_b(1, "g"))) + { + break lab1; + } + cursor = limit - v_2; + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 195 + // literal, line 195 + if (!(eq_s_b(1, "i"))) + { + return false; + } + // ], line 195 + bra = cursor; + // test, line 195 + v_3 = limit - cursor; + // literal, line 195 + if (!(eq_s_b(1, "c"))) + { + return false; + } + cursor = limit - v_3; + } while (false); + // call RV, line 195 + if (!r_RV()) + { + return false; + } + // delete, line 195 + slice_del(); + break; + case 2: + // (, line 196 + // <-, line 196 + slice_from("c"); + break; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + // (, line 201 + // do, line 202 + v_1 = cursor; + lab0: do { + // call prelude, line 202 + if (!r_prelude()) + { + break lab0; + } + } while (false); + cursor = v_1; + // do, line 203 + v_2 = cursor; + lab1: do { + // call mark_regions, line 203 + if (!r_mark_regions()) + { + break lab1; + } + } while (false); + cursor = v_2; + // backwards, line 204 + limit_backward = cursor; cursor = limit; + // (, line 204 + // do, line 205 + v_3 = limit - cursor; + lab2: do { + // (, line 205 + // or, line 209 + lab3: do { + v_4 = limit - cursor; + lab4: do { + // (, line 206 + // and, line 207 + v_5 = limit - cursor; + // (, line 206 + // or, line 206 + lab5: do { + v_6 = limit - cursor; + lab6: do { + // call standard_suffix, line 206 + if (!r_standard_suffix()) + { + break lab6; + } + break lab5; + } while (false); + cursor = limit - v_6; + // call verb_suffix, line 206 + if (!r_verb_suffix()) + { + break lab4; + } + } while (false); + cursor = limit - v_5; + // do, line 207 + v_7 = limit - cursor; + lab7: do { + // (, line 207 + // [, line 207 + ket = cursor; + // literal, line 207 + if (!(eq_s_b(1, "i"))) + { + break lab7; + } + // ], line 207 + bra = cursor; + // test, line 207 + v_8 = limit - cursor; + // literal, line 207 + if (!(eq_s_b(1, "c"))) + { + break lab7; + } + cursor = limit - v_8; + // call RV, line 207 + if (!r_RV()) + { + break lab7; + } + // delete, line 207 + slice_del(); + } while (false); + cursor = limit - v_7; + break lab3; + } while (false); + cursor = limit - v_4; + // call residual_suffix, line 209 + if (!r_residual_suffix()) + { + break lab2; + } + } while (false); + } while (false); + cursor = limit - v_3; + // do, line 211 + v_9 = limit - cursor; + lab8: do { + // call residual_form, line 211 + if (!r_residual_form()) + { + break lab8; + } + } while (false); + cursor = limit - v_9; + cursor = limit_backward; // do, line 213 + v_10 = cursor; + lab9: do { + // call postlude, line 213 + if (!r_postlude()) + { + break lab9; + } + } while (false); + cursor = v_10; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/RomanianStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/RomanianStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/RomanianStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,1024 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class RomanianStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "", -1, 3, "", this), + new Among ( "I", 0, 1, "", this), + new Among ( "U", 0, 2, "", this) + }; + + private Among a_1[] = { + new Among ( "ea", -1, 3, "", this), + new Among ( "a\u0163ia", -1, 7, "", this), + new Among ( "aua", -1, 2, "", this), + new Among ( "iua", -1, 4, "", this), + new Among ( "a\u0163ie", -1, 7, "", this), + new Among ( "ele", -1, 3, "", this), + new Among ( "ile", -1, 5, "", this), + new Among ( "iile", 6, 4, "", this), + new Among ( "iei", -1, 4, "", this), + new Among ( "atei", -1, 6, "", this), + new Among ( "ii", -1, 4, "", this), + new Among ( "ului", -1, 1, "", this), + new Among ( "ul", -1, 1, "", this), + new Among ( "elor", -1, 3, "", this), + new Among ( "ilor", -1, 4, "", this), + new Among ( "iilor", 14, 4, "", this) + }; + + private Among a_2[] = { + new Among ( "icala", -1, 4, "", this), + new Among ( "iciva", -1, 4, "", this), + new Among ( "ativa", -1, 5, "", this), + new Among ( "itiva", -1, 6, "", this), + new Among ( "icale", -1, 4, "", this), + new Among ( "a\u0163iune", -1, 5, "", this), + new Among ( "i\u0163iune", -1, 6, "", this), + new Among ( "atoare", -1, 5, "", this), + new Among ( "itoare", -1, 6, "", this), + new Among ( "\u0103toare", -1, 5, "", this), + new Among ( "icitate", -1, 4, "", this), + new Among ( "abilitate", -1, 1, "", this), + new Among ( "ibilitate", -1, 2, "", this), + new Among ( "ivitate", -1, 3, "", this), + new Among ( "icive", -1, 4, "", this), + new Among ( "ative", -1, 5, "", this), + new Among ( "itive", -1, 6, "", this), + new Among ( "icali", -1, 4, "", this), + new Among ( "atori", -1, 5, "", this), + new Among ( "icatori", 18, 4, "", this), + new Among ( "itori", -1, 6, "", this), + new Among ( "\u0103tori", -1, 5, "", this), + new Among ( "icitati", -1, 4, "", this), + new Among ( "abilitati", -1, 1, "", this), + new Among ( "ivitati", -1, 3, "", this), + new Among ( "icivi", -1, 4, "", this), + new Among ( "ativi", -1, 5, "", this), + new Among ( "itivi", -1, 6, "", this), + new Among ( "icit\u0103i", -1, 4, "", this), + new Among ( "abilit\u0103i", -1, 1, "", this), + new Among ( "ivit\u0103i", -1, 3, "", this), + new Among ( "icit\u0103\u0163i", -1, 4, "", this), + new Among ( "abilit\u0103\u0163i", -1, 1, "", this), + new Among ( "ivit\u0103\u0163i", -1, 3, "", this), + new Among ( "ical", -1, 4, "", this), + new Among ( "ator", -1, 5, "", this), + new Among ( "icator", 35, 4, "", this), + new Among ( "itor", -1, 6, "", this), + new Among ( "\u0103tor", -1, 5, "", this), + new Among ( "iciv", -1, 4, "", this), + new Among ( "ativ", -1, 5, "", this), + new Among ( "itiv", -1, 6, "", this), + new Among ( "ical\u0103", -1, 4, "", this), + new Among ( "iciv\u0103", -1, 4, "", this), + new Among ( "ativ\u0103", -1, 5, "", this), + new Among ( "itiv\u0103", -1, 6, "", this) + }; + + private Among a_3[] = { + new Among ( "ica", -1, 1, "", this), + new Among ( "abila", -1, 1, "", this), + new Among ( "ibila", -1, 1, "", this), + new Among ( "oasa", -1, 1, "", this), + new Among ( "ata", -1, 1, "", this), + new Among ( "ita", -1, 1, "", this), + new Among ( "anta", -1, 1, "", this), + new Among ( "ista", -1, 3, "", this), + new Among ( "uta", -1, 1, "", this), + new Among ( "iva", -1, 1, "", this), + new Among ( "ic", -1, 1, "", this), + new Among ( "ice", -1, 1, "", this), + new Among ( "abile", -1, 1, "", this), + new Among ( "ibile", -1, 1, "", this), + new Among ( "isme", -1, 3, "", this), + new Among ( "iune", -1, 2, "", this), + new Among ( "oase", -1, 1, "", this), + new Among ( "ate", -1, 1, "", this), + new Among ( "itate", 17, 1, "", this), + new Among ( "ite", -1, 1, "", this), + new Among ( "ante", -1, 1, "", this), + new Among ( "iste", -1, 3, "", this), + new Among ( "ute", -1, 1, "", this), + new Among ( "ive", -1, 1, "", this), + new Among ( "ici", -1, 1, "", this), + new Among ( "abili", -1, 1, "", this), + new Among ( "ibili", -1, 1, "", this), + new Among ( "iuni", -1, 2, "", this), + new Among ( "atori", -1, 1, "", this), + new Among ( "osi", -1, 1, "", this), + new Among ( "ati", -1, 1, "", this), + new Among ( "itati", 30, 1, "", this), + new Among ( "iti", -1, 1, "", this), + new Among ( "anti", -1, 1, "", this), + new Among ( "isti", -1, 3, "", this), + new Among ( "uti", -1, 1, "", this), + new Among ( "i\u015Fti", -1, 3, "", this), + new Among ( "ivi", -1, 1, "", this), + new Among ( "it\u0103i", -1, 1, "", this), + new Among ( "o\u015Fi", -1, 1, "", this), + new Among ( "it\u0103\u0163i", -1, 1, "", this), + new Among ( "abil", -1, 1, "", this), + new Among ( "ibil", -1, 1, "", this), + new Among ( "ism", -1, 3, "", this), + new Among ( "ator", -1, 1, "", this), + new Among ( "os", -1, 1, "", this), + new Among ( "at", -1, 1, "", this), + new Among ( "it", -1, 1, "", this), + new Among ( "ant", -1, 1, "", this), + new Among ( "ist", -1, 3, "", this), + new Among ( "ut", -1, 1, "", this), + new Among ( "iv", -1, 1, "", this), + new Among ( "ic\u0103", -1, 1, "", this), + new Among ( "abil\u0103", -1, 1, "", this), + new Among ( "ibil\u0103", -1, 1, "", this), + new Among ( "oas\u0103", -1, 1, "", this), + new Among ( "at\u0103", -1, 1, "", this), + new Among ( "it\u0103", -1, 1, "", this), + new Among ( "ant\u0103", -1, 1, "", this), + new Among ( "ist\u0103", -1, 3, "", this), + new Among ( "ut\u0103", -1, 1, "", this), + new Among ( "iv\u0103", -1, 1, "", this) + }; + + private Among a_4[] = { + new Among ( "ea", -1, 1, "", this), + new Among ( "ia", -1, 1, "", this), + new Among ( "esc", -1, 1, "", this), + new Among ( "\u0103sc", -1, 1, "", this), + new Among ( "ind", -1, 1, "", this), + new Among ( "\u00E2nd", -1, 1, "", this), + new Among ( "are", -1, 1, "", this), + new Among ( "ere", -1, 1, "", this), + new Among ( "ire", -1, 1, "", this), + new Among ( "\u00E2re", -1, 1, "", this), + new Among ( "se", -1, 2, "", this), + new Among ( "ase", 10, 1, "", this), + new Among ( "sese", 10, 2, "", this), + new Among ( "ise", 10, 1, "", this), + new Among ( "use", 10, 1, "", this), + new Among ( "\u00E2se", 10, 1, "", this), + new Among ( "e\u015Fte", -1, 1, "", this), + new Among ( "\u0103\u015Fte", -1, 1, "", this), + new Among ( "eze", -1, 1, "", this), + new Among ( "ai", -1, 1, "", this), + new Among ( "eai", 19, 1, "", this), + new Among ( "iai", 19, 1, "", this), + new Among ( "sei", -1, 2, "", this), + new Among ( "e\u015Fti", -1, 1, "", this), + new Among ( "\u0103\u015Fti", -1, 1, "", this), + new Among ( "ui", -1, 1, "", this), + new Among ( "ezi", -1, 1, "", this), + new Among ( "\u00E2i", -1, 1, "", this), + new Among ( "a\u015Fi", -1, 1, "", this), + new Among ( "se\u015Fi", -1, 2, "", this), + new Among ( "ase\u015Fi", 29, 1, "", this), + new Among ( "sese\u015Fi", 29, 2, "", this), + new Among ( "ise\u015Fi", 29, 1, "", this), + new Among ( "use\u015Fi", 29, 1, "", this), + new Among ( "\u00E2se\u015Fi", 29, 1, "", this), + new Among ( "i\u015Fi", -1, 1, "", this), + new Among ( "u\u015Fi", -1, 1, "", this), + new Among ( "\u00E2\u015Fi", -1, 1, "", this), + new Among ( "a\u0163i", -1, 2, "", this), + new Among ( "ea\u0163i", 38, 1, "", this), + new Among ( "ia\u0163i", 38, 1, "", this), + new Among ( "e\u0163i", -1, 2, "", this), + new Among ( "i\u0163i", -1, 2, "", this), + new Among ( "\u00E2\u0163i", -1, 2, "", this), + new Among ( "ar\u0103\u0163i", -1, 1, "", this), + new Among ( "ser\u0103\u0163i", -1, 2, "", this), + new Among ( "aser\u0103\u0163i", 45, 1, "", this), + new Among ( "seser\u0103\u0163i", 45, 2, "", this), + new Among ( "iser\u0103\u0163i", 45, 1, "", this), + new Among ( "user\u0103\u0163i", 45, 1, "", this), + new Among ( "\u00E2ser\u0103\u0163i", 45, 1, "", this), + new Among ( "ir\u0103\u0163i", -1, 1, "", this), + new Among ( "ur\u0103\u0163i", -1, 1, "", this), + new Among ( "\u00E2r\u0103\u0163i", -1, 1, "", this), + new Among ( "am", -1, 1, "", this), + new Among ( "eam", 54, 1, "", this), + new Among ( "iam", 54, 1, "", this), + new Among ( "em", -1, 2, "", this), + new Among ( "asem", 57, 1, "", this), + new Among ( "sesem", 57, 2, "", this), + new Among ( "isem", 57, 1, "", this), + new Among ( "usem", 57, 1, "", this), + new Among ( "\u00E2sem", 57, 1, "", this), + new Among ( "im", -1, 2, "", this), + new Among ( "\u00E2m", -1, 2, "", this), + new Among ( "\u0103m", -1, 2, "", this), + new Among ( "ar\u0103m", 65, 1, "", this), + new Among ( "ser\u0103m", 65, 2, "", this), + new Among ( "aser\u0103m", 67, 1, "", this), + new Among ( "seser\u0103m", 67, 2, "", this), + new Among ( "iser\u0103m", 67, 1, "", this), + new Among ( "user\u0103m", 67, 1, "", this), + new Among ( "\u00E2ser\u0103m", 67, 1, "", this), + new Among ( "ir\u0103m", 65, 1, "", this), + new Among ( "ur\u0103m", 65, 1, "", this), + new Among ( "\u00E2r\u0103m", 65, 1, "", this), + new Among ( "au", -1, 1, "", this), + new Among ( "eau", 76, 1, "", this), + new Among ( "iau", 76, 1, "", this), + new Among ( "indu", -1, 1, "", this), + new Among ( "\u00E2ndu", -1, 1, "", this), + new Among ( "ez", -1, 1, "", this), + new Among ( "easc\u0103", -1, 1, "", this), + new Among ( "ar\u0103", -1, 1, "", this), + new Among ( "ser\u0103", -1, 2, "", this), + new Among ( "aser\u0103", 84, 1, "", this), + new Among ( "seser\u0103", 84, 2, "", this), + new Among ( "iser\u0103", 84, 1, "", this), + new Among ( "user\u0103", 84, 1, "", this), + new Among ( "\u00E2ser\u0103", 84, 1, "", this), + new Among ( "ir\u0103", -1, 1, "", this), + new Among ( "ur\u0103", -1, 1, "", this), + new Among ( "\u00E2r\u0103", -1, 1, "", this), + new Among ( "eaz\u0103", -1, 1, "", this) + }; + + private Among a_5[] = { + new Among ( "a", -1, 1, "", this), + new Among ( "e", -1, 1, "", this), + new Among ( "ie", 1, 1, "", this), + new Among ( "i", -1, 1, "", this), + new Among ( "\u0103", -1, 1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 32, 0, 0, 4 }; + + private boolean B_standard_suffix_removed; + private int I_p2; + private int I_p1; + private int I_pV; + + private void copy_from(RomanianStemmer other) { + B_standard_suffix_removed = other.B_standard_suffix_removed; + I_p2 = other.I_p2; + I_p1 = other.I_p1; + I_pV = other.I_pV; + super.copy_from(other); + } + + private boolean r_prelude() { + int v_1; + int v_2; + int v_3; + // (, line 31 + // repeat, line 32 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // goto, line 32 + golab2: while(true) + { + v_2 = cursor; + lab3: do { + // (, line 32 + if (!(in_grouping(g_v, 97, 259))) + { + break lab3; + } + // [, line 33 + bra = cursor; + // or, line 33 + lab4: do { + v_3 = cursor; + lab5: do { + // (, line 33 + // literal, line 33 + if (!(eq_s(1, "u"))) + { + break lab5; + } + // ], line 33 + ket = cursor; + if (!(in_grouping(g_v, 97, 259))) + { + break lab5; + } + // <-, line 33 + slice_from("U"); + break lab4; + } while (false); + cursor = v_3; + // (, line 34 + // literal, line 34 + if (!(eq_s(1, "i"))) + { + break lab3; + } + // ], line 34 + ket = cursor; + if (!(in_grouping(g_v, 97, 259))) + { + break lab3; + } + // <-, line 34 + slice_from("I"); + } while (false); + cursor = v_2; + break golab2; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + break lab1; + } + cursor++; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + int v_3; + int v_6; + int v_8; + // (, line 38 + I_pV = limit; + I_p1 = limit; + I_p2 = limit; + // do, line 44 + v_1 = cursor; + lab0: do { + // (, line 44 + // or, line 46 + lab1: do { + v_2 = cursor; + lab2: do { + // (, line 45 + if (!(in_grouping(g_v, 97, 259))) + { + break lab2; + } + // or, line 45 + lab3: do { + v_3 = cursor; + lab4: do { + // (, line 45 + if (!(out_grouping(g_v, 97, 259))) + { + break lab4; + } + // gopast, line 45 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 97, 259))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + break lab4; + } + cursor++; + } + break lab3; + } while (false); + cursor = v_3; + // (, line 45 + if (!(in_grouping(g_v, 97, 259))) + { + break lab2; + } + // gopast, line 45 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 97, 259))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab2; + } + cursor++; + } + } while (false); + break lab1; + } while (false); + cursor = v_2; + // (, line 47 + if (!(out_grouping(g_v, 97, 259))) + { + break lab0; + } + // or, line 47 + lab9: do { + v_6 = cursor; + lab10: do { + // (, line 47 + if (!(out_grouping(g_v, 97, 259))) + { + break lab10; + } + // gopast, line 47 + golab11: while(true) + { + lab12: do { + if (!(in_grouping(g_v, 97, 259))) + { + break lab12; + } + break golab11; + } while (false); + if (cursor >= limit) + { + break lab10; + } + cursor++; + } + break lab9; + } while (false); + cursor = v_6; + // (, line 47 + if (!(in_grouping(g_v, 97, 259))) + { + break lab0; + } + // next, line 47 + if (cursor >= limit) + { + break lab0; + } + cursor++; + } while (false); + } while (false); + // setmark pV, line 48 + I_pV = cursor; + } while (false); + cursor = v_1; + // do, line 50 + v_8 = cursor; + lab13: do { + // (, line 50 + // gopast, line 51 + golab14: while(true) + { + lab15: do { + if (!(in_grouping(g_v, 97, 259))) + { + break lab15; + } + break golab14; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 51 + golab16: while(true) + { + lab17: do { + if (!(out_grouping(g_v, 97, 259))) + { + break lab17; + } + break golab16; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p1, line 51 + I_p1 = cursor; + // gopast, line 52 + golab18: while(true) + { + lab19: do { + if (!(in_grouping(g_v, 97, 259))) + { + break lab19; + } + break golab18; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 52 + golab20: while(true) + { + lab21: do { + if (!(out_grouping(g_v, 97, 259))) + { + break lab21; + } + break golab20; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p2, line 52 + I_p2 = cursor; + } while (false); + cursor = v_8; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 56 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 56 + // [, line 58 + bra = cursor; + // substring, line 58 + among_var = find_among(a_0, 3); + if (among_var == 0) + { + break lab1; + } + // ], line 58 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 59 + // <-, line 59 + slice_from("i"); + break; + case 2: + // (, line 60 + // <-, line 60 + slice_from("u"); + break; + case 3: + // (, line 61 + // next, line 61 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_RV() { + if (!(I_pV <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_step_0() { + int among_var; + int v_1; + // (, line 72 + // [, line 73 + ket = cursor; + // substring, line 73 + among_var = find_among_b(a_1, 16); + if (among_var == 0) + { + return false; + } + // ], line 73 + bra = cursor; + // call R1, line 73 + if (!r_R1()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 75 + // delete, line 75 + slice_del(); + break; + case 2: + // (, line 77 + // <-, line 77 + slice_from("a"); + break; + case 3: + // (, line 79 + // <-, line 79 + slice_from("e"); + break; + case 4: + // (, line 81 + // <-, line 81 + slice_from("i"); + break; + case 5: + // (, line 83 + // not, line 83 + { + v_1 = limit - cursor; + lab0: do { + // literal, line 83 + if (!(eq_s_b(2, "ab"))) + { + break lab0; + } + return false; + } while (false); + cursor = limit - v_1; + } + // <-, line 83 + slice_from("i"); + break; + case 6: + // (, line 85 + // <-, line 85 + slice_from("at"); + break; + case 7: + // (, line 87 + // <-, line 87 + slice_from("a\u0163i"); + break; + } + return true; + } + + private boolean r_combo_suffix() { + int among_var; + int v_1; + // test, line 91 + v_1 = limit - cursor; + // (, line 91 + // [, line 92 + ket = cursor; + // substring, line 92 + among_var = find_among_b(a_2, 46); + if (among_var == 0) + { + return false; + } + // ], line 92 + bra = cursor; + // call R1, line 92 + if (!r_R1()) + { + return false; + } + // (, line 92 + switch(among_var) { + case 0: + return false; + case 1: + // (, line 100 + // <-, line 101 + slice_from("abil"); + break; + case 2: + // (, line 103 + // <-, line 104 + slice_from("ibil"); + break; + case 3: + // (, line 106 + // <-, line 107 + slice_from("iv"); + break; + case 4: + // (, line 112 + // <-, line 113 + slice_from("ic"); + break; + case 5: + // (, line 117 + // <-, line 118 + slice_from("at"); + break; + case 6: + // (, line 121 + // <-, line 122 + slice_from("it"); + break; + } + // set standard_suffix_removed, line 125 + B_standard_suffix_removed = true; + cursor = limit - v_1; + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + // (, line 129 + // unset standard_suffix_removed, line 130 + B_standard_suffix_removed = false; + // repeat, line 131 + replab0: while(true) + { + v_1 = limit - cursor; + lab1: do { + // call combo_suffix, line 131 + if (!r_combo_suffix()) + { + break lab1; + } + continue replab0; + } while (false); + cursor = limit - v_1; + break replab0; + } + // [, line 132 + ket = cursor; + // substring, line 132 + among_var = find_among_b(a_3, 62); + if (among_var == 0) + { + return false; + } + // ], line 132 + bra = cursor; + // call R2, line 132 + if (!r_R2()) + { + return false; + } + // (, line 132 + switch(among_var) { + case 0: + return false; + case 1: + // (, line 148 + // delete, line 149 + slice_del(); + break; + case 2: + // (, line 151 + // literal, line 152 + if (!(eq_s_b(1, "\u0163"))) + { + return false; + } + // ], line 152 + bra = cursor; + // <-, line 152 + slice_from("t"); + break; + case 3: + // (, line 155 + // <-, line 156 + slice_from("ist"); + break; + } + // set standard_suffix_removed, line 160 + B_standard_suffix_removed = true; + return true; + } + + private boolean r_verb_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + // setlimit, line 164 + v_1 = limit - cursor; + // tomark, line 164 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 164 + // [, line 165 + ket = cursor; + // substring, line 165 + among_var = find_among_b(a_4, 94); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 165 + bra = cursor; + switch(among_var) { + case 0: + limit_backward = v_2; + return false; + case 1: + // (, line 200 + // or, line 200 + lab0: do { + v_3 = limit - cursor; + lab1: do { + if (!(out_grouping_b(g_v, 97, 259))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_3; + // literal, line 200 + if (!(eq_s_b(1, "u"))) + { + limit_backward = v_2; + return false; + } + } while (false); + // delete, line 200 + slice_del(); + break; + case 2: + // (, line 214 + // delete, line 214 + slice_del(); + break; + } + limit_backward = v_2; + return true; + } + + private boolean r_vowel_suffix() { + int among_var; + // (, line 218 + // [, line 219 + ket = cursor; + // substring, line 219 + among_var = find_among_b(a_5, 5); + if (among_var == 0) + { + return false; + } + // ], line 219 + bra = cursor; + // call RV, line 219 + if (!r_RV()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 220 + // delete, line 220 + slice_del(); + break; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + // (, line 225 + // do, line 226 + v_1 = cursor; + lab0: do { + // call prelude, line 226 + if (!r_prelude()) + { + break lab0; + } + } while (false); + cursor = v_1; + // do, line 227 + v_2 = cursor; + lab1: do { + // call mark_regions, line 227 + if (!r_mark_regions()) + { + break lab1; + } + } while (false); + cursor = v_2; + // backwards, line 228 + limit_backward = cursor; cursor = limit; + // (, line 228 + // do, line 229 + v_3 = limit - cursor; + lab2: do { + // call step_0, line 229 + if (!r_step_0()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 230 + v_4 = limit - cursor; + lab3: do { + // call standard_suffix, line 230 + if (!r_standard_suffix()) + { + break lab3; + } + } while (false); + cursor = limit - v_4; + // do, line 231 + v_5 = limit - cursor; + lab4: do { + // (, line 231 + // or, line 231 + lab5: do { + v_6 = limit - cursor; + lab6: do { + // Boolean test standard_suffix_removed, line 231 + if (!(B_standard_suffix_removed)) + { + break lab6; + } + break lab5; + } while (false); + cursor = limit - v_6; + // call verb_suffix, line 231 + if (!r_verb_suffix()) + { + break lab4; + } + } while (false); + } while (false); + cursor = limit - v_5; + // do, line 232 + v_7 = limit - cursor; + lab7: do { + // call vowel_suffix, line 232 + if (!r_vowel_suffix()) + { + break lab7; + } + } while (false); + cursor = limit - v_7; + cursor = limit_backward; // do, line 234 + v_8 = cursor; + lab8: do { + // call postlude, line 234 + if (!r_postlude()) + { + break lab8; + } + } while (false); + cursor = v_8; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/RussianStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/RussianStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/RussianStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,727 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class RussianStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "\u0432", -1, 1, "", this), + new Among ( "\u0438\u0432", 0, 2, "", this), + new Among ( "\u044B\u0432", 0, 2, "", this), + new Among ( "\u0432\u0448\u0438", -1, 1, "", this), + new Among ( "\u0438\u0432\u0448\u0438", 3, 2, "", this), + new Among ( "\u044B\u0432\u0448\u0438", 3, 2, "", this), + new Among ( "\u0432\u0448\u0438\u0441\u044C", -1, 1, "", this), + new Among ( "\u0438\u0432\u0448\u0438\u0441\u044C", 6, 2, "", this), + new Among ( "\u044B\u0432\u0448\u0438\u0441\u044C", 6, 2, "", this) + }; + + private Among a_1[] = { + new Among ( "\u0435\u0435", -1, 1, "", this), + new Among ( "\u0438\u0435", -1, 1, "", this), + new Among ( "\u043E\u0435", -1, 1, "", this), + new Among ( "\u044B\u0435", -1, 1, "", this), + new Among ( "\u0438\u043C\u0438", -1, 1, "", this), + new Among ( "\u044B\u043C\u0438", -1, 1, "", this), + new Among ( "\u0435\u0439", -1, 1, "", this), + new Among ( "\u0438\u0439", -1, 1, "", this), + new Among ( "\u043E\u0439", -1, 1, "", this), + new Among ( "\u044B\u0439", -1, 1, "", this), + new Among ( "\u0435\u043C", -1, 1, "", this), + new Among ( "\u0438\u043C", -1, 1, "", this), + new Among ( "\u043E\u043C", -1, 1, "", this), + new Among ( "\u044B\u043C", -1, 1, "", this), + new Among ( "\u0435\u0433\u043E", -1, 1, "", this), + new Among ( "\u043E\u0433\u043E", -1, 1, "", this), + new Among ( "\u0435\u043C\u0443", -1, 1, "", this), + new Among ( "\u043E\u043C\u0443", -1, 1, "", this), + new Among ( "\u0438\u0445", -1, 1, "", this), + new Among ( "\u044B\u0445", -1, 1, "", this), + new Among ( "\u0435\u044E", -1, 1, "", this), + new Among ( "\u043E\u044E", -1, 1, "", this), + new Among ( "\u0443\u044E", -1, 1, "", this), + new Among ( "\u044E\u044E", -1, 1, "", this), + new Among ( "\u0430\u044F", -1, 1, "", this), + new Among ( "\u044F\u044F", -1, 1, "", this) + }; + + private Among a_2[] = { + new Among ( "\u0435\u043C", -1, 1, "", this), + new Among ( "\u043D\u043D", -1, 1, "", this), + new Among ( "\u0432\u0448", -1, 1, "", this), + new Among ( "\u0438\u0432\u0448", 2, 2, "", this), + new Among ( "\u044B\u0432\u0448", 2, 2, "", this), + new Among ( "\u0449", -1, 1, "", this), + new Among ( "\u044E\u0449", 5, 1, "", this), + new Among ( "\u0443\u044E\u0449", 6, 2, "", this) + }; + + private Among a_3[] = { + new Among ( "\u0441\u044C", -1, 1, "", this), + new Among ( "\u0441\u044F", -1, 1, "", this) + }; + + private Among a_4[] = { + new Among ( "\u043B\u0430", -1, 1, "", this), + new Among ( "\u0438\u043B\u0430", 0, 2, "", this), + new Among ( "\u044B\u043B\u0430", 0, 2, "", this), + new Among ( "\u043D\u0430", -1, 1, "", this), + new Among ( "\u0435\u043D\u0430", 3, 2, "", this), + new Among ( "\u0435\u0442\u0435", -1, 1, "", this), + new Among ( "\u0438\u0442\u0435", -1, 2, "", this), + new Among ( "\u0439\u0442\u0435", -1, 1, "", this), + new Among ( "\u0435\u0439\u0442\u0435", 7, 2, "", this), + new Among ( "\u0443\u0439\u0442\u0435", 7, 2, "", this), + new Among ( "\u043B\u0438", -1, 1, "", this), + new Among ( "\u0438\u043B\u0438", 10, 2, "", this), + new Among ( "\u044B\u043B\u0438", 10, 2, "", this), + new Among ( "\u0439", -1, 1, "", this), + new Among ( "\u0435\u0439", 13, 2, "", this), + new Among ( "\u0443\u0439", 13, 2, "", this), + new Among ( "\u043B", -1, 1, "", this), + new Among ( "\u0438\u043B", 16, 2, "", this), + new Among ( "\u044B\u043B", 16, 2, "", this), + new Among ( "\u0435\u043C", -1, 1, "", this), + new Among ( "\u0438\u043C", -1, 2, "", this), + new Among ( "\u044B\u043C", -1, 2, "", this), + new Among ( "\u043D", -1, 1, "", this), + new Among ( "\u0435\u043D", 22, 2, "", this), + new Among ( "\u043B\u043E", -1, 1, "", this), + new Among ( "\u0438\u043B\u043E", 24, 2, "", this), + new Among ( "\u044B\u043B\u043E", 24, 2, "", this), + new Among ( "\u043D\u043E", -1, 1, "", this), + new Among ( "\u0435\u043D\u043E", 27, 2, "", this), + new Among ( "\u043D\u043D\u043E", 27, 1, "", this), + new Among ( "\u0435\u0442", -1, 1, "", this), + new Among ( "\u0443\u0435\u0442", 30, 2, "", this), + new Among ( "\u0438\u0442", -1, 2, "", this), + new Among ( "\u044B\u0442", -1, 2, "", this), + new Among ( "\u044E\u0442", -1, 1, "", this), + new Among ( "\u0443\u044E\u0442", 34, 2, "", this), + new Among ( "\u044F\u0442", -1, 2, "", this), + new Among ( "\u043D\u044B", -1, 1, "", this), + new Among ( "\u0435\u043D\u044B", 37, 2, "", this), + new Among ( "\u0442\u044C", -1, 1, "", this), + new Among ( "\u0438\u0442\u044C", 39, 2, "", this), + new Among ( "\u044B\u0442\u044C", 39, 2, "", this), + new Among ( "\u0435\u0448\u044C", -1, 1, "", this), + new Among ( "\u0438\u0448\u044C", -1, 2, "", this), + new Among ( "\u044E", -1, 2, "", this), + new Among ( "\u0443\u044E", 44, 2, "", this) + }; + + private Among a_5[] = { + new Among ( "\u0430", -1, 1, "", this), + new Among ( "\u0435\u0432", -1, 1, "", this), + new Among ( "\u043E\u0432", -1, 1, "", this), + new Among ( "\u0435", -1, 1, "", this), + new Among ( "\u0438\u0435", 3, 1, "", this), + new Among ( "\u044C\u0435", 3, 1, "", this), + new Among ( "\u0438", -1, 1, "", this), + new Among ( "\u0435\u0438", 6, 1, "", this), + new Among ( "\u0438\u0438", 6, 1, "", this), + new Among ( "\u0430\u043C\u0438", 6, 1, "", this), + new Among ( "\u044F\u043C\u0438", 6, 1, "", this), + new Among ( "\u0438\u044F\u043C\u0438", 10, 1, "", this), + new Among ( "\u0439", -1, 1, "", this), + new Among ( "\u0435\u0439", 12, 1, "", this), + new Among ( "\u0438\u0435\u0439", 13, 1, "", this), + new Among ( "\u0438\u0439", 12, 1, "", this), + new Among ( "\u043E\u0439", 12, 1, "", this), + new Among ( "\u0430\u043C", -1, 1, "", this), + new Among ( "\u0435\u043C", -1, 1, "", this), + new Among ( "\u0438\u0435\u043C", 18, 1, "", this), + new Among ( "\u043E\u043C", -1, 1, "", this), + new Among ( "\u044F\u043C", -1, 1, "", this), + new Among ( "\u0438\u044F\u043C", 21, 1, "", this), + new Among ( "\u043E", -1, 1, "", this), + new Among ( "\u0443", -1, 1, "", this), + new Among ( "\u0430\u0445", -1, 1, "", this), + new Among ( "\u044F\u0445", -1, 1, "", this), + new Among ( "\u0438\u044F\u0445", 26, 1, "", this), + new Among ( "\u044B", -1, 1, "", this), + new Among ( "\u044C", -1, 1, "", this), + new Among ( "\u044E", -1, 1, "", this), + new Among ( "\u0438\u044E", 30, 1, "", this), + new Among ( "\u044C\u044E", 30, 1, "", this), + new Among ( "\u044F", -1, 1, "", this), + new Among ( "\u0438\u044F", 33, 1, "", this), + new Among ( "\u044C\u044F", 33, 1, "", this) + }; + + private Among a_6[] = { + new Among ( "\u043E\u0441\u0442", -1, 1, "", this), + new Among ( "\u043E\u0441\u0442\u044C", -1, 1, "", this) + }; + + private Among a_7[] = { + new Among ( "\u0435\u0439\u0448\u0435", -1, 1, "", this), + new Among ( "\u043D", -1, 2, "", this), + new Among ( "\u0435\u0439\u0448", -1, 1, "", this), + new Among ( "\u044C", -1, 3, "", this) + }; + + private static final char g_v[] = {33, 65, 8, 232 }; + + private int I_p2; + private int I_pV; + + private void copy_from(RussianStemmer other) { + I_p2 = other.I_p2; + I_pV = other.I_pV; + super.copy_from(other); + } + + private boolean r_mark_regions() { + int v_1; + // (, line 57 + I_pV = limit; + I_p2 = limit; + // do, line 61 + v_1 = cursor; + lab0: do { + // (, line 61 + // gopast, line 62 + golab1: while(true) + { + lab2: do { + if (!(in_grouping(g_v, 1072, 1103))) + { + break lab2; + } + break golab1; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + // setmark pV, line 62 + I_pV = cursor; + // gopast, line 62 + golab3: while(true) + { + lab4: do { + if (!(out_grouping(g_v, 1072, 1103))) + { + break lab4; + } + break golab3; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + // gopast, line 63 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 1072, 1103))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + // gopast, line 63 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 1072, 1103))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab0; + } + cursor++; + } + // setmark p2, line 63 + I_p2 = cursor; + } while (false); + cursor = v_1; + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_perfective_gerund() { + int among_var; + int v_1; + // (, line 71 + // [, line 72 + ket = cursor; + // substring, line 72 + among_var = find_among_b(a_0, 9); + if (among_var == 0) + { + return false; + } + // ], line 72 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 76 + // or, line 76 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // literal, line 76 + if (!(eq_s_b(1, "\u0430"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // literal, line 76 + if (!(eq_s_b(1, "\u044F"))) + { + return false; + } + } while (false); + // delete, line 76 + slice_del(); + break; + case 2: + // (, line 83 + // delete, line 83 + slice_del(); + break; + } + return true; + } + + private boolean r_adjective() { + int among_var; + // (, line 87 + // [, line 88 + ket = cursor; + // substring, line 88 + among_var = find_among_b(a_1, 26); + if (among_var == 0) + { + return false; + } + // ], line 88 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 97 + // delete, line 97 + slice_del(); + break; + } + return true; + } + + private boolean r_adjectival() { + int among_var; + int v_1; + int v_2; + // (, line 101 + // call adjective, line 102 + if (!r_adjective()) + { + return false; + } + // try, line 109 + v_1 = limit - cursor; + lab0: do { + // (, line 109 + // [, line 110 + ket = cursor; + // substring, line 110 + among_var = find_among_b(a_2, 8); + if (among_var == 0) + { + cursor = limit - v_1; + break lab0; + } + // ], line 110 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_1; + break lab0; + case 1: + // (, line 115 + // or, line 115 + lab1: do { + v_2 = limit - cursor; + lab2: do { + // literal, line 115 + if (!(eq_s_b(1, "\u0430"))) + { + break lab2; + } + break lab1; + } while (false); + cursor = limit - v_2; + // literal, line 115 + if (!(eq_s_b(1, "\u044F"))) + { + cursor = limit - v_1; + break lab0; + } + } while (false); + // delete, line 115 + slice_del(); + break; + case 2: + // (, line 122 + // delete, line 122 + slice_del(); + break; + } + } while (false); + return true; + } + + private boolean r_reflexive() { + int among_var; + // (, line 128 + // [, line 129 + ket = cursor; + // substring, line 129 + among_var = find_among_b(a_3, 2); + if (among_var == 0) + { + return false; + } + // ], line 129 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 132 + // delete, line 132 + slice_del(); + break; + } + return true; + } + + private boolean r_verb() { + int among_var; + int v_1; + // (, line 136 + // [, line 137 + ket = cursor; + // substring, line 137 + among_var = find_among_b(a_4, 46); + if (among_var == 0) + { + return false; + } + // ], line 137 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 143 + // or, line 143 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // literal, line 143 + if (!(eq_s_b(1, "\u0430"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_1; + // literal, line 143 + if (!(eq_s_b(1, "\u044F"))) + { + return false; + } + } while (false); + // delete, line 143 + slice_del(); + break; + case 2: + // (, line 151 + // delete, line 151 + slice_del(); + break; + } + return true; + } + + private boolean r_noun() { + int among_var; + // (, line 159 + // [, line 160 + ket = cursor; + // substring, line 160 + among_var = find_among_b(a_5, 36); + if (among_var == 0) + { + return false; + } + // ], line 160 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 167 + // delete, line 167 + slice_del(); + break; + } + return true; + } + + private boolean r_derivational() { + int among_var; + // (, line 175 + // [, line 176 + ket = cursor; + // substring, line 176 + among_var = find_among_b(a_6, 2); + if (among_var == 0) + { + return false; + } + // ], line 176 + bra = cursor; + // call R2, line 176 + if (!r_R2()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 179 + // delete, line 179 + slice_del(); + break; + } + return true; + } + + private boolean r_tidy_up() { + int among_var; + // (, line 183 + // [, line 184 + ket = cursor; + // substring, line 184 + among_var = find_among_b(a_7, 4); + if (among_var == 0) + { + return false; + } + // ], line 184 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 188 + // delete, line 188 + slice_del(); + // [, line 189 + ket = cursor; + // literal, line 189 + if (!(eq_s_b(1, "\u043D"))) + { + return false; + } + // ], line 189 + bra = cursor; + // literal, line 189 + if (!(eq_s_b(1, "\u043D"))) + { + return false; + } + // delete, line 189 + slice_del(); + break; + case 2: + // (, line 192 + // literal, line 192 + if (!(eq_s_b(1, "\u043D"))) + { + return false; + } + // delete, line 192 + slice_del(); + break; + case 3: + // (, line 194 + // delete, line 194 + slice_del(); + break; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + // (, line 199 + // do, line 201 + v_1 = cursor; + lab0: do { + // call mark_regions, line 201 + if (!r_mark_regions()) + { + break lab0; + } + } while (false); + cursor = v_1; + // backwards, line 202 + limit_backward = cursor; cursor = limit; + // setlimit, line 202 + v_2 = limit - cursor; + // tomark, line 202 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_3 = limit_backward; + limit_backward = cursor; + cursor = limit - v_2; + // (, line 202 + // do, line 203 + v_4 = limit - cursor; + lab1: do { + // (, line 203 + // or, line 204 + lab2: do { + v_5 = limit - cursor; + lab3: do { + // call perfective_gerund, line 204 + if (!r_perfective_gerund()) + { + break lab3; + } + break lab2; + } while (false); + cursor = limit - v_5; + // (, line 205 + // try, line 205 + v_6 = limit - cursor; + lab4: do { + // call reflexive, line 205 + if (!r_reflexive()) + { + cursor = limit - v_6; + break lab4; + } + } while (false); + // or, line 206 + lab5: do { + v_7 = limit - cursor; + lab6: do { + // call adjectival, line 206 + if (!r_adjectival()) + { + break lab6; + } + break lab5; + } while (false); + cursor = limit - v_7; + lab7: do { + // call verb, line 206 + if (!r_verb()) + { + break lab7; + } + break lab5; + } while (false); + cursor = limit - v_7; + // call noun, line 206 + if (!r_noun()) + { + break lab1; + } + } while (false); + } while (false); + } while (false); + cursor = limit - v_4; + // try, line 209 + v_8 = limit - cursor; + lab8: do { + // (, line 209 + // [, line 209 + ket = cursor; + // literal, line 209 + if (!(eq_s_b(1, "\u0438"))) + { + cursor = limit - v_8; + break lab8; + } + // ], line 209 + bra = cursor; + // delete, line 209 + slice_del(); + } while (false); + // do, line 212 + v_9 = limit - cursor; + lab9: do { + // call derivational, line 212 + if (!r_derivational()) + { + break lab9; + } + } while (false); + cursor = limit - v_9; + // do, line 213 + v_10 = limit - cursor; + lab10: do { + // call tidy_up, line 213 + if (!r_tidy_up()) + { + break lab10; + } + } while (false); + cursor = limit - v_10; + limit_backward = v_3; + cursor = limit_backward; return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/SpanishStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/SpanishStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/SpanishStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,1182 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class SpanishStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "", -1, 6, "", this), + new Among ( "\u00E1", 0, 1, "", this), + new Among ( "\u00E9", 0, 2, "", this), + new Among ( "\u00ED", 0, 3, "", this), + new Among ( "\u00F3", 0, 4, "", this), + new Among ( "\u00FA", 0, 5, "", this) + }; + + private Among a_1[] = { + new Among ( "la", -1, -1, "", this), + new Among ( "sela", 0, -1, "", this), + new Among ( "le", -1, -1, "", this), + new Among ( "me", -1, -1, "", this), + new Among ( "se", -1, -1, "", this), + new Among ( "lo", -1, -1, "", this), + new Among ( "selo", 5, -1, "", this), + new Among ( "las", -1, -1, "", this), + new Among ( "selas", 7, -1, "", this), + new Among ( "les", -1, -1, "", this), + new Among ( "los", -1, -1, "", this), + new Among ( "selos", 10, -1, "", this), + new Among ( "nos", -1, -1, "", this) + }; + + private Among a_2[] = { + new Among ( "ando", -1, 6, "", this), + new Among ( "iendo", -1, 6, "", this), + new Among ( "yendo", -1, 7, "", this), + new Among ( "\u00E1ndo", -1, 2, "", this), + new Among ( "i\u00E9ndo", -1, 1, "", this), + new Among ( "ar", -1, 6, "", this), + new Among ( "er", -1, 6, "", this), + new Among ( "ir", -1, 6, "", this), + new Among ( "\u00E1r", -1, 3, "", this), + new Among ( "\u00E9r", -1, 4, "", this), + new Among ( "\u00EDr", -1, 5, "", this) + }; + + private Among a_3[] = { + new Among ( "ic", -1, -1, "", this), + new Among ( "ad", -1, -1, "", this), + new Among ( "os", -1, -1, "", this), + new Among ( "iv", -1, 1, "", this) + }; + + private Among a_4[] = { + new Among ( "able", -1, 1, "", this), + new Among ( "ible", -1, 1, "", this), + new Among ( "ante", -1, 1, "", this) + }; + + private Among a_5[] = { + new Among ( "ic", -1, 1, "", this), + new Among ( "abil", -1, 1, "", this), + new Among ( "iv", -1, 1, "", this) + }; + + private Among a_6[] = { + new Among ( "ica", -1, 1, "", this), + new Among ( "ancia", -1, 2, "", this), + new Among ( "encia", -1, 5, "", this), + new Among ( "adora", -1, 2, "", this), + new Among ( "osa", -1, 1, "", this), + new Among ( "ista", -1, 1, "", this), + new Among ( "iva", -1, 9, "", this), + new Among ( "anza", -1, 1, "", this), + new Among ( "log\u00EDa", -1, 3, "", this), + new Among ( "idad", -1, 8, "", this), + new Among ( "able", -1, 1, "", this), + new Among ( "ible", -1, 1, "", this), + new Among ( "ante", -1, 2, "", this), + new Among ( "mente", -1, 7, "", this), + new Among ( "amente", 13, 6, "", this), + new Among ( "aci\u00F3n", -1, 2, "", this), + new Among ( "uci\u00F3n", -1, 4, "", this), + new Among ( "ico", -1, 1, "", this), + new Among ( "ismo", -1, 1, "", this), + new Among ( "oso", -1, 1, "", this), + new Among ( "amiento", -1, 1, "", this), + new Among ( "imiento", -1, 1, "", this), + new Among ( "ivo", -1, 9, "", this), + new Among ( "ador", -1, 2, "", this), + new Among ( "icas", -1, 1, "", this), + new Among ( "ancias", -1, 2, "", this), + new Among ( "encias", -1, 5, "", this), + new Among ( "adoras", -1, 2, "", this), + new Among ( "osas", -1, 1, "", this), + new Among ( "istas", -1, 1, "", this), + new Among ( "ivas", -1, 9, "", this), + new Among ( "anzas", -1, 1, "", this), + new Among ( "log\u00EDas", -1, 3, "", this), + new Among ( "idades", -1, 8, "", this), + new Among ( "ables", -1, 1, "", this), + new Among ( "ibles", -1, 1, "", this), + new Among ( "aciones", -1, 2, "", this), + new Among ( "uciones", -1, 4, "", this), + new Among ( "adores", -1, 2, "", this), + new Among ( "antes", -1, 2, "", this), + new Among ( "icos", -1, 1, "", this), + new Among ( "ismos", -1, 1, "", this), + new Among ( "osos", -1, 1, "", this), + new Among ( "amientos", -1, 1, "", this), + new Among ( "imientos", -1, 1, "", this), + new Among ( "ivos", -1, 9, "", this) + }; + + private Among a_7[] = { + new Among ( "ya", -1, 1, "", this), + new Among ( "ye", -1, 1, "", this), + new Among ( "yan", -1, 1, "", this), + new Among ( "yen", -1, 1, "", this), + new Among ( "yeron", -1, 1, "", this), + new Among ( "yendo", -1, 1, "", this), + new Among ( "yo", -1, 1, "", this), + new Among ( "yas", -1, 1, "", this), + new Among ( "yes", -1, 1, "", this), + new Among ( "yais", -1, 1, "", this), + new Among ( "yamos", -1, 1, "", this), + new Among ( "y\u00F3", -1, 1, "", this) + }; + + private Among a_8[] = { + new Among ( "aba", -1, 2, "", this), + new Among ( "ada", -1, 2, "", this), + new Among ( "ida", -1, 2, "", this), + new Among ( "ara", -1, 2, "", this), + new Among ( "iera", -1, 2, "", this), + new Among ( "\u00EDa", -1, 2, "", this), + new Among ( "ar\u00EDa", 5, 2, "", this), + new Among ( "er\u00EDa", 5, 2, "", this), + new Among ( "ir\u00EDa", 5, 2, "", this), + new Among ( "ad", -1, 2, "", this), + new Among ( "ed", -1, 2, "", this), + new Among ( "id", -1, 2, "", this), + new Among ( "ase", -1, 2, "", this), + new Among ( "iese", -1, 2, "", this), + new Among ( "aste", -1, 2, "", this), + new Among ( "iste", -1, 2, "", this), + new Among ( "an", -1, 2, "", this), + new Among ( "aban", 16, 2, "", this), + new Among ( "aran", 16, 2, "", this), + new Among ( "ieran", 16, 2, "", this), + new Among ( "\u00EDan", 16, 2, "", this), + new Among ( "ar\u00EDan", 20, 2, "", this), + new Among ( "er\u00EDan", 20, 2, "", this), + new Among ( "ir\u00EDan", 20, 2, "", this), + new Among ( "en", -1, 1, "", this), + new Among ( "asen", 24, 2, "", this), + new Among ( "iesen", 24, 2, "", this), + new Among ( "aron", -1, 2, "", this), + new Among ( "ieron", -1, 2, "", this), + new Among ( "ar\u00E1n", -1, 2, "", this), + new Among ( "er\u00E1n", -1, 2, "", this), + new Among ( "ir\u00E1n", -1, 2, "", this), + new Among ( "ado", -1, 2, "", this), + new Among ( "ido", -1, 2, "", this), + new Among ( "ando", -1, 2, "", this), + new Among ( "iendo", -1, 2, "", this), + new Among ( "ar", -1, 2, "", this), + new Among ( "er", -1, 2, "", this), + new Among ( "ir", -1, 2, "", this), + new Among ( "as", -1, 2, "", this), + new Among ( "abas", 39, 2, "", this), + new Among ( "adas", 39, 2, "", this), + new Among ( "idas", 39, 2, "", this), + new Among ( "aras", 39, 2, "", this), + new Among ( "ieras", 39, 2, "", this), + new Among ( "\u00EDas", 39, 2, "", this), + new Among ( "ar\u00EDas", 45, 2, "", this), + new Among ( "er\u00EDas", 45, 2, "", this), + new Among ( "ir\u00EDas", 45, 2, "", this), + new Among ( "es", -1, 1, "", this), + new Among ( "ases", 49, 2, "", this), + new Among ( "ieses", 49, 2, "", this), + new Among ( "abais", -1, 2, "", this), + new Among ( "arais", -1, 2, "", this), + new Among ( "ierais", -1, 2, "", this), + new Among ( "\u00EDais", -1, 2, "", this), + new Among ( "ar\u00EDais", 55, 2, "", this), + new Among ( "er\u00EDais", 55, 2, "", this), + new Among ( "ir\u00EDais", 55, 2, "", this), + new Among ( "aseis", -1, 2, "", this), + new Among ( "ieseis", -1, 2, "", this), + new Among ( "asteis", -1, 2, "", this), + new Among ( "isteis", -1, 2, "", this), + new Among ( "\u00E1is", -1, 2, "", this), + new Among ( "\u00E9is", -1, 1, "", this), + new Among ( "ar\u00E9is", 64, 2, "", this), + new Among ( "er\u00E9is", 64, 2, "", this), + new Among ( "ir\u00E9is", 64, 2, "", this), + new Among ( "ados", -1, 2, "", this), + new Among ( "idos", -1, 2, "", this), + new Among ( "amos", -1, 2, "", this), + new Among ( "\u00E1bamos", 70, 2, "", this), + new Among ( "\u00E1ramos", 70, 2, "", this), + new Among ( "i\u00E9ramos", 70, 2, "", this), + new Among ( "\u00EDamos", 70, 2, "", this), + new Among ( "ar\u00EDamos", 74, 2, "", this), + new Among ( "er\u00EDamos", 74, 2, "", this), + new Among ( "ir\u00EDamos", 74, 2, "", this), + new Among ( "emos", -1, 1, "", this), + new Among ( "aremos", 78, 2, "", this), + new Among ( "eremos", 78, 2, "", this), + new Among ( "iremos", 78, 2, "", this), + new Among ( "\u00E1semos", 78, 2, "", this), + new Among ( "i\u00E9semos", 78, 2, "", this), + new Among ( "imos", -1, 2, "", this), + new Among ( "ar\u00E1s", -1, 2, "", this), + new Among ( "er\u00E1s", -1, 2, "", this), + new Among ( "ir\u00E1s", -1, 2, "", this), + new Among ( "\u00EDs", -1, 2, "", this), + new Among ( "ar\u00E1", -1, 2, "", this), + new Among ( "er\u00E1", -1, 2, "", this), + new Among ( "ir\u00E1", -1, 2, "", this), + new Among ( "ar\u00E9", -1, 2, "", this), + new Among ( "er\u00E9", -1, 2, "", this), + new Among ( "ir\u00E9", -1, 2, "", this), + new Among ( "i\u00F3", -1, 2, "", this) + }; + + private Among a_9[] = { + new Among ( "a", -1, 1, "", this), + new Among ( "e", -1, 2, "", this), + new Among ( "o", -1, 1, "", this), + new Among ( "os", -1, 1, "", this), + new Among ( "\u00E1", -1, 1, "", this), + new Among ( "\u00E9", -1, 2, "", this), + new Among ( "\u00ED", -1, 1, "", this), + new Among ( "\u00F3", -1, 1, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 4, 10 }; + + private int I_p2; + private int I_p1; + private int I_pV; + + private void copy_from(SpanishStemmer other) { + I_p2 = other.I_p2; + I_p1 = other.I_p1; + I_pV = other.I_pV; + super.copy_from(other); + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + int v_3; + int v_6; + int v_8; + // (, line 31 + I_pV = limit; + I_p1 = limit; + I_p2 = limit; + // do, line 37 + v_1 = cursor; + lab0: do { + // (, line 37 + // or, line 39 + lab1: do { + v_2 = cursor; + lab2: do { + // (, line 38 + if (!(in_grouping(g_v, 97, 252))) + { + break lab2; + } + // or, line 38 + lab3: do { + v_3 = cursor; + lab4: do { + // (, line 38 + if (!(out_grouping(g_v, 97, 252))) + { + break lab4; + } + // gopast, line 38 + golab5: while(true) + { + lab6: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab6; + } + break golab5; + } while (false); + if (cursor >= limit) + { + break lab4; + } + cursor++; + } + break lab3; + } while (false); + cursor = v_3; + // (, line 38 + if (!(in_grouping(g_v, 97, 252))) + { + break lab2; + } + // gopast, line 38 + golab7: while(true) + { + lab8: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab8; + } + break golab7; + } while (false); + if (cursor >= limit) + { + break lab2; + } + cursor++; + } + } while (false); + break lab1; + } while (false); + cursor = v_2; + // (, line 40 + if (!(out_grouping(g_v, 97, 252))) + { + break lab0; + } + // or, line 40 + lab9: do { + v_6 = cursor; + lab10: do { + // (, line 40 + if (!(out_grouping(g_v, 97, 252))) + { + break lab10; + } + // gopast, line 40 + golab11: while(true) + { + lab12: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab12; + } + break golab11; + } while (false); + if (cursor >= limit) + { + break lab10; + } + cursor++; + } + break lab9; + } while (false); + cursor = v_6; + // (, line 40 + if (!(in_grouping(g_v, 97, 252))) + { + break lab0; + } + // next, line 40 + if (cursor >= limit) + { + break lab0; + } + cursor++; + } while (false); + } while (false); + // setmark pV, line 41 + I_pV = cursor; + } while (false); + cursor = v_1; + // do, line 43 + v_8 = cursor; + lab13: do { + // (, line 43 + // gopast, line 44 + golab14: while(true) + { + lab15: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab15; + } + break golab14; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 44 + golab16: while(true) + { + lab17: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab17; + } + break golab16; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p1, line 44 + I_p1 = cursor; + // gopast, line 45 + golab18: while(true) + { + lab19: do { + if (!(in_grouping(g_v, 97, 252))) + { + break lab19; + } + break golab18; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // gopast, line 45 + golab20: while(true) + { + lab21: do { + if (!(out_grouping(g_v, 97, 252))) + { + break lab21; + } + break golab20; + } while (false); + if (cursor >= limit) + { + break lab13; + } + cursor++; + } + // setmark p2, line 45 + I_p2 = cursor; + } while (false); + cursor = v_8; + return true; + } + + private boolean r_postlude() { + int among_var; + int v_1; + // repeat, line 49 + replab0: while(true) + { + v_1 = cursor; + lab1: do { + // (, line 49 + // [, line 50 + bra = cursor; + // substring, line 50 + among_var = find_among(a_0, 6); + if (among_var == 0) + { + break lab1; + } + // ], line 50 + ket = cursor; + switch(among_var) { + case 0: + break lab1; + case 1: + // (, line 51 + // <-, line 51 + slice_from("a"); + break; + case 2: + // (, line 52 + // <-, line 52 + slice_from("e"); + break; + case 3: + // (, line 53 + // <-, line 53 + slice_from("i"); + break; + case 4: + // (, line 54 + // <-, line 54 + slice_from("o"); + break; + case 5: + // (, line 55 + // <-, line 55 + slice_from("u"); + break; + case 6: + // (, line 57 + // next, line 57 + if (cursor >= limit) + { + break lab1; + } + cursor++; + break; + } + continue replab0; + } while (false); + cursor = v_1; + break replab0; + } + return true; + } + + private boolean r_RV() { + if (!(I_pV <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R1() { + if (!(I_p1 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_R2() { + if (!(I_p2 <= cursor)) + { + return false; + } + return true; + } + + private boolean r_attached_pronoun() { + int among_var; + // (, line 67 + // [, line 68 + ket = cursor; + // substring, line 68 + if (find_among_b(a_1, 13) == 0) + { + return false; + } + // ], line 68 + bra = cursor; + // substring, line 72 + among_var = find_among_b(a_2, 11); + if (among_var == 0) + { + return false; + } + // call RV, line 72 + if (!r_RV()) + { + return false; + } + switch(among_var) { + case 0: + return false; + case 1: + // (, line 73 + // ], line 73 + bra = cursor; + // <-, line 73 + slice_from("iendo"); + break; + case 2: + // (, line 74 + // ], line 74 + bra = cursor; + // <-, line 74 + slice_from("ando"); + break; + case 3: + // (, line 75 + // ], line 75 + bra = cursor; + // <-, line 75 + slice_from("ar"); + break; + case 4: + // (, line 76 + // ], line 76 + bra = cursor; + // <-, line 76 + slice_from("er"); + break; + case 5: + // (, line 77 + // ], line 77 + bra = cursor; + // <-, line 77 + slice_from("ir"); + break; + case 6: + // (, line 81 + // delete, line 81 + slice_del(); + break; + case 7: + // (, line 82 + // literal, line 82 + if (!(eq_s_b(1, "u"))) + { + return false; + } + // delete, line 82 + slice_del(); + break; + } + return true; + } + + private boolean r_standard_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + // (, line 86 + // [, line 87 + ket = cursor; + // substring, line 87 + among_var = find_among_b(a_6, 46); + if (among_var == 0) + { + return false; + } + // ], line 87 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 98 + // call R2, line 99 + if (!r_R2()) + { + return false; + } + // delete, line 99 + slice_del(); + break; + case 2: + // (, line 104 + // call R2, line 105 + if (!r_R2()) + { + return false; + } + // delete, line 105 + slice_del(); + // try, line 106 + v_1 = limit - cursor; + lab0: do { + // (, line 106 + // [, line 106 + ket = cursor; + // literal, line 106 + if (!(eq_s_b(2, "ic"))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 106 + bra = cursor; + // call R2, line 106 + if (!r_R2()) + { + cursor = limit - v_1; + break lab0; + } + // delete, line 106 + slice_del(); + } while (false); + break; + case 3: + // (, line 110 + // call R2, line 111 + if (!r_R2()) + { + return false; + } + // <-, line 111 + slice_from("log"); + break; + case 4: + // (, line 114 + // call R2, line 115 + if (!r_R2()) + { + return false; + } + // <-, line 115 + slice_from("u"); + break; + case 5: + // (, line 118 + // call R2, line 119 + if (!r_R2()) + { + return false; + } + // <-, line 119 + slice_from("ente"); + break; + case 6: + // (, line 122 + // call R1, line 123 + if (!r_R1()) + { + return false; + } + // delete, line 123 + slice_del(); + // try, line 124 + v_2 = limit - cursor; + lab1: do { + // (, line 124 + // [, line 125 + ket = cursor; + // substring, line 125 + among_var = find_among_b(a_3, 4); + if (among_var == 0) + { + cursor = limit - v_2; + break lab1; + } + // ], line 125 + bra = cursor; + // call R2, line 125 + if (!r_R2()) + { + cursor = limit - v_2; + break lab1; + } + // delete, line 125 + slice_del(); + switch(among_var) { + case 0: + cursor = limit - v_2; + break lab1; + case 1: + // (, line 126 + // [, line 126 + ket = cursor; + // literal, line 126 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_2; + break lab1; + } + // ], line 126 + bra = cursor; + // call R2, line 126 + if (!r_R2()) + { + cursor = limit - v_2; + break lab1; + } + // delete, line 126 + slice_del(); + break; + } + } while (false); + break; + case 7: + // (, line 134 + // call R2, line 135 + if (!r_R2()) + { + return false; + } + // delete, line 135 + slice_del(); + // try, line 136 + v_3 = limit - cursor; + lab2: do { + // (, line 136 + // [, line 137 + ket = cursor; + // substring, line 137 + among_var = find_among_b(a_4, 3); + if (among_var == 0) + { + cursor = limit - v_3; + break lab2; + } + // ], line 137 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_3; + break lab2; + case 1: + // (, line 140 + // call R2, line 140 + if (!r_R2()) + { + cursor = limit - v_3; + break lab2; + } + // delete, line 140 + slice_del(); + break; + } + } while (false); + break; + case 8: + // (, line 146 + // call R2, line 147 + if (!r_R2()) + { + return false; + } + // delete, line 147 + slice_del(); + // try, line 148 + v_4 = limit - cursor; + lab3: do { + // (, line 148 + // [, line 149 + ket = cursor; + // substring, line 149 + among_var = find_among_b(a_5, 3); + if (among_var == 0) + { + cursor = limit - v_4; + break lab3; + } + // ], line 149 + bra = cursor; + switch(among_var) { + case 0: + cursor = limit - v_4; + break lab3; + case 1: + // (, line 152 + // call R2, line 152 + if (!r_R2()) + { + cursor = limit - v_4; + break lab3; + } + // delete, line 152 + slice_del(); + break; + } + } while (false); + break; + case 9: + // (, line 158 + // call R2, line 159 + if (!r_R2()) + { + return false; + } + // delete, line 159 + slice_del(); + // try, line 160 + v_5 = limit - cursor; + lab4: do { + // (, line 160 + // [, line 161 + ket = cursor; + // literal, line 161 + if (!(eq_s_b(2, "at"))) + { + cursor = limit - v_5; + break lab4; + } + // ], line 161 + bra = cursor; + // call R2, line 161 + if (!r_R2()) + { + cursor = limit - v_5; + break lab4; + } + // delete, line 161 + slice_del(); + } while (false); + break; + } + return true; + } + + private boolean r_y_verb_suffix() { + int among_var; + int v_1; + int v_2; + // (, line 167 + // setlimit, line 168 + v_1 = limit - cursor; + // tomark, line 168 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 168 + // [, line 168 + ket = cursor; + // substring, line 168 + among_var = find_among_b(a_7, 12); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 168 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 171 + // literal, line 171 + if (!(eq_s_b(1, "u"))) + { + return false; + } + // delete, line 171 + slice_del(); + break; + } + return true; + } + + private boolean r_verb_suffix() { + int among_var; + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 175 + // setlimit, line 176 + v_1 = limit - cursor; + // tomark, line 176 + if (cursor < I_pV) + { + return false; + } + cursor = I_pV; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 176 + // [, line 176 + ket = cursor; + // substring, line 176 + among_var = find_among_b(a_8, 96); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 176 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 179 + // try, line 179 + v_3 = limit - cursor; + lab0: do { + // (, line 179 + // literal, line 179 + if (!(eq_s_b(1, "u"))) + { + cursor = limit - v_3; + break lab0; + } + // test, line 179 + v_4 = limit - cursor; + // literal, line 179 + if (!(eq_s_b(1, "g"))) + { + cursor = limit - v_3; + break lab0; + } + cursor = limit - v_4; + } while (false); + // ], line 179 + bra = cursor; + // delete, line 179 + slice_del(); + break; + case 2: + // (, line 200 + // delete, line 200 + slice_del(); + break; + } + return true; + } + + private boolean r_residual_suffix() { + int among_var; + int v_1; + int v_2; + // (, line 204 + // [, line 205 + ket = cursor; + // substring, line 205 + among_var = find_among_b(a_9, 8); + if (among_var == 0) + { + return false; + } + // ], line 205 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 208 + // call RV, line 208 + if (!r_RV()) + { + return false; + } + // delete, line 208 + slice_del(); + break; + case 2: + // (, line 210 + // call RV, line 210 + if (!r_RV()) + { + return false; + } + // delete, line 210 + slice_del(); + // try, line 210 + v_1 = limit - cursor; + lab0: do { + // (, line 210 + // [, line 210 + ket = cursor; + // literal, line 210 + if (!(eq_s_b(1, "u"))) + { + cursor = limit - v_1; + break lab0; + } + // ], line 210 + bra = cursor; + // test, line 210 + v_2 = limit - cursor; + // literal, line 210 + if (!(eq_s_b(1, "g"))) + { + cursor = limit - v_1; + break lab0; + } + cursor = limit - v_2; + // call RV, line 210 + if (!r_RV()) + { + cursor = limit - v_1; + break lab0; + } + // delete, line 210 + slice_del(); + } while (false); + break; + } + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + // (, line 215 + // do, line 216 + v_1 = cursor; + lab0: do { + // call mark_regions, line 216 + if (!r_mark_regions()) + { + break lab0; + } + } while (false); + cursor = v_1; + // backwards, line 217 + limit_backward = cursor; cursor = limit; + // (, line 217 + // do, line 218 + v_2 = limit - cursor; + lab1: do { + // call attached_pronoun, line 218 + if (!r_attached_pronoun()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 219 + v_3 = limit - cursor; + lab2: do { + // (, line 219 + // or, line 219 + lab3: do { + v_4 = limit - cursor; + lab4: do { + // call standard_suffix, line 219 + if (!r_standard_suffix()) + { + break lab4; + } + break lab3; + } while (false); + cursor = limit - v_4; + lab5: do { + // call y_verb_suffix, line 220 + if (!r_y_verb_suffix()) + { + break lab5; + } + break lab3; + } while (false); + cursor = limit - v_4; + // call verb_suffix, line 221 + if (!r_verb_suffix()) + { + break lab2; + } + } while (false); + } while (false); + cursor = limit - v_3; + // do, line 223 + v_5 = limit - cursor; + lab6: do { + // call residual_suffix, line 223 + if (!r_residual_suffix()) + { + break lab6; + } + } while (false); + cursor = limit - v_5; + cursor = limit_backward; // do, line 225 + v_6 = cursor; + lab7: do { + // call postlude, line 225 + if (!r_postlude()) + { + break lab7; + } + } while (false); + cursor = v_6; + return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/SwedishStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/SwedishStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/SwedishStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,349 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class SwedishStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "a", -1, 1, "", this), + new Among ( "arna", 0, 1, "", this), + new Among ( "erna", 0, 1, "", this), + new Among ( "heterna", 2, 1, "", this), + new Among ( "orna", 0, 1, "", this), + new Among ( "ad", -1, 1, "", this), + new Among ( "e", -1, 1, "", this), + new Among ( "ade", 6, 1, "", this), + new Among ( "ande", 6, 1, "", this), + new Among ( "arne", 6, 1, "", this), + new Among ( "are", 6, 1, "", this), + new Among ( "aste", 6, 1, "", this), + new Among ( "en", -1, 1, "", this), + new Among ( "anden", 12, 1, "", this), + new Among ( "aren", 12, 1, "", this), + new Among ( "heten", 12, 1, "", this), + new Among ( "ern", -1, 1, "", this), + new Among ( "ar", -1, 1, "", this), + new Among ( "er", -1, 1, "", this), + new Among ( "heter", 18, 1, "", this), + new Among ( "or", -1, 1, "", this), + new Among ( "s", -1, 2, "", this), + new Among ( "as", 21, 1, "", this), + new Among ( "arnas", 22, 1, "", this), + new Among ( "ernas", 22, 1, "", this), + new Among ( "ornas", 22, 1, "", this), + new Among ( "es", 21, 1, "", this), + new Among ( "ades", 26, 1, "", this), + new Among ( "andes", 26, 1, "", this), + new Among ( "ens", 21, 1, "", this), + new Among ( "arens", 29, 1, "", this), + new Among ( "hetens", 29, 1, "", this), + new Among ( "erns", 21, 1, "", this), + new Among ( "at", -1, 1, "", this), + new Among ( "andet", -1, 1, "", this), + new Among ( "het", -1, 1, "", this), + new Among ( "ast", -1, 1, "", this) + }; + + private Among a_1[] = { + new Among ( "dd", -1, -1, "", this), + new Among ( "gd", -1, -1, "", this), + new Among ( "nn", -1, -1, "", this), + new Among ( "dt", -1, -1, "", this), + new Among ( "gt", -1, -1, "", this), + new Among ( "kt", -1, -1, "", this), + new Among ( "tt", -1, -1, "", this) + }; + + private Among a_2[] = { + new Among ( "ig", -1, 1, "", this), + new Among ( "lig", 0, 1, "", this), + new Among ( "els", -1, 1, "", this), + new Among ( "fullt", -1, 3, "", this), + new Among ( "l\u00F6st", -1, 2, "", this) + }; + + private static final char g_v[] = {17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 32 }; + + private static final char g_s_ending[] = {119, 127, 149 }; + + private int I_x; + private int I_p1; + + private void copy_from(SwedishStemmer other) { + I_x = other.I_x; + I_p1 = other.I_p1; + super.copy_from(other); + } + + private boolean r_mark_regions() { + int v_1; + int v_2; + // (, line 26 + I_p1 = limit; + // test, line 29 + v_1 = cursor; + // (, line 29 + // hop, line 29 + { + int c = cursor + 3; + if (0 > c || c > limit) + { + return false; + } + cursor = c; + } + // setmark x, line 29 + I_x = cursor; + cursor = v_1; + // goto, line 30 + golab0: while(true) + { + v_2 = cursor; + lab1: do { + if (!(in_grouping(g_v, 97, 246))) + { + break lab1; + } + cursor = v_2; + break golab0; + } while (false); + cursor = v_2; + if (cursor >= limit) + { + return false; + } + cursor++; + } + // gopast, line 30 + golab2: while(true) + { + lab3: do { + if (!(out_grouping(g_v, 97, 246))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // setmark p1, line 30 + I_p1 = cursor; + // try, line 31 + lab4: do { + // (, line 31 + if (!(I_p1 < I_x)) + { + break lab4; + } + I_p1 = I_x; + } while (false); + return true; + } + + private boolean r_main_suffix() { + int among_var; + int v_1; + int v_2; + // (, line 36 + // setlimit, line 37 + v_1 = limit - cursor; + // tomark, line 37 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 37 + // [, line 37 + ket = cursor; + // substring, line 37 + among_var = find_among_b(a_0, 37); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 37 + bra = cursor; + limit_backward = v_2; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 44 + // delete, line 44 + slice_del(); + break; + case 2: + // (, line 46 + if (!(in_grouping_b(g_s_ending, 98, 121))) + { + return false; + } + // delete, line 46 + slice_del(); + break; + } + return true; + } + + private boolean r_consonant_pair() { + int v_1; + int v_2; + int v_3; + // setlimit, line 50 + v_1 = limit - cursor; + // tomark, line 50 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 50 + // and, line 52 + v_3 = limit - cursor; + // among, line 51 + if (find_among_b(a_1, 7) == 0) + { + limit_backward = v_2; + return false; + } + cursor = limit - v_3; + // (, line 52 + // [, line 52 + ket = cursor; + // next, line 52 + if (cursor <= limit_backward) + { + limit_backward = v_2; + return false; + } + cursor--; + // ], line 52 + bra = cursor; + // delete, line 52 + slice_del(); + limit_backward = v_2; + return true; + } + + private boolean r_other_suffix() { + int among_var; + int v_1; + int v_2; + // setlimit, line 55 + v_1 = limit - cursor; + // tomark, line 55 + if (cursor < I_p1) + { + return false; + } + cursor = I_p1; + v_2 = limit_backward; + limit_backward = cursor; + cursor = limit - v_1; + // (, line 55 + // [, line 56 + ket = cursor; + // substring, line 56 + among_var = find_among_b(a_2, 5); + if (among_var == 0) + { + limit_backward = v_2; + return false; + } + // ], line 56 + bra = cursor; + switch(among_var) { + case 0: + limit_backward = v_2; + return false; + case 1: + // (, line 57 + // delete, line 57 + slice_del(); + break; + case 2: + // (, line 58 + // <-, line 58 + slice_from("l\u00F6s"); + break; + case 3: + // (, line 59 + // <-, line 59 + slice_from("full"); + break; + } + limit_backward = v_2; + return true; + } + + public boolean stem() { + int v_1; + int v_2; + int v_3; + int v_4; + // (, line 64 + // do, line 66 + v_1 = cursor; + lab0: do { + // call mark_regions, line 66 + if (!r_mark_regions()) + { + break lab0; + } + } while (false); + cursor = v_1; + // backwards, line 67 + limit_backward = cursor; cursor = limit; + // (, line 67 + // do, line 68 + v_2 = limit - cursor; + lab1: do { + // call main_suffix, line 68 + if (!r_main_suffix()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 69 + v_3 = limit - cursor; + lab2: do { + // call consonant_pair, line 69 + if (!r_consonant_pair()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + // do, line 70 + v_4 = limit - cursor; + lab3: do { + // call other_suffix, line 70 + if (!r_other_suffix()) + { + break lab3; + } + } while (false); + cursor = limit - v_4; + cursor = limit_backward; return true; + } + +} + Index: 3rdParty_sources/lucene/org/tartarus/snowball/ext/TurkishStemmer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/lucene/org/tartarus/snowball/ext/TurkishStemmer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/lucene/org/tartarus/snowball/ext/TurkishStemmer.java 17 Aug 2012 14:55:09 -0000 1.1 @@ -0,0 +1,3130 @@ +// This file was generated automatically by the Snowball to Java compiler + +package org.tartarus.snowball.ext; +import org.tartarus.snowball.SnowballProgram; +import org.tartarus.snowball.Among; + +/** + * Generated class implementing code defined by a snowball script. + */ +public class TurkishStemmer extends SnowballProgram { + + private Among a_0[] = { + new Among ( "m", -1, -1, "", this), + new Among ( "n", -1, -1, "", this), + new Among ( "miz", -1, -1, "", this), + new Among ( "niz", -1, -1, "", this), + new Among ( "muz", -1, -1, "", this), + new Among ( "nuz", -1, -1, "", this), + new Among ( "m\u00FCz", -1, -1, "", this), + new Among ( "n\u00FCz", -1, -1, "", this), + new Among ( "m\u0131z", -1, -1, "", this), + new Among ( "n\u0131z", -1, -1, "", this) + }; + + private Among a_1[] = { + new Among ( "leri", -1, -1, "", this), + new Among ( "lar\u0131", -1, -1, "", this) + }; + + private Among a_2[] = { + new Among ( "ni", -1, -1, "", this), + new Among ( "nu", -1, -1, "", this), + new Among ( "n\u00FC", -1, -1, "", this), + new Among ( "n\u0131", -1, -1, "", this) + }; + + private Among a_3[] = { + new Among ( "in", -1, -1, "", this), + new Among ( "un", -1, -1, "", this), + new Among ( "\u00FCn", -1, -1, "", this), + new Among ( "\u0131n", -1, -1, "", this) + }; + + private Among a_4[] = { + new Among ( "a", -1, -1, "", this), + new Among ( "e", -1, -1, "", this) + }; + + private Among a_5[] = { + new Among ( "na", -1, -1, "", this), + new Among ( "ne", -1, -1, "", this) + }; + + private Among a_6[] = { + new Among ( "da", -1, -1, "", this), + new Among ( "ta", -1, -1, "", this), + new Among ( "de", -1, -1, "", this), + new Among ( "te", -1, -1, "", this) + }; + + private Among a_7[] = { + new Among ( "nda", -1, -1, "", this), + new Among ( "nde", -1, -1, "", this) + }; + + private Among a_8[] = { + new Among ( "dan", -1, -1, "", this), + new Among ( "tan", -1, -1, "", this), + new Among ( "den", -1, -1, "", this), + new Among ( "ten", -1, -1, "", this) + }; + + private Among a_9[] = { + new Among ( "ndan", -1, -1, "", this), + new Among ( "nden", -1, -1, "", this) + }; + + private Among a_10[] = { + new Among ( "la", -1, -1, "", this), + new Among ( "le", -1, -1, "", this) + }; + + private Among a_11[] = { + new Among ( "ca", -1, -1, "", this), + new Among ( "ce", -1, -1, "", this) + }; + + private Among a_12[] = { + new Among ( "im", -1, -1, "", this), + new Among ( "um", -1, -1, "", this), + new Among ( "\u00FCm", -1, -1, "", this), + new Among ( "\u0131m", -1, -1, "", this) + }; + + private Among a_13[] = { + new Among ( "sin", -1, -1, "", this), + new Among ( "sun", -1, -1, "", this), + new Among ( "s\u00FCn", -1, -1, "", this), + new Among ( "s\u0131n", -1, -1, "", this) + }; + + private Among a_14[] = { + new Among ( "iz", -1, -1, "", this), + new Among ( "uz", -1, -1, "", this), + new Among ( "\u00FCz", -1, -1, "", this), + new Among ( "\u0131z", -1, -1, "", this) + }; + + private Among a_15[] = { + new Among ( "siniz", -1, -1, "", this), + new Among ( "sunuz", -1, -1, "", this), + new Among ( "s\u00FCn\u00FCz", -1, -1, "", this), + new Among ( "s\u0131n\u0131z", -1, -1, "", this) + }; + + private Among a_16[] = { + new Among ( "lar", -1, -1, "", this), + new Among ( "ler", -1, -1, "", this) + }; + + private Among a_17[] = { + new Among ( "niz", -1, -1, "", this), + new Among ( "nuz", -1, -1, "", this), + new Among ( "n\u00FCz", -1, -1, "", this), + new Among ( "n\u0131z", -1, -1, "", this) + }; + + private Among a_18[] = { + new Among ( "dir", -1, -1, "", this), + new Among ( "tir", -1, -1, "", this), + new Among ( "dur", -1, -1, "", this), + new Among ( "tur", -1, -1, "", this), + new Among ( "d\u00FCr", -1, -1, "", this), + new Among ( "t\u00FCr", -1, -1, "", this), + new Among ( "d\u0131r", -1, -1, "", this), + new Among ( "t\u0131r", -1, -1, "", this) + }; + + private Among a_19[] = { + new Among ( "cas\u0131na", -1, -1, "", this), + new Among ( "cesine", -1, -1, "", this) + }; + + private Among a_20[] = { + new Among ( "di", -1, -1, "", this), + new Among ( "ti", -1, -1, "", this), + new Among ( "dik", -1, -1, "", this), + new Among ( "tik", -1, -1, "", this), + new Among ( "duk", -1, -1, "", this), + new Among ( "tuk", -1, -1, "", this), + new Among ( "d\u00FCk", -1, -1, "", this), + new Among ( "t\u00FCk", -1, -1, "", this), + new Among ( "d\u0131k", -1, -1, "", this), + new Among ( "t\u0131k", -1, -1, "", this), + new Among ( "dim", -1, -1, "", this), + new Among ( "tim", -1, -1, "", this), + new Among ( "dum", -1, -1, "", this), + new Among ( "tum", -1, -1, "", this), + new Among ( "d\u00FCm", -1, -1, "", this), + new Among ( "t\u00FCm", -1, -1, "", this), + new Among ( "d\u0131m", -1, -1, "", this), + new Among ( "t\u0131m", -1, -1, "", this), + new Among ( "din", -1, -1, "", this), + new Among ( "tin", -1, -1, "", this), + new Among ( "dun", -1, -1, "", this), + new Among ( "tun", -1, -1, "", this), + new Among ( "d\u00FCn", -1, -1, "", this), + new Among ( "t\u00FCn", -1, -1, "", this), + new Among ( "d\u0131n", -1, -1, "", this), + new Among ( "t\u0131n", -1, -1, "", this), + new Among ( "du", -1, -1, "", this), + new Among ( "tu", -1, -1, "", this), + new Among ( "d\u00FC", -1, -1, "", this), + new Among ( "t\u00FC", -1, -1, "", this), + new Among ( "d\u0131", -1, -1, "", this), + new Among ( "t\u0131", -1, -1, "", this) + }; + + private Among a_21[] = { + new Among ( "sa", -1, -1, "", this), + new Among ( "se", -1, -1, "", this), + new Among ( "sak", -1, -1, "", this), + new Among ( "sek", -1, -1, "", this), + new Among ( "sam", -1, -1, "", this), + new Among ( "sem", -1, -1, "", this), + new Among ( "san", -1, -1, "", this), + new Among ( "sen", -1, -1, "", this) + }; + + private Among a_22[] = { + new Among ( "mi\u015F", -1, -1, "", this), + new Among ( "mu\u015F", -1, -1, "", this), + new Among ( "m\u00FC\u015F", -1, -1, "", this), + new Among ( "m\u0131\u015F", -1, -1, "", this) + }; + + private Among a_23[] = { + new Among ( "b", -1, 1, "", this), + new Among ( "c", -1, 2, "", this), + new Among ( "d", -1, 3, "", this), + new Among ( "\u011F", -1, 4, "", this) + }; + + private static final char g_vowel[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 8, 0, 0, 0, 0, 0, 0, 1 }; + + private static final char g_U[] = {1, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 1 }; + + private static final char g_vowel1[] = {1, 64, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; + + private static final char g_vowel2[] = {17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 130 }; + + private static final char g_vowel3[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; + + private static final char g_vowel4[] = {17 }; + + private static final char g_vowel5[] = {65 }; + + private static final char g_vowel6[] = {65 }; + + private boolean B_continue_stemming_noun_suffixes; + private int I_strlen; + + private void copy_from(TurkishStemmer other) { + B_continue_stemming_noun_suffixes = other.B_continue_stemming_noun_suffixes; + I_strlen = other.I_strlen; + super.copy_from(other); + } + + private boolean r_check_vowel_harmony() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + // (, line 111 + // test, line 112 + v_1 = limit - cursor; + // (, line 113 + // (, line 114 + // goto, line 114 + golab0: while(true) + { + v_2 = limit - cursor; + lab1: do { + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab1; + } + cursor = limit - v_2; + break golab0; + } while (false); + cursor = limit - v_2; + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + // (, line 115 + // or, line 116 + lab2: do { + v_3 = limit - cursor; + lab3: do { + // (, line 116 + // literal, line 116 + if (!(eq_s_b(1, "a"))) + { + break lab3; + } + // goto, line 116 + golab4: while(true) + { + v_4 = limit - cursor; + lab5: do { + if (!(in_grouping_b(g_vowel1, 97, 305))) + { + break lab5; + } + cursor = limit - v_4; + break golab4; + } while (false); + cursor = limit - v_4; + if (cursor <= limit_backward) + { + break lab3; + } + cursor--; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab6: do { + // (, line 117 + // literal, line 117 + if (!(eq_s_b(1, "e"))) + { + break lab6; + } + // goto, line 117 + golab7: while(true) + { + v_5 = limit - cursor; + lab8: do { + if (!(in_grouping_b(g_vowel2, 101, 252))) + { + break lab8; + } + cursor = limit - v_5; + break golab7; + } while (false); + cursor = limit - v_5; + if (cursor <= limit_backward) + { + break lab6; + } + cursor--; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab9: do { + // (, line 118 + // literal, line 118 + if (!(eq_s_b(1, "\u0131"))) + { + break lab9; + } + // goto, line 118 + golab10: while(true) + { + v_6 = limit - cursor; + lab11: do { + if (!(in_grouping_b(g_vowel3, 97, 305))) + { + break lab11; + } + cursor = limit - v_6; + break golab10; + } while (false); + cursor = limit - v_6; + if (cursor <= limit_backward) + { + break lab9; + } + cursor--; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab12: do { + // (, line 119 + // literal, line 119 + if (!(eq_s_b(1, "i"))) + { + break lab12; + } + // goto, line 119 + golab13: while(true) + { + v_7 = limit - cursor; + lab14: do { + if (!(in_grouping_b(g_vowel4, 101, 105))) + { + break lab14; + } + cursor = limit - v_7; + break golab13; + } while (false); + cursor = limit - v_7; + if (cursor <= limit_backward) + { + break lab12; + } + cursor--; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab15: do { + // (, line 120 + // literal, line 120 + if (!(eq_s_b(1, "o"))) + { + break lab15; + } + // goto, line 120 + golab16: while(true) + { + v_8 = limit - cursor; + lab17: do { + if (!(in_grouping_b(g_vowel5, 111, 117))) + { + break lab17; + } + cursor = limit - v_8; + break golab16; + } while (false); + cursor = limit - v_8; + if (cursor <= limit_backward) + { + break lab15; + } + cursor--; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab18: do { + // (, line 121 + // literal, line 121 + if (!(eq_s_b(1, "\u00F6"))) + { + break lab18; + } + // goto, line 121 + golab19: while(true) + { + v_9 = limit - cursor; + lab20: do { + if (!(in_grouping_b(g_vowel6, 246, 252))) + { + break lab20; + } + cursor = limit - v_9; + break golab19; + } while (false); + cursor = limit - v_9; + if (cursor <= limit_backward) + { + break lab18; + } + cursor--; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab21: do { + // (, line 122 + // literal, line 122 + if (!(eq_s_b(1, "u"))) + { + break lab21; + } + // goto, line 122 + golab22: while(true) + { + v_10 = limit - cursor; + lab23: do { + if (!(in_grouping_b(g_vowel5, 111, 117))) + { + break lab23; + } + cursor = limit - v_10; + break golab22; + } while (false); + cursor = limit - v_10; + if (cursor <= limit_backward) + { + break lab21; + } + cursor--; + } + break lab2; + } while (false); + cursor = limit - v_3; + // (, line 123 + // literal, line 123 + if (!(eq_s_b(1, "\u00FC"))) + { + return false; + } + // goto, line 123 + golab24: while(true) + { + v_11 = limit - cursor; + lab25: do { + if (!(in_grouping_b(g_vowel6, 246, 252))) + { + break lab25; + } + cursor = limit - v_11; + break golab24; + } while (false); + cursor = limit - v_11; + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + } while (false); + cursor = limit - v_1; + return true; + } + + private boolean r_mark_suffix_with_optional_n_consonant() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + // (, line 132 + // or, line 134 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 133 + // (, line 133 + // test, line 133 + v_2 = limit - cursor; + // literal, line 133 + if (!(eq_s_b(1, "n"))) + { + break lab1; + } + cursor = limit - v_2; + // next, line 133 + if (cursor <= limit_backward) + { + break lab1; + } + cursor--; + // (, line 133 + // test, line 133 + v_3 = limit - cursor; + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab1; + } + cursor = limit - v_3; + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 135 + // (, line 135 + // not, line 135 + { + v_4 = limit - cursor; + lab2: do { + // (, line 135 + // test, line 135 + v_5 = limit - cursor; + // literal, line 135 + if (!(eq_s_b(1, "n"))) + { + break lab2; + } + cursor = limit - v_5; + return false; + } while (false); + cursor = limit - v_4; + } + // test, line 135 + v_6 = limit - cursor; + // (, line 135 + // next, line 135 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // (, line 135 + // test, line 135 + v_7 = limit - cursor; + if (!(in_grouping_b(g_vowel, 97, 305))) + { + return false; + } + cursor = limit - v_7; + cursor = limit - v_6; + } while (false); + return true; + } + + private boolean r_mark_suffix_with_optional_s_consonant() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + // (, line 143 + // or, line 145 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 144 + // (, line 144 + // test, line 144 + v_2 = limit - cursor; + // literal, line 144 + if (!(eq_s_b(1, "s"))) + { + break lab1; + } + cursor = limit - v_2; + // next, line 144 + if (cursor <= limit_backward) + { + break lab1; + } + cursor--; + // (, line 144 + // test, line 144 + v_3 = limit - cursor; + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab1; + } + cursor = limit - v_3; + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 146 + // (, line 146 + // not, line 146 + { + v_4 = limit - cursor; + lab2: do { + // (, line 146 + // test, line 146 + v_5 = limit - cursor; + // literal, line 146 + if (!(eq_s_b(1, "s"))) + { + break lab2; + } + cursor = limit - v_5; + return false; + } while (false); + cursor = limit - v_4; + } + // test, line 146 + v_6 = limit - cursor; + // (, line 146 + // next, line 146 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // (, line 146 + // test, line 146 + v_7 = limit - cursor; + if (!(in_grouping_b(g_vowel, 97, 305))) + { + return false; + } + cursor = limit - v_7; + cursor = limit - v_6; + } while (false); + return true; + } + + private boolean r_mark_suffix_with_optional_y_consonant() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + // (, line 153 + // or, line 155 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 154 + // (, line 154 + // test, line 154 + v_2 = limit - cursor; + // literal, line 154 + if (!(eq_s_b(1, "y"))) + { + break lab1; + } + cursor = limit - v_2; + // next, line 154 + if (cursor <= limit_backward) + { + break lab1; + } + cursor--; + // (, line 154 + // test, line 154 + v_3 = limit - cursor; + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab1; + } + cursor = limit - v_3; + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 156 + // (, line 156 + // not, line 156 + { + v_4 = limit - cursor; + lab2: do { + // (, line 156 + // test, line 156 + v_5 = limit - cursor; + // literal, line 156 + if (!(eq_s_b(1, "y"))) + { + break lab2; + } + cursor = limit - v_5; + return false; + } while (false); + cursor = limit - v_4; + } + // test, line 156 + v_6 = limit - cursor; + // (, line 156 + // next, line 156 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // (, line 156 + // test, line 156 + v_7 = limit - cursor; + if (!(in_grouping_b(g_vowel, 97, 305))) + { + return false; + } + cursor = limit - v_7; + cursor = limit - v_6; + } while (false); + return true; + } + + private boolean r_mark_suffix_with_optional_U_vowel() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + // (, line 159 + // or, line 161 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 160 + // (, line 160 + // test, line 160 + v_2 = limit - cursor; + if (!(in_grouping_b(g_U, 105, 305))) + { + break lab1; + } + cursor = limit - v_2; + // next, line 160 + if (cursor <= limit_backward) + { + break lab1; + } + cursor--; + // (, line 160 + // test, line 160 + v_3 = limit - cursor; + if (!(out_grouping_b(g_vowel, 97, 305))) + { + break lab1; + } + cursor = limit - v_3; + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 162 + // (, line 162 + // not, line 162 + { + v_4 = limit - cursor; + lab2: do { + // (, line 162 + // test, line 162 + v_5 = limit - cursor; + if (!(in_grouping_b(g_U, 105, 305))) + { + break lab2; + } + cursor = limit - v_5; + return false; + } while (false); + cursor = limit - v_4; + } + // test, line 162 + v_6 = limit - cursor; + // (, line 162 + // next, line 162 + if (cursor <= limit_backward) + { + return false; + } + cursor--; + // (, line 162 + // test, line 162 + v_7 = limit - cursor; + if (!(out_grouping_b(g_vowel, 97, 305))) + { + return false; + } + cursor = limit - v_7; + cursor = limit - v_6; + } while (false); + return true; + } + + private boolean r_mark_possessives() { + // (, line 166 + // among, line 167 + if (find_among_b(a_0, 10) == 0) + { + return false; + } + // (, line 169 + // call mark_suffix_with_optional_U_vowel, line 169 + if (!r_mark_suffix_with_optional_U_vowel()) + { + return false; + } + return true; + } + + private boolean r_mark_sU() { + // (, line 172 + // call check_vowel_harmony, line 173 + if (!r_check_vowel_harmony()) + { + return false; + } + if (!(in_grouping_b(g_U, 105, 305))) + { + return false; + } + // (, line 175 + // call mark_suffix_with_optional_s_consonant, line 175 + if (!r_mark_suffix_with_optional_s_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_lArI() { + // (, line 178 + // among, line 179 + if (find_among_b(a_1, 2) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_yU() { + // (, line 182 + // call check_vowel_harmony, line 183 + if (!r_check_vowel_harmony()) + { + return false; + } + if (!(in_grouping_b(g_U, 105, 305))) + { + return false; + } + // (, line 185 + // call mark_suffix_with_optional_y_consonant, line 185 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_nU() { + // (, line 188 + // call check_vowel_harmony, line 189 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 190 + if (find_among_b(a_2, 4) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_nUn() { + // (, line 193 + // call check_vowel_harmony, line 194 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 195 + if (find_among_b(a_3, 4) == 0) + { + return false; + } + // (, line 196 + // call mark_suffix_with_optional_n_consonant, line 196 + if (!r_mark_suffix_with_optional_n_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_yA() { + // (, line 199 + // call check_vowel_harmony, line 200 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 201 + if (find_among_b(a_4, 2) == 0) + { + return false; + } + // (, line 202 + // call mark_suffix_with_optional_y_consonant, line 202 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_nA() { + // (, line 205 + // call check_vowel_harmony, line 206 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 207 + if (find_among_b(a_5, 2) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_DA() { + // (, line 210 + // call check_vowel_harmony, line 211 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 212 + if (find_among_b(a_6, 4) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_ndA() { + // (, line 215 + // call check_vowel_harmony, line 216 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 217 + if (find_among_b(a_7, 2) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_DAn() { + // (, line 220 + // call check_vowel_harmony, line 221 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 222 + if (find_among_b(a_8, 4) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_ndAn() { + // (, line 225 + // call check_vowel_harmony, line 226 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 227 + if (find_among_b(a_9, 2) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_ylA() { + // (, line 230 + // call check_vowel_harmony, line 231 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 232 + if (find_among_b(a_10, 2) == 0) + { + return false; + } + // (, line 233 + // call mark_suffix_with_optional_y_consonant, line 233 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_ki() { + // (, line 236 + // literal, line 237 + if (!(eq_s_b(2, "ki"))) + { + return false; + } + return true; + } + + private boolean r_mark_ncA() { + // (, line 240 + // call check_vowel_harmony, line 241 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 242 + if (find_among_b(a_11, 2) == 0) + { + return false; + } + // (, line 243 + // call mark_suffix_with_optional_n_consonant, line 243 + if (!r_mark_suffix_with_optional_n_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_yUm() { + // (, line 246 + // call check_vowel_harmony, line 247 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 248 + if (find_among_b(a_12, 4) == 0) + { + return false; + } + // (, line 249 + // call mark_suffix_with_optional_y_consonant, line 249 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_sUn() { + // (, line 252 + // call check_vowel_harmony, line 253 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 254 + if (find_among_b(a_13, 4) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_yUz() { + // (, line 257 + // call check_vowel_harmony, line 258 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 259 + if (find_among_b(a_14, 4) == 0) + { + return false; + } + // (, line 260 + // call mark_suffix_with_optional_y_consonant, line 260 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_sUnUz() { + // (, line 263 + // among, line 264 + if (find_among_b(a_15, 4) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_lAr() { + // (, line 267 + // call check_vowel_harmony, line 268 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 269 + if (find_among_b(a_16, 2) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_nUz() { + // (, line 272 + // call check_vowel_harmony, line 273 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 274 + if (find_among_b(a_17, 4) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_DUr() { + // (, line 277 + // call check_vowel_harmony, line 278 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 279 + if (find_among_b(a_18, 8) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_cAsInA() { + // (, line 282 + // among, line 283 + if (find_among_b(a_19, 2) == 0) + { + return false; + } + return true; + } + + private boolean r_mark_yDU() { + // (, line 286 + // call check_vowel_harmony, line 287 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 288 + if (find_among_b(a_20, 32) == 0) + { + return false; + } + // (, line 292 + // call mark_suffix_with_optional_y_consonant, line 292 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_ysA() { + // (, line 296 + // among, line 297 + if (find_among_b(a_21, 8) == 0) + { + return false; + } + // (, line 298 + // call mark_suffix_with_optional_y_consonant, line 298 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_ymUs_() { + // (, line 301 + // call check_vowel_harmony, line 302 + if (!r_check_vowel_harmony()) + { + return false; + } + // among, line 303 + if (find_among_b(a_22, 4) == 0) + { + return false; + } + // (, line 304 + // call mark_suffix_with_optional_y_consonant, line 304 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_mark_yken() { + // (, line 307 + // literal, line 308 + if (!(eq_s_b(3, "ken"))) + { + return false; + } + // (, line 308 + // call mark_suffix_with_optional_y_consonant, line 308 + if (!r_mark_suffix_with_optional_y_consonant()) + { + return false; + } + return true; + } + + private boolean r_stem_nominal_verb_suffixes() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + // (, line 311 + // [, line 312 + ket = cursor; + // set continue_stemming_noun_suffixes, line 313 + B_continue_stemming_noun_suffixes = true; + // or, line 315 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 314 + // or, line 314 + lab2: do { + v_2 = limit - cursor; + lab3: do { + // call mark_ymUs_, line 314 + if (!r_mark_ymUs_()) + { + break lab3; + } + break lab2; + } while (false); + cursor = limit - v_2; + lab4: do { + // call mark_yDU, line 314 + if (!r_mark_yDU()) + { + break lab4; + } + break lab2; + } while (false); + cursor = limit - v_2; + lab5: do { + // call mark_ysA, line 314 + if (!r_mark_ysA()) + { + break lab5; + } + break lab2; + } while (false); + cursor = limit - v_2; + // call mark_yken, line 314 + if (!r_mark_yken()) + { + break lab1; + } + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab6: do { + // (, line 316 + // call mark_cAsInA, line 316 + if (!r_mark_cAsInA()) + { + break lab6; + } + // (, line 316 + // or, line 316 + lab7: do { + v_3 = limit - cursor; + lab8: do { + // call mark_sUnUz, line 316 + if (!r_mark_sUnUz()) + { + break lab8; + } + break lab7; + } while (false); + cursor = limit - v_3; + lab9: do { + // call mark_lAr, line 316 + if (!r_mark_lAr()) + { + break lab9; + } + break lab7; + } while (false); + cursor = limit - v_3; + lab10: do { + // call mark_yUm, line 316 + if (!r_mark_yUm()) + { + break lab10; + } + break lab7; + } while (false); + cursor = limit - v_3; + lab11: do { + // call mark_sUn, line 316 + if (!r_mark_sUn()) + { + break lab11; + } + break lab7; + } while (false); + cursor = limit - v_3; + lab12: do { + // call mark_yUz, line 316 + if (!r_mark_yUz()) + { + break lab12; + } + break lab7; + } while (false); + cursor = limit - v_3; + } while (false); + // call mark_ymUs_, line 316 + if (!r_mark_ymUs_()) + { + break lab6; + } + break lab0; + } while (false); + cursor = limit - v_1; + lab13: do { + // (, line 318 + // call mark_lAr, line 319 + if (!r_mark_lAr()) + { + break lab13; + } + // ], line 319 + bra = cursor; + // delete, line 319 + slice_del(); + // try, line 319 + v_4 = limit - cursor; + lab14: do { + // (, line 319 + // [, line 319 + ket = cursor; + // (, line 319 + // or, line 319 + lab15: do { + v_5 = limit - cursor; + lab16: do { + // call mark_DUr, line 319 + if (!r_mark_DUr()) + { + break lab16; + } + break lab15; + } while (false); + cursor = limit - v_5; + lab17: do { + // call mark_yDU, line 319 + if (!r_mark_yDU()) + { + break lab17; + } + break lab15; + } while (false); + cursor = limit - v_5; + lab18: do { + // call mark_ysA, line 319 + if (!r_mark_ysA()) + { + break lab18; + } + break lab15; + } while (false); + cursor = limit - v_5; + // call mark_ymUs_, line 319 + if (!r_mark_ymUs_()) + { + cursor = limit - v_4; + break lab14; + } + } while (false); + } while (false); + // unset continue_stemming_noun_suffixes, line 320 + B_continue_stemming_noun_suffixes = false; + break lab0; + } while (false); + cursor = limit - v_1; + lab19: do { + // (, line 323 + // call mark_nUz, line 323 + if (!r_mark_nUz()) + { + break lab19; + } + // (, line 323 + // or, line 323 + lab20: do { + v_6 = limit - cursor; + lab21: do { + // call mark_yDU, line 323 + if (!r_mark_yDU()) + { + break lab21; + } + break lab20; + } while (false); + cursor = limit - v_6; + // call mark_ysA, line 323 + if (!r_mark_ysA()) + { + break lab19; + } + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab22: do { + // (, line 325 + // (, line 325 + // or, line 325 + lab23: do { + v_7 = limit - cursor; + lab24: do { + // call mark_sUnUz, line 325 + if (!r_mark_sUnUz()) + { + break lab24; + } + break lab23; + } while (false); + cursor = limit - v_7; + lab25: do { + // call mark_yUz, line 325 + if (!r_mark_yUz()) + { + break lab25; + } + break lab23; + } while (false); + cursor = limit - v_7; + lab26: do { + // call mark_sUn, line 325 + if (!r_mark_sUn()) + { + break lab26; + } + break lab23; + } while (false); + cursor = limit - v_7; + // call mark_yUm, line 325 + if (!r_mark_yUm()) + { + break lab22; + } + } while (false); + // ], line 325 + bra = cursor; + // delete, line 325 + slice_del(); + // try, line 325 + v_8 = limit - cursor; + lab27: do { + // (, line 325 + // [, line 325 + ket = cursor; + // call mark_ymUs_, line 325 + if (!r_mark_ymUs_()) + { + cursor = limit - v_8; + break lab27; + } + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 327 + // call mark_DUr, line 327 + if (!r_mark_DUr()) + { + return false; + } + // ], line 327 + bra = cursor; + // delete, line 327 + slice_del(); + // try, line 327 + v_9 = limit - cursor; + lab28: do { + // (, line 327 + // [, line 327 + ket = cursor; + // (, line 327 + // or, line 327 + lab29: do { + v_10 = limit - cursor; + lab30: do { + // call mark_sUnUz, line 327 + if (!r_mark_sUnUz()) + { + break lab30; + } + break lab29; + } while (false); + cursor = limit - v_10; + lab31: do { + // call mark_lAr, line 327 + if (!r_mark_lAr()) + { + break lab31; + } + break lab29; + } while (false); + cursor = limit - v_10; + lab32: do { + // call mark_yUm, line 327 + if (!r_mark_yUm()) + { + break lab32; + } + break lab29; + } while (false); + cursor = limit - v_10; + lab33: do { + // call mark_sUn, line 327 + if (!r_mark_sUn()) + { + break lab33; + } + break lab29; + } while (false); + cursor = limit - v_10; + lab34: do { + // call mark_yUz, line 327 + if (!r_mark_yUz()) + { + break lab34; + } + break lab29; + } while (false); + cursor = limit - v_10; + } while (false); + // call mark_ymUs_, line 327 + if (!r_mark_ymUs_()) + { + cursor = limit - v_9; + break lab28; + } + } while (false); + } while (false); + // ], line 328 + bra = cursor; + // delete, line 328 + slice_del(); + return true; + } + + private boolean r_stem_suffix_chain_before_ki() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + // (, line 332 + // [, line 333 + ket = cursor; + // call mark_ki, line 334 + if (!r_mark_ki()) + { + return false; + } + // (, line 335 + // or, line 342 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 336 + // call mark_DA, line 336 + if (!r_mark_DA()) + { + break lab1; + } + // ], line 336 + bra = cursor; + // delete, line 336 + slice_del(); + // try, line 336 + v_2 = limit - cursor; + lab2: do { + // (, line 336 + // [, line 336 + ket = cursor; + // or, line 338 + lab3: do { + v_3 = limit - cursor; + lab4: do { + // (, line 337 + // call mark_lAr, line 337 + if (!r_mark_lAr()) + { + break lab4; + } + // ], line 337 + bra = cursor; + // delete, line 337 + slice_del(); + // try, line 337 + v_4 = limit - cursor; + lab5: do { + // (, line 337 + // call stem_suffix_chain_before_ki, line 337 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_4; + break lab5; + } + } while (false); + break lab3; + } while (false); + cursor = limit - v_3; + // (, line 339 + // call mark_possessives, line 339 + if (!r_mark_possessives()) + { + cursor = limit - v_2; + break lab2; + } + // ], line 339 + bra = cursor; + // delete, line 339 + slice_del(); + // try, line 339 + v_5 = limit - cursor; + lab6: do { + // (, line 339 + // [, line 339 + ket = cursor; + // call mark_lAr, line 339 + if (!r_mark_lAr()) + { + cursor = limit - v_5; + break lab6; + } + // ], line 339 + bra = cursor; + // delete, line 339 + slice_del(); + // call stem_suffix_chain_before_ki, line 339 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_5; + break lab6; + } + } while (false); + } while (false); + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab7: do { + // (, line 343 + // call mark_nUn, line 343 + if (!r_mark_nUn()) + { + break lab7; + } + // ], line 343 + bra = cursor; + // delete, line 343 + slice_del(); + // try, line 343 + v_6 = limit - cursor; + lab8: do { + // (, line 343 + // [, line 343 + ket = cursor; + // or, line 345 + lab9: do { + v_7 = limit - cursor; + lab10: do { + // (, line 344 + // call mark_lArI, line 344 + if (!r_mark_lArI()) + { + break lab10; + } + // ], line 344 + bra = cursor; + // delete, line 344 + slice_del(); + break lab9; + } while (false); + cursor = limit - v_7; + lab11: do { + // (, line 346 + // [, line 346 + ket = cursor; + // or, line 346 + lab12: do { + v_8 = limit - cursor; + lab13: do { + // call mark_possessives, line 346 + if (!r_mark_possessives()) + { + break lab13; + } + break lab12; + } while (false); + cursor = limit - v_8; + // call mark_sU, line 346 + if (!r_mark_sU()) + { + break lab11; + } + } while (false); + // ], line 346 + bra = cursor; + // delete, line 346 + slice_del(); + // try, line 346 + v_9 = limit - cursor; + lab14: do { + // (, line 346 + // [, line 346 + ket = cursor; + // call mark_lAr, line 346 + if (!r_mark_lAr()) + { + cursor = limit - v_9; + break lab14; + } + // ], line 346 + bra = cursor; + // delete, line 346 + slice_del(); + // call stem_suffix_chain_before_ki, line 346 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_9; + break lab14; + } + } while (false); + break lab9; + } while (false); + cursor = limit - v_7; + // (, line 348 + // call stem_suffix_chain_before_ki, line 348 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_6; + break lab8; + } + } while (false); + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 351 + // call mark_ndA, line 351 + if (!r_mark_ndA()) + { + return false; + } + // (, line 351 + // or, line 353 + lab15: do { + v_10 = limit - cursor; + lab16: do { + // (, line 352 + // call mark_lArI, line 352 + if (!r_mark_lArI()) + { + break lab16; + } + // ], line 352 + bra = cursor; + // delete, line 352 + slice_del(); + break lab15; + } while (false); + cursor = limit - v_10; + lab17: do { + // (, line 354 + // (, line 354 + // call mark_sU, line 354 + if (!r_mark_sU()) + { + break lab17; + } + // ], line 354 + bra = cursor; + // delete, line 354 + slice_del(); + // try, line 354 + v_11 = limit - cursor; + lab18: do { + // (, line 354 + // [, line 354 + ket = cursor; + // call mark_lAr, line 354 + if (!r_mark_lAr()) + { + cursor = limit - v_11; + break lab18; + } + // ], line 354 + bra = cursor; + // delete, line 354 + slice_del(); + // call stem_suffix_chain_before_ki, line 354 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_11; + break lab18; + } + } while (false); + break lab15; + } while (false); + cursor = limit - v_10; + // (, line 356 + // call stem_suffix_chain_before_ki, line 356 + if (!r_stem_suffix_chain_before_ki()) + { + return false; + } + } while (false); + } while (false); + return true; + } + + private boolean r_stem_noun_suffixes() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + int v_12; + int v_13; + int v_14; + int v_15; + int v_16; + int v_17; + int v_18; + int v_19; + int v_20; + int v_21; + int v_22; + int v_23; + int v_24; + int v_25; + int v_26; + int v_27; + // (, line 361 + // or, line 363 + lab0: do { + v_1 = limit - cursor; + lab1: do { + // (, line 362 + // [, line 362 + ket = cursor; + // call mark_lAr, line 362 + if (!r_mark_lAr()) + { + break lab1; + } + // ], line 362 + bra = cursor; + // delete, line 362 + slice_del(); + // try, line 362 + v_2 = limit - cursor; + lab2: do { + // (, line 362 + // call stem_suffix_chain_before_ki, line 362 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_2; + break lab2; + } + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab3: do { + // (, line 364 + // [, line 364 + ket = cursor; + // call mark_ncA, line 364 + if (!r_mark_ncA()) + { + break lab3; + } + // ], line 364 + bra = cursor; + // delete, line 364 + slice_del(); + // try, line 365 + v_3 = limit - cursor; + lab4: do { + // (, line 365 + // or, line 367 + lab5: do { + v_4 = limit - cursor; + lab6: do { + // (, line 366 + // [, line 366 + ket = cursor; + // call mark_lArI, line 366 + if (!r_mark_lArI()) + { + break lab6; + } + // ], line 366 + bra = cursor; + // delete, line 366 + slice_del(); + break lab5; + } while (false); + cursor = limit - v_4; + lab7: do { + // (, line 368 + // [, line 368 + ket = cursor; + // or, line 368 + lab8: do { + v_5 = limit - cursor; + lab9: do { + // call mark_possessives, line 368 + if (!r_mark_possessives()) + { + break lab9; + } + break lab8; + } while (false); + cursor = limit - v_5; + // call mark_sU, line 368 + if (!r_mark_sU()) + { + break lab7; + } + } while (false); + // ], line 368 + bra = cursor; + // delete, line 368 + slice_del(); + // try, line 368 + v_6 = limit - cursor; + lab10: do { + // (, line 368 + // [, line 368 + ket = cursor; + // call mark_lAr, line 368 + if (!r_mark_lAr()) + { + cursor = limit - v_6; + break lab10; + } + // ], line 368 + bra = cursor; + // delete, line 368 + slice_del(); + // call stem_suffix_chain_before_ki, line 368 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_6; + break lab10; + } + } while (false); + break lab5; + } while (false); + cursor = limit - v_4; + // (, line 370 + // [, line 370 + ket = cursor; + // call mark_lAr, line 370 + if (!r_mark_lAr()) + { + cursor = limit - v_3; + break lab4; + } + // ], line 370 + bra = cursor; + // delete, line 370 + slice_del(); + // call stem_suffix_chain_before_ki, line 370 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_3; + break lab4; + } + } while (false); + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab11: do { + // (, line 374 + // [, line 374 + ket = cursor; + // (, line 374 + // or, line 374 + lab12: do { + v_7 = limit - cursor; + lab13: do { + // call mark_ndA, line 374 + if (!r_mark_ndA()) + { + break lab13; + } + break lab12; + } while (false); + cursor = limit - v_7; + // call mark_nA, line 374 + if (!r_mark_nA()) + { + break lab11; + } + } while (false); + // (, line 375 + // or, line 377 + lab14: do { + v_8 = limit - cursor; + lab15: do { + // (, line 376 + // call mark_lArI, line 376 + if (!r_mark_lArI()) + { + break lab15; + } + // ], line 376 + bra = cursor; + // delete, line 376 + slice_del(); + break lab14; + } while (false); + cursor = limit - v_8; + lab16: do { + // (, line 378 + // call mark_sU, line 378 + if (!r_mark_sU()) + { + break lab16; + } + // ], line 378 + bra = cursor; + // delete, line 378 + slice_del(); + // try, line 378 + v_9 = limit - cursor; + lab17: do { + // (, line 378 + // [, line 378 + ket = cursor; + // call mark_lAr, line 378 + if (!r_mark_lAr()) + { + cursor = limit - v_9; + break lab17; + } + // ], line 378 + bra = cursor; + // delete, line 378 + slice_del(); + // call stem_suffix_chain_before_ki, line 378 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_9; + break lab17; + } + } while (false); + break lab14; + } while (false); + cursor = limit - v_8; + // (, line 380 + // call stem_suffix_chain_before_ki, line 380 + if (!r_stem_suffix_chain_before_ki()) + { + break lab11; + } + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab18: do { + // (, line 384 + // [, line 384 + ket = cursor; + // (, line 384 + // or, line 384 + lab19: do { + v_10 = limit - cursor; + lab20: do { + // call mark_ndAn, line 384 + if (!r_mark_ndAn()) + { + break lab20; + } + break lab19; + } while (false); + cursor = limit - v_10; + // call mark_nU, line 384 + if (!r_mark_nU()) + { + break lab18; + } + } while (false); + // (, line 384 + // or, line 384 + lab21: do { + v_11 = limit - cursor; + lab22: do { + // (, line 384 + // call mark_sU, line 384 + if (!r_mark_sU()) + { + break lab22; + } + // ], line 384 + bra = cursor; + // delete, line 384 + slice_del(); + // try, line 384 + v_12 = limit - cursor; + lab23: do { + // (, line 384 + // [, line 384 + ket = cursor; + // call mark_lAr, line 384 + if (!r_mark_lAr()) + { + cursor = limit - v_12; + break lab23; + } + // ], line 384 + bra = cursor; + // delete, line 384 + slice_del(); + // call stem_suffix_chain_before_ki, line 384 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_12; + break lab23; + } + } while (false); + break lab21; + } while (false); + cursor = limit - v_11; + // (, line 384 + // call mark_lArI, line 384 + if (!r_mark_lArI()) + { + break lab18; + } + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab24: do { + // (, line 386 + // [, line 386 + ket = cursor; + // call mark_DAn, line 386 + if (!r_mark_DAn()) + { + break lab24; + } + // ], line 386 + bra = cursor; + // delete, line 386 + slice_del(); + // try, line 386 + v_13 = limit - cursor; + lab25: do { + // (, line 386 + // [, line 386 + ket = cursor; + // (, line 387 + // or, line 389 + lab26: do { + v_14 = limit - cursor; + lab27: do { + // (, line 388 + // call mark_possessives, line 388 + if (!r_mark_possessives()) + { + break lab27; + } + // ], line 388 + bra = cursor; + // delete, line 388 + slice_del(); + // try, line 388 + v_15 = limit - cursor; + lab28: do { + // (, line 388 + // [, line 388 + ket = cursor; + // call mark_lAr, line 388 + if (!r_mark_lAr()) + { + cursor = limit - v_15; + break lab28; + } + // ], line 388 + bra = cursor; + // delete, line 388 + slice_del(); + // call stem_suffix_chain_before_ki, line 388 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_15; + break lab28; + } + } while (false); + break lab26; + } while (false); + cursor = limit - v_14; + lab29: do { + // (, line 390 + // call mark_lAr, line 390 + if (!r_mark_lAr()) + { + break lab29; + } + // ], line 390 + bra = cursor; + // delete, line 390 + slice_del(); + // try, line 390 + v_16 = limit - cursor; + lab30: do { + // (, line 390 + // call stem_suffix_chain_before_ki, line 390 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_16; + break lab30; + } + } while (false); + break lab26; + } while (false); + cursor = limit - v_14; + // (, line 392 + // call stem_suffix_chain_before_ki, line 392 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_13; + break lab25; + } + } while (false); + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab31: do { + // (, line 396 + // [, line 396 + ket = cursor; + // or, line 396 + lab32: do { + v_17 = limit - cursor; + lab33: do { + // call mark_nUn, line 396 + if (!r_mark_nUn()) + { + break lab33; + } + break lab32; + } while (false); + cursor = limit - v_17; + // call mark_ylA, line 396 + if (!r_mark_ylA()) + { + break lab31; + } + } while (false); + // ], line 396 + bra = cursor; + // delete, line 396 + slice_del(); + // try, line 397 + v_18 = limit - cursor; + lab34: do { + // (, line 397 + // or, line 399 + lab35: do { + v_19 = limit - cursor; + lab36: do { + // (, line 398 + // [, line 398 + ket = cursor; + // call mark_lAr, line 398 + if (!r_mark_lAr()) + { + break lab36; + } + // ], line 398 + bra = cursor; + // delete, line 398 + slice_del(); + // call stem_suffix_chain_before_ki, line 398 + if (!r_stem_suffix_chain_before_ki()) + { + break lab36; + } + break lab35; + } while (false); + cursor = limit - v_19; + lab37: do { + // (, line 400 + // [, line 400 + ket = cursor; + // or, line 400 + lab38: do { + v_20 = limit - cursor; + lab39: do { + // call mark_possessives, line 400 + if (!r_mark_possessives()) + { + break lab39; + } + break lab38; + } while (false); + cursor = limit - v_20; + // call mark_sU, line 400 + if (!r_mark_sU()) + { + break lab37; + } + } while (false); + // ], line 400 + bra = cursor; + // delete, line 400 + slice_del(); + // try, line 400 + v_21 = limit - cursor; + lab40: do { + // (, line 400 + // [, line 400 + ket = cursor; + // call mark_lAr, line 400 + if (!r_mark_lAr()) + { + cursor = limit - v_21; + break lab40; + } + // ], line 400 + bra = cursor; + // delete, line 400 + slice_del(); + // call stem_suffix_chain_before_ki, line 400 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_21; + break lab40; + } + } while (false); + break lab35; + } while (false); + cursor = limit - v_19; + // call stem_suffix_chain_before_ki, line 402 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_18; + break lab34; + } + } while (false); + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + lab41: do { + // (, line 406 + // [, line 406 + ket = cursor; + // call mark_lArI, line 406 + if (!r_mark_lArI()) + { + break lab41; + } + // ], line 406 + bra = cursor; + // delete, line 406 + slice_del(); + break lab0; + } while (false); + cursor = limit - v_1; + lab42: do { + // (, line 408 + // call stem_suffix_chain_before_ki, line 408 + if (!r_stem_suffix_chain_before_ki()) + { + break lab42; + } + break lab0; + } while (false); + cursor = limit - v_1; + lab43: do { + // (, line 410 + // [, line 410 + ket = cursor; + // or, line 410 + lab44: do { + v_22 = limit - cursor; + lab45: do { + // call mark_DA, line 410 + if (!r_mark_DA()) + { + break lab45; + } + break lab44; + } while (false); + cursor = limit - v_22; + lab46: do { + // call mark_yU, line 410 + if (!r_mark_yU()) + { + break lab46; + } + break lab44; + } while (false); + cursor = limit - v_22; + // call mark_yA, line 410 + if (!r_mark_yA()) + { + break lab43; + } + } while (false); + // ], line 410 + bra = cursor; + // delete, line 410 + slice_del(); + // try, line 410 + v_23 = limit - cursor; + lab47: do { + // (, line 410 + // [, line 410 + ket = cursor; + // (, line 410 + // or, line 410 + lab48: do { + v_24 = limit - cursor; + lab49: do { + // (, line 410 + // call mark_possessives, line 410 + if (!r_mark_possessives()) + { + break lab49; + } + // ], line 410 + bra = cursor; + // delete, line 410 + slice_del(); + // try, line 410 + v_25 = limit - cursor; + lab50: do { + // (, line 410 + // [, line 410 + ket = cursor; + // call mark_lAr, line 410 + if (!r_mark_lAr()) + { + cursor = limit - v_25; + break lab50; + } + } while (false); + break lab48; + } while (false); + cursor = limit - v_24; + // call mark_lAr, line 410 + if (!r_mark_lAr()) + { + cursor = limit - v_23; + break lab47; + } + } while (false); + // ], line 410 + bra = cursor; + // delete, line 410 + slice_del(); + // [, line 410 + ket = cursor; + // call stem_suffix_chain_before_ki, line 410 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_23; + break lab47; + } + } while (false); + break lab0; + } while (false); + cursor = limit - v_1; + // (, line 412 + // [, line 412 + ket = cursor; + // or, line 412 + lab51: do { + v_26 = limit - cursor; + lab52: do { + // call mark_possessives, line 412 + if (!r_mark_possessives()) + { + break lab52; + } + break lab51; + } while (false); + cursor = limit - v_26; + // call mark_sU, line 412 + if (!r_mark_sU()) + { + return false; + } + } while (false); + // ], line 412 + bra = cursor; + // delete, line 412 + slice_del(); + // try, line 412 + v_27 = limit - cursor; + lab53: do { + // (, line 412 + // [, line 412 + ket = cursor; + // call mark_lAr, line 412 + if (!r_mark_lAr()) + { + cursor = limit - v_27; + break lab53; + } + // ], line 412 + bra = cursor; + // delete, line 412 + slice_del(); + // call stem_suffix_chain_before_ki, line 412 + if (!r_stem_suffix_chain_before_ki()) + { + cursor = limit - v_27; + break lab53; + } + } while (false); + } while (false); + return true; + } + + private boolean r_post_process_last_consonants() { + int among_var; + // (, line 415 + // [, line 416 + ket = cursor; + // substring, line 416 + among_var = find_among_b(a_23, 4); + if (among_var == 0) + { + return false; + } + // ], line 416 + bra = cursor; + switch(among_var) { + case 0: + return false; + case 1: + // (, line 417 + // <-, line 417 + slice_from("p"); + break; + case 2: + // (, line 418 + // <-, line 418 + slice_from("\u00E7"); + break; + case 3: + // (, line 419 + // <-, line 419 + slice_from("t"); + break; + case 4: + // (, line 420 + // <-, line 420 + slice_from("k"); + break; + } + return true; + } + + private boolean r_append_U_to_stems_ending_with_d_or_g() { + int v_1; + int v_2; + int v_3; + int v_4; + int v_5; + int v_6; + int v_7; + int v_8; + int v_9; + int v_10; + int v_11; + int v_12; + int v_13; + int v_14; + int v_15; + // (, line 430 + // test, line 431 + v_1 = limit - cursor; + // (, line 431 + // or, line 431 + lab0: do { + v_2 = limit - cursor; + lab1: do { + // literal, line 431 + if (!(eq_s_b(1, "d"))) + { + break lab1; + } + break lab0; + } while (false); + cursor = limit - v_2; + // literal, line 431 + if (!(eq_s_b(1, "g"))) + { + return false; + } + } while (false); + cursor = limit - v_1; + // or, line 433 + lab2: do { + v_3 = limit - cursor; + lab3: do { + // (, line 432 + // test, line 432 + v_4 = limit - cursor; + // (, line 432 + // (, line 432 + // goto, line 432 + golab4: while(true) + { + v_5 = limit - cursor; + lab5: do { + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab5; + } + cursor = limit - v_5; + break golab4; + } while (false); + cursor = limit - v_5; + if (cursor <= limit_backward) + { + break lab3; + } + cursor--; + } + // or, line 432 + lab6: do { + v_6 = limit - cursor; + lab7: do { + // literal, line 432 + if (!(eq_s_b(1, "a"))) + { + break lab7; + } + break lab6; + } while (false); + cursor = limit - v_6; + // literal, line 432 + if (!(eq_s_b(1, "\u0131"))) + { + break lab3; + } + } while (false); + cursor = limit - v_4; + // <+, line 432 + { + int c = cursor; + insert(cursor, cursor, "\u0131"); + cursor = c; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab8: do { + // (, line 434 + // test, line 434 + v_7 = limit - cursor; + // (, line 434 + // (, line 434 + // goto, line 434 + golab9: while(true) + { + v_8 = limit - cursor; + lab10: do { + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab10; + } + cursor = limit - v_8; + break golab9; + } while (false); + cursor = limit - v_8; + if (cursor <= limit_backward) + { + break lab8; + } + cursor--; + } + // or, line 434 + lab11: do { + v_9 = limit - cursor; + lab12: do { + // literal, line 434 + if (!(eq_s_b(1, "e"))) + { + break lab12; + } + break lab11; + } while (false); + cursor = limit - v_9; + // literal, line 434 + if (!(eq_s_b(1, "i"))) + { + break lab8; + } + } while (false); + cursor = limit - v_7; + // <+, line 434 + { + int c = cursor; + insert(cursor, cursor, "i"); + cursor = c; + } + break lab2; + } while (false); + cursor = limit - v_3; + lab13: do { + // (, line 436 + // test, line 436 + v_10 = limit - cursor; + // (, line 436 + // (, line 436 + // goto, line 436 + golab14: while(true) + { + v_11 = limit - cursor; + lab15: do { + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab15; + } + cursor = limit - v_11; + break golab14; + } while (false); + cursor = limit - v_11; + if (cursor <= limit_backward) + { + break lab13; + } + cursor--; + } + // or, line 436 + lab16: do { + v_12 = limit - cursor; + lab17: do { + // literal, line 436 + if (!(eq_s_b(1, "o"))) + { + break lab17; + } + break lab16; + } while (false); + cursor = limit - v_12; + // literal, line 436 + if (!(eq_s_b(1, "u"))) + { + break lab13; + } + } while (false); + cursor = limit - v_10; + // <+, line 436 + { + int c = cursor; + insert(cursor, cursor, "u"); + cursor = c; + } + break lab2; + } while (false); + cursor = limit - v_3; + // (, line 438 + // test, line 438 + v_13 = limit - cursor; + // (, line 438 + // (, line 438 + // goto, line 438 + golab18: while(true) + { + v_14 = limit - cursor; + lab19: do { + if (!(in_grouping_b(g_vowel, 97, 305))) + { + break lab19; + } + cursor = limit - v_14; + break golab18; + } while (false); + cursor = limit - v_14; + if (cursor <= limit_backward) + { + return false; + } + cursor--; + } + // or, line 438 + lab20: do { + v_15 = limit - cursor; + lab21: do { + // literal, line 438 + if (!(eq_s_b(1, "\u00F6"))) + { + break lab21; + } + break lab20; + } while (false); + cursor = limit - v_15; + // literal, line 438 + if (!(eq_s_b(1, "\u00FC"))) + { + return false; + } + } while (false); + cursor = limit - v_13; + // <+, line 438 + { + int c = cursor; + insert(cursor, cursor, "\u00FC"); + cursor = c; + } + } while (false); + return true; + } + + private boolean r_more_than_one_syllable_word() { + int v_1; + int v_3; + // (, line 445 + // test, line 446 + v_1 = cursor; + // (, line 446 + // atleast, line 446 + { + int v_2 = 2; + // atleast, line 446 + replab0: while(true) + { + v_3 = cursor; + lab1: do { + // (, line 446 + // gopast, line 446 + golab2: while(true) + { + lab3: do { + if (!(in_grouping(g_vowel, 97, 305))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + break lab1; + } + cursor++; + } + v_2--; + continue replab0; + } while (false); + cursor = v_3; + break replab0; + } + if (v_2 > 0) + { + return false; + } + } + cursor = v_1; + return true; + } + + private boolean r_is_reserved_word() { + int v_1; + int v_2; + int v_4; + // (, line 449 + // or, line 451 + lab0: do { + v_1 = cursor; + lab1: do { + // test, line 450 + v_2 = cursor; + // (, line 450 + // gopast, line 450 + golab2: while(true) + { + lab3: do { + // literal, line 450 + if (!(eq_s(2, "ad"))) + { + break lab3; + } + break golab2; + } while (false); + if (cursor >= limit) + { + break lab1; + } + cursor++; + } + // (, line 450 + I_strlen = 2; + // (, line 450 + if (!(I_strlen == limit)) + { + break lab1; + } + cursor = v_2; + break lab0; + } while (false); + cursor = v_1; + // test, line 452 + v_4 = cursor; + // (, line 452 + // gopast, line 452 + golab4: while(true) + { + lab5: do { + // literal, line 452 + if (!(eq_s(5, "soyad"))) + { + break lab5; + } + break golab4; + } while (false); + if (cursor >= limit) + { + return false; + } + cursor++; + } + // (, line 452 + I_strlen = 5; + // (, line 452 + if (!(I_strlen == limit)) + { + return false; + } + cursor = v_4; + } while (false); + return true; + } + + private boolean r_postlude() { + int v_1; + int v_2; + int v_3; + // (, line 455 + // not, line 456 + { + v_1 = cursor; + lab0: do { + // (, line 456 + // call is_reserved_word, line 456 + if (!r_is_reserved_word()) + { + break lab0; + } + return false; + } while (false); + cursor = v_1; + } + // backwards, line 457 + limit_backward = cursor; cursor = limit; + // (, line 457 + // do, line 458 + v_2 = limit - cursor; + lab1: do { + // call append_U_to_stems_ending_with_d_or_g, line 458 + if (!r_append_U_to_stems_ending_with_d_or_g()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + // do, line 459 + v_3 = limit - cursor; + lab2: do { + // call post_process_last_consonants, line 459 + if (!r_post_process_last_consonants()) + { + break lab2; + } + } while (false); + cursor = limit - v_3; + cursor = limit_backward; return true; + } + + public boolean stem() { + int v_1; + int v_2; + // (, line 464 + // (, line 465 + // call more_than_one_syllable_word, line 465 + if (!r_more_than_one_syllable_word()) + { + return false; + } + // (, line 466 + // backwards, line 467 + limit_backward = cursor; cursor = limit; + // (, line 467 + // do, line 468 + v_1 = limit - cursor; + lab0: do { + // call stem_nominal_verb_suffixes, line 468 + if (!r_stem_nominal_verb_suffixes()) + { + break lab0; + } + } while (false); + cursor = limit - v_1; + // Boolean test continue_stemming_noun_suffixes, line 469 + if (!(B_continue_stemming_noun_suffixes)) + { + return false; + } + // do, line 470 + v_2 = limit - cursor; + lab1: do { + // call stem_noun_suffixes, line 470 + if (!r_stem_noun_suffixes()) + { + break lab1; + } + } while (false); + cursor = limit - v_2; + cursor = limit_backward; // call postlude, line 473 + if (!r_postlude()) + { + return false; + } + return true; + } + +} + Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/AssertionFailedException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/AssertionFailedException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/AssertionFailedException.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,66 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Assertions for empty code paths that should never be executed. + * + * @author Mark Matthews + * + * @version $Id: AssertionFailedException.java,v 1.1.2.1 2005/05/13 18:58:37 + * mmatthews Exp $ + */ +public class AssertionFailedException extends RuntimeException { + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Convenience method. + * + * @param ex + * the exception that should never have been thrown. + * @throws AssertionFailedException + * for the exception ex. + */ + public static void shouldNotHappen(Exception ex) + throws AssertionFailedException { + throw new AssertionFailedException(ex); + } + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Creates an AssertionFailedException for the given exception that should + * never have been thrown. + * + * @param ex + * the exception that should never have been thrown. + */ + public AssertionFailedException(Exception ex) { + super(Messages.getString("AssertionFailedException.0") + ex.toString() //$NON-NLS-1$ + + Messages.getString("AssertionFailedException.1")); //$NON-NLS-1$ + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Blob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Blob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Blob.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,247 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.OutputStream; + +import java.sql.SQLException; + +/** + * The representation (mapping) in the JavaTM programming language of an SQL + * BLOB value. An SQL BLOB is a built-in type that stores a Binary Large Object + * as a column value in a row of a database table. The driver implements Blob + * using an SQL locator(BLOB), which means that a Blob object contains a logical + * pointer to the SQL BLOB data rather than the data itself. A Blob object is + * valid for the duration of the transaction in which is was created. Methods in + * the interfaces ResultSet, CallableStatement, and PreparedStatement, such as + * getBlob and setBlob allow a programmer to access an SQL BLOB value. The Blob + * interface provides methods for getting the length of an SQL BLOB (Binary + * Large Object) value, for materializing a BLOB value on the client, and for + * determining the position of a pattern of bytes within a BLOB value. This + * class is new in the JDBC 2.0 API. + * + * @author Mark Matthews + * @version $Id: Blob.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + */ +public class Blob implements java.sql.Blob, OutputStreamWatcher { + + // + // This is a real brain-dead implementation of BLOB. Once I add + // streamability to the I/O for MySQL this will be more efficiently + // implemented (except for the position() method, ugh). + // + + /** The binary data that makes up this BLOB */ + private byte[] binaryData = null; + + /** + * Creates a BLOB encapsulating the given binary data + * + * @param data + * DOCUMENT ME! + */ + Blob(byte[] data) { + setBinaryData(data); + } + + /** + * Creates an updatable BLOB that can update in-place (not implemented yet). + * + * @param data + * DOCUMENT ME! + * @param creatorResultSetToSet + * DOCUMENT ME! + * @param columnIndexToSet + * DOCUMENT ME! + */ + Blob(byte[] data, ResultSet creatorResultSetToSet, int columnIndexToSet) { + setBinaryData(data); + } + + private byte[] getBinaryData() { + return this.binaryData; + } + + /** + * Retrieves the BLOB designated by this Blob instance as a stream. + * + * @return this BLOB represented as a binary stream of bytes. + * + * @throws SQLException + * if a database error occurs + */ + public java.io.InputStream getBinaryStream() throws SQLException { + return new ByteArrayInputStream(getBinaryData()); + } + + /** + * Returns as an array of bytes, part or all of the BLOB value that this + * Blob object designates. + * + * @param pos + * where to start the part of the BLOB + * @param length + * the length of the part of the BLOB you want returned. + * + * @return the bytes stored in the blob starting at position + * pos and having a length of length. + * + * @throws SQLException + * if a database error occurs + */ + public byte[] getBytes(long pos, int length) throws SQLException { + if (pos < 1) { + throw SQLError.createSQLException(Messages.getString("Blob.2"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + byte[] newData = new byte[length]; + System.arraycopy(getBinaryData(), (int) (pos - 1), newData, 0, length); + + return newData; + } + + /** + * Returns the number of bytes in the BLOB value designated by this Blob + * object. + * + * @return the length of this blob + * + * @throws SQLException + * if a database error occurs + */ + public long length() throws SQLException { + return getBinaryData().length; + } + + /** + * @see java.sql.Blob#position(byte[], long) + */ + public long position(byte[] pattern, long start) throws SQLException { + throw SQLError.createSQLException("Not implemented"); //$NON-NLS-1$ + } + + /** + * Finds the position of the given pattern in this BLOB. + * + * @param pattern + * the pattern to find + * @param start + * where to start finding the pattern + * + * @return the position where the pattern is found in the BLOB, -1 if not + * found + * + * @throws SQLException + * if a database error occurs + */ + public long position(java.sql.Blob pattern, long start) throws SQLException { + return position(pattern.getBytes(0, (int) pattern.length()), start); + } + + private void setBinaryData(byte[] newBinaryData) { + this.binaryData = newBinaryData; + } + + /** + * @see Blob#setBinaryStream(long) + */ + public OutputStream setBinaryStream(long indexToWriteAt) + throws SQLException { + if (indexToWriteAt < 1) { + throw SQLError.createSQLException(Messages.getString("Blob.0"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + WatchableOutputStream bytesOut = new WatchableOutputStream(); + bytesOut.setWatcher(this); + + if (indexToWriteAt > 0) { + bytesOut.write(this.binaryData, 0, (int) (indexToWriteAt - 1)); + } + + return bytesOut; + } + + /** + * @see Blob#setBytes(long, byte[]) + */ + public int setBytes(long writeAt, byte[] bytes) throws SQLException { + return setBytes(writeAt, bytes, 0, bytes.length); + } + + /** + * @see Blob#setBytes(long, byte[], int, int) + */ + public int setBytes(long writeAt, byte[] bytes, int offset, int length) + throws SQLException { + OutputStream bytesOut = setBinaryStream(writeAt); + + try { + bytesOut.write(bytes, offset, length); + } catch (IOException ioEx) { + throw SQLError.createSQLException(Messages.getString("Blob.1"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + try { + bytesOut.close(); + } catch (IOException doNothing) { + ; // do nothing + } + } + + return length; + } + + /** + * @see com.mysql.jdbc.OutputStreamWatcher#streamClosed(byte[]) + */ + public void streamClosed(byte[] byteData) { + this.binaryData = byteData; + } + + /** + * @see com.mysql.jdbc.OutputStreamWatcher#streamClosed(byte[]) + */ + public void streamClosed(WatchableOutputStream out) { + int streamSize = out.size(); + + if (streamSize < this.binaryData.length) { + out.write(this.binaryData, streamSize, this.binaryData.length + - streamSize); + } + + this.binaryData = out.toByteArray(); + } + + /** + * @see Blob#truncate(long) + */ + public void truncate(long arg0) throws SQLException { + throw new NotImplemented(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/BlobFromLocator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/BlobFromLocator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/BlobFromLocator.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,670 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * The representation (mapping) in the JavaTM programming language of an SQL + * BLOB value. An SQL BLOB is a built-in type that stores a Binary Large Object + * as a column value in a row of a database table. The driver implements Blob + * using an SQL locator(BLOB), which means that a Blob object contains a logical + * pointer to the SQL BLOB data rather than the data itself. A Blob object is + * valid for the duration of the transaction in which is was created. Methods in + * the interfaces ResultSet, CallableStatement, and PreparedStatement, such as + * getBlob and setBlob allow a programmer to access an SQL BLOB value. The Blob + * interface provides methods for getting the length of an SQL BLOB (Binary + * Large Object) value, for materializing a BLOB value on the client, and for + * determining the position of a pattern of bytes within a BLOB value. This + * class is new in the JDBC 2.0 API. + * + * @author Mark Matthews + * + * @version $Id: BlobFromLocator.java,v 1.1.4.1 2005/05/19 18:31:49 mmatthews + * Exp $ + */ +public class BlobFromLocator implements java.sql.Blob { + private List primaryKeyColumns = null; + + private List primaryKeyValues = null; + + /** The ResultSet that created this BLOB */ + private ResultSet creatorResultSet; + + private String blobColumnName = null; + + private String tableName = null; + + private int numColsInResultSet = 0; + + private int numPrimaryKeys = 0; + + private String quotedId; + + /** + * Creates an updatable BLOB that can update in-place + */ + BlobFromLocator(ResultSet creatorResultSetToSet, int blobColumnIndex) + throws SQLException { + this.creatorResultSet = creatorResultSetToSet; + + this.numColsInResultSet = this.creatorResultSet.fields.length; + this.quotedId = this.creatorResultSet.connection.getMetaData() + .getIdentifierQuoteString(); + + if (this.numColsInResultSet > 1) { + this.primaryKeyColumns = new ArrayList(); + this.primaryKeyValues = new ArrayList(); + + for (int i = 0; i < this.numColsInResultSet; i++) { + if (this.creatorResultSet.fields[i].isPrimaryKey()) { + StringBuffer keyName = new StringBuffer(); + keyName.append(quotedId); + + String originalColumnName = this.creatorResultSet.fields[i] + .getOriginalName(); + + if ((originalColumnName != null) + && (originalColumnName.length() > 0)) { + keyName.append(originalColumnName); + } else { + keyName.append(this.creatorResultSet.fields[i] + .getName()); + } + + keyName.append(quotedId); + + this.primaryKeyColumns.add(keyName.toString()); + this.primaryKeyValues.add(this.creatorResultSet + .getString(i + 1)); + } + } + } else { + notEnoughInformationInQuery(); + } + + this.numPrimaryKeys = this.primaryKeyColumns.size(); + + if (this.numPrimaryKeys == 0) { + notEnoughInformationInQuery(); + } + + if (this.creatorResultSet.fields[0].getOriginalTableName() != null) { + StringBuffer tableNameBuffer = new StringBuffer(); + + String databaseName = this.creatorResultSet.fields[0] + .getDatabaseName(); + + if ((databaseName != null) && (databaseName.length() > 0)) { + tableNameBuffer.append(quotedId); + tableNameBuffer.append(databaseName); + tableNameBuffer.append(quotedId); + tableNameBuffer.append('.'); + } + + tableNameBuffer.append(quotedId); + tableNameBuffer.append(this.creatorResultSet.fields[0] + .getOriginalTableName()); + tableNameBuffer.append(quotedId); + + this.tableName = tableNameBuffer.toString(); + } else { + StringBuffer tableNameBuffer = new StringBuffer(); + + tableNameBuffer.append(quotedId); + tableNameBuffer.append(this.creatorResultSet.fields[0] + .getTableName()); + tableNameBuffer.append(quotedId); + + this.tableName = tableNameBuffer.toString(); + } + + this.blobColumnName = quotedId + + this.creatorResultSet.getString(blobColumnIndex) + quotedId; + } + + private void notEnoughInformationInQuery() throws SQLException { + throw SQLError.createSQLException("Emulated BLOB locators must come from " + + "a ResultSet with only one table selected, and all primary " + + "keys selected", SQLError.SQL_STATE_GENERAL_ERROR); + } + + /** + * @see Blob#setBinaryStream(long) + */ + public OutputStream setBinaryStream(long indexToWriteAt) + throws SQLException { + throw new NotImplemented(); + } + + /** + * Retrieves the BLOB designated by this Blob instance as a stream. + * + * @return this BLOB represented as a binary stream of bytes. + * + * @throws SQLException + * if a database error occurs + */ + public java.io.InputStream getBinaryStream() throws SQLException { + // TODO: Make fetch size configurable + return new BufferedInputStream(new LocatorInputStream(), + this.creatorResultSet.connection.getLocatorFetchBufferSize()); + } + + /** + * @see Blob#setBytes(long, byte[], int, int) + */ + public int setBytes(long writeAt, byte[] bytes, int offset, int length) + throws SQLException { + java.sql.PreparedStatement pStmt = null; + + if ((offset + length) > bytes.length) { + length = bytes.length - offset; + } + + byte[] bytesToWrite = new byte[length]; + System.arraycopy(bytes, offset, bytesToWrite, 0, length); + + // FIXME: Needs to use identifiers for column/table names + StringBuffer query = new StringBuffer("UPDATE "); + query.append(this.tableName); + query.append(" SET "); + query.append(this.blobColumnName); + query.append(" = INSERT("); + query.append(this.blobColumnName); + query.append(", "); + query.append(writeAt); + query.append(", "); + query.append(length); + query.append(", ?) WHERE "); + + query.append((String) this.primaryKeyColumns.get(0)); + query.append(" = ?"); + + for (int i = 1; i < this.numPrimaryKeys; i++) { + query.append(" AND "); + query.append((String) this.primaryKeyColumns.get(i)); + query.append(" = ?"); + } + + try { + // FIXME: Have this passed in instead + pStmt = this.creatorResultSet.connection.prepareStatement(query + .toString()); + + pStmt.setBytes(1, bytesToWrite); + + for (int i = 0; i < this.numPrimaryKeys; i++) { + pStmt.setString(i + 2, (String) this.primaryKeyValues.get(i)); + } + + int rowsUpdated = pStmt.executeUpdate(); + + if (rowsUpdated != 1) { + throw SQLError.createSQLException( + "BLOB data not found! Did primary keys change?", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } finally { + if (pStmt != null) { + try { + pStmt.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + pStmt = null; + } + } + + return (int) length(); + } + + /** + * @see Blob#setBytes(long, byte[]) + */ + public int setBytes(long writeAt, byte[] bytes) throws SQLException { + return setBytes(writeAt, bytes, 0, bytes.length); + } + + /** + * Returns as an array of bytes, part or all of the BLOB value that this + * Blob object designates. + * + * @param pos + * where to start the part of the BLOB + * @param length + * the length of the part of the BLOB you want returned. + * + * @return the bytes stored in the blob starting at position + * pos and having a length of length. + * + * @throws SQLException + * if a database error occurs + */ + public byte[] getBytes(long pos, int length) throws SQLException { + java.sql.PreparedStatement pStmt = null; + + try { + + pStmt = createGetBytesStatement(); + + return getBytesInternal(pStmt, pos, length); + } finally { + if (pStmt != null) { + try { + pStmt.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + pStmt = null; + } + } + } + + /** + * Returns the number of bytes in the BLOB value designated by this Blob + * object. + * + * @return the length of this blob + * + * @throws SQLException + * if a database error occurs + */ + public long length() throws SQLException { + java.sql.ResultSet blobRs = null; + java.sql.PreparedStatement pStmt = null; + + // FIXME: Needs to use identifiers for column/table names + StringBuffer query = new StringBuffer("SELECT LENGTH("); + query.append(this.blobColumnName); + query.append(") FROM "); + query.append(this.tableName); + query.append(" WHERE "); + + query.append((String) this.primaryKeyColumns.get(0)); + query.append(" = ?"); + + for (int i = 1; i < this.numPrimaryKeys; i++) { + query.append(" AND "); + query.append((String) this.primaryKeyColumns.get(i)); + query.append(" = ?"); + } + + try { + // FIXME: Have this passed in instead + pStmt = this.creatorResultSet.connection.prepareStatement(query + .toString()); + + for (int i = 0; i < this.numPrimaryKeys; i++) { + pStmt.setString(i + 1, (String) this.primaryKeyValues.get(i)); + } + + blobRs = pStmt.executeQuery(); + + if (blobRs.next()) { + return blobRs.getLong(1); + } + + throw SQLError.createSQLException( + "BLOB data not found! Did primary keys change?", + SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + if (blobRs != null) { + try { + blobRs.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + blobRs = null; + } + + if (pStmt != null) { + try { + pStmt.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + pStmt = null; + } + } + } + + /** + * Finds the position of the given pattern in this BLOB. + * + * @param pattern + * the pattern to find + * @param start + * where to start finding the pattern + * + * @return the position where the pattern is found in the BLOB, -1 if not + * found + * + * @throws SQLException + * if a database error occurs + */ + public long position(java.sql.Blob pattern, long start) throws SQLException { + return position(pattern.getBytes(0, (int) pattern.length()), start); + } + + /** + * @see java.sql.Blob#position(byte[], long) + */ + public long position(byte[] pattern, long start) throws SQLException { + java.sql.ResultSet blobRs = null; + java.sql.PreparedStatement pStmt = null; + + // FIXME: Needs to use identifiers for column/table names + StringBuffer query = new StringBuffer("SELECT LOCATE("); + query.append("?, "); + query.append(this.blobColumnName); + query.append(", "); + query.append(start); + query.append(") FROM "); + query.append(this.tableName); + query.append(" WHERE "); + + query.append((String) this.primaryKeyColumns.get(0)); + query.append(" = ?"); + + for (int i = 1; i < this.numPrimaryKeys; i++) { + query.append(" AND "); + query.append((String) this.primaryKeyColumns.get(i)); + query.append(" = ?"); + } + + try { + // FIXME: Have this passed in instead + pStmt = this.creatorResultSet.connection.prepareStatement(query + .toString()); + pStmt.setBytes(1, pattern); + + for (int i = 0; i < this.numPrimaryKeys; i++) { + pStmt.setString(i + 2, (String) this.primaryKeyValues.get(i)); + } + + blobRs = pStmt.executeQuery(); + + if (blobRs.next()) { + return blobRs.getLong(1); + } + + throw SQLError.createSQLException( + "BLOB data not found! Did primary keys change?", + SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + if (blobRs != null) { + try { + blobRs.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + blobRs = null; + } + + if (pStmt != null) { + try { + pStmt.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + pStmt = null; + } + } + } + + /** + * @see Blob#truncate(long) + */ + public void truncate(long length) throws SQLException { + java.sql.PreparedStatement pStmt = null; + + // FIXME: Needs to use identifiers for column/table names + StringBuffer query = new StringBuffer("UPDATE "); + query.append(this.tableName); + query.append(" SET "); + query.append(this.blobColumnName); + query.append(" = LEFT("); + query.append(this.blobColumnName); + query.append(", "); + query.append(length); + query.append(") WHERE "); + + query.append((String) this.primaryKeyColumns.get(0)); + query.append(" = ?"); + + for (int i = 1; i < this.numPrimaryKeys; i++) { + query.append(" AND "); + query.append((String) this.primaryKeyColumns.get(i)); + query.append(" = ?"); + } + + try { + // FIXME: Have this passed in instead + pStmt = this.creatorResultSet.connection.prepareStatement(query + .toString()); + + for (int i = 0; i < this.numPrimaryKeys; i++) { + pStmt.setString(i + 1, (String) this.primaryKeyValues.get(i)); + } + + int rowsUpdated = pStmt.executeUpdate(); + + if (rowsUpdated != 1) { + throw SQLError.createSQLException( + "BLOB data not found! Did primary keys change?", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } finally { + if (pStmt != null) { + try { + pStmt.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + pStmt = null; + } + } + } + + java.sql.PreparedStatement createGetBytesStatement() throws SQLException { + StringBuffer query = new StringBuffer("SELECT SUBSTRING("); + + query.append(this.blobColumnName); + query.append(", "); + query.append("?"); + query.append(", "); + query.append("?"); + query.append(") FROM "); + query.append(this.tableName); + query.append(" WHERE "); + + query.append((String) this.primaryKeyColumns.get(0)); + query.append(" = ?"); + + for (int i = 1; i < this.numPrimaryKeys; i++) { + query.append(" AND "); + query.append((String) this.primaryKeyColumns.get(i)); + query.append(" = ?"); + } + + return this.creatorResultSet.connection.prepareStatement(query + .toString()); + } + + byte[] getBytesInternal(java.sql.PreparedStatement pStmt, long pos, + int length) throws SQLException { + + java.sql.ResultSet blobRs = null; + + try { + + pStmt.setLong(1, pos); + pStmt.setInt(2, length); + + for (int i = 0; i < this.numPrimaryKeys; i++) { + pStmt.setString(i + 3, (String) this.primaryKeyValues.get(i)); + } + + blobRs = pStmt.executeQuery(); + + if (blobRs.next()) { + return ((com.mysql.jdbc.ResultSet) blobRs).getBytes(1, true); + } + + throw SQLError.createSQLException( + "BLOB data not found! Did primary keys change?", + SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + if (blobRs != null) { + try { + blobRs.close(); + } catch (SQLException sqlEx) { + ; // do nothing + } + + blobRs = null; + } + } + } + + class LocatorInputStream extends InputStream { + long currentPositionInBlob = 0; + + long length = 0; + + java.sql.PreparedStatement pStmt = null; + + LocatorInputStream() throws SQLException { + length = length(); + pStmt = createGetBytesStatement(); + } + + public int read() throws IOException { + if (currentPositionInBlob + 1 > length) { + return -1; + } + + try { + byte[] asBytes = getBytesInternal(pStmt, + (currentPositionInBlob++) + 1, 1); + + if (asBytes == null) { + return -1; + } + + return asBytes[0]; + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); + } + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#read(byte[], int, int) + */ + public int read(byte[] b, int off, int len) throws IOException { + if (currentPositionInBlob + 1 > length) { + return -1; + } + + try { + byte[] asBytes = getBytesInternal(pStmt, + (currentPositionInBlob) + 1, len); + + if (asBytes == null) { + return -1; + } + + System.arraycopy(asBytes, 0, b, off, asBytes.length); + + currentPositionInBlob += asBytes.length; + + return asBytes.length; + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); + } + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#read(byte[]) + */ + public int read(byte[] b) throws IOException { + if (currentPositionInBlob + 1 > length) { + return -1; + } + + try { + byte[] asBytes = getBytesInternal(pStmt, + (currentPositionInBlob) + 1, b.length); + + if (asBytes == null) { + return -1; + } + + System.arraycopy(asBytes, 0, b, 0, asBytes.length); + + currentPositionInBlob += asBytes.length; + + return asBytes.length; + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); + } + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#close() + */ + public void close() throws IOException { + if (pStmt != null) { + try { + pStmt.close(); + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); + } + } + + super.close(); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Buffer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Buffer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Buffer.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,663 @@ +/* + Copyright (C) 2002-2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.UnsupportedEncodingException; + +import java.nio.ByteBuffer; + +import java.sql.SQLException; + +/** + * Buffer contains code to read and write packets from/to the MySQL server. + * + * @version $Id: Buffer.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + * @author Mark Matthews + */ +class Buffer { + static final int MAX_BYTES_TO_DUMP = 512; + + static final int NO_LENGTH_LIMIT = -1; + + static final long NULL_LENGTH = -1; + + private int bufLength = 0; + + private byte[] byteBuffer; + + private int position = 0; + + protected boolean wasMultiPacket = false; + + Buffer(byte[] buf) { + this.byteBuffer = buf; + setBufLength(buf.length); + } + + Buffer(int size) { + this.byteBuffer = new byte[size]; + setBufLength(this.byteBuffer.length); + this.position = MysqlIO.HEADER_LENGTH; + } + + final void clear() { + this.position = MysqlIO.HEADER_LENGTH; + } + + final void dump() { + dump(getBufLength()); + } + + final String dump(int numBytes) { + return StringUtils.dumpAsHex(getBytes(0, + numBytes > getBufLength() ? getBufLength() : numBytes), + numBytes > getBufLength() ? getBufLength() : numBytes); + } + + final String dumpClampedBytes(int numBytes) { + int numBytesToDump = numBytes < MAX_BYTES_TO_DUMP ? numBytes + : MAX_BYTES_TO_DUMP; + + String dumped = StringUtils.dumpAsHex(getBytes(0, + numBytesToDump > getBufLength() ? getBufLength() + : numBytesToDump), + numBytesToDump > getBufLength() ? getBufLength() + : numBytesToDump); + + if (numBytesToDump < numBytes) { + return dumped + " ....(packet exceeds max. dump length)"; + } + + return dumped; + } + + final void dumpHeader() { + for (int i = 0; i < MysqlIO.HEADER_LENGTH; i++) { + String hexVal = Integer.toHexString(readByte(i) & 0xff); + + if (hexVal.length() == 1) { + hexVal = "0" + hexVal; //$NON-NLS-1$ + } + + System.out.print(hexVal + " "); //$NON-NLS-1$ + } + } + + final void dumpNBytes(int start, int nBytes) { + StringBuffer asciiBuf = new StringBuffer(); + + for (int i = start; (i < (start + nBytes)) && (i < getBufLength()); i++) { + String hexVal = Integer.toHexString(readByte(i) & 0xff); + + if (hexVal.length() == 1) { + hexVal = "0" + hexVal; //$NON-NLS-1$ + } + + System.out.print(hexVal + " "); //$NON-NLS-1$ + + if ((readByte(i) > 32) && (readByte(i) < 127)) { + asciiBuf.append((char) readByte(i)); + } else { + asciiBuf.append("."); //$NON-NLS-1$ + } + + asciiBuf.append(" "); //$NON-NLS-1$ + } + + System.out.println(" " + asciiBuf.toString()); //$NON-NLS-1$ + } + + final void ensureCapacity(int additionalData) throws SQLException { + if ((this.position + additionalData) > getBufLength()) { + if ((this.position + additionalData) < this.byteBuffer.length) { + // byteBuffer.length is != getBufLength() all of the time + // due to re-using of packets (we don't shrink them) + // + // If we can, don't re-alloc, just set buffer length + // to size of current buffer + setBufLength(this.byteBuffer.length); + } else { + // + // Otherwise, re-size, and pad so we can avoid + // allocing again in the near future + // + int newLength = (int) (this.byteBuffer.length * 1.25); + + if (newLength < (this.byteBuffer.length + additionalData)) { + newLength = this.byteBuffer.length + + (int) (additionalData * 1.25); + } + + if (newLength < this.byteBuffer.length) { + newLength = this.byteBuffer.length + additionalData; + } + + byte[] newBytes = new byte[newLength]; + + System.arraycopy(this.byteBuffer, 0, newBytes, 0, + this.byteBuffer.length); + this.byteBuffer = newBytes; + setBufLength(this.byteBuffer.length); + } + } + } + + /** + * Skip over a length-encoded string + * + * @return The position past the end of the string + */ + public int fastSkipLenString() { + long len = this.readFieldLength(); + + this.position += len; + + return (int) len; // this is safe, as this is only + } + + protected final byte[] getBufferSource() { + return this.byteBuffer; + } + + int getBufLength() { + return this.bufLength; + } + + /** + * Returns the array of bytes this Buffer is using to read from. + * + * @return byte array being read from + */ + public byte[] getByteBuffer() { + return this.byteBuffer; + } + + final byte[] getBytes(int len) { + byte[] b = new byte[len]; + System.arraycopy(this.byteBuffer, this.position, b, 0, len); + this.position += len; // update cursor + + return b; + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.Buffer#getBytes(int, int) + */ + byte[] getBytes(int offset, int len) { + byte[] dest = new byte[len]; + System.arraycopy(this.byteBuffer, offset, dest, 0, len); + + return dest; + } + + int getCapacity() { + return this.byteBuffer.length; + } + + public ByteBuffer getNioBuffer() { + throw new IllegalArgumentException(Messages + .getString("ByteArrayBuffer.0")); //$NON-NLS-1$ + } + + /** + * Returns the current position to write to/ read from + * + * @return the current position to write to/ read from + */ + public int getPosition() { + return this.position; + } + + // 2000-06-05 Changed + final boolean isLastDataPacket() { + return ((getBufLength() < 9) && ((this.byteBuffer[0] & 0xff) == 254)); + } + + final long newReadLength() { + int sw = this.byteBuffer[this.position++] & 0xff; + + switch (sw) { + case 251: + return 0; + + case 252: + return readInt(); + + case 253: + return readLongInt(); + + case 254: // changed for 64 bit lengths + return readLongLong(); + + default: + return sw; + } + } + + final byte readByte() { + return this.byteBuffer[this.position++]; + } + + final byte readByte(int readAt) { + return this.byteBuffer[readAt]; + } + + final long readFieldLength() { + int sw = this.byteBuffer[this.position++] & 0xff; + + switch (sw) { + case 251: + return NULL_LENGTH; + + case 252: + return readInt(); + + case 253: + return readLongInt(); + + case 254: + return readLongLong(); + + default: + return sw; + } + } + + // 2000-06-05 Changed + final int readInt() { + byte[] b = this.byteBuffer; // a little bit optimization + + return (b[this.position++] & 0xff) | ((b[this.position++] & 0xff) << 8); + } + + final int readIntAsLong() { + byte[] b = this.byteBuffer; + + return (b[this.position++] & 0xff) | ((b[this.position++] & 0xff) << 8) + | ((b[this.position++] & 0xff) << 16) + | ((b[this.position++] & 0xff) << 24); + } + + final byte[] readLenByteArray(int offset) { + long len = this.readFieldLength(); + + if (len == NULL_LENGTH) { + return null; + } + + if (len == 0) { + return Constants.EMPTY_BYTE_ARRAY; + } + + this.position += offset; + + return getBytes((int) len); + } + + final long readLength() { + int sw = this.byteBuffer[this.position++] & 0xff; + + switch (sw) { + case 251: + return 0; + + case 252: + return readInt(); + + case 253: + return readLongInt(); + + case 254: + return readLong(); + + default: + return sw; + } + } + + // 2000-06-05 Fixed + final long readLong() { + byte[] b = this.byteBuffer; + + return ((long) b[this.position++] & 0xff) + | (((long) b[this.position++] & 0xff) << 8) + | ((long) (b[this.position++] & 0xff) << 16) + | ((long) (b[this.position++] & 0xff) << 24); + } + + // 2000-06-05 Changed + final int readLongInt() { + byte[] b = this.byteBuffer; + + return (b[this.position++] & 0xff) | ((b[this.position++] & 0xff) << 8) + | ((b[this.position++] & 0xff) << 16); + } + + // 2000-06-05 Fixed + final long readLongLong() { + byte[] b = this.byteBuffer; + + return (b[this.position++] & 0xff) + | ((long) (b[this.position++] & 0xff) << 8) + | ((long) (b[this.position++] & 0xff) << 16) + | ((long) (b[this.position++] & 0xff) << 24) + | ((long) (b[this.position++] & 0xff) << 32) + | ((long) (b[this.position++] & 0xff) << 40) + | ((long) (b[this.position++] & 0xff) << 48) + | ((long) (b[this.position++] & 0xff) << 56); + } + + final int readnBytes() { + int sw = this.byteBuffer[this.position++] & 0xff; + + switch (sw) { + case 1: + return this.byteBuffer[this.position++] & 0xff; + + case 2: + return this.readInt(); + + case 3: + return this.readLongInt(); + + case 4: + return (int) this.readLong(); + + default: + return 255; + } + } + + // + // Read a null-terminated string + // + // To avoid alloc'ing a new byte array, we + // do this by hand, rather than calling getNullTerminatedBytes() + // + final String readString() { + int i = this.position; + int len = 0; + int maxLen = getBufLength(); + + while ((i < maxLen) && (this.byteBuffer[i] != 0)) { + len++; + i++; + } + + String s = new String(this.byteBuffer, this.position, len); + this.position += (len + 1); // update cursor + + return s; + } + + final String readString(String encoding) throws SQLException { + int i = this.position; + int len = 0; + int maxLen = getBufLength(); + + while ((i < maxLen) && (this.byteBuffer[i] != 0)) { + len++; + i++; + } + + try { + return new String(this.byteBuffer, this.position, len, encoding); + } catch (UnsupportedEncodingException uEE) { + throw SQLError.createSQLException(Messages.getString("ByteArrayBuffer.1") //$NON-NLS-1$ + + encoding + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } finally { + this.position += (len + 1); // update cursor + } + } + + void setBufLength(int bufLengthToSet) { + this.bufLength = bufLengthToSet; + } + + /** + * Sets the array of bytes to use as a buffer to read from. + * + * @param byteBuffer + * the array of bytes to use as a buffer + */ + public void setByteBuffer(byte[] byteBufferToSet) { + this.byteBuffer = byteBufferToSet; + } + + /** + * Set the current position to write to/ read from + * + * @param position + * the position (0-based index) + */ + public void setPosition(int positionToSet) { + this.position = positionToSet; + } + + /** + * Sets whether this packet was part of a multipacket + * + * @param flag + * was this packet part of a multipacket? + */ + public void setWasMultiPacket(boolean flag) { + this.wasMultiPacket = flag; + } + + public String toString() { + return dumpClampedBytes(getPosition()); + } + + public String toSuperString() { + return super.toString(); + } + + /** + * Was this packet part of a multipacket? + * + * @return was this packet part of a multipacket? + */ + public boolean wasMultiPacket() { + return this.wasMultiPacket; + } + + final void writeByte(byte b) throws SQLException { + ensureCapacity(1); + + this.byteBuffer[this.position++] = b; + } + + // Write a byte array + final void writeBytesNoNull(byte[] bytes) throws SQLException { + int len = bytes.length; + ensureCapacity(len); + System.arraycopy(bytes, 0, this.byteBuffer, this.position, len); + this.position += len; + } + + // Write a byte array with the given offset and length + final void writeBytesNoNull(byte[] bytes, int offset, int length) + throws SQLException { + ensureCapacity(length); + System.arraycopy(bytes, offset, this.byteBuffer, this.position, length); + this.position += length; + } + + final void writeDouble(double d) throws SQLException { + long l = Double.doubleToLongBits(d); + writeLongLong(l); + } + + final void writeFieldLength(long length) throws SQLException { + if (length < 251) { + writeByte((byte) length); + } else if (length < 65536L) { + ensureCapacity(3); + writeByte((byte) 252); + writeInt((int) length); + } else if (length < 16777216L) { + ensureCapacity(4); + writeByte((byte) 253); + writeLongInt((int) length); + } else { + ensureCapacity(9); + writeByte((byte) 254); + writeLongLong(length); + } + } + + final void writeFloat(float f) throws SQLException { + ensureCapacity(4); + + int i = Float.floatToIntBits(f); + byte[] b = this.byteBuffer; + b[this.position++] = (byte) (i & 0xff); + b[this.position++] = (byte) (i >>> 8); + b[this.position++] = (byte) (i >>> 16); + b[this.position++] = (byte) (i >>> 24); + } + + // 2000-06-05 Changed + final void writeInt(int i) throws SQLException { + ensureCapacity(2); + + byte[] b = this.byteBuffer; + b[this.position++] = (byte) (i & 0xff); + b[this.position++] = (byte) (i >>> 8); + } + + // Write a String using the specified character + // encoding + final void writeLenBytes(byte[] b) throws SQLException { + int len = b.length; + ensureCapacity(len + 9); + writeFieldLength(len); + System.arraycopy(b, 0, this.byteBuffer, this.position, len); + this.position += len; + } + + // Write a String using the specified character + // encoding + final void writeLenString(String s, String encoding, String serverEncoding, + SingleByteCharsetConverter converter, boolean parserKnowsUnicode, + Connection conn) + throws UnsupportedEncodingException, SQLException { + byte[] b = null; + + if (converter != null) { + b = converter.toBytes(s); + } else { + b = StringUtils.getBytes(s, encoding, serverEncoding, + parserKnowsUnicode, conn); + } + + int len = b.length; + ensureCapacity(len + 9); + writeFieldLength(len); + System.arraycopy(b, 0, this.byteBuffer, this.position, len); + this.position += len; + } + + // 2000-06-05 Changed + final void writeLong(long i) throws SQLException { + ensureCapacity(4); + + byte[] b = this.byteBuffer; + b[this.position++] = (byte) (i & 0xff); + b[this.position++] = (byte) (i >>> 8); + b[this.position++] = (byte) (i >>> 16); + b[this.position++] = (byte) (i >>> 24); + } + + // 2000-06-05 Changed + final void writeLongInt(int i) throws SQLException { + ensureCapacity(3); + byte[] b = this.byteBuffer; + b[this.position++] = (byte) (i & 0xff); + b[this.position++] = (byte) (i >>> 8); + b[this.position++] = (byte) (i >>> 16); + } + + final void writeLongLong(long i) throws SQLException { + ensureCapacity(8); + byte[] b = this.byteBuffer; + b[this.position++] = (byte) (i & 0xff); + b[this.position++] = (byte) (i >>> 8); + b[this.position++] = (byte) (i >>> 16); + b[this.position++] = (byte) (i >>> 24); + b[this.position++] = (byte) (i >>> 32); + b[this.position++] = (byte) (i >>> 40); + b[this.position++] = (byte) (i >>> 48); + b[this.position++] = (byte) (i >>> 56); + } + + // Write null-terminated string + final void writeString(String s) throws SQLException { + ensureCapacity((s.length() * 2) + 1); + writeStringNoNull(s); + this.byteBuffer[this.position++] = 0; + } + + // Write null-terminated string in the given encoding + final void writeString(String s, String encoding, Connection conn) throws SQLException { + ensureCapacity((s.length() * 2) + 1); + try { + writeStringNoNull(s, encoding, encoding, false, conn); + } catch (UnsupportedEncodingException ue) { + throw new SQLException(ue.toString(), SQLError.SQL_STATE_GENERAL_ERROR); + } + + this.byteBuffer[this.position++] = 0; + } + + // Write string, with no termination + final void writeStringNoNull(String s) throws SQLException { + int len = s.length(); + ensureCapacity(len * 2); + System.arraycopy(s.getBytes(), 0, this.byteBuffer, this.position, len); + this.position += len; + + // for (int i = 0; i < len; i++) + // { + // this.byteBuffer[this.position++] = (byte)s.charAt(i); + // } + } + + // Write a String using the specified character + // encoding + final void writeStringNoNull(String s, String encoding, + String serverEncoding, boolean parserKnowsUnicode, Connection conn) + throws UnsupportedEncodingException, SQLException { + byte[] b = StringUtils.getBytes(s, encoding, serverEncoding, + parserKnowsUnicode, conn); + + int len = b.length; + ensureCapacity(len); + System.arraycopy(b, 0, this.byteBuffer, this.position, len); + this.position += len; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/CachedResultSetMetaData.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/CachedResultSetMetaData.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/CachedResultSetMetaData.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,40 @@ +/* + Copyright (C) 2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + +package com.mysql.jdbc; + +import java.util.Map; + +class CachedResultSetMetaData { + /** Map column names (and all of their permutations) to column indices */ + Map columnNameToIndex = null; + + /** Cached Field info */ + Field[] fields; + + /** Map of fully-specified column names to column indices */ + Map fullColumnNameToIndex = null; + + /** Cached ResultSetMetaData */ + java.sql.ResultSetMetaData metadata; + } \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/CallableStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/CallableStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/CallableStatement.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,2181 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ +package com.mysql.jdbc; + +import java.io.InputStream; +import java.io.Reader; +import java.io.UnsupportedEncodingException; + +import java.math.BigDecimal; + +import java.net.URL; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.ParameterMetaData; +import java.sql.Ref; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Representation of stored procedures for JDBC + * + * @author Mark Matthews + * @version $Id: CallableStatement.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews + * Exp $ + */ +public class CallableStatement extends PreparedStatement implements + java.sql.CallableStatement { + class CallableStatementParam { + int desiredJdbcType; + + int index; + + int inOutModifier; + + boolean isIn; + + boolean isOut; + + int jdbcType; + + short nullability; + + String paramName; + + int precision; + + int scale; + + String typeName; + + CallableStatementParam(String name, int idx, boolean in, boolean out, + int jdbcType, String typeName, int precision, int scale, + short nullability, int inOutModifier) { + this.paramName = name; + this.isIn = in; + this.isOut = out; + this.index = idx; + + this.jdbcType = jdbcType; + this.typeName = typeName; + this.precision = precision; + this.scale = scale; + this.nullability = nullability; + this.inOutModifier = inOutModifier; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#clone() + */ + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } + } + + class CallableStatementParamInfo { + String catalogInUse; + + boolean isFunctionCall; + + String nativeSql; + + int numParameters; + + List parameterList; + + Map parameterMap; + + /** + * Constructor that converts a full list of parameter metadata into one + * that only represents the placeholders present in the {CALL ()}. + * + * @param fullParamInfo the metadata for all parameters for this stored + * procedure or function. + */ + CallableStatementParamInfo(CallableStatementParamInfo fullParamInfo) { + this.nativeSql = originalSql; + this.catalogInUse = currentCatalog; + isFunctionCall = fullParamInfo.isFunctionCall; + int[] localParameterMap = placeholderToParameterIndexMap; + int parameterMapLength = localParameterMap.length; + + parameterList = new ArrayList(fullParamInfo.numParameters); + parameterMap = new HashMap(fullParamInfo.numParameters); + + if (isFunctionCall) { + // Take the return value + parameterList.add(fullParamInfo.parameterList.get(0)); + } + + int offset = isFunctionCall ? 1 : 0; + + for (int i = 0; i < parameterMapLength; i++) { + if (localParameterMap[i] != 0) { + CallableStatementParam param = (CallableStatementParam)fullParamInfo.parameterList.get(localParameterMap[i] + offset); + + parameterList.add(param); + parameterMap.put(param.paramName, param); + } + } + + this.numParameters = parameterList.size(); + } + + CallableStatementParamInfo(java.sql.ResultSet paramTypesRs) + throws SQLException { + boolean hadRows = paramTypesRs.last(); + + this.nativeSql = originalSql; + this.catalogInUse = currentCatalog; + isFunctionCall = callingStoredFunction; + + if (hadRows) { + this.numParameters = paramTypesRs.getRow(); + + this.parameterList = new ArrayList(this.numParameters); + this.parameterMap = new HashMap(this.numParameters); + + paramTypesRs.beforeFirst(); + + addParametersFromDBMD(paramTypesRs); + } else { + this.numParameters = 0; + } + + if (isFunctionCall) { + this.numParameters += 1; + } + } + + private void addParametersFromDBMD(java.sql.ResultSet paramTypesRs) + throws SQLException { + int i = 0; + + while (paramTypesRs.next()) { + String paramName = paramTypesRs.getString(4); + int inOutModifier = paramTypesRs.getInt(5); + + boolean isOutParameter = false; + boolean isInParameter = false; + + if (i == 0 && isFunctionCall) { + isOutParameter = true; + isInParameter = false; + } else if (inOutModifier == DatabaseMetaData.procedureColumnInOut) { + isOutParameter = true; + isInParameter = true; + } else if (inOutModifier == DatabaseMetaData.procedureColumnIn) { + isOutParameter = false; + isInParameter = true; + } else if (inOutModifier == DatabaseMetaData.procedureColumnOut) { + isOutParameter = true; + isInParameter = false; + } + + int jdbcType = paramTypesRs.getInt(6); + String typeName = paramTypesRs.getString(7); + int precision = paramTypesRs.getInt(8); + int scale = paramTypesRs.getInt(10); + short nullability = paramTypesRs.getShort(12); + + CallableStatementParam paramInfoToAdd = new CallableStatementParam( + paramName, i++, isInParameter, isOutParameter, + jdbcType, typeName, precision, scale, nullability, + inOutModifier); + + this.parameterList.add(paramInfoToAdd); + this.parameterMap.put(paramName, paramInfoToAdd); + } + } + + protected void checkBounds(int paramIndex) throws SQLException { + int localParamIndex = paramIndex - 1; + + if ((paramIndex < 0) || (localParamIndex >= this.numParameters)) { + throw SQLError.createSQLException( + Messages.getString("CallableStatement.11") + paramIndex //$NON-NLS-1$ + + Messages.getString("CallableStatement.12") + numParameters //$NON-NLS-1$ + + Messages.getString("CallableStatement.13"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#clone() + */ + protected Object clone() throws CloneNotSupportedException { + // TODO Auto-generated method stub + return super.clone(); + } + + CallableStatementParam getParameter(int index) { + return (CallableStatementParam) this.parameterList.get(index); + } + + CallableStatementParam getParameter(String name) { + return (CallableStatementParam) this.parameterMap.get(name); + } + + public String getParameterClassName(int arg0) throws SQLException { + String mysqlTypeName = getParameterTypeName(arg0); + + boolean isBinaryOrBlob = StringUtils.indexOfIgnoreCase(mysqlTypeName, "BLOB") != -1 || + StringUtils.indexOfIgnoreCase(mysqlTypeName, "BINARY") != -1; + + boolean isUnsigned = StringUtils.indexOfIgnoreCase(mysqlTypeName, "UNSIGNED") != -1; + + int mysqlTypeIfKnown = 0; + + if (StringUtils.startsWithIgnoreCase(mysqlTypeName, "MEDIUMINT")) { + mysqlTypeIfKnown = MysqlDefs.FIELD_TYPE_INT24; + } + + return ResultSetMetaData.getClassNameForJavaType(getParameterType(arg0), + isUnsigned, mysqlTypeIfKnown, isBinaryOrBlob, false); + } + + public int getParameterCount() throws SQLException { + if (this.parameterList == null) { + return 0; + } + + return this.parameterList.size(); + } + + public int getParameterMode(int arg0) throws SQLException { + checkBounds(arg0); + + return getParameter(arg0 - 1).inOutModifier; + } + + public int getParameterType(int arg0) throws SQLException { + checkBounds(arg0); + + return getParameter(arg0 - 1).jdbcType; + } + + public String getParameterTypeName(int arg0) throws SQLException { + checkBounds(arg0); + + return getParameter(arg0 - 1).typeName; + } + + public int getPrecision(int arg0) throws SQLException { + checkBounds(arg0); + + return getParameter(arg0 - 1).precision; + } + + public int getScale(int arg0) throws SQLException { + checkBounds(arg0); + + return getParameter(arg0 - 1).scale; + } + + public int isNullable(int arg0) throws SQLException { + checkBounds(arg0); + + return getParameter(arg0 - 1).nullability; + } + + public boolean isSigned(int arg0) throws SQLException { + checkBounds(arg0); + + return false; + } + + Iterator iterator() { + return this.parameterList.iterator(); + } + + int numberOfParameters() { + return this.numParameters; + } + } + + /** + * Can't implement this directly, as then you can't use callable statements + * on JDK-1.3.1, which unfortunately isn't EOL'd yet, and still present + * quite a bit out there in the wild (Websphere, FreeBSD, anyone?) + */ + + class CallableStatementParamInfoJDBC3 extends CallableStatementParamInfo + implements ParameterMetaData { + + CallableStatementParamInfoJDBC3(java.sql.ResultSet paramTypesRs) + throws SQLException { + super(paramTypesRs); + } + + public CallableStatementParamInfoJDBC3(CallableStatementParamInfo paramInfo) { + super(paramInfo); + } + } + + private final static int NOT_OUTPUT_PARAMETER_INDICATOR = Integer.MIN_VALUE; + + private final static String PARAMETER_NAMESPACE_PREFIX = "@com_mysql_jdbc_outparam_"; //$NON-NLS-1$ + + private static String mangleParameterName(String origParameterName) { + if (origParameterName == null) { + return null; + } + + int offset = 0; + + if (origParameterName.length() > 0 + && origParameterName.charAt(0) == '@') { + offset = 1; + } + + StringBuffer paramNameBuf = new StringBuffer(PARAMETER_NAMESPACE_PREFIX + .length() + + origParameterName.length()); + paramNameBuf.append(PARAMETER_NAMESPACE_PREFIX); + paramNameBuf.append(origParameterName.substring(offset)); + + return paramNameBuf.toString(); + } + + private boolean callingStoredFunction = false; + + private ResultSet functionReturnValueResults; + + private boolean hasOutputParams = false; + + // private List parameterList; + // private Map parameterMap; + private ResultSet outputParameterResults; + + private boolean outputParamWasNull = false; + + private int[] parameterIndexToRsIndex; + + protected CallableStatementParamInfo paramInfo; + + private CallableStatementParam returnValueParam; + + /** + * Creates a new CallableStatement + * + * @param conn + * the connection creating this statement + * @param paramInfo + * the SQL to prepare + * + * @throws SQLException + * if an error occurs + */ + public CallableStatement(Connection conn, + CallableStatementParamInfo paramInfo) throws SQLException { + super(conn, paramInfo.nativeSql, paramInfo.catalogInUse); + + this.paramInfo = paramInfo; + this.callingStoredFunction = this.paramInfo.isFunctionCall; + + if (this.callingStoredFunction) { + this.parameterCount += 1; + } + } + + /** + * Creates a new CallableStatement + * + * @param conn + * the connection creating this statement + * @param catalog + * catalog the current catalog + * + * @throws SQLException + * if an error occurs + */ + public CallableStatement(Connection conn, String catalog) + throws SQLException { + super(conn, catalog, null); + + determineParameterTypes(); + generateParameterMap(); + + if (this.callingStoredFunction) { + this.parameterCount += 1; + } + } + + private int[] placeholderToParameterIndexMap; + + + private void generateParameterMap() throws SQLException { + // if the user specified some parameters as literals, we need to + // provide a map from the specified placeholders to the actual + // parameter numbers + + int parameterCountFromMetaData = this.paramInfo.getParameterCount(); + + // Ignore the first ? if this is a stored function, it doesn't count + + if (this.callingStoredFunction) { + parameterCountFromMetaData--; + } + + if (this.paramInfo != null && + this.parameterCount != parameterCountFromMetaData) { + this.placeholderToParameterIndexMap = new int[this.parameterCount]; + + int startPos = this.callingStoredFunction ? StringUtils.indexOfIgnoreCase(this.originalSql, + "SELECT") : StringUtils.indexOfIgnoreCase(this.originalSql, "CALL"); + + if (startPos != -1) { + int parenOpenPos = this.originalSql.indexOf('(', startPos + 4); + + if (parenOpenPos != -1) { + int parenClosePos = StringUtils.indexOfIgnoreCaseRespectQuotes(parenOpenPos, + this.originalSql, ")", '\'', true); + + if (parenClosePos != -1) { + List parsedParameters = StringUtils.split(this.originalSql.substring(parenOpenPos + 1, parenClosePos), ",", "'\"", "'\"", true); + + int numParsedParameters = parsedParameters.size(); + + // sanity check + + if (numParsedParameters != this.parameterCount) { + // bail? + } + + int placeholderCount = 0; + + for (int i = 0; i < numParsedParameters; i++) { + if (((String)parsedParameters.get(i)).equals("?")) { + this.placeholderToParameterIndexMap[placeholderCount++] = i; + } + } + } + } + } + } + } + + /** + * Creates a new CallableStatement + * + * @param conn + * the connection creating this statement + * @param sql + * the SQL to prepare + * @param catalog + * the current catalog + * + * @throws SQLException + * if an error occurs + */ + public CallableStatement(Connection conn, String sql, String catalog, + boolean isFunctionCall) throws SQLException { + super(conn, sql, catalog); + + this.callingStoredFunction = isFunctionCall; + + determineParameterTypes(); + generateParameterMap(); + + if (this.callingStoredFunction) { + this.parameterCount += 1; + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#addBatch() + */ + public void addBatch() throws SQLException { + setOutParams(); + + super.addBatch(); + } + + private CallableStatementParam checkIsOutputParam(int paramIndex) + throws SQLException { + + if (this.callingStoredFunction) { + if (paramIndex == 1) { + + if (this.returnValueParam == null) { + this.returnValueParam = new CallableStatementParam("", 0, + false, true, Types.VARCHAR, "VARCHAR", 0, 0, + DatabaseMetaData.attributeNullableUnknown, + DatabaseMetaData.procedureColumnReturn); + } + + return this.returnValueParam; + } + + // Move to position in output result set + paramIndex--; + } + + checkParameterIndexBounds(paramIndex); + + int localParamIndex = paramIndex - 1; + + if (this.placeholderToParameterIndexMap != null) { + localParamIndex = this.placeholderToParameterIndexMap[localParamIndex]; + } + + CallableStatementParam paramDescriptor = this.paramInfo + .getParameter(localParamIndex); + + // We don't have reliable metadata in this case, trust + // the caller + + if (this.connection.getNoAccessToProcedureBodies()) { + paramDescriptor.isOut = true; + paramDescriptor.isIn = true; + paramDescriptor.inOutModifier = DatabaseMetaData.procedureColumnInOut; + } else if (!paramDescriptor.isOut) { + throw SQLError.createSQLException( + Messages.getString("CallableStatement.9") + paramIndex //$NON-NLS-1$ + + Messages.getString("CallableStatement.10"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + this.hasOutputParams = true; + + return paramDescriptor; + } + + /** + * DOCUMENT ME! + * + * @param paramIndex + * + * @throws SQLException + */ + private void checkParameterIndexBounds(int paramIndex) throws SQLException { + this.paramInfo.checkBounds(paramIndex); + } + + /** + * Checks whether or not this statement is supposed to be providing + * streamable result sets...If output parameters are registered, the driver + * can not stream the results. + * + * @throws SQLException + * DOCUMENT ME! + */ + private void checkStreamability() throws SQLException { + if (this.hasOutputParams && createStreamingResultSet()) { + throw SQLError.createSQLException(Messages.getString("CallableStatement.14"), //$NON-NLS-1$ + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } + } + + public synchronized void clearParameters() throws SQLException { + super.clearParameters(); + + try { + if (this.outputParameterResults != null) { + this.outputParameterResults.close(); + } + } finally { + this.outputParameterResults = null; + } + } + + /** + * Used to fake up some metadata when we don't have access to + * SHOW CREATE PROCEDURE or mysql.proc. + * + * @throws SQLException if we can't build the metadata. + */ + private void fakeParameterTypes() throws SQLException { + Field[] fields = new Field[13]; + + fields[0] = new Field("", "PROCEDURE_CAT", Types.CHAR, 0); + fields[1] = new Field("", "PROCEDURE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "PROCEDURE_NAME", Types.CHAR, 0); + fields[3] = new Field("", "COLUMN_NAME", Types.CHAR, 0); + fields[4] = new Field("", "COLUMN_TYPE", Types.CHAR, 0); + fields[5] = new Field("", "DATA_TYPE", Types.SMALLINT, 0); + fields[6] = new Field("", "TYPE_NAME", Types.CHAR, 0); + fields[7] = new Field("", "PRECISION", Types.INTEGER, 0); + fields[8] = new Field("", "LENGTH", Types.INTEGER, 0); + fields[9] = new Field("", "SCALE", Types.SMALLINT, 0); + fields[10] = new Field("", "RADIX", Types.SMALLINT, 0); + fields[11] = new Field("", "NULLABLE", Types.SMALLINT, 0); + fields[12] = new Field("", "REMARKS", Types.CHAR, 0); + + String procName = extractProcedureName(); + + byte[] procNameAsBytes = null; + + try { + procNameAsBytes = procName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException ueEx) { + procNameAsBytes = StringUtils.s2b(procName, this.connection); + } + + ArrayList resultRows = new ArrayList(); + + for (int i = 0; i < this.parameterCount; i++) { + byte[][] row = new byte[13][]; + row[0] = null; // PROCEDURE_CAT + row[1] = null; // PROCEDURE_SCHEM + row[2] = procNameAsBytes; // PROCEDURE/NAME + row[3] = StringUtils.s2b(String.valueOf(i), this.connection); // COLUMN_NAME + + row[4] = StringUtils.s2b(String + .valueOf(DatabaseMetaData.procedureColumnIn), + this.connection); + + row[5] = StringUtils.s2b(String.valueOf(Types.VARCHAR), + this.connection); // DATA_TYPE + row[6] = StringUtils.s2b("VARCHAR", this.connection); // TYPE_NAME + row[7] = StringUtils.s2b(Integer.toString(65535), this.connection); // PRECISION + row[8] = StringUtils.s2b(Integer.toString(65535), this.connection); // LENGTH + row[9] = StringUtils.s2b(Integer.toString(0), this.connection); // SCALE + row[10] = StringUtils.s2b(Integer.toString(10), this.connection); // RADIX + + row[11] = StringUtils.s2b(Integer + .toString(DatabaseMetaData.procedureNullableUnknown), + this.connection); // nullable + + row[12] = null; + + resultRows.add(row); + } + + java.sql.ResultSet paramTypesRs = DatabaseMetaData.buildResultSet( + fields, resultRows, this.connection); + + convertGetProcedureColumnsToInternalDescriptors(paramTypesRs); + } + + private void determineParameterTypes() throws SQLException { + if (this.connection.getNoAccessToProcedureBodies()) { + fakeParameterTypes(); + + return; + } + + java.sql.ResultSet paramTypesRs = null; + + try { + String procName = extractProcedureName(); + + java.sql.DatabaseMetaData dbmd = this.connection.getMetaData(); + + boolean useCatalog = false; + + if (procName.indexOf(".") == -1) { + useCatalog = true; + } + + paramTypesRs = dbmd.getProcedureColumns(this.connection + .versionMeetsMinimum(5, 0, 2) + && useCatalog ? this.currentCatalog : null, null, procName, + "%"); //$NON-NLS-1$ + + convertGetProcedureColumnsToInternalDescriptors(paramTypesRs); + } finally { + SQLException sqlExRethrow = null; + + if (paramTypesRs != null) { + try { + paramTypesRs.close(); + } catch (SQLException sqlEx) { + sqlExRethrow = sqlEx; + } + + paramTypesRs = null; + } + + if (sqlExRethrow != null) { + throw sqlExRethrow; + } + } + } + + private void convertGetProcedureColumnsToInternalDescriptors(java.sql.ResultSet paramTypesRs) throws SQLException { + if (!this.connection.isRunningOnJDK13()) { + this.paramInfo = new CallableStatementParamInfoJDBC3( + paramTypesRs); + } else { + this.paramInfo = new CallableStatementParamInfo(paramTypesRs); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#execute() + */ + public boolean execute() throws SQLException { + boolean returnVal = false; + + checkClosed(); + + checkStreamability(); + + synchronized (this.connection.getMutex()) { + setInOutParamsOnServer(); + setOutParams(); + + returnVal = super.execute(); + + if (this.callingStoredFunction) { + this.functionReturnValueResults = this.results; + this.functionReturnValueResults.next(); + this.results = null; + } + + retrieveOutParams(); + } + + if (!this.callingStoredFunction) { + return returnVal; + } + + // Functions can't return results + return false; + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#executeQuery() + */ + public java.sql.ResultSet executeQuery() throws SQLException { + checkClosed(); + + checkStreamability(); + + java.sql.ResultSet execResults = null; + + synchronized (this.connection.getMutex()) { + setInOutParamsOnServer(); + setOutParams(); + + execResults = super.executeQuery(); + + retrieveOutParams(); + } + + return execResults; + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#executeUpdate() + */ + public int executeUpdate() throws SQLException { + int returnVal = -1; + + checkClosed(); + + checkStreamability(); + + if (this.callingStoredFunction) { + execute(); + + return -1; + } + + synchronized (this.connection.getMutex()) { + setInOutParamsOnServer(); + setOutParams(); + + returnVal = super.executeUpdate(); + + retrieveOutParams(); + } + + return returnVal; + } + + private String extractProcedureName() throws SQLException { + String sanitizedSql = StringUtils.stripComments(this.originalSql, + "`\"'", "`\"'", true, false, true, true); + + // TODO: Do this with less memory allocation + int endCallIndex = StringUtils.indexOfIgnoreCase(sanitizedSql, + "CALL "); //$NON-NLS-1$ + int offset = 5; + + if (endCallIndex == -1) { + endCallIndex = StringUtils.indexOfIgnoreCase(sanitizedSql, + "SELECT "); + offset = 7; + } + + if (endCallIndex != -1) { + StringBuffer nameBuf = new StringBuffer(); + + String trimmedStatement = sanitizedSql.substring( + endCallIndex + offset).trim(); + + int statementLength = trimmedStatement.length(); + + for (int i = 0; i < statementLength; i++) { + char c = trimmedStatement.charAt(i); + + if (Character.isWhitespace(c) || (c == '(') || (c == '?')) { + break; + } + nameBuf.append(c); + + } + + return nameBuf.toString(); + } + + throw SQLError.createSQLException(Messages.getString("CallableStatement.1"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + + /** + * Adds 'at' symbol to beginning of parameter names if needed. + * + * @param paramNameIn + * the parameter name to 'fix' + * + * @return the parameter name with an 'a' prepended, if needed + * + * @throws SQLException + * if the parameter name is null or empty. + */ + private String fixParameterName(String paramNameIn) throws SQLException { + if ((paramNameIn == null) || (paramNameIn.length() == 0)) { + throw SQLError.createSQLException( + ((Messages.getString("CallableStatement.0") + paramNameIn) == null) //$NON-NLS-1$ + ? Messages.getString("CallableStatement.15") : Messages.getString("CallableStatement.16"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (this.connection.getNoAccessToProcedureBodies()) { + throw SQLError.createSQLException("No access to parameters by name when connection has been configured not to access procedure bodies", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + return mangleParameterName(paramNameIn); + + /* + * if (paramNameIn.startsWith("@")) { return paramNameIn; } else { + * StringBuffer paramNameBuf = new StringBuffer("@"); + * paramNameBuf.append(paramNameIn); + * + * return paramNameBuf.toString(); } + */ + } + + /** + * @see java.sql.CallableStatement#getArray(int) + */ + public synchronized Array getArray(int i) throws SQLException { + ResultSet rs = getOutputParameters(i); + + Array retValue = rs.getArray(mapOutputParameterIndexToRsIndex(i)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getArray(java.lang.String) + */ + public synchronized Array getArray(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Array retValue = rs.getArray(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBigDecimal(int) + */ + public synchronized BigDecimal getBigDecimal(int parameterIndex) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + BigDecimal retValue = rs + .getBigDecimal(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * DOCUMENT ME! + * + * @param parameterIndex + * DOCUMENT ME! + * @param scale + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + * + * @see java.sql.CallableStatement#getBigDecimal(int, int) + * @deprecated + */ + public synchronized BigDecimal getBigDecimal(int parameterIndex, int scale) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + BigDecimal retValue = rs.getBigDecimal( + mapOutputParameterIndexToRsIndex(parameterIndex), scale); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBigDecimal(java.lang.String) + */ + public synchronized BigDecimal getBigDecimal(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + BigDecimal retValue = rs.getBigDecimal(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBlob(int) + */ + public synchronized Blob getBlob(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Blob retValue = rs + .getBlob(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBlob(java.lang.String) + */ + public synchronized Blob getBlob(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Blob retValue = rs.getBlob(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBoolean(int) + */ + public synchronized boolean getBoolean(int parameterIndex) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + boolean retValue = rs + .getBoolean(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBoolean(java.lang.String) + */ + public synchronized boolean getBoolean(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + boolean retValue = rs.getBoolean(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getByte(int) + */ + public synchronized byte getByte(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + byte retValue = rs + .getByte(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getByte(java.lang.String) + */ + public synchronized byte getByte(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + byte retValue = rs.getByte(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBytes(int) + */ + public synchronized byte[] getBytes(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + byte[] retValue = rs + .getBytes(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getBytes(java.lang.String) + */ + public synchronized byte[] getBytes(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + byte[] retValue = rs.getBytes(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getClob(int) + */ + public synchronized Clob getClob(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Clob retValue = rs + .getClob(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getClob(java.lang.String) + */ + public synchronized Clob getClob(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Clob retValue = rs.getClob(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getDate(int) + */ + public synchronized Date getDate(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Date retValue = rs + .getDate(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getDate(int, java.util.Calendar) + */ + public synchronized Date getDate(int parameterIndex, Calendar cal) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Date retValue = rs.getDate( + mapOutputParameterIndexToRsIndex(parameterIndex), cal); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getDate(java.lang.String) + */ + public synchronized Date getDate(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Date retValue = rs.getDate(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getDate(java.lang.String, + * java.util.Calendar) + */ + public synchronized Date getDate(String parameterName, Calendar cal) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Date retValue = rs.getDate(fixParameterName(parameterName), cal); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getDouble(int) + */ + public synchronized double getDouble(int parameterIndex) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + double retValue = rs + .getDouble(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getDouble(java.lang.String) + */ + public synchronized double getDouble(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + double retValue = rs.getDouble(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getFloat(int) + */ + public synchronized float getFloat(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + float retValue = rs + .getFloat(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getFloat(java.lang.String) + */ + public synchronized float getFloat(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + float retValue = rs.getFloat(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getInt(int) + */ + public synchronized int getInt(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + int retValue = rs + .getInt(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getInt(java.lang.String) + */ + public synchronized int getInt(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + int retValue = rs.getInt(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getLong(int) + */ + public synchronized long getLong(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + long retValue = rs + .getLong(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getLong(java.lang.String) + */ + public synchronized long getLong(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + long retValue = rs.getLong(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + private int getNamedParamIndex(String paramName, boolean forOut) + throws SQLException { + if (this.connection.getNoAccessToProcedureBodies()) { + throw SQLError.createSQLException("No access to parameters by name when connection has been configured not to access procedure bodies", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if ((paramName == null) || (paramName.length() == 0)) { + throw SQLError.createSQLException(Messages.getString("CallableStatement.2"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + CallableStatementParam namedParamInfo = this.paramInfo + .getParameter(paramName); + + if (this.paramInfo == null) { + throw SQLError.createSQLException( + Messages.getString("CallableStatement.3") + paramName + Messages.getString("CallableStatement.4"), //$NON-NLS-1$ //$NON-NLS-2$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (forOut && !namedParamInfo.isOut) { + throw SQLError.createSQLException( + Messages.getString("CallableStatement.5") + paramName //$NON-NLS-1$ + + Messages.getString("CallableStatement.6"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + + if (this.placeholderToParameterIndexMap == null) { + return namedParamInfo.index + 1; // JDBC indices are 1-based + } + + for (int i = 0; i < this.placeholderToParameterIndexMap.length; i++) { + if (this.placeholderToParameterIndexMap[i] == namedParamInfo.index) { + return i + 1; + } + } + + throw SQLError.createSQLException("Can't find local placeholder mapping for parameter named \"" + + paramName + "\".", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + /** + * @see java.sql.CallableStatement#getObject(int) + */ + public synchronized Object getObject(int parameterIndex) + throws SQLException { + CallableStatementParam paramDescriptor = checkIsOutputParam(parameterIndex); + + ResultSet rs = getOutputParameters(parameterIndex); + + Object retVal = rs.getObjectStoredProc( + mapOutputParameterIndexToRsIndex(parameterIndex), + paramDescriptor.desiredJdbcType); + + this.outputParamWasNull = rs.wasNull(); + + return retVal; + } + + /** + * @see java.sql.CallableStatement#getObject(int, java.util.Map) + */ + public synchronized Object getObject(int parameterIndex, Map map) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Object retVal = rs.getObject( + mapOutputParameterIndexToRsIndex(parameterIndex), map); + + this.outputParamWasNull = rs.wasNull(); + + return retVal; + } + + /** + * @see java.sql.CallableStatement#getObject(java.lang.String) + */ + public synchronized Object getObject(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Object retValue = rs.getObject(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getObject(java.lang.String, + * java.util.Map) + */ + public synchronized Object getObject(String parameterName, Map map) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Object retValue = rs.getObject(fixParameterName(parameterName), map); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * Returns the ResultSet that holds the output parameters, or throws an + * appropriate exception if none exist, or they weren't returned. + * + * @return the ResultSet that holds the output parameters + * + * @throws SQLException + * if no output parameters were defined, or if no output + * parameters were returned. + */ + private ResultSet getOutputParameters(int paramIndex) throws SQLException { + this.outputParamWasNull = false; + + if (paramIndex == 1 && this.callingStoredFunction + && this.returnValueParam != null) { + return this.functionReturnValueResults; + } + + if (this.outputParameterResults == null) { + if (this.paramInfo.numberOfParameters() == 0) { + throw SQLError.createSQLException(Messages + .getString("CallableStatement.7"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + throw SQLError.createSQLException(Messages.getString("CallableStatement.8"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + + return this.outputParameterResults; + + } + + public synchronized ParameterMetaData getParameterMetaData() + throws SQLException { + if (this.placeholderToParameterIndexMap == null) { + return (CallableStatementParamInfoJDBC3) this.paramInfo; + } else { + return new CallableStatementParamInfoJDBC3(this.paramInfo); + } + } + + /** + * @see java.sql.CallableStatement#getRef(int) + */ + public synchronized Ref getRef(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Ref retValue = rs + .getRef(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getRef(java.lang.String) + */ + public synchronized Ref getRef(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Ref retValue = rs.getRef(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getShort(int) + */ + public synchronized short getShort(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + short retValue = rs + .getShort(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getShort(java.lang.String) + */ + public synchronized short getShort(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + short retValue = rs.getShort(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getString(int) + */ + public synchronized String getString(int parameterIndex) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + String retValue = rs + .getString(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getString(java.lang.String) + */ + public synchronized String getString(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + String retValue = rs.getString(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTime(int) + */ + public synchronized Time getTime(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Time retValue = rs + .getTime(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTime(int, java.util.Calendar) + */ + public synchronized Time getTime(int parameterIndex, Calendar cal) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Time retValue = rs.getTime( + mapOutputParameterIndexToRsIndex(parameterIndex), cal); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTime(java.lang.String) + */ + public synchronized Time getTime(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Time retValue = rs.getTime(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTime(java.lang.String, + * java.util.Calendar) + */ + public synchronized Time getTime(String parameterName, Calendar cal) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Time retValue = rs.getTime(fixParameterName(parameterName), cal); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTimestamp(int) + */ + public synchronized Timestamp getTimestamp(int parameterIndex) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Timestamp retValue = rs + .getTimestamp(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTimestamp(int, java.util.Calendar) + */ + public synchronized Timestamp getTimestamp(int parameterIndex, Calendar cal) + throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + Timestamp retValue = rs.getTimestamp( + mapOutputParameterIndexToRsIndex(parameterIndex), cal); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTimestamp(java.lang.String) + */ + public synchronized Timestamp getTimestamp(String parameterName) + throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Timestamp retValue = rs.getTimestamp(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getTimestamp(java.lang.String, + * java.util.Calendar) + */ + public synchronized Timestamp getTimestamp(String parameterName, + Calendar cal) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + Timestamp retValue = rs.getTimestamp(fixParameterName(parameterName), + cal); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getURL(int) + */ + public synchronized URL getURL(int parameterIndex) throws SQLException { + ResultSet rs = getOutputParameters(parameterIndex); + + URL retValue = rs + .getURL(mapOutputParameterIndexToRsIndex(parameterIndex)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + /** + * @see java.sql.CallableStatement#getURL(java.lang.String) + */ + public synchronized URL getURL(String parameterName) throws SQLException { + ResultSet rs = getOutputParameters(0); // definitely not going to be + // from ?= + + URL retValue = rs.getURL(fixParameterName(parameterName)); + + this.outputParamWasNull = rs.wasNull(); + + return retValue; + } + + private int mapOutputParameterIndexToRsIndex(int paramIndex) + throws SQLException { + + if (this.returnValueParam != null && paramIndex == 1) { + return 1; + } + + checkParameterIndexBounds(paramIndex); + + int localParamIndex = paramIndex - 1; + + if (this.placeholderToParameterIndexMap != null) { + localParamIndex = this.placeholderToParameterIndexMap[localParamIndex]; + } + + int rsIndex = this.parameterIndexToRsIndex[localParamIndex]; + + if (rsIndex == NOT_OUTPUT_PARAMETER_INDICATOR) { + throw SQLError.createSQLException( + Messages.getString("CallableStatement.21") + paramIndex //$NON-NLS-1$ + + Messages.getString("CallableStatement.22"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + return rsIndex + 1; + } + + /** + * @see java.sql.CallableStatement#registerOutParameter(int, int) + */ + public void registerOutParameter(int parameterIndex, int sqlType) + throws SQLException { + CallableStatementParam paramDescriptor = checkIsOutputParam(parameterIndex); + paramDescriptor.desiredJdbcType = sqlType; + } + + /** + * @see java.sql.CallableStatement#registerOutParameter(int, int, int) + */ + public void registerOutParameter(int parameterIndex, int sqlType, int scale) + throws SQLException { + registerOutParameter(parameterIndex, sqlType); + } + + /** + * @see java.sql.CallableStatement#registerOutParameter(int, int, + * java.lang.String) + */ + public void registerOutParameter(int parameterIndex, int sqlType, + String typeName) throws SQLException { + checkIsOutputParam(parameterIndex); + } + + /** + * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, + * int) + */ + public synchronized void registerOutParameter(String parameterName, + int sqlType) throws SQLException { + registerOutParameter(getNamedParamIndex(parameterName, true), sqlType); + } + + /** + * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, + * int, int) + */ + public void registerOutParameter(String parameterName, int sqlType, + int scale) throws SQLException { + registerOutParameter(getNamedParamIndex(parameterName, true), sqlType); + } + + /** + * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, + * int, java.lang.String) + */ + public void registerOutParameter(String parameterName, int sqlType, + String typeName) throws SQLException { + registerOutParameter(getNamedParamIndex(parameterName, true), sqlType, + typeName); + } + + /** + * Issues a second query to retrieve all output parameters. + * + * @throws SQLException + * if an error occurs. + */ + private void retrieveOutParams() throws SQLException { + int numParameters = this.paramInfo.numberOfParameters(); + + this.parameterIndexToRsIndex = new int[numParameters]; + + for (int i = 0; i < numParameters; i++) { + this.parameterIndexToRsIndex[i] = NOT_OUTPUT_PARAMETER_INDICATOR; + } + + int localParamIndex = 0; + + if (numParameters > 0) { + StringBuffer outParameterQuery = new StringBuffer("SELECT "); //$NON-NLS-1$ + + boolean firstParam = true; + boolean hadOutputParams = false; + + for (Iterator paramIter = this.paramInfo.iterator(); paramIter + .hasNext();) { + CallableStatementParam retrParamInfo = (CallableStatementParam) paramIter + .next(); + + if (retrParamInfo.isOut) { + hadOutputParams = true; + + this.parameterIndexToRsIndex[retrParamInfo.index] = localParamIndex++; + + String outParameterName = mangleParameterName(retrParamInfo.paramName); + + if (!firstParam) { + outParameterQuery.append(","); //$NON-NLS-1$ + } else { + firstParam = false; + } + + if (!outParameterName.startsWith("@")) { //$NON-NLS-1$ + outParameterQuery.append('@'); + } + + outParameterQuery.append(outParameterName); + } + } + + if (hadOutputParams) { + // We can't use 'ourself' to execute this query, or any + // pending result sets would be overwritten + java.sql.Statement outParameterStmt = null; + java.sql.ResultSet outParamRs = null; + + try { + outParameterStmt = this.connection.createStatement(); + outParamRs = outParameterStmt + .executeQuery(outParameterQuery.toString()); + this.outputParameterResults = ((com.mysql.jdbc.ResultSet) outParamRs) + .copy(); + + if (!this.outputParameterResults.next()) { + this.outputParameterResults.close(); + this.outputParameterResults = null; + } + } finally { + if (outParameterStmt != null) { + outParameterStmt.close(); + } + } + } else { + this.outputParameterResults = null; + } + } else { + this.outputParameterResults = null; + } + } + + /** + * @see java.sql.CallableStatement#setAsciiStream(java.lang.String, + * java.io.InputStream, int) + */ + public void setAsciiStream(String parameterName, InputStream x, int length) + throws SQLException { + setAsciiStream(getNamedParamIndex(parameterName, false), x, length); + } + + /** + * @see java.sql.CallableStatement#setBigDecimal(java.lang.String, + * java.math.BigDecimal) + */ + public void setBigDecimal(String parameterName, BigDecimal x) + throws SQLException { + setBigDecimal(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setBinaryStream(java.lang.String, + * java.io.InputStream, int) + */ + public void setBinaryStream(String parameterName, InputStream x, int length) + throws SQLException { + setBinaryStream(getNamedParamIndex(parameterName, false), x, length); + } + + /** + * @see java.sql.CallableStatement#setBoolean(java.lang.String, boolean) + */ + public void setBoolean(String parameterName, boolean x) throws SQLException { + setBoolean(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setByte(java.lang.String, byte) + */ + public void setByte(String parameterName, byte x) throws SQLException { + setByte(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setBytes(java.lang.String, byte[]) + */ + public void setBytes(String parameterName, byte[] x) throws SQLException { + setBytes(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setCharacterStream(java.lang.String, + * java.io.Reader, int) + */ + public void setCharacterStream(String parameterName, Reader reader, + int length) throws SQLException { + setCharacterStream(getNamedParamIndex(parameterName, false), reader, + length); + } + + /** + * @see java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date) + */ + public void setDate(String parameterName, Date x) throws SQLException { + setDate(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date, + * java.util.Calendar) + */ + public void setDate(String parameterName, Date x, Calendar cal) + throws SQLException { + setDate(getNamedParamIndex(parameterName, false), x, cal); + } + + /** + * @see java.sql.CallableStatement#setDouble(java.lang.String, double) + */ + public void setDouble(String parameterName, double x) throws SQLException { + setDouble(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setFloat(java.lang.String, float) + */ + public void setFloat(String parameterName, float x) throws SQLException { + setFloat(getNamedParamIndex(parameterName, false), x); + } + + /** + * + */ + private void setInOutParamsOnServer() throws SQLException { + if (this.paramInfo.numParameters > 0) { + int parameterIndex = 0; + + for (Iterator paramIter = this.paramInfo.iterator(); paramIter + .hasNext();) { + + CallableStatementParam inParamInfo = (CallableStatementParam) paramIter + .next(); + + if (inParamInfo.isOut && inParamInfo.isIn) { + String inOutParameterName = mangleParameterName(inParamInfo.paramName); + StringBuffer queryBuf = new StringBuffer( + 4 + inOutParameterName.length() + 1 + 1); + queryBuf.append("SET "); //$NON-NLS-1$ + queryBuf.append(inOutParameterName); + queryBuf.append("=?"); //$NON-NLS-1$ + + PreparedStatement setPstmt = null; + + try { + setPstmt = this.connection + .clientPrepareStatement(queryBuf.toString()); + + byte[] parameterAsBytes = getBytesRepresentation( + inParamInfo.index); + + if (parameterAsBytes != null) { + if (parameterAsBytes.length > 8 + && parameterAsBytes[0] == '_' + && parameterAsBytes[1] == 'b' + && parameterAsBytes[2] == 'i' + && parameterAsBytes[3] == 'n' + && parameterAsBytes[4] == 'a' + && parameterAsBytes[5] == 'r' + && parameterAsBytes[6] == 'y' + && parameterAsBytes[7] == '\'') { + setPstmt.setBytesNoEscapeNoQuotes(1, + parameterAsBytes); + } else { + int sqlType = inParamInfo.desiredJdbcType; + + switch (sqlType) { + case Types.BIT: + case Types.BINARY: + case Types.BLOB: + case Types.JAVA_OBJECT: + case Types.LONGVARBINARY: + case Types.VARBINARY: + setPstmt.setBytes(1, parameterAsBytes); + break; + default: + // the inherited PreparedStatement methods + // have already escaped and quoted these parameters + setPstmt.setBytesNoEscape(1, parameterAsBytes); + } + } + } else { + setPstmt.setNull(1, Types.NULL); + } + + setPstmt.executeUpdate(); + } finally { + if (setPstmt != null) { + setPstmt.close(); + } + } + } + + parameterIndex++; + } + } + } + + /** + * @see java.sql.CallableStatement#setInt(java.lang.String, int) + */ + public void setInt(String parameterName, int x) throws SQLException { + setInt(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setLong(java.lang.String, long) + */ + public void setLong(String parameterName, long x) throws SQLException { + setLong(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setNull(java.lang.String, int) + */ + public void setNull(String parameterName, int sqlType) throws SQLException { + setNull(getNamedParamIndex(parameterName, false), sqlType); + } + + /** + * @see java.sql.CallableStatement#setNull(java.lang.String, int, + * java.lang.String) + */ + public void setNull(String parameterName, int sqlType, String typeName) + throws SQLException { + setNull(getNamedParamIndex(parameterName, false), sqlType, typeName); + } + + /** + * @see java.sql.CallableStatement#setObject(java.lang.String, + * java.lang.Object) + */ + public void setObject(String parameterName, Object x) throws SQLException { + setObject(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setObject(java.lang.String, + * java.lang.Object, int) + */ + public void setObject(String parameterName, Object x, int targetSqlType) + throws SQLException { + setObject(getNamedParamIndex(parameterName, false), x, targetSqlType); + } + + /** + * @see java.sql.CallableStatement#setObject(java.lang.String, + * java.lang.Object, int, int) + */ + public void setObject(String parameterName, Object x, int targetSqlType, + int scale) throws SQLException { + } + + private void setOutParams() throws SQLException { + if (this.paramInfo.numParameters > 0) { + for (Iterator paramIter = this.paramInfo.iterator(); paramIter + .hasNext();) { + CallableStatementParam outParamInfo = (CallableStatementParam) paramIter + .next(); + + if (!this.callingStoredFunction && outParamInfo.isOut) { + String outParameterName = mangleParameterName(outParamInfo.paramName); + + int outParamIndex; + + if (this.placeholderToParameterIndexMap == null) { + outParamIndex = outParamInfo.index + 1; + } else { + outParamIndex = this.placeholderToParameterIndexMap[outParamInfo.index - 1 /* JDBC is 1-based */]; + } + + this.setBytesNoEscapeNoQuotes(outParamIndex, + StringUtils.getBytes(outParameterName, + this.charConverter, this.charEncoding, + this.connection + .getServerCharacterEncoding(), + this.connection.parserKnowsUnicode())); + } + } + } + } + + /** + * @see java.sql.CallableStatement#setShort(java.lang.String, short) + */ + public void setShort(String parameterName, short x) throws SQLException { + setShort(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setString(java.lang.String, + * java.lang.String) + */ + public void setString(String parameterName, String x) throws SQLException { + setString(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time) + */ + public void setTime(String parameterName, Time x) throws SQLException { + setTime(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time, + * java.util.Calendar) + */ + public void setTime(String parameterName, Time x, Calendar cal) + throws SQLException { + setTime(getNamedParamIndex(parameterName, false), x, cal); + } + + /** + * @see java.sql.CallableStatement#setTimestamp(java.lang.String, + * java.sql.Timestamp) + */ + public void setTimestamp(String parameterName, Timestamp x) + throws SQLException { + setTimestamp(getNamedParamIndex(parameterName, false), x); + } + + /** + * @see java.sql.CallableStatement#setTimestamp(java.lang.String, + * java.sql.Timestamp, java.util.Calendar) + */ + public void setTimestamp(String parameterName, Timestamp x, Calendar cal) + throws SQLException { + setTimestamp(getNamedParamIndex(parameterName, false), x, cal); + } + + /** + * @see java.sql.CallableStatement#setURL(java.lang.String, java.net.URL) + */ + public void setURL(String parameterName, URL val) throws SQLException { + setURL(getNamedParamIndex(parameterName, false), val); + } + + /** + * @see java.sql.CallableStatement#wasNull() + */ + public synchronized boolean wasNull() throws SQLException { + return this.outputParamWasNull; + } + + public int[] executeBatch() throws SQLException { + if (this.hasOutputParams) { + throw SQLError.createSQLException("Can't call executeBatch() on CallableStatement with OUTPUT parameters", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + return super.executeBatch(); + } + + protected int getParameterIndexOffset() { + if (this.callingStoredFunction) { + return -1; + } + + return super.getParameterIndexOffset(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/CharsetMapping.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/CharsetMapping.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/CharsetMapping.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,995 @@ +/* + Copyright (C) 2002-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.TreeMap; + +/** + * Mapping between MySQL charset names and Java charset names. I've investigated + * placing these in a .properties file, but unfortunately under most appservers + * this complicates configuration because the security policy needs to be + * changed by the user to allow the driver to read them :( + * + * @author Mark Matthews + */ +public class CharsetMapping { + private static final Properties CHARSET_CONFIG = new Properties(); + + /** + * Map of MySQL-4.1 charset indexes to Java encoding names + */ + public static final String[] INDEX_TO_CHARSET; + + /** + * Map of MySQL-4.1 collation index to collation names + */ + public static final String[] INDEX_TO_COLLATION; + + /** Mapping of Java charset names to MySQL charset names */ + private static final Map JAVA_TO_MYSQL_CHARSET_MAP; + + private static final Map JAVA_UC_TO_MYSQL_CHARSET_MAP; + + private static final Map ERROR_MESSAGE_FILE_TO_MYSQL_CHARSET_MAP; + + /** Map/List of multibyte character sets (using MySQL names) */ + private static final Map MULTIBYTE_CHARSETS; + + private static final Map MYSQL_TO_JAVA_CHARSET_MAP; + + private static final String NOT_USED = "ISO8859_1"; // punting for not-used character sets + + public static final Map STATIC_CHARSET_TO_NUM_BYTES_MAP; + + static { + HashMap tempNumBytesMap = new HashMap(); + + tempNumBytesMap.put("big5", new Integer(2)); + tempNumBytesMap.put("dec8" , new Integer(1)); + tempNumBytesMap.put("cp850", new Integer(1)); + tempNumBytesMap.put("hp8", new Integer(1)); + tempNumBytesMap.put("koi8r", new Integer(1)); + tempNumBytesMap.put("latin1", new Integer(1)); + tempNumBytesMap.put("latin2", new Integer(1)); + tempNumBytesMap.put("swe7", new Integer(1)); + tempNumBytesMap.put("ascii", new Integer(1)); + tempNumBytesMap.put("ujis", new Integer(3)); + tempNumBytesMap.put("sjis", new Integer(2)); + tempNumBytesMap.put("hebrew", new Integer(1)); + tempNumBytesMap.put("tis620", new Integer(1)); + tempNumBytesMap.put("euckr", new Integer(2)); + tempNumBytesMap.put("koi8u", new Integer(1)); + tempNumBytesMap.put("gb2312", new Integer(2)); + tempNumBytesMap.put("greek", new Integer(1)); + tempNumBytesMap.put("cp1250", new Integer(1)); + tempNumBytesMap.put("gbk", new Integer(2)); + tempNumBytesMap.put("latin5", new Integer(1)); + tempNumBytesMap.put("armscii8", new Integer(1)); + tempNumBytesMap.put("utf8", new Integer(3)); + tempNumBytesMap.put("ucs2", new Integer(2)); + tempNumBytesMap.put("cp866", new Integer(1)); + tempNumBytesMap.put("keybcs2", new Integer(1)); + tempNumBytesMap.put("macce", new Integer(1)); + tempNumBytesMap.put("macroman", new Integer(1)); + tempNumBytesMap.put("cp852" , new Integer(1)); + tempNumBytesMap.put("latin7", new Integer(1)); + tempNumBytesMap.put("cp1251", new Integer(1)); + tempNumBytesMap.put("cp1256" , new Integer(1)); + tempNumBytesMap.put("cp1257", new Integer(1)); + tempNumBytesMap.put("binary", new Integer(1)); + tempNumBytesMap.put("geostd8", new Integer(1)); + tempNumBytesMap.put("cp932", new Integer(2)); + tempNumBytesMap.put("eucjpms", new Integer(3)); + + STATIC_CHARSET_TO_NUM_BYTES_MAP = Collections.unmodifiableMap( + tempNumBytesMap); + + CHARSET_CONFIG.setProperty("javaToMysqlMappings", + // + // Note: This used to be stored in Charsets.properties, + // but turned out to be problematic when dealing with + // Tomcat classloaders when the security manager was + // enabled + // + // Java Encoding MySQL Name (and version, '*' + // denotes preferred value) + // + "US-ASCII = usa7," + + "US-ASCII = >4.1.0 ascii," + + "Big5 = big5," + + "GBK = gbk," + + "SJIS = sjis," + + "EUC_CN = gb2312," + + "EUC_JP = ujis," + + "EUC_JP_Solaris = >5.0.3 eucjpms," + + "EUC_KR = euc_kr," + + "EUC_KR = >4.1.0 euckr," + + "ISO8859_1 = *latin1," + + "ISO8859_1 = latin1_de," + + "ISO8859_1 = german1," + + "ISO8859_1 = danish," + + "ISO8859_2 = latin2," + + "ISO8859_2 = czech," + + "ISO8859_2 = hungarian," + + "ISO8859_2 = croat," + + "ISO8859_7 = greek," + + "ISO8859_7 = latin7," + + "ISO8859_8 = hebrew," + + "ISO8859_9 = latin5," + + "ISO8859_13 = latvian," + + "ISO8859_13 = latvian1," + + "ISO8859_13 = estonia," + + "Cp437 = *>4.1.0 cp850," + + "Cp437 = dos," + + "Cp850 = cp850," + + "Cp852 = cp852," + + "Cp866 = cp866," + + "KOI8_R = koi8_ru," + + "KOI8_R = >4.1.0 koi8r," + + "TIS620 = tis620," + + "Cp1250 = cp1250," + + "Cp1250 = win1250," + + "Cp1251 = *>4.1.0 cp1251," + + "Cp1251 = win1251," + + "Cp1251 = cp1251cias," + + "Cp1251 = cp1251csas," + + "Cp1256 = cp1256," + + "Cp1251 = win1251ukr," + + "Cp1252 = latin1," + + "Cp1257 = cp1257," + + "MacRoman = macroman," + + "MacCentralEurope = macce," + + "UTF-8 = utf8," + + "UnicodeBig = ucs2," + + "US-ASCII = binary," + + "Cp943 = sjis," + + "MS932 = sjis," + + "MS932 = >4.1.11 cp932," + + "WINDOWS-31J = sjis," + + "WINDOWS-31J = >4.1.11 cp932," + + "CP932 = sjis," + + "CP932 = *>4.1.11 cp932," + + "SHIFT_JIS = sjis," + + "ASCII = ascii," + + "LATIN5 = latin5," + + "LATIN7 = latin7," + + "HEBREW = hebrew," + + "GREEK = greek," + + "EUCKR = euckr," + + "GB2312 = gb2312," + + "LATIN2 = latin2"); + + HashMap javaToMysqlMap = new HashMap(); + + populateMapWithKeyValuePairs("javaToMysqlMappings", javaToMysqlMap, + true, false); + JAVA_TO_MYSQL_CHARSET_MAP = Collections.unmodifiableMap(javaToMysqlMap); + + HashMap mysqlToJavaMap = new HashMap(); + + Set keySet = JAVA_TO_MYSQL_CHARSET_MAP.keySet(); + + Iterator javaCharsets = keySet.iterator(); + + while (javaCharsets.hasNext()) { + Object javaEncodingName = javaCharsets.next(); + List mysqlEncodingList = (List) JAVA_TO_MYSQL_CHARSET_MAP + .get(javaEncodingName); + + Iterator mysqlEncodings = mysqlEncodingList.iterator(); + + String mysqlEncodingName = null; + + while (mysqlEncodings.hasNext()) { + VersionedStringProperty mysqlProp = (VersionedStringProperty) mysqlEncodings + .next(); + mysqlEncodingName = mysqlProp.toString(); + + mysqlToJavaMap.put(mysqlEncodingName, javaEncodingName); + mysqlToJavaMap.put(mysqlEncodingName + .toUpperCase(Locale.ENGLISH), javaEncodingName); + } + } + + // we don't want CP932 to map to CP932 + mysqlToJavaMap.put("cp932", "Windows-31J"); + mysqlToJavaMap.put("CP932", "Windows-31J"); + + MYSQL_TO_JAVA_CHARSET_MAP = Collections.unmodifiableMap(mysqlToJavaMap); + + TreeMap ucMap = new TreeMap(String.CASE_INSENSITIVE_ORDER); + + Iterator javaNamesKeys = JAVA_TO_MYSQL_CHARSET_MAP.keySet().iterator(); + + while (javaNamesKeys.hasNext()) { + String key = (String) javaNamesKeys.next(); + + ucMap.put(key.toUpperCase(Locale.ENGLISH), + JAVA_TO_MYSQL_CHARSET_MAP.get(key)); + } + + JAVA_UC_TO_MYSQL_CHARSET_MAP = Collections.unmodifiableMap(ucMap); + + // + // Character sets that we can't convert + // ourselves. + // + HashMap tempMapMulti = new HashMap(); + + CHARSET_CONFIG.setProperty("multibyteCharsets", + // + // Note: This used to be stored in Charsets.properties, + // but turned out to be problematic when dealing with + // Tomcat classloaders when the security manager was + // enabled + // + // Java Name MySQL Name (not currently used) + // + + "Big5 = big5," + + "GBK = gbk," + + "SJIS = sjis," + + "EUC_CN = gb2312," + + "EUC_JP = ujis," + + "EUC_JP_Solaris = eucjpms," + + "EUC_KR = euc_kr," + + "EUC_KR = >4.1.0 euckr," + + "Cp943 = sjis," + + "Cp943 = cp943," + + "WINDOWS-31J = sjis," + + "WINDOWS-31J = cp932," + + "CP932 = cp932," + + "MS932 = sjis," + + "MS932 = cp932," + + "SHIFT_JIS = sjis," + + "EUCKR = euckr," + + "GB2312 = gb2312," + + "UTF-8 = utf8," + + "utf8 = utf8," + + "UnicodeBig = ucs2"); + + populateMapWithKeyValuePairs("multibyteCharsets", tempMapMulti, false, + true); + + MULTIBYTE_CHARSETS = Collections.unmodifiableMap(tempMapMulti); + + INDEX_TO_CHARSET = new String[211]; + + try { + INDEX_TO_CHARSET[1] = getJavaEncodingForMysqlEncoding("big5", null); + INDEX_TO_CHARSET[2] = getJavaEncodingForMysqlEncoding("czech", null); + INDEX_TO_CHARSET[3] = "ISO8859_1"; // punting for "dec8" + INDEX_TO_CHARSET[4] = "ISO8859_1"; // punting for "dos" + INDEX_TO_CHARSET[5] = getJavaEncodingForMysqlEncoding("german1", + null); + INDEX_TO_CHARSET[6] = "ISO8859_1"; // punting for "hp8" + INDEX_TO_CHARSET[7] = getJavaEncodingForMysqlEncoding("koi8_ru", + null); + INDEX_TO_CHARSET[8] = getJavaEncodingForMysqlEncoding("latin1", + null); + INDEX_TO_CHARSET[9] = getJavaEncodingForMysqlEncoding("latin2", + null); + INDEX_TO_CHARSET[10] = "ISO8859_1"; // punting for "swe7" + INDEX_TO_CHARSET[11] = getJavaEncodingForMysqlEncoding("usa7", null); + INDEX_TO_CHARSET[12] = getJavaEncodingForMysqlEncoding("ujis", null); + INDEX_TO_CHARSET[13] = getJavaEncodingForMysqlEncoding("sjis", null); + INDEX_TO_CHARSET[14] = getJavaEncodingForMysqlEncoding("cp1251", + null); + INDEX_TO_CHARSET[15] = getJavaEncodingForMysqlEncoding("danish", + null); + INDEX_TO_CHARSET[16] = getJavaEncodingForMysqlEncoding("hebrew", + null); + + INDEX_TO_CHARSET[17] = NOT_USED; // not used in the server + + INDEX_TO_CHARSET[18] = getJavaEncodingForMysqlEncoding("tis620", + null); + INDEX_TO_CHARSET[19] = getJavaEncodingForMysqlEncoding("euc_kr", + null); + INDEX_TO_CHARSET[20] = getJavaEncodingForMysqlEncoding("estonia", + null); + INDEX_TO_CHARSET[21] = getJavaEncodingForMysqlEncoding("hungarian", + null); + INDEX_TO_CHARSET[22] = "KOI8_R"; //punting for "koi8_ukr" + INDEX_TO_CHARSET[23] = getJavaEncodingForMysqlEncoding( + "win1251ukr", null); + INDEX_TO_CHARSET[24] = getJavaEncodingForMysqlEncoding("gb2312", + null); + INDEX_TO_CHARSET[25] = getJavaEncodingForMysqlEncoding("greek", + null); + INDEX_TO_CHARSET[26] = getJavaEncodingForMysqlEncoding("win1250", + null); + INDEX_TO_CHARSET[27] = getJavaEncodingForMysqlEncoding("croat", + null); + INDEX_TO_CHARSET[28] = getJavaEncodingForMysqlEncoding("gbk", null); + INDEX_TO_CHARSET[29] = getJavaEncodingForMysqlEncoding("cp1257", + null); + INDEX_TO_CHARSET[30] = getJavaEncodingForMysqlEncoding("latin5", + null); + INDEX_TO_CHARSET[31] = getJavaEncodingForMysqlEncoding("latin1_de", + null); + INDEX_TO_CHARSET[32] = "ISO8859_1"; // punting "armscii8" + INDEX_TO_CHARSET[33] = getJavaEncodingForMysqlEncoding("utf8", null); + INDEX_TO_CHARSET[34] = "Cp1250"; // punting "win1250ch" + INDEX_TO_CHARSET[35] = getJavaEncodingForMysqlEncoding("ucs2", null); + INDEX_TO_CHARSET[36] = getJavaEncodingForMysqlEncoding("cp866", + null); + INDEX_TO_CHARSET[37] = "Cp895"; // punting "keybcs2" + INDEX_TO_CHARSET[38] = getJavaEncodingForMysqlEncoding("macce", + null); + INDEX_TO_CHARSET[39] = getJavaEncodingForMysqlEncoding("macroman", + null); + INDEX_TO_CHARSET[40] = "latin2"; // punting "pclatin2" + INDEX_TO_CHARSET[41] = getJavaEncodingForMysqlEncoding("latvian", + null); + INDEX_TO_CHARSET[42] = getJavaEncodingForMysqlEncoding("latvian1", + null); + INDEX_TO_CHARSET[43] = getJavaEncodingForMysqlEncoding("macce", + null); + INDEX_TO_CHARSET[44] = getJavaEncodingForMysqlEncoding("macce", + null); + INDEX_TO_CHARSET[45] = getJavaEncodingForMysqlEncoding("macce", + null); + INDEX_TO_CHARSET[46] = getJavaEncodingForMysqlEncoding("macce", + null); + INDEX_TO_CHARSET[47] = getJavaEncodingForMysqlEncoding("latin1", + null); + INDEX_TO_CHARSET[48] = getJavaEncodingForMysqlEncoding( + "latin1", null); + INDEX_TO_CHARSET[49] = getJavaEncodingForMysqlEncoding( + "latin1", null); + INDEX_TO_CHARSET[50] = getJavaEncodingForMysqlEncoding("cp1251", + null); + INDEX_TO_CHARSET[51] = getJavaEncodingForMysqlEncoding( + "cp1251", null); + INDEX_TO_CHARSET[52] = getJavaEncodingForMysqlEncoding( + "cp1251", null); + INDEX_TO_CHARSET[53] = getJavaEncodingForMysqlEncoding( + "macroman", null); + INDEX_TO_CHARSET[54] = getJavaEncodingForMysqlEncoding( + "macroman", null); + INDEX_TO_CHARSET[55] = getJavaEncodingForMysqlEncoding( + "macroman", null); + INDEX_TO_CHARSET[56] = getJavaEncodingForMysqlEncoding( + "macroman", null); + INDEX_TO_CHARSET[57] = getJavaEncodingForMysqlEncoding("cp1256", + null); + + INDEX_TO_CHARSET[58] = NOT_USED; // not used + INDEX_TO_CHARSET[59] = NOT_USED; // not used + INDEX_TO_CHARSET[60] = NOT_USED; // not used + INDEX_TO_CHARSET[61] = NOT_USED; // not used + INDEX_TO_CHARSET[62] = NOT_USED; // not used + + INDEX_TO_CHARSET[63] = getJavaEncodingForMysqlEncoding("binary", + null); + INDEX_TO_CHARSET[64] = "ISO8859_2"; // punting "armscii" + INDEX_TO_CHARSET[65] = getJavaEncodingForMysqlEncoding("ascii", + null); + INDEX_TO_CHARSET[66] = getJavaEncodingForMysqlEncoding("cp1250", + null); + INDEX_TO_CHARSET[67] = getJavaEncodingForMysqlEncoding("cp1256", + null); + INDEX_TO_CHARSET[68] = getJavaEncodingForMysqlEncoding("cp866", + null); + INDEX_TO_CHARSET[69] = "US-ASCII"; // punting for "dec8" + INDEX_TO_CHARSET[70] = getJavaEncodingForMysqlEncoding("greek", + null); + INDEX_TO_CHARSET[71] = getJavaEncodingForMysqlEncoding("hebrew", + null); + INDEX_TO_CHARSET[72] = "US-ASCII"; // punting for "hp8" + INDEX_TO_CHARSET[73] = "Cp895"; // punting for "keybcs2" + INDEX_TO_CHARSET[74] = getJavaEncodingForMysqlEncoding("koi8r", + null); + INDEX_TO_CHARSET[75] = "KOI8_r"; // punting for koi8ukr" + + INDEX_TO_CHARSET[76] = NOT_USED; // not used + + INDEX_TO_CHARSET[77] = getJavaEncodingForMysqlEncoding("latin2", + null); + INDEX_TO_CHARSET[78] = getJavaEncodingForMysqlEncoding("latin5", + null); + INDEX_TO_CHARSET[79] = getJavaEncodingForMysqlEncoding("latin7", + null); + INDEX_TO_CHARSET[80] = getJavaEncodingForMysqlEncoding("cp850", + null); + INDEX_TO_CHARSET[81] = getJavaEncodingForMysqlEncoding("cp852", + null); + INDEX_TO_CHARSET[82] = "ISO8859_1"; // punting for "swe7" + INDEX_TO_CHARSET[83] = getJavaEncodingForMysqlEncoding("utf8", null); + INDEX_TO_CHARSET[84] = getJavaEncodingForMysqlEncoding("big5", null); + INDEX_TO_CHARSET[85] = getJavaEncodingForMysqlEncoding("euckr", + null); + INDEX_TO_CHARSET[86] = getJavaEncodingForMysqlEncoding("gb2312", + null); + INDEX_TO_CHARSET[87] = getJavaEncodingForMysqlEncoding("gbk", null); + INDEX_TO_CHARSET[88] = getJavaEncodingForMysqlEncoding("sjis", null); + INDEX_TO_CHARSET[89] = getJavaEncodingForMysqlEncoding("tis620", + null); + INDEX_TO_CHARSET[90] = getJavaEncodingForMysqlEncoding("ucs2", null); + INDEX_TO_CHARSET[91] = getJavaEncodingForMysqlEncoding("ujis", null); + INDEX_TO_CHARSET[92] = "US-ASCII"; //punting for "geostd8" + INDEX_TO_CHARSET[93] = "US-ASCII"; // punting for "geostd8" + INDEX_TO_CHARSET[94] = getJavaEncodingForMysqlEncoding("latin1", + null); + INDEX_TO_CHARSET[95] = getJavaEncodingForMysqlEncoding("cp932", + null); + INDEX_TO_CHARSET[96] = getJavaEncodingForMysqlEncoding("cp932", + null); + INDEX_TO_CHARSET[97] = getJavaEncodingForMysqlEncoding("eucjpms", + null); + INDEX_TO_CHARSET[98] = getJavaEncodingForMysqlEncoding("eucjpms", + null); + + for (int i = 99; i < 128; i++) { + INDEX_TO_CHARSET[i] = NOT_USED; // not used + } + + INDEX_TO_CHARSET[128] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[129] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[130] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[131] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[132] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[133] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[134] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[135] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[136] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[137] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[138] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[139] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[140] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[141] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[142] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[143] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[144] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[145] = getJavaEncodingForMysqlEncoding("ucs2", + null); + INDEX_TO_CHARSET[146] = getJavaEncodingForMysqlEncoding("ucs2", + null); + + for (int i = 147; i < 192; i++) { + INDEX_TO_CHARSET[i] = NOT_USED; // not used + } + + INDEX_TO_CHARSET[192] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[193] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[194] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[195] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[196] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[197] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[198] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[199] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[200] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[201] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[202] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[203] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[204] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[205] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[206] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[207] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[208] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[209] = getJavaEncodingForMysqlEncoding("utf8", + null); + INDEX_TO_CHARSET[210] = getJavaEncodingForMysqlEncoding("utf8", + null); + + // Sanity check + + for (int i = 1; i < INDEX_TO_CHARSET.length; i++) { + if (INDEX_TO_CHARSET[i] == null) { + throw new RuntimeException("Assertion failure: No mapping from charset index " + i + " to a Java character set"); + } + } + } catch (SQLException sqlEx) { + // ignore, it won't happen in this case + } + + INDEX_TO_COLLATION = new String[211]; + + INDEX_TO_COLLATION[1] = "big5_chinese_ci"; + INDEX_TO_COLLATION[2] = "latin2_czech_cs"; + INDEX_TO_COLLATION[3] = "dec8_swedish_ci"; + INDEX_TO_COLLATION[4] = "cp850_general_ci"; + INDEX_TO_COLLATION[5] = "latin1_german1_ci"; + INDEX_TO_COLLATION[6] = "hp8_english_ci"; + INDEX_TO_COLLATION[7] = "koi8r_general_ci"; + INDEX_TO_COLLATION[8] = "latin1_swedish_ci"; + INDEX_TO_COLLATION[9] = "latin2_general_ci"; + INDEX_TO_COLLATION[10] = "swe7_swedish_ci"; + INDEX_TO_COLLATION[11] = "ascii_general_ci"; + INDEX_TO_COLLATION[12] = "ujis_japanese_ci"; + INDEX_TO_COLLATION[13] = "sjis_japanese_ci"; + INDEX_TO_COLLATION[14] = "cp1251_bulgarian_ci"; + INDEX_TO_COLLATION[15] = "latin1_danish_ci"; + INDEX_TO_COLLATION[16] = "hebrew_general_ci"; + INDEX_TO_COLLATION[18] = "tis620_thai_ci"; + INDEX_TO_COLLATION[19] = "euckr_korean_ci"; + INDEX_TO_COLLATION[20] = "latin7_estonian_cs"; + INDEX_TO_COLLATION[21] = "latin2_hungarian_ci"; + INDEX_TO_COLLATION[22] = "koi8u_general_ci"; + INDEX_TO_COLLATION[23] = "cp1251_ukrainian_ci"; + INDEX_TO_COLLATION[24] = "gb2312_chinese_ci"; + INDEX_TO_COLLATION[25] = "greek_general_ci"; + INDEX_TO_COLLATION[26] = "cp1250_general_ci"; + INDEX_TO_COLLATION[27] = "latin2_croatian_ci"; + INDEX_TO_COLLATION[28] = "gbk_chinese_ci"; + INDEX_TO_COLLATION[29] = "cp1257_lithuanian_ci"; + INDEX_TO_COLLATION[30] = "latin5_turkish_ci"; + INDEX_TO_COLLATION[31] = "latin1_german2_ci"; + INDEX_TO_COLLATION[32] = "armscii8_general_ci"; + INDEX_TO_COLLATION[33] = "utf8_general_ci"; + INDEX_TO_COLLATION[34] = "cp1250_czech_cs"; + INDEX_TO_COLLATION[35] = "ucs2_general_ci"; + INDEX_TO_COLLATION[36] = "cp866_general_ci"; + INDEX_TO_COLLATION[37] = "keybcs2_general_ci"; + INDEX_TO_COLLATION[38] = "macce_general_ci"; + INDEX_TO_COLLATION[39] = "macroman_general_ci"; + INDEX_TO_COLLATION[40] = "cp852_general_ci"; + INDEX_TO_COLLATION[41] = "latin7_general_ci"; + INDEX_TO_COLLATION[42] = "latin7_general_cs"; + INDEX_TO_COLLATION[43] = "macce_bin"; + INDEX_TO_COLLATION[44] = "cp1250_croatian_ci"; + INDEX_TO_COLLATION[47] = "latin1_bin"; + INDEX_TO_COLLATION[48] = "latin1_general_ci"; + INDEX_TO_COLLATION[49] = "latin1_general_cs"; + INDEX_TO_COLLATION[50] = "cp1251_bin"; + INDEX_TO_COLLATION[51] = "cp1251_general_ci"; + INDEX_TO_COLLATION[52] = "cp1251_general_cs"; + INDEX_TO_COLLATION[53] = "macroman_bin"; + INDEX_TO_COLLATION[57] = "cp1256_general_ci"; + INDEX_TO_COLLATION[58] = "cp1257_bin"; + INDEX_TO_COLLATION[59] = "cp1257_general_ci"; + INDEX_TO_COLLATION[63] = "binary"; + INDEX_TO_COLLATION[64] = "armscii8_bin"; + INDEX_TO_COLLATION[65] = "ascii_bin"; + INDEX_TO_COLLATION[66] = "cp1250_bin"; + INDEX_TO_COLLATION[67] = "cp1256_bin"; + INDEX_TO_COLLATION[68] = "cp866_bin"; + INDEX_TO_COLLATION[69] = "dec8_bin"; + INDEX_TO_COLLATION[70] = "greek_bin"; + INDEX_TO_COLLATION[71] = "hebrew_bin"; + INDEX_TO_COLLATION[72] = "hp8_bin"; + INDEX_TO_COLLATION[73] = "keybcs2_bin"; + INDEX_TO_COLLATION[74] = "koi8r_bin"; + INDEX_TO_COLLATION[75] = "koi8u_bin"; + INDEX_TO_COLLATION[77] = "latin2_bin"; + INDEX_TO_COLLATION[78] = "latin5_bin"; + INDEX_TO_COLLATION[79] = "latin7_bin"; + INDEX_TO_COLLATION[80] = "cp850_bin"; + INDEX_TO_COLLATION[81] = "cp852_bin"; + INDEX_TO_COLLATION[82] = "swe7_bin"; + INDEX_TO_COLLATION[83] = "utf8_bin"; + INDEX_TO_COLLATION[84] = "big5_bin"; + INDEX_TO_COLLATION[85] = "euckr_bin"; + INDEX_TO_COLLATION[86] = "gb2312_bin"; + INDEX_TO_COLLATION[87] = "gbk_bin"; + INDEX_TO_COLLATION[88] = "sjis_bin"; + INDEX_TO_COLLATION[89] = "tis620_bin"; + INDEX_TO_COLLATION[90] = "ucs2_bin"; + INDEX_TO_COLLATION[91] = "ujis_bin"; + INDEX_TO_COLLATION[92] = "geostd8_general_ci"; + INDEX_TO_COLLATION[93] = "geostd8_bin"; + INDEX_TO_COLLATION[94] = "latin1_spanish_ci"; + INDEX_TO_COLLATION[95] = "cp932_japanese_ci"; + INDEX_TO_COLLATION[96] = "cp932_bin"; + INDEX_TO_COLLATION[97] = "eucjpms_japanese_ci"; + INDEX_TO_COLLATION[98] = "eucjpms_bin"; + INDEX_TO_COLLATION[99] = "cp1250_polish_ci"; + INDEX_TO_COLLATION[128] = "ucs2_unicode_ci"; + INDEX_TO_COLLATION[129] = "ucs2_icelandic_ci"; + INDEX_TO_COLLATION[130] = "ucs2_latvian_ci"; + INDEX_TO_COLLATION[131] = "ucs2_romanian_ci"; + INDEX_TO_COLLATION[132] = "ucs2_slovenian_ci"; + INDEX_TO_COLLATION[133] = "ucs2_polish_ci"; + INDEX_TO_COLLATION[134] = "ucs2_estonian_ci"; + INDEX_TO_COLLATION[135] = "ucs2_spanish_ci"; + INDEX_TO_COLLATION[136] = "ucs2_swedish_ci"; + INDEX_TO_COLLATION[137] = "ucs2_turkish_ci"; + INDEX_TO_COLLATION[138] = "ucs2_czech_ci"; + INDEX_TO_COLLATION[139] = "ucs2_danish_ci"; + INDEX_TO_COLLATION[140] = "ucs2_lithuanian_ci "; + INDEX_TO_COLLATION[141] = "ucs2_slovak_ci"; + INDEX_TO_COLLATION[142] = "ucs2_spanish2_ci"; + INDEX_TO_COLLATION[143] = "ucs2_roman_ci"; + INDEX_TO_COLLATION[144] = "ucs2_persian_ci"; + INDEX_TO_COLLATION[145] = "ucs2_esperanto_ci"; + INDEX_TO_COLLATION[146] = "ucs2_hungarian_ci"; + INDEX_TO_COLLATION[192] = "utf8_unicode_ci"; + INDEX_TO_COLLATION[193] = "utf8_icelandic_ci"; + INDEX_TO_COLLATION[194] = "utf8_latvian_ci"; + INDEX_TO_COLLATION[195] = "utf8_romanian_ci"; + INDEX_TO_COLLATION[196] = "utf8_slovenian_ci"; + INDEX_TO_COLLATION[197] = "utf8_polish_ci"; + INDEX_TO_COLLATION[198] = "utf8_estonian_ci"; + INDEX_TO_COLLATION[199] = "utf8_spanish_ci"; + INDEX_TO_COLLATION[200] = "utf8_swedish_ci"; + INDEX_TO_COLLATION[201] = "utf8_turkish_ci"; + INDEX_TO_COLLATION[202] = "utf8_czech_ci"; + INDEX_TO_COLLATION[203] = "utf8_danish_ci"; + INDEX_TO_COLLATION[204] = "utf8_lithuanian_ci "; + INDEX_TO_COLLATION[205] = "utf8_slovak_ci"; + INDEX_TO_COLLATION[206] = "utf8_spanish2_ci"; + INDEX_TO_COLLATION[207] = "utf8_roman_ci"; + INDEX_TO_COLLATION[208] = "utf8_persian_ci"; + INDEX_TO_COLLATION[209] = "utf8_esperanto_ci"; + INDEX_TO_COLLATION[210] = "utf8_hungarian_ci"; + + Map tempMap = new HashMap(); + + tempMap.put("czech", "latin2"); + tempMap.put("danish", "latin1"); + tempMap.put("dutch", "latin1"); + tempMap.put("english", "latin1"); + tempMap.put("estonian", "latin7"); + tempMap.put("french", "latin1"); + tempMap.put("german", "latin1"); + tempMap.put("greek", "greek"); + tempMap.put("hungarian", "latin2"); + tempMap.put("italian", "latin1"); + tempMap.put("japanese", "ujis"); + tempMap.put("japanese-sjis", "sjis"); + tempMap.put("korean", "euckr"); + tempMap.put("norwegian", "latin1"); + tempMap.put("norwegian-ny", "latin1"); + tempMap.put("polish", "latin2"); + tempMap.put("portuguese", "latin1"); + tempMap.put("romanian", "latin2"); + tempMap.put("russian", "koi8r"); + tempMap.put("serbian", "cp1250"); + tempMap.put("slovak", "latin2"); + tempMap.put("spanish", "latin1"); + tempMap.put("swedish", "latin1"); + tempMap.put("ukrainian", "koi8u"); + + ERROR_MESSAGE_FILE_TO_MYSQL_CHARSET_MAP = + Collections.unmodifiableMap(tempMap); + } + + public final static String getJavaEncodingForMysqlEncoding(String mysqlEncoding, + Connection conn) throws SQLException { + + if (conn != null && conn.versionMeetsMinimum(4, 1, 0) && + "latin1".equalsIgnoreCase(mysqlEncoding)) { + return "Cp1252"; + } + + return (String) MYSQL_TO_JAVA_CHARSET_MAP.get(mysqlEncoding); + } + + public final static String getMysqlEncodingForJavaEncoding(String javaEncodingUC, + Connection conn) throws SQLException { + List mysqlEncodings = (List) CharsetMapping.JAVA_UC_TO_MYSQL_CHARSET_MAP + .get(javaEncodingUC); + ; + + if (mysqlEncodings != null) { + Iterator iter = mysqlEncodings.iterator(); + + VersionedStringProperty versionedProp = null; + + while (iter.hasNext()) { + VersionedStringProperty propToCheck = (VersionedStringProperty) iter + .next(); + + if (conn == null) { + // Take the first one we get + + return propToCheck.toString(); + } + + if (versionedProp != null && !versionedProp.preferredValue) { + if (versionedProp.majorVersion == propToCheck.majorVersion + && versionedProp.minorVersion == propToCheck.minorVersion + && versionedProp.subminorVersion == propToCheck.subminorVersion) { + return versionedProp.toString(); + } + } + + if (propToCheck.isOkayForVersion(conn)) { + if (propToCheck.preferredValue) { + return propToCheck.toString(); + } + + versionedProp = propToCheck; + } else { + break; + } + } + + if (versionedProp != null) { + return versionedProp.toString(); + } + } + + return null; + } + + final static int getNumberOfCharsetsConfigured() { + return MYSQL_TO_JAVA_CHARSET_MAP.size() / 2; // because we UC every + // key + } + + /** + * Returns the character encoding for error messages returned from the + * server. Doesn't return useful values other than Cp1252 until the driver + * has gone through initialization phase and determined server configuration, + * as not enough information is available to make an intelligent decision + * until then. + * + * @param conn the connection to the MySQL server + * @return the Java encoding name that error messages use + * @throws SQLException if determination of the character encoding fails + */ + final static String getCharacterEncodingForErrorMessages(Connection conn) throws SQLException { + String errorMessageFile = conn.getServerVariable("language"); + + if (errorMessageFile == null || errorMessageFile.length() == 0) { + // punt + return "Cp1252"; + } + + int endWithoutSlash = errorMessageFile.length(); + + if (errorMessageFile.endsWith("/") || errorMessageFile.endsWith("\\")) { + endWithoutSlash--; + } + + int lastSlashIndex = errorMessageFile.lastIndexOf('/', endWithoutSlash - 1); + + if (lastSlashIndex == -1) { + lastSlashIndex = errorMessageFile.lastIndexOf('\\', endWithoutSlash - 1); + } + + if (lastSlashIndex == -1) { + lastSlashIndex = 0; + } + + if (lastSlashIndex == endWithoutSlash || endWithoutSlash < lastSlashIndex) { + // punt + return "Cp1252"; + } + + errorMessageFile = errorMessageFile.substring(lastSlashIndex + 1, endWithoutSlash); + + String errorMessageEncodingMysql = (String)ERROR_MESSAGE_FILE_TO_MYSQL_CHARSET_MAP.get(errorMessageFile); + + if (errorMessageEncodingMysql == null) { + // punt + return "Cp1252"; + } + + String javaEncoding = getJavaEncodingForMysqlEncoding(errorMessageEncodingMysql, conn); + + if (javaEncoding == null) { + // punt + return "Cp1252"; + } + + return javaEncoding; + } + + final static boolean isAliasForSjis(String encoding) { + return ("SJIS".equalsIgnoreCase(encoding) + || "WINDOWS-31J".equalsIgnoreCase(encoding) + || "MS932".equalsIgnoreCase(encoding) + || "SHIFT_JIS".equalsIgnoreCase(encoding) || "CP943" + .equalsIgnoreCase(encoding)); + + } + + final static boolean isMultibyteCharset(String javaEncodingName) { + String javaEncodingNameUC = javaEncodingName + .toUpperCase(Locale.ENGLISH); + + return MULTIBYTE_CHARSETS.containsKey(javaEncodingNameUC); + } + + private static void populateMapWithKeyValuePairs(String configKey, + Map mapToPopulate, boolean addVersionedProperties, + boolean addUppercaseKeys) { + String javaToMysqlConfig = CHARSET_CONFIG.getProperty(configKey); + + if (javaToMysqlConfig != null) { + List mappings = StringUtils.split(javaToMysqlConfig, ",", true); + + if (mappings != null) { + Iterator mappingsIter = mappings.iterator(); + + while (mappingsIter.hasNext()) { + String aMapping = (String) mappingsIter.next(); + + List parsedPair = StringUtils.split(aMapping, "=", true); + + if (parsedPair.size() == 2) { + String key = parsedPair.get(0).toString(); + String value = parsedPair.get(1).toString(); + + if (addVersionedProperties) { + List versionedProperties = (List) mapToPopulate + .get(key); + + if (versionedProperties == null) { + versionedProperties = new ArrayList(); + mapToPopulate.put(key, versionedProperties); + } + + VersionedStringProperty verProp = new VersionedStringProperty( + value); + versionedProperties.add(verProp); + + if (addUppercaseKeys) { + String keyUc = key.toUpperCase(Locale.ENGLISH); + + versionedProperties = (List) mapToPopulate + .get(keyUc); + + if (versionedProperties == null) { + versionedProperties = new ArrayList(); + mapToPopulate.put(keyUc, + versionedProperties); + } + + versionedProperties.add(verProp); + } + } else { + mapToPopulate.put(key, value); + + if (addUppercaseKeys) { + mapToPopulate.put(key + .toUpperCase(Locale.ENGLISH), value); + } + } + } else { + throw new RuntimeException( + "Syntax error in Charsets.properties " + + "resource for token \"" + aMapping + + "\"."); + } + } + } else { + throw new RuntimeException("Missing/corrupt entry for \"" + + configKey + "\" in Charsets.properties."); + } + } else { + throw new RuntimeException("Could not find configuration value " + + "\"" + configKey + "\" in Charsets.properties resource"); + } + } +} + +class VersionedStringProperty { + int majorVersion, minorVersion, subminorVersion; + + boolean preferredValue = false; + + String propertyInfo; + + VersionedStringProperty(String property) { + property = property.trim(); + + if (property.startsWith("*")) { + property = property.substring(1); + preferredValue = true; + } + + if (property.startsWith(">")) { + property = property.substring(1); + + int charPos = 0; + + for (charPos = 0; charPos < property.length(); charPos++) { + char c = property.charAt(charPos); + + if (!Character.isWhitespace(c) && !Character.isDigit(c) + && c != '.') { + break; + } + } + + String versionInfo = property.substring(0, charPos); + List versionParts = StringUtils.split(versionInfo, ".", true); + + majorVersion = Integer.parseInt(versionParts.get(0).toString()); + + if (versionParts.size() > 1) { + minorVersion = Integer.parseInt(versionParts.get(1).toString()); + } else { + minorVersion = 0; + } + + if (versionParts.size() > 2) { + subminorVersion = Integer.parseInt(versionParts.get(2) + .toString()); + } else { + subminorVersion = 0; + } + + propertyInfo = property.substring(charPos); + } else { + majorVersion = minorVersion = subminorVersion = 0; + propertyInfo = property; + } + } + + VersionedStringProperty(String property, int major, int minor, int subminor) { + propertyInfo = property; + majorVersion = major; + minorVersion = minor; + subminorVersion = subminor; + } + + boolean isOkayForVersion(Connection conn) throws SQLException { + return conn.versionMeetsMinimum(majorVersion, minorVersion, + subminorVersion); + } + + public String toString() { + return propertyInfo; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Charsets.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Charsets.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Charsets.properties 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,102 @@ +# +# Charset Mappings +# +# Java Encoding MySQL Name (and version, '*' +# denotes preferred value) +# + +javaToMysqlMappings=\ + US-ASCII = usa7,\ + US-ASCII = ascii,\ + Big5 = big5,\ + GBK = gbk,\ + SJIS = sjis,\ + EUC_CN = gb2312,\ + EUC_JP = ujis,\ + EUC_JP_Solaris = >5.0.3 eucjpms,\ + EUC_KR = euc_kr,\ + EUC_KR = >4.1.0 euckr,\ + ISO8859_1 = *latin1,\ + ISO8859_1 = latin1_de,\ + ISO8859_1 = german1,\ + ISO8859_1 = danish,\ + ISO8859_2 = latin2,\ + ISO8859_2 = czech,\ + ISO8859_2 = hungarian,\ + ISO8859_2 = croat,\ + ISO8859_7 = greek,\ + ISO8859_7 = latin7,\ + ISO8859_8 = hebrew,\ + ISO8859_9 = latin5,\ + ISO8859_13 = latvian,\ + ISO8859_13 = latvian1,\ + ISO8859_13 = estonia,\ + Cp437 = *>4.1.0 cp850,\ + Cp437 = dos,\ + Cp850 = Cp850,\ + Cp852 = Cp852,\ + Cp866 = cp866,\ + KOI8_R = koi8_ru,\ + KOI8_R = >4.1.0 koi8r,\ + TIS620 = tis620,\ + Cp1250 = cp1250,\ + Cp1250 = win1250,\ + Cp1251 = *>4.1.0 cp1251,\ + Cp1251 = win1251,\ + Cp1251 = cp1251cias,\ + Cp1251 = cp1251csas,\ + Cp1256 = cp1256,\ + Cp1251 = win1251ukr,\ + Cp1257 = cp1257,\ + MacRoman = macroman,\ + MacCentralEurope = macce,\ + UTF-8 = utf8,\ + UnicodeBig = ucs2,\ + US-ASCII = binary,\ + Cp943 = sjis,\ + MS932 = sjis,\ + MS932 = >4.1.11 cp932,\ + WINDOWS-31J = sjis,\ + WINDOWS-31J = >4.1.11 cp932,\ + CP932 = sjis,\ + CP932 = *>4.1.11 cp932,\ + SHIFT_JIS = sjis,\ + ASCII = ascii,\ + LATIN5 = latin5,\ + LATIN7 = latin7,\ + HEBREW = hebrew,\ + GREEK = greek,\ + EUCKR = euckr,\ + GB2312 = gb2312,\ + LATIN2 = latin2 + +# +# List of multibyte character sets that can not +# use efficient charset conversion or escaping +# +# This map is made case-insensitive inside CharsetMapping +# +# Java Name MySQL Name (not currently used) + +multibyteCharsets=\ + Big5 = big5,\ + GBK = gbk,\ + SJIS = sjis,\ + EUC_CN = gb2312,\ + EUC_JP = ujis,\ + EUC_JP_Solaris = eucjpms,\ + EUC_KR = euc_kr,\ + EUC_KR = >4.1.0 euckr,\ + Cp943 = sjis,\ + Cp943 = cp943,\ + WINDOWS-31J = sjis,\ + WINDOWS-31J = cp932,\ + CP932 = cp932,\ + MS932 = sjis,\ + MS932 = cp932,\ + SHIFT_JIS = sjis,\ + EUCKR = euckr,\ + GB2312 = gb2312,\ + UTF-8 = utf8,\ + utf8 = utf8,\ + UnicodeBig = ucs2 \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Clob.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Clob.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Clob.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,290 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.Writer; + +import java.sql.SQLException; + +/** + * Simplistic implementation of java.sql.Clob for MySQL Connector/J + * + * @author Mark Matthews + * @version $Id: Clob.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + */ +public class Clob implements java.sql.Clob, OutputStreamWatcher, WriterWatcher { + private String charData; + + Clob(String charDataInit) { + this.charData = charDataInit; + } + + /** + * @see java.sql.Clob#getAsciiStream() + */ + public InputStream getAsciiStream() throws SQLException { + if (this.charData != null) { + return new ByteArrayInputStream(this.charData.getBytes()); + } + + return null; + } + + /** + * @see java.sql.Clob#getCharacterStream() + */ + public Reader getCharacterStream() throws SQLException { + if (this.charData != null) { + return new StringReader(this.charData); + } + + return null; + } + + /** + * @see java.sql.Clob#getSubString(long, int) + */ + public String getSubString(long startPos, int length) throws SQLException { + if (startPos < 1) { + throw SQLError.createSQLException(Messages.getString("Clob.6"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + int adjustedStartPos = (int)startPos - 1; + int adjustedEndIndex = adjustedStartPos + length; + + if (this.charData != null) { + if (adjustedEndIndex > this.charData.length()) { + throw SQLError.createSQLException(Messages.getString("Clob.7"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + return this.charData.substring(adjustedStartPos, + adjustedEndIndex); + } + + return null; + } + + /** + * @see java.sql.Clob#length() + */ + public long length() throws SQLException { + if (this.charData != null) { + return this.charData.length(); + } + + return 0; + } + + /** + * @see java.sql.Clob#position(Clob, long) + */ + public long position(java.sql.Clob arg0, long arg1) throws SQLException { + return position(arg0.getSubString(0L, (int) arg0.length()), arg1); + } + + /** + * @see java.sql.Clob#position(String, long) + */ + public long position(String stringToFind, long startPos) + throws SQLException { + if (startPos < 1) { + throw SQLError.createSQLException( + Messages.getString("Clob.8") //$NON-NLS-1$ + + startPos + Messages.getString("Clob.9"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + if (this.charData != null) { + if ((startPos - 1) > this.charData.length()) { + throw SQLError.createSQLException(Messages.getString("Clob.10"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + int pos = this.charData.indexOf(stringToFind, (int) (startPos - 1)); + + return (pos == -1) ? (-1) : (pos + 1); + } + + return -1; + } + + /** + * @see java.sql.Clob#setAsciiStream(long) + */ + public OutputStream setAsciiStream(long indexToWriteAt) throws SQLException { + if (indexToWriteAt < 1) { + throw SQLError.createSQLException(Messages.getString("Clob.0"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + WatchableOutputStream bytesOut = new WatchableOutputStream(); + bytesOut.setWatcher(this); + + if (indexToWriteAt > 0) { + bytesOut.write(this.charData.getBytes(), 0, + (int) (indexToWriteAt - 1)); + } + + return bytesOut; + } + + /** + * @see java.sql.Clob#setCharacterStream(long) + */ + public Writer setCharacterStream(long indexToWriteAt) throws SQLException { + if (indexToWriteAt < 1) { + throw SQLError.createSQLException(Messages.getString("Clob.1"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + WatchableWriter writer = new WatchableWriter(); + writer.setWatcher(this); + + // + // Don't call write() if nothing to write... + // + if (indexToWriteAt > 1) { + writer.write(this.charData, 0, (int) (indexToWriteAt - 1)); + } + + return writer; + } + + /** + * @see java.sql.Clob#setString(long, String) + */ + public int setString(long pos, String str) throws SQLException { + if (pos < 1) { + throw SQLError.createSQLException(Messages.getString("Clob.2"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (str == null) { + throw SQLError.createSQLException(Messages.getString("Clob.3"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + StringBuffer charBuf = new StringBuffer(this.charData); + + pos--; + + int strLength = str.length(); + + charBuf.replace((int) pos, (int) (pos + strLength), str); + + this.charData = charBuf.toString(); + + return strLength; + } + + /** + * @see java.sql.Clob#setString(long, String, int, int) + */ + public int setString(long pos, String str, int offset, int len) + throws SQLException { + if (pos < 1) { + throw SQLError.createSQLException(Messages.getString("Clob.4"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (str == null) { + throw SQLError.createSQLException(Messages.getString("Clob.5"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + StringBuffer charBuf = new StringBuffer(this.charData); + + pos--; + + String replaceString = str.substring(offset, len); + + charBuf.replace((int) pos, (int) (pos + replaceString.length()), + replaceString); + + this.charData = charBuf.toString(); + + return len; + } + + /** + * @see com.mysql.jdbc.OutputStreamWatcher#streamClosed(byte[]) + */ + public void streamClosed(WatchableOutputStream out) { + int streamSize = out.size(); + + if (streamSize < this.charData.length()) { + try { + out.write(StringUtils + .getBytes(this.charData, null, null, false, null), + streamSize, this.charData.length() - streamSize); + } catch (SQLException ex) { + // + } + } + + this.charData = StringUtils.toAsciiString(out.toByteArray()); + } + + /** + * @see java.sql.Clob#truncate(long) + */ + public void truncate(long length) throws SQLException { + if (length > this.charData.length()) { + throw SQLError.createSQLException( + Messages.getString("Clob.11") //$NON-NLS-1$ + + this.charData.length() + + Messages.getString("Clob.12") + length + Messages.getString("Clob.13")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + this.charData = this.charData.substring(0, (int) length); + } + + /** + * @see com.mysql.jdbc.WriterWatcher#writerClosed(char[]) + */ + public void writerClosed(char[] charDataBeingWritten) { + this.charData = new String(charDataBeingWritten); + } + + /** + * @see com.mysql.jdbc.WriterWatcher#writerClosed(char[]) + */ + public void writerClosed(WatchableWriter out) { + int dataLength = out.size(); + + if (dataLength < this.charData.length()) { + out.write(this.charData, dataLength, this.charData.length() + - dataLength); + } + + this.charData = out.toString(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/CommunicationsException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/CommunicationsException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/CommunicationsException.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,230 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.net.BindException; + +import java.sql.SQLException; + +/** + * An exception to represent communications errors with the database. + * + * Attempts to provide 'friendler' error messages to end-users, including last + * time a packet was sent to the database, what the client-timeout is set to, + * and whether the idle time has been exceeded. + * + * @author Mark Matthews + * + * @version $Id: CommunicationsException.java,v 1.1.2.1 2005/05/13 18:58:37 + * mmatthews Exp $ + */ +public class CommunicationsException extends SQLException { + + private static final long DEFAULT_WAIT_TIMEOUT_SECONDS = 28800; + + private static final int DUE_TO_TIMEOUT_FALSE = 0; + + private static final int DUE_TO_TIMEOUT_MAYBE = 2; + + private static final int DUE_TO_TIMEOUT_TRUE = 1; + + private String exceptionMessage; + + private boolean streamingResultSetInPlay = false; + + public CommunicationsException(Connection conn, long lastPacketSentTimeMs, + Exception underlyingException) { + + long serverTimeoutSeconds = 0; + boolean isInteractiveClient = false; + + if (conn != null) { + isInteractiveClient = conn.getInteractiveClient(); + + String serverTimeoutSecondsStr = null; + + if (isInteractiveClient) { + serverTimeoutSecondsStr = conn + .getServerVariable("interactive_timeout"); //$NON-NLS-1$ + } else { + serverTimeoutSecondsStr = conn + .getServerVariable("wait_timeout"); //$NON-NLS-1$ + } + + if (serverTimeoutSecondsStr != null) { + try { + serverTimeoutSeconds = Long + .parseLong(serverTimeoutSecondsStr); + } catch (NumberFormatException nfe) { + serverTimeoutSeconds = 0; + } + } + } + + StringBuffer exceptionMessageBuf = new StringBuffer(); + + if (lastPacketSentTimeMs == 0) { + lastPacketSentTimeMs = System.currentTimeMillis(); + } + + long timeSinceLastPacket = (System.currentTimeMillis() - lastPacketSentTimeMs) / 1000; + + int dueToTimeout = DUE_TO_TIMEOUT_FALSE; + + StringBuffer timeoutMessageBuf = null; + + if (this.streamingResultSetInPlay) { + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.ClientWasStreaming")); //$NON-NLS-1$ + } else { + if (serverTimeoutSeconds != 0) { + if (timeSinceLastPacket > serverTimeoutSeconds) { + dueToTimeout = DUE_TO_TIMEOUT_TRUE; + + timeoutMessageBuf = new StringBuffer(); + + timeoutMessageBuf.append(Messages + .getString("CommunicationsException.2")); //$NON-NLS-1$ + + if (!isInteractiveClient) { + timeoutMessageBuf.append(Messages + .getString("CommunicationsException.3")); //$NON-NLS-1$ + } else { + timeoutMessageBuf.append(Messages + .getString("CommunicationsException.4")); //$NON-NLS-1$ + } + + } + } else if (timeSinceLastPacket > DEFAULT_WAIT_TIMEOUT_SECONDS) { + dueToTimeout = DUE_TO_TIMEOUT_MAYBE; + + timeoutMessageBuf = new StringBuffer(); + + timeoutMessageBuf.append(Messages + .getString("CommunicationsException.5")); //$NON-NLS-1$ + timeoutMessageBuf.append(Messages + .getString("CommunicationsException.6")); //$NON-NLS-1$ + timeoutMessageBuf.append(Messages + .getString("CommunicationsException.7")); //$NON-NLS-1$ + timeoutMessageBuf.append(Messages + .getString("CommunicationsException.8")); //$NON-NLS-1$ + } + + if (dueToTimeout == DUE_TO_TIMEOUT_TRUE + || dueToTimeout == DUE_TO_TIMEOUT_MAYBE) { + + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.9")); //$NON-NLS-1$ + exceptionMessageBuf.append(timeSinceLastPacket); + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.10")); //$NON-NLS-1$ + + if (timeoutMessageBuf != null) { + exceptionMessageBuf.append(timeoutMessageBuf); + } + + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.11")); //$NON-NLS-1$ + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.12")); //$NON-NLS-1$ + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.13")); //$NON-NLS-1$ + + } else { + // + // Attempt to determine the reason for the underlying exception + // (we can only make a best-guess here) + // + + if (underlyingException instanceof BindException) { + if (conn.getLocalSocketAddress() != null && + !Util.interfaceExists(conn.getLocalSocketAddress())) { + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.19a")); //$NON-NLS-1$ + } else { + // too many client connections??? + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.14")); //$NON-NLS-1$ + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.15")); //$NON-NLS-1$ + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.16")); //$NON-NLS-1$ + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.17")); //$NON-NLS-1$ + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.18")); //$NON-NLS-1$ + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.19")); //$NON-NLS-1$ + } + } + } + } + + if (exceptionMessageBuf.length() == 0) { + // We haven't figured out a good reason, so copy it. + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.20")); //$NON-NLS-1$ + + if (underlyingException != null) { + exceptionMessageBuf.append(Messages + .getString("CommunicationsException.21")); //$NON-NLS-1$ + exceptionMessageBuf.append(Util + .stackTraceToString(underlyingException)); + } + + if (conn != null && conn.getMaintainTimeStats() && + !conn.getParanoid()) { + exceptionMessageBuf.append("\n\nLast packet sent to the server was "); + exceptionMessageBuf.append(System.currentTimeMillis() - lastPacketSentTimeMs); + exceptionMessageBuf.append(" ms ago."); + } + } + + this.exceptionMessage = exceptionMessageBuf.toString(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Throwable#getMessage() + */ + public String getMessage() { + return this.exceptionMessage; + } + + /* + * (non-Javadoc) + * + * @see java.sql.SQLException#getSQLState() + */ + public String getSQLState() { + return SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE; + } + + protected void setWasStreamingResults() { + this.streamingResultSetInPlay = true; + } + +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/CompressedInputStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/CompressedInputStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/CompressedInputStream.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,325 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; + +import java.sql.SQLException; + +import java.util.zip.DataFormatException; +import java.util.zip.Inflater; + +/** + * Used to de-compress packets from the MySQL server when protocol-level + * compression is turned on. + * + * @author Mark Matthews + * + * @version $Id: CompressedInputStream.java,v 1.1.2.1 2005/05/13 18:58:37 + * mmatthews Exp $ + */ +class CompressedInputStream extends InputStream { + /** The packet data after it has been un-compressed */ + private byte[] buffer; + + /** The connection that is using us (used to read config values) */ + private Connection connection; + + /** The stream we are reading from the server */ + private InputStream in; + + /** The ZIP inflater used to un-compress packets */ + private Inflater inflater; + + /** + * The buffer to read packet headers into + */ + private byte[] packetHeaderBuffer = new byte[7]; + + /** The position we are reading from */ + private int pos = 0; + + /** + * Creates a new CompressedInputStream that reads the given stream from the + * server. + * + * @param conn + * DOCUMENT ME! + * @param streamFromServer + */ + public CompressedInputStream(Connection conn, InputStream streamFromServer) { + this.connection = conn; + this.in = streamFromServer; + this.inflater = new Inflater(); + } + + /** + * @see java.io.InputStream#available() + */ + public int available() throws IOException { + if (this.buffer == null) { + return this.in.available(); + } + + return this.buffer.length - this.pos + this.in.available(); + } + + /** + * @see java.io.InputStream#close() + */ + public void close() throws IOException { + this.in.close(); + this.buffer = null; + this.inflater = null; + } + + /** + * Retrieves and un-compressed (if necessary) the next packet from the + * server. + * + * @throws IOException + * if an I/O error occurs + */ + private void getNextPacketFromServer() throws IOException { + byte[] uncompressedData = null; + + int lengthRead = readFully(this.packetHeaderBuffer, 0, 7); + + if (lengthRead < 7) { + throw new IOException("Unexpected end of input stream"); + } + + int compressedPacketLength = ((this.packetHeaderBuffer[0] & 0xff)) + + (((this.packetHeaderBuffer[1] & 0xff)) << 8) + + (((this.packetHeaderBuffer[2] & 0xff)) << 16); + + int uncompressedLength = ((this.packetHeaderBuffer[4] & 0xff)) + + (((this.packetHeaderBuffer[5] & 0xff)) << 8) + + (((this.packetHeaderBuffer[6] & 0xff)) << 16); + + if (this.connection.getTraceProtocol()) { + try { + this.connection.getLog().logTrace( + "Reading compressed packet of length " + + compressedPacketLength + " uncompressed to " + + uncompressedLength); + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); // should never + // happen + } + } + + if (uncompressedLength > 0) { + uncompressedData = new byte[uncompressedLength]; + + byte[] compressedBuffer = new byte[compressedPacketLength]; + + readFully(compressedBuffer, 0, compressedPacketLength); + + try { + this.inflater.reset(); + } catch (NullPointerException npe) { + this.inflater = new Inflater(); + } + + this.inflater.setInput(compressedBuffer); + + try { + this.inflater.inflate(uncompressedData); + } catch (DataFormatException dfe) { + throw new IOException( + "Error while uncompressing packet from server."); + } + + this.inflater.end(); + } else { + if (this.connection.getTraceProtocol()) { + try { + this.connection + .getLog() + .logTrace( + "Packet didn't meet compression threshold, not uncompressing..."); + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); // should never + // happen + } + } + + // + // Read data, note this this code is reached when using + // compressed packets that have not been compressed, as well + // + uncompressedData = new byte[compressedPacketLength]; + readFully(uncompressedData, 0, compressedPacketLength); + } + + if (this.connection.getTraceProtocol()) { + try { + this.connection.getLog().logTrace( + "Uncompressed packet: \n" + + StringUtils.dumpAsHex(uncompressedData, + compressedPacketLength)); + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); // should never + // happen + } + } + + if ((this.buffer != null) && (this.pos < this.buffer.length)) { + if (this.connection.getTraceProtocol()) { + try { + this.connection.getLog().logTrace( + "Combining remaining packet with new: "); + } catch (SQLException sqlEx) { + throw new IOException(sqlEx.toString()); // should never + // happen + } + } + + int remaining = this.buffer.length - this.pos; + byte[] newBuffer = new byte[remaining + uncompressedData.length]; + + int newIndex = 0; + + for (int i = this.pos; i < this.buffer.length; i++) + newBuffer[newIndex++] = this.buffer[i]; + + System.arraycopy(uncompressedData, 0, newBuffer, newIndex, + uncompressedData.length); + + uncompressedData = newBuffer; + } + + this.pos = 0; + this.buffer = uncompressedData; + + return; + } + + /** + * Determines if another packet needs to be read from the server to be able + * to read numBytes from the stream. + * + * @param numBytes + * the number of bytes to be read + * + * @throws IOException + * if an I/O error occors. + */ + private void getNextPacketIfRequired(int numBytes) throws IOException { + if ((this.buffer == null) + || ((this.pos + numBytes) > this.buffer.length)) { + getNextPacketFromServer(); + } + } + + /** + * @see java.io.InputStream#read() + */ + public int read() throws IOException { + try { + getNextPacketIfRequired(1); + } catch (IOException ioEx) { + return -1; + } + + return this.buffer[this.pos++] & 0xff; + } + + /** + * @see java.io.InputStream#read(byte) + */ + public int read(byte[] b) throws IOException { + return read(b, 0, b.length); + } + + /** + * @see java.io.InputStream#read(byte, int, int) + */ + public int read(byte[] b, int off, int len) throws IOException { + if (b == null) { + throw new NullPointerException(); + } else if ((off < 0) || (off > b.length) || (len < 0) + || ((off + len) > b.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } + + if (len <= 0) { + return 0; + } + + try { + getNextPacketIfRequired(len); + } catch (IOException ioEx) { + return -1; + } + + System.arraycopy(this.buffer, this.pos, b, off, len); + this.pos += len; + + return len; + } + + private final int readFully(byte[] b, int off, int len) throws IOException { + if (len < 0) { + throw new IndexOutOfBoundsException(); + } + + int n = 0; + + while (n < len) { + int count = this.in.read(b, off + n, len - n); + + if (count < 0) { + throw new EOFException(); + } + + n += count; + } + + return n; + } + + /** + * @see java.io.InputStream#skip(long) + */ + public long skip(long n) throws IOException { + long count = 0; + + for (long i = 0; i < n; i++) { + int bytesRead = read(); + + if (bytesRead == -1) { + break; + } + + count++; + } + + return count; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Connection.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Connection.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Connection.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,5994 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import com.mysql.jdbc.log.Log; +import com.mysql.jdbc.log.LogFactory; +import com.mysql.jdbc.log.NullLogger; +import com.mysql.jdbc.profiler.ProfileEventSink; +import com.mysql.jdbc.profiler.ProfilerEvent; +import com.mysql.jdbc.util.LRUCache; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.UnsupportedEncodingException; + +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.math.BigDecimal; + +import java.net.URL; + +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.ParameterMetaData; +import java.sql.Ref; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Savepoint; +import java.sql.Time; +import java.sql.Timestamp; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Stack; +import java.util.StringTokenizer; +import java.util.TimeZone; +import java.util.Timer; +import java.util.TreeMap; + +/** + * A Connection represents a session with a specific database. Within the + * context of a Connection, SQL statements are executed and results are + * returned. + *

+ * A Connection's database is able to provide information describing its tables, + * its supported SQL grammar, its stored procedures, the capabilities of this + * connection, etc. This information is obtained with the getMetaData method. + *

+ * + * @author Mark Matthews + * @version $Id: Connection.java,v 1.1 2012/08/17 14:57:10 marcin Exp $ + * @see java.sql.Connection + */ +public class Connection extends ConnectionProperties implements + java.sql.Connection { + private static final String JDBC_LOCAL_CHARACTER_SET_RESULTS = "jdbc.local.character_set_results"; + + /** + * Used as a key for caching callable statements which (may) depend on + * current catalog...In 5.0.x, they don't (currently), but stored procedure + * names soon will, so current catalog is a (hidden) component of the name. + */ + class CompoundCacheKey { + String componentOne; + + String componentTwo; + + int hashCode; + + CompoundCacheKey(String partOne, String partTwo) { + this.componentOne = partOne; + this.componentTwo = partTwo; + + // Handle first component (in most cases, currentCatalog) + // being NULL.... + this.hashCode = (((this.componentOne != null) ? this.componentOne + : "") + this.componentTwo).hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (obj instanceof CompoundCacheKey) { + CompoundCacheKey another = (CompoundCacheKey) obj; + + boolean firstPartEqual = false; + + if (this.componentOne == null) { + firstPartEqual = (another.componentOne == null); + } else { + firstPartEqual = this.componentOne + .equals(another.componentOne); + } + + return (firstPartEqual && this.componentTwo + .equals(another.componentTwo)); + } + + return false; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return this.hashCode; + } + } + + /** + * Wrapper class for UltraDev CallableStatements that are really + * PreparedStatments. Nice going, UltraDev developers. + */ + class UltraDevWorkAround implements java.sql.CallableStatement { + private java.sql.PreparedStatement delegate = null; + + UltraDevWorkAround(java.sql.PreparedStatement pstmt) { + this.delegate = pstmt; + } + + public void addBatch() throws SQLException { + this.delegate.addBatch(); + } + + public void addBatch(java.lang.String p1) throws SQLException { + this.delegate.addBatch(p1); + } + + public void cancel() throws SQLException { + this.delegate.cancel(); + } + + public void clearBatch() throws SQLException { + this.delegate.clearBatch(); + } + + public void clearParameters() throws SQLException { + this.delegate.clearParameters(); + } + + public void clearWarnings() throws SQLException { + this.delegate.clearWarnings(); + } + + public void close() throws SQLException { + this.delegate.close(); + } + + public boolean execute() throws SQLException { + return this.delegate.execute(); + } + + public boolean execute(java.lang.String p1) throws SQLException { + return this.delegate.execute(p1); + } + + /** + * @see Statement#execute(String, int) + */ + public boolean execute(String arg0, int arg1) throws SQLException { + return this.delegate.execute(arg0, arg1); + } + + /** + * @see Statement#execute(String, int[]) + */ + public boolean execute(String arg0, int[] arg1) throws SQLException { + return this.delegate.execute(arg0, arg1); + } + + /** + * @see Statement#execute(String, String[]) + */ + public boolean execute(String arg0, String[] arg1) throws SQLException { + return this.delegate.execute(arg0, arg1); + } + + public int[] executeBatch() throws SQLException { + return this.delegate.executeBatch(); + } + + public java.sql.ResultSet executeQuery() throws SQLException { + return this.delegate.executeQuery(); + } + + public java.sql.ResultSet executeQuery(java.lang.String p1) + throws SQLException { + return this.delegate.executeQuery(p1); + } + + public int executeUpdate() throws SQLException { + return this.delegate.executeUpdate(); + } + + public int executeUpdate(java.lang.String p1) throws SQLException { + return this.delegate.executeUpdate(p1); + } + + /** + * @see Statement#executeUpdate(String, int) + */ + public int executeUpdate(String arg0, int arg1) throws SQLException { + return this.delegate.executeUpdate(arg0, arg1); + } + + /** + * @see Statement#executeUpdate(String, int[]) + */ + public int executeUpdate(String arg0, int[] arg1) throws SQLException { + return this.delegate.executeUpdate(arg0, arg1); + } + + /** + * @see Statement#executeUpdate(String, String[]) + */ + public int executeUpdate(String arg0, String[] arg1) + throws SQLException { + return this.delegate.executeUpdate(arg0, arg1); + } + + public java.sql.Array getArray(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getArray(String) + */ + public java.sql.Array getArray(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public java.math.BigDecimal getBigDecimal(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * DOCUMENT ME! + * + * @param p1 + * DOCUMENT ME! + * @param p2 + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + * @deprecated + */ + public java.math.BigDecimal getBigDecimal(int p1, int p2) + throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getBigDecimal(String) + */ + public BigDecimal getBigDecimal(String arg0) throws SQLException { + return null; + } + + public java.sql.Blob getBlob(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getBlob(String) + */ + public java.sql.Blob getBlob(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public boolean getBoolean(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getBoolean(String) + */ + public boolean getBoolean(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public byte getByte(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getByte(String) + */ + public byte getByte(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public byte[] getBytes(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getBytes(String) + */ + public byte[] getBytes(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public java.sql.Clob getClob(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getClob(String) + */ + public Clob getClob(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public java.sql.Connection getConnection() throws SQLException { + return this.delegate.getConnection(); + } + + public java.sql.Date getDate(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public java.sql.Date getDate(int p1, final Calendar p2) + throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getDate(String) + */ + public Date getDate(String arg0) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#getDate(String, Calendar) + */ + public Date getDate(String arg0, Calendar arg1) throws SQLException { + throw new NotImplemented(); + } + + public double getDouble(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getDouble(String) + */ + public double getDouble(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public int getFetchDirection() throws SQLException { + return this.delegate.getFetchDirection(); + } + + public int getFetchSize() throws java.sql.SQLException { + return this.delegate.getFetchSize(); + } + + public float getFloat(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getFloat(String) + */ + public float getFloat(String arg0) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see Statement#getGeneratedKeys() + */ + public java.sql.ResultSet getGeneratedKeys() throws SQLException { + return this.delegate.getGeneratedKeys(); + } + + public int getInt(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getInt(String) + */ + public int getInt(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public long getLong(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getLong(String) + */ + public long getLong(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public int getMaxFieldSize() throws SQLException { + return this.delegate.getMaxFieldSize(); + } + + public int getMaxRows() throws SQLException { + return this.delegate.getMaxRows(); + } + + public java.sql.ResultSetMetaData getMetaData() throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public boolean getMoreResults() throws SQLException { + return this.delegate.getMoreResults(); + } + + /** + * @see Statement#getMoreResults(int) + */ + public boolean getMoreResults(int arg0) throws SQLException { + return this.delegate.getMoreResults(); + } + + public java.lang.Object getObject(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public java.lang.Object getObject(int p1, final java.util.Map p2) + throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getObject(String) + */ + public Object getObject(String arg0) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#getObject(String, Map) + */ + public Object getObject(String arg0, Map arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see PreparedStatement#getParameterMetaData() + */ + public ParameterMetaData getParameterMetaData() throws SQLException { + return this.delegate.getParameterMetaData(); + } + + public int getQueryTimeout() throws SQLException { + return this.delegate.getQueryTimeout(); + } + + public java.sql.Ref getRef(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getRef(String) + */ + public Ref getRef(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public java.sql.ResultSet getResultSet() throws SQLException { + return this.delegate.getResultSet(); + } + + public int getResultSetConcurrency() throws SQLException { + return this.delegate.getResultSetConcurrency(); + } + + /** + * @see Statement#getResultSetHoldability() + */ + public int getResultSetHoldability() throws SQLException { + return this.delegate.getResultSetHoldability(); + } + + public int getResultSetType() throws SQLException { + return this.delegate.getResultSetType(); + } + + public short getShort(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getShort(String) + */ + public short getShort(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public java.lang.String getString(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getString(String) + */ + public String getString(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public java.sql.Time getTime(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public java.sql.Time getTime(int p1, final java.util.Calendar p2) + throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getTime(String) + */ + public Time getTime(String arg0) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#getTime(String, Calendar) + */ + public Time getTime(String arg0, Calendar arg1) throws SQLException { + throw new NotImplemented(); + } + + public java.sql.Timestamp getTimestamp(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public java.sql.Timestamp getTimestamp(int p1, + final java.util.Calendar p2) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#getTimestamp(String) + */ + public Timestamp getTimestamp(String arg0) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#getTimestamp(String, Calendar) + */ + public Timestamp getTimestamp(String arg0, Calendar arg1) + throws SQLException { + throw new NotImplemented(); + } + + public int getUpdateCount() throws SQLException { + return this.delegate.getUpdateCount(); + } + + /** + * @see CallableStatement#getURL(int) + */ + public URL getURL(int arg0) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#getURL(String) + */ + public URL getURL(String arg0) throws SQLException { + throw new NotImplemented(); + } + + public java.sql.SQLWarning getWarnings() throws SQLException { + return this.delegate.getWarnings(); + } + + public void registerOutParameter(int p1, int p2) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public void registerOutParameter(int p1, int p2, int p3) + throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public void registerOutParameter(int p1, int p2, java.lang.String p3) + throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + /** + * @see CallableStatement#registerOutParameter(String, int) + */ + public void registerOutParameter(String arg0, int arg1) + throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#registerOutParameter(String, int, int) + */ + public void registerOutParameter(String arg0, int arg1, int arg2) + throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#registerOutParameter(String, int, String) + */ + public void registerOutParameter(String arg0, int arg1, String arg2) + throws SQLException { + throw new NotImplemented(); + } + + public void setArray(int p1, final java.sql.Array p2) + throws SQLException { + this.delegate.setArray(p1, p2); + } + + public void setAsciiStream(int p1, final java.io.InputStream p2, int p3) + throws SQLException { + this.delegate.setAsciiStream(p1, p2, p3); + } + + /** + * @see CallableStatement#setAsciiStream(String, InputStream, int) + */ + public void setAsciiStream(String arg0, InputStream arg1, int arg2) + throws SQLException { + throw new NotImplemented(); + } + + public void setBigDecimal(int p1, final java.math.BigDecimal p2) + throws SQLException { + this.delegate.setBigDecimal(p1, p2); + } + + /** + * @see CallableStatement#setBigDecimal(String, BigDecimal) + */ + public void setBigDecimal(String arg0, BigDecimal arg1) + throws SQLException { + throw new NotImplemented(); + } + + public void setBinaryStream(int p1, final java.io.InputStream p2, int p3) + throws SQLException { + this.delegate.setBinaryStream(p1, p2, p3); + } + + /** + * @see CallableStatement#setBinaryStream(String, InputStream, int) + */ + public void setBinaryStream(String arg0, InputStream arg1, int arg2) + throws SQLException { + throw new NotImplemented(); + } + + public void setBlob(int p1, final java.sql.Blob p2) throws SQLException { + this.delegate.setBlob(p1, p2); + } + + public void setBoolean(int p1, boolean p2) throws SQLException { + this.delegate.setBoolean(p1, p2); + } + + /** + * @see CallableStatement#setBoolean(String, boolean) + */ + public void setBoolean(String arg0, boolean arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setByte(int p1, byte p2) throws SQLException { + this.delegate.setByte(p1, p2); + } + + /** + * @see CallableStatement#setByte(String, byte) + */ + public void setByte(String arg0, byte arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setBytes(int p1, byte[] p2) throws SQLException { + this.delegate.setBytes(p1, p2); + } + + /** + * @see CallableStatement#setBytes(String, byte[]) + */ + public void setBytes(String arg0, byte[] arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setCharacterStream(int p1, final java.io.Reader p2, int p3) + throws SQLException { + this.delegate.setCharacterStream(p1, p2, p3); + } + + /** + * @see CallableStatement#setCharacterStream(String, Reader, int) + */ + public void setCharacterStream(String arg0, Reader arg1, int arg2) + throws SQLException { + throw new NotImplemented(); + } + + public void setClob(int p1, final java.sql.Clob p2) throws SQLException { + this.delegate.setClob(p1, p2); + } + + public void setCursorName(java.lang.String p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public void setDate(int p1, final java.sql.Date p2) throws SQLException { + this.delegate.setDate(p1, p2); + } + + public void setDate(int p1, final java.sql.Date p2, + final java.util.Calendar p3) throws SQLException { + this.delegate.setDate(p1, p2, p3); + } + + /** + * @see CallableStatement#setDate(String, Date) + */ + public void setDate(String arg0, Date arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#setDate(String, Date, Calendar) + */ + public void setDate(String arg0, Date arg1, Calendar arg2) + throws SQLException { + throw new NotImplemented(); + } + + public void setDouble(int p1, double p2) throws SQLException { + this.delegate.setDouble(p1, p2); + } + + /** + * @see CallableStatement#setDouble(String, double) + */ + public void setDouble(String arg0, double arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setEscapeProcessing(boolean p1) throws SQLException { + this.delegate.setEscapeProcessing(p1); + } + + public void setFetchDirection(int p1) throws SQLException { + this.delegate.setFetchDirection(p1); + } + + public void setFetchSize(int p1) throws SQLException { + this.delegate.setFetchSize(p1); + } + + public void setFloat(int p1, float p2) throws SQLException { + this.delegate.setFloat(p1, p2); + } + + /** + * @see CallableStatement#setFloat(String, float) + */ + public void setFloat(String arg0, float arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setInt(int p1, int p2) throws SQLException { + this.delegate.setInt(p1, p2); + } + + /** + * @see CallableStatement#setInt(String, int) + */ + public void setInt(String arg0, int arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setLong(int p1, long p2) throws SQLException { + this.delegate.setLong(p1, p2); + } + + /** + * @see CallableStatement#setLong(String, long) + */ + public void setLong(String arg0, long arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setMaxFieldSize(int p1) throws SQLException { + this.delegate.setMaxFieldSize(p1); + } + + public void setMaxRows(int p1) throws SQLException { + this.delegate.setMaxRows(p1); + } + + public void setNull(int p1, int p2) throws SQLException { + this.delegate.setNull(p1, p2); + } + + public void setNull(int p1, int p2, java.lang.String p3) + throws SQLException { + this.delegate.setNull(p1, p2, p3); + } + + /** + * @see CallableStatement#setNull(String, int) + */ + public void setNull(String arg0, int arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#setNull(String, int, String) + */ + public void setNull(String arg0, int arg1, String arg2) + throws SQLException { + throw new NotImplemented(); + } + + public void setObject(int p1, final java.lang.Object p2) + throws SQLException { + this.delegate.setObject(p1, p2); + } + + public void setObject(int p1, final java.lang.Object p2, int p3) + throws SQLException { + this.delegate.setObject(p1, p2, p3); + } + + public void setObject(int p1, final java.lang.Object p2, int p3, int p4) + throws SQLException { + this.delegate.setObject(p1, p2, p3, p4); + } + + /** + * @see CallableStatement#setObject(String, Object) + */ + public void setObject(String arg0, Object arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#setObject(String, Object, int) + */ + public void setObject(String arg0, Object arg1, int arg2) + throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#setObject(String, Object, int, int) + */ + public void setObject(String arg0, Object arg1, int arg2, int arg3) + throws SQLException { + throw new NotImplemented(); + } + + public void setQueryTimeout(int p1) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public void setRef(int p1, final Ref p2) throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + + public void setShort(int p1, short p2) throws SQLException { + this.delegate.setShort(p1, p2); + } + + /** + * @see CallableStatement#setShort(String, short) + */ + public void setShort(String arg0, short arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setString(int p1, java.lang.String p2) + throws java.sql.SQLException { + this.delegate.setString(p1, p2); + } + + /** + * @see CallableStatement#setString(String, String) + */ + public void setString(String arg0, String arg1) throws SQLException { + throw new NotImplemented(); + } + + public void setTime(int p1, final java.sql.Time p2) throws SQLException { + this.delegate.setTime(p1, p2); + } + + public void setTime(int p1, final java.sql.Time p2, + final java.util.Calendar p3) throws SQLException { + this.delegate.setTime(p1, p2, p3); + } + + /** + * @see CallableStatement#setTime(String, Time) + */ + public void setTime(String arg0, Time arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#setTime(String, Time, Calendar) + */ + public void setTime(String arg0, Time arg1, Calendar arg2) + throws SQLException { + throw new NotImplemented(); + } + + public void setTimestamp(int p1, final java.sql.Timestamp p2) + throws SQLException { + this.delegate.setTimestamp(p1, p2); + } + + public void setTimestamp(int p1, final java.sql.Timestamp p2, + final java.util.Calendar p3) throws SQLException { + this.delegate.setTimestamp(p1, p2, p3); + } + + /** + * @see CallableStatement#setTimestamp(String, Timestamp) + */ + public void setTimestamp(String arg0, Timestamp arg1) + throws SQLException { + throw new NotImplemented(); + } + + /** + * @see CallableStatement#setTimestamp(String, Timestamp, Calendar) + */ + public void setTimestamp(String arg0, Timestamp arg1, Calendar arg2) + throws SQLException { + throw new NotImplemented(); + } + + /** + * DOCUMENT ME! + * + * @param p1 + * DOCUMENT ME! + * @param p2 + * DOCUMENT ME! + * @param p3 + * DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + * @deprecated + */ + public void setUnicodeStream(int p1, final java.io.InputStream p2, + int p3) throws SQLException { + this.delegate.setUnicodeStream(p1, p2, p3); + } + + /** + * @see PreparedStatement#setURL(int, URL) + */ + public void setURL(int arg0, URL arg1) throws SQLException { + this.delegate.setURL(arg0, arg1); + } + + /** + * @see CallableStatement#setURL(String, URL) + */ + public void setURL(String arg0, URL arg1) throws SQLException { + throw new NotImplemented(); + } + + public boolean wasNull() throws SQLException { + throw SQLError.createSQLException("Not supported"); + } + } + + /** + * Marker for character set converter not being available (not written, + * multibyte, etc) Used to prevent multiple instantiation requests. + */ + private static final Object CHARSET_CONVERTER_NOT_AVAILABLE_MARKER = new Object(); + + /** + * The mapping between MySQL charset names and Java charset names. + * Initialized by loadCharacterSetMapping() + */ + public static Map charsetMap; + + /** Default logger class name */ + protected static final String DEFAULT_LOGGER_CLASS = "com.mysql.jdbc.log.StandardLogger"; + + private final static int HISTOGRAM_BUCKETS = 20; + + /** Logger instance name */ + private static final String LOGGER_INSTANCE_NAME = "MySQL"; + + /** + * Map mysql transaction isolation level name to + * java.sql.Connection.TRANSACTION_XXX + */ + private static Map mapTransIsolationNameToValue = null; + + /** Null logger shared by all connections at startup */ + private static final Log NULL_LOGGER = new NullLogger(LOGGER_INSTANCE_NAME); + + private static Map roundRobinStatsMap; + + private static final Map serverCollationByUrl = new HashMap(); + + private static final Map serverConfigByUrl = new HashMap(); + + private static Timer cancelTimer; + + static { + mapTransIsolationNameToValue = new HashMap(8); + mapTransIsolationNameToValue.put("READ-UNCOMMITED", new Integer( + TRANSACTION_READ_UNCOMMITTED)); + mapTransIsolationNameToValue.put("READ-UNCOMMITTED", new Integer( + TRANSACTION_READ_UNCOMMITTED)); + mapTransIsolationNameToValue.put("READ-COMMITTED", new Integer( + TRANSACTION_READ_COMMITTED)); + mapTransIsolationNameToValue.put("REPEATABLE-READ", new Integer( + TRANSACTION_REPEATABLE_READ)); + mapTransIsolationNameToValue.put("SERIALIZABLE", new Integer( + TRANSACTION_SERIALIZABLE)); + + boolean createdNamedTimer = false; + + // Use reflection magic to try this on JDK's 1.5 and newer, fallback to non-named + // timer on older VMs. + try { + Constructor ctr = Timer.class.getConstructor(new Class[] {String.class, Boolean.TYPE}); + + cancelTimer = (Timer)ctr.newInstance(new Object[] { "MySQL Statement Cancellation Timer", Boolean.TRUE}); + createdNamedTimer = true; + } catch (Throwable t) { + createdNamedTimer = false; + } + + if (!createdNamedTimer) { + cancelTimer = new Timer(true); + } + } + + protected static SQLException appendMessageToException(SQLException sqlEx, + String messageToAppend) { + String origMessage = sqlEx.getMessage(); + String sqlState = sqlEx.getSQLState(); + int vendorErrorCode = sqlEx.getErrorCode(); + + StringBuffer messageBuf = new StringBuffer(origMessage.length() + + messageToAppend.length()); + messageBuf.append(origMessage); + messageBuf.append(messageToAppend); + + SQLException sqlExceptionWithNewMessage = SQLError.createSQLException(messageBuf + .toString(), sqlState, vendorErrorCode); + + // + // Try and maintain the original stack trace, + // only works on JDK-1.4 and newer + // + + try { + // Have to do this with reflection, otherwise older JVMs croak + Method getStackTraceMethod = null; + Method setStackTraceMethod = null; + Object theStackTraceAsObject = null; + + Class stackTraceElementClass = Class + .forName("java.lang.StackTraceElement"); + Class stackTraceElementArrayClass = Array.newInstance( + stackTraceElementClass, new int[] { 0 }).getClass(); + + getStackTraceMethod = Throwable.class.getMethod("getStackTrace", + new Class[] {}); + + setStackTraceMethod = Throwable.class.getMethod("setStackTrace", + new Class[] { stackTraceElementArrayClass }); + + if (getStackTraceMethod != null && setStackTraceMethod != null) { + theStackTraceAsObject = getStackTraceMethod.invoke(sqlEx, + new Object[0]); + setStackTraceMethod.invoke(sqlExceptionWithNewMessage, + new Object[] { theStackTraceAsObject }); + } + } catch (NoClassDefFoundError noClassDefFound) { + + } catch (NoSuchMethodException noSuchMethodEx) { + + } catch (Throwable catchAll) { + + } + + return sqlExceptionWithNewMessage; + } + + protected static Timer getCancelTimer() { + return cancelTimer; + } + + private static synchronized int getNextRoundRobinHostIndex(String url, + List hostList) { + if (roundRobinStatsMap == null) { + roundRobinStatsMap = new HashMap(); + } + + int[] index = (int[]) roundRobinStatsMap.get(url); + + if (index == null) { + index = new int[1]; + index[0] = -1; + + roundRobinStatsMap.put(url, index); + } + + index[0]++; + + if (index[0] >= hostList.size()) { + index[0] = 0; + } + + return index[0]; + } + + private static boolean nullSafeCompare(String s1, String s2) { + if (s1 == null && s2 == null) { + return true; + } + + if (s1 == null && s2 != null) { + return false; + } + + return s1.equals(s2); + } + + /** Are we in autoCommit mode? */ + private boolean autoCommit = true; + + /** A map of SQL to parsed prepared statement parameters. */ + private Map cachedPreparedStatementParams; + + /** + * For servers > 4.1.0, what character set is the metadata returned in? + */ + private String characterSetMetadata = null; + + /** + * The character set we want results and result metadata returned in (null == + * results in any charset, metadata in UTF-8). + */ + private String characterSetResultsOnServer = null; + + /** + * Holds cached mappings to charset converters to avoid static + * synchronization and at the same time save memory (each charset converter + * takes approx 65K of static data). + */ + private Map charsetConverterMap = new HashMap(CharsetMapping + .getNumberOfCharsetsConfigured()); + + /** + * The mapping between MySQL charset names and the max number of chars in + * them. Lazily instantiated via getMaxBytesPerChar(). + */ + private Map charsetToNumBytesMap; + + /** The point in time when this connection was created */ + private long connectionCreationTimeMillis = 0; + + /** ID used when profiling */ + private long connectionId; + + /** The database we're currently using (called Catalog in JDBC terms). */ + private String database = null; + + /** Internal DBMD to use for various database-version specific features */ + private DatabaseMetaData dbmd = null; + + private TimeZone defaultTimeZone; + + /** The event sink to use for profiling */ + private ProfileEventSink eventSink; + + private boolean executingFailoverReconnect = false; + + /** Are we failed-over to a non-master host */ + private boolean failedOver = false; + + /** Why was this connection implicitly closed, if known? (for diagnostics) */ + private Throwable forceClosedReason; + + /** Where was this connection implicitly closed? (for diagnostics) */ + private Throwable forcedClosedLocation; + + /** Does the server suuport isolation levels? */ + private boolean hasIsolationLevels = false; + + /** Does this version of MySQL support quoted identifiers? */ + private boolean hasQuotedIdentifiers = false; + + /** The hostname we're connected to */ + private String host = null; + + /** The list of host(s) to try and connect to */ + private List hostList = null; + + /** How many hosts are in the host list? */ + private int hostListSize = 0; + + /** + * We need this 'bootstrapped', because 4.1 and newer will send fields back + * with this even before we fill this dynamically from the server. + */ + private String[] indexToCharsetMapping = CharsetMapping.INDEX_TO_CHARSET; + + /** The I/O abstraction interface (network conn to MySQL server */ + private MysqlIO io = null; + + private boolean isClientTzUTC = false; + + /** Has this connection been closed? */ + private boolean isClosed = true; + + /** Is this connection associated with a global tx? */ + private boolean isInGlobalTx = false; + + /** Is this connection running inside a JDK-1.3 VM? */ + private boolean isRunningOnJDK13 = false; + + /** isolation level */ + private int isolationLevel = java.sql.Connection.TRANSACTION_READ_COMMITTED; + + private boolean isServerTzUTC = false; + + /** When did the last query finish? */ + private long lastQueryFinishedTime = 0; + + /** The logger we're going to use */ + private Log log = NULL_LOGGER; + + /** + * If gathering metrics, what was the execution time of the longest query so + * far ? + */ + private long longestQueryTimeMs = 0; + + /** Is the server configured to use lower-case table names only? */ + private boolean lowerCaseTableNames = false; + + /** When did the master fail? */ + private long masterFailTimeMillis = 0L; + + /** + * The largest packet we can send (changed once we know what the server + * supports, we get this at connection init). + */ + private int maxAllowedPacket = 65536; + + private long maximumNumberTablesAccessed = 0; + + /** Has the max-rows setting been changed from the default? */ + private boolean maxRowsChanged = false; + + /** When was the last time we reported metrics? */ + private long metricsLastReportedMs; + + private long minimumNumberTablesAccessed = Long.MAX_VALUE; + + /** Mutex */ + private final Object mutex = new Object(); + + /** The JDBC URL we're using */ + private String myURL = null; + + /** Does this connection need to be tested? */ + private boolean needsPing = false; + + private int netBufferLength = 16384; + + private boolean noBackslashEscapes = false; + + private long numberOfPreparedExecutes = 0; + + private long numberOfPrepares = 0; + + private long numberOfQueriesIssued = 0; + + private long numberOfResultSetsCreated = 0; + + private long[] numTablesMetricsHistBreakpoints; + + private int[] numTablesMetricsHistCounts; + + private long[] oldHistBreakpoints = null; + + private int[] oldHistCounts = null; + + /** A map of currently open statements */ + private Map openStatements; + + private LRUCache parsedCallableStatementCache; + + private boolean parserKnowsUnicode = false; + + /** The password we used */ + private String password = null; + + private long[] perfMetricsHistBreakpoints; + + private int[] perfMetricsHistCounts; + + /** Point of origin where this Connection was created */ + private Throwable pointOfOrigin; + + /** The port number we're connected to (defaults to 3306) */ + private int port = 3306; + + /** + * Used only when testing failover functionality for regressions, causes the + * failover code to not retry the master first + */ + private boolean preferSlaveDuringFailover = false; + + /** Properties for this connection specified by user */ + private Properties props = null; + + /** Number of queries we've issued since the master failed */ + private long queriesIssuedFailedOver = 0; + + /** Should we retrieve 'info' messages from the server? */ + private boolean readInfoMsg = false; + + /** Are we in read-only mode? */ + private boolean readOnly = false; + + /** Cache of ResultSet metadata */ + protected LRUCache resultSetMetadataCache; + + /** The timezone of the server */ + private TimeZone serverTimezoneTZ = null; + + /** The map of server variables that we retrieve at connection init. */ + private Map serverVariables = null; + + private long shortestQueryTimeMs = Long.MAX_VALUE; + + /** A map of statements that have had setMaxRows() called on them */ + private Map statementsUsingMaxRows; + + private double totalQueryTimeMs = 0; + + /** Are transactions supported by the MySQL server we are connected to? */ + private boolean transactionsSupported = false; + + /** + * The type map for UDTs (not implemented, but used by some third-party + * vendors, most notably IBM WebSphere) + */ + private Map typeMap; + + /** Has ANSI_QUOTES been enabled on the server? */ + private boolean useAnsiQuotes = false; + + /** The user we're connected as */ + private String user = null; + + /** + * Should we use server-side prepared statements? (auto-detected, but can be + * disabled by user) + */ + private boolean useServerPreparedStmts = false; + + private LRUCache serverSideStatementCheckCache; + + private LRUCache serverSideStatementCache; + private Calendar sessionCalendar; + private Calendar utcCalendar; + + private String origHostToConnectTo; + + private int origPortToConnectTo; + + // we don't want to be able to publicly clone this... + + private String origDatabaseToConnectTo; + + private String errorMessageEncoding = "Cp1252"; // to begin with, changes after we talk to the server + + private boolean usePlatformCharsetConverters; + + + /** + * Creates a connection to a MySQL Server. + * + * @param hostToConnectTo + * the hostname of the database server + * @param portToConnectTo + * the port number the server is listening on + * @param info + * a Properties[] list holding the user and password + * @param databaseToConnectTo + * the database to connect to + * @param url + * the URL of the connection + * @param d + * the Driver instantation of the connection + * @exception SQLException + * if a database access error occurs + */ + Connection(String hostToConnectTo, int portToConnectTo, Properties info, + String databaseToConnectTo, String url) + throws SQLException { + this.charsetToNumBytesMap = new HashMap(); + + this.connectionCreationTimeMillis = System.currentTimeMillis(); + this.pointOfOrigin = new Throwable(); + + // Stash away for later, used to clone this connection for Statement.cancel + // and Statement.setQueryTimeout(). + // + + this.origHostToConnectTo = hostToConnectTo; + this.origPortToConnectTo = portToConnectTo; + this.origDatabaseToConnectTo = databaseToConnectTo; + + try { + Blob.class.getMethod("truncate", new Class[] {Long.TYPE}); + + this.isRunningOnJDK13 = false; + } catch (NoSuchMethodException nsme) { + this.isRunningOnJDK13 = true; + } + + this.sessionCalendar = new GregorianCalendar(); + this.utcCalendar = new GregorianCalendar(); + this.utcCalendar.setTimeZone(TimeZone.getTimeZone("GMT")); + + // + // Normally, this code would be in initializeDriverProperties, + // but we need to do this as early as possible, so we can start + // logging to the 'correct' place as early as possible...this.log + // points to 'NullLogger' for every connection at startup to avoid + // NPEs and the overhead of checking for NULL at every logging call. + // + // We will reset this to the configured logger during properties + // initialization. + // + this.log = LogFactory.getLogger(getLogger(), LOGGER_INSTANCE_NAME); + + // We store this per-connection, due to static synchronization + // issues in Java's built-in TimeZone class... + this.defaultTimeZone = Util.getDefaultTimeZone(); + + if ("GMT".equalsIgnoreCase(this.defaultTimeZone.getID())) { + this.isClientTzUTC = true; + } else { + this.isClientTzUTC = false; + } + + this.openStatements = new HashMap(); + this.serverVariables = new HashMap(); + this.hostList = new ArrayList(); + + if (hostToConnectTo == null) { + this.host = "localhost"; + this.hostList.add(this.host); + } else if (hostToConnectTo.indexOf(",") != -1) { + // multiple hosts separated by commas (failover) + StringTokenizer hostTokenizer = new StringTokenizer( + hostToConnectTo, ",", false); + + while (hostTokenizer.hasMoreTokens()) { + this.hostList.add(hostTokenizer.nextToken().trim()); + } + } else { + this.host = hostToConnectTo; + this.hostList.add(this.host); + } + + this.hostListSize = this.hostList.size(); + this.port = portToConnectTo; + + if (databaseToConnectTo == null) { + databaseToConnectTo = ""; + } + + this.database = databaseToConnectTo; + this.myURL = url; + this.user = info.getProperty(NonRegisteringDriver.USER_PROPERTY_KEY); + this.password = info + .getProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY); + + if ((this.user == null) || this.user.equals("")) { + this.user = ""; + } + + if (this.password == null) { + this.password = ""; + } + + this.props = info; + initializeDriverProperties(info); + + try { + createNewIO(false); + this.dbmd = new DatabaseMetaData(this, this.database); + } catch (SQLException ex) { + cleanup(ex); + + // don't clobber SQL exceptions + throw ex; + } catch (Exception ex) { + cleanup(ex); + + StringBuffer mesg = new StringBuffer(); + + if (getParanoid()) { + mesg.append("Cannot connect to MySQL server on "); + mesg.append(this.host); + mesg.append(":"); + mesg.append(this.port); + mesg.append(".\n\n"); + mesg.append("Make sure that there is a MySQL server "); + mesg.append("running on the machine/port you are trying "); + mesg + .append("to connect to and that the machine this software is " + + "running on "); + mesg.append("is able to connect to this host/port " + + "(i.e. not firewalled). "); + mesg + .append("Also make sure that the server has not been started " + + "with the --skip-networking "); + mesg.append("flag.\n\n"); + } else { + mesg.append("Unable to connect to database."); + } + + mesg.append("Underlying exception: \n\n"); + mesg.append(ex.getClass().getName()); + + if (!getParanoid()) { + mesg.append(Util.stackTraceToString(ex)); + } + + throw SQLError.createSQLException(mesg.toString(), + SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE); + } + } + + private void addToHistogram(int[] histogramCounts, + long[] histogramBreakpoints, long value, int numberOfTimes, + long currentLowerBound, long currentUpperBound) { + if (histogramCounts == null) { + createInitialHistogram(histogramBreakpoints, + currentLowerBound, currentUpperBound); + } + + for (int i = 0; i < HISTOGRAM_BUCKETS; i++) { + if (histogramBreakpoints[i] >= value) { + histogramCounts[i] += numberOfTimes; + + break; + } + } + } + + private void addToPerformanceHistogram(long value, int numberOfTimes) { + checkAndCreatePerformanceHistogram(); + + addToHistogram(this.perfMetricsHistCounts, + this.perfMetricsHistBreakpoints, value, numberOfTimes, + this.shortestQueryTimeMs == Long.MAX_VALUE ? 0 + : this.shortestQueryTimeMs, this.longestQueryTimeMs); + } + + private void addToTablesAccessedHistogram(long value, int numberOfTimes) { + checkAndCreateTablesAccessedHistogram(); + + addToHistogram(this.numTablesMetricsHistCounts, + this.numTablesMetricsHistBreakpoints, value, numberOfTimes, + this.minimumNumberTablesAccessed == Long.MAX_VALUE ? 0 + : this.minimumNumberTablesAccessed, + this.maximumNumberTablesAccessed); + } + + /** + * Builds the map needed for 4.1.0 and newer servers that maps field-level + * charset/collation info to a java character encoding name. + * + * @throws SQLException + * DOCUMENT ME! + */ + private void buildCollationMapping() throws SQLException { + if (versionMeetsMinimum(4, 1, 0)) { + + TreeMap sortedCollationMap = null; + + if (getCacheServerConfiguration()) { + synchronized (serverConfigByUrl) { + sortedCollationMap = (TreeMap) serverCollationByUrl + .get(getURL()); + } + } + + com.mysql.jdbc.Statement stmt = null; + com.mysql.jdbc.ResultSet results = null; + + try { + if (sortedCollationMap == null) { + sortedCollationMap = new TreeMap(); + + stmt = (com.mysql.jdbc.Statement) createStatement(); + + if (stmt.getMaxRows() != 0) { + stmt.setMaxRows(0); + } + + results = (com.mysql.jdbc.ResultSet) stmt + .executeQuery("SHOW COLLATION"); + + while (results.next()) { + String charsetName = results.getString(2); + Integer charsetIndex = new Integer(results.getInt(3)); + + sortedCollationMap.put(charsetIndex, charsetName); + } + + if (getCacheServerConfiguration()) { + synchronized (serverConfigByUrl) { + serverCollationByUrl.put(getURL(), + sortedCollationMap); + } + } + + } + + // Now, merge with what we already know + int highestIndex = ((Integer) sortedCollationMap.lastKey()) + .intValue(); + + if (CharsetMapping.INDEX_TO_CHARSET.length > highestIndex) { + highestIndex = CharsetMapping.INDEX_TO_CHARSET.length; + } + + this.indexToCharsetMapping = new String[highestIndex + 1]; + + for (int i = 0; i < CharsetMapping.INDEX_TO_CHARSET.length; i++) { + this.indexToCharsetMapping[i] = CharsetMapping.INDEX_TO_CHARSET[i]; + } + + for (Iterator indexIter = sortedCollationMap.entrySet() + .iterator(); indexIter.hasNext();) { + Map.Entry indexEntry = (Map.Entry) indexIter.next(); + + String mysqlCharsetName = (String) indexEntry.getValue(); + + this.indexToCharsetMapping[((Integer) indexEntry.getKey()) + .intValue()] = CharsetMapping + .getJavaEncodingForMysqlEncoding(mysqlCharsetName, + this); + } + } catch (java.sql.SQLException e) { + throw e; + } finally { + if (results != null) { + try { + results.close(); + } catch (java.sql.SQLException sqlE) { + ; + } + } + + if (stmt != null) { + try { + stmt.close(); + } catch (java.sql.SQLException sqlE) { + ; + } + } + } + } else { + // Safety, we already do this as an initializer, but this makes + // the intent more clear + this.indexToCharsetMapping = CharsetMapping.INDEX_TO_CHARSET; + } + } + + private boolean canHandleAsServerPreparedStatement(String sql) + throws SQLException { + if (sql == null || sql.length() == 0) { + return true; + } + + if (getCachePreparedStatements()) { + synchronized (this.serverSideStatementCheckCache) { + Boolean flag = (Boolean)this.serverSideStatementCheckCache.get(sql); + + if (flag != null) { + return flag.booleanValue(); + } + + boolean canHandle = canHandleAsServerPreparedStatementNoCache(sql); + + if (sql.length() < getPreparedStatementCacheSqlLimit()) { + this.serverSideStatementCheckCache.put(sql, + canHandle ? Boolean.TRUE : Boolean.FALSE); + } + + return canHandle; + } + } + + return canHandleAsServerPreparedStatementNoCache(sql); + } + + private boolean canHandleAsServerPreparedStatementNoCache(String sql) + throws SQLException { + + // Can't use server-side prepare for CALL + if (StringUtils.startsWithIgnoreCaseAndNonAlphaNumeric(sql, "CALL")) { + return false; + } + + boolean canHandleAsStatement = true; + + if (!versionMeetsMinimum(5, 0, 7) && + (StringUtils.startsWithIgnoreCaseAndNonAlphaNumeric(sql, "SELECT") + || StringUtils.startsWithIgnoreCaseAndNonAlphaNumeric(sql, + "DELETE") + || StringUtils.startsWithIgnoreCaseAndNonAlphaNumeric(sql, + "INSERT") + || StringUtils.startsWithIgnoreCaseAndNonAlphaNumeric(sql, + "UPDATE") + || StringUtils.startsWithIgnoreCaseAndNonAlphaNumeric(sql, + "REPLACE"))) { + + // check for limit ?[,?] + + /* + * The grammar for this (from the server) is: ULONG_NUM | ULONG_NUM + * ',' ULONG_NUM | ULONG_NUM OFFSET_SYM ULONG_NUM + */ + + int currentPos = 0; + int statementLength = sql.length(); + int lastPosToLook = statementLength - 7; // "LIMIT ".length() + boolean allowBackslashEscapes = !this.noBackslashEscapes; + char quoteChar = this.useAnsiQuotes ? '"' : '\''; + boolean foundLimitWithPlaceholder = false; + + while (currentPos < lastPosToLook) { + int limitStart = StringUtils.indexOfIgnoreCaseRespectQuotes( + currentPos, sql, "LIMIT ", quoteChar, + allowBackslashEscapes); + + if (limitStart == -1) { + break; + } + + currentPos = limitStart + 7; + + while (currentPos < statementLength) { + char c = sql.charAt(currentPos); + + // + // Have we reached the end + // of what can be in a LIMIT clause? + // + + if (!Character.isDigit(c) && !Character.isWhitespace(c) + && c != ',' && c != '?') { + break; + } + + if (c == '?') { + foundLimitWithPlaceholder = true; + break; + } + + currentPos++; + } + } + + canHandleAsStatement = !foundLimitWithPlaceholder; + } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "CREATE TABLE")) { + canHandleAsStatement = false; + } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "DO")) { + canHandleAsStatement = false; + } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "SET")) { + canHandleAsStatement = false; + } + + + + return canHandleAsStatement; + } + + /** + * Changes the user on this connection by performing a re-authentication. If + * authentication fails, the connection will remain under the context of the + * current user. + * + * @param userName + * the username to authenticate with + * @param newPassword + * the password to authenticate with + * @throws SQLException + * if authentication fails, or some other error occurs while + * performing the command. + */ + public void changeUser(String userName, String newPassword) + throws SQLException { + if ((userName == null) || userName.equals("")) { + userName = ""; + } + + if (newPassword == null) { + newPassword = ""; + } + + this.io.changeUser(userName, newPassword, this.database); + this.user = userName; + this.password = newPassword; + + if (versionMeetsMinimum(4, 1, 0)) { + configureClientCharacterSet(); + } + + setupServerForTruncationChecks(); + } + + private void checkAndCreatePerformanceHistogram() { + if (this.perfMetricsHistCounts == null) { + this.perfMetricsHistCounts = new int[HISTOGRAM_BUCKETS]; + } + + if (this.perfMetricsHistBreakpoints == null) { + this.perfMetricsHistBreakpoints = new long[HISTOGRAM_BUCKETS]; + } + } + + private void checkAndCreateTablesAccessedHistogram() { + if (this.numTablesMetricsHistCounts == null) { + this.numTablesMetricsHistCounts = new int[HISTOGRAM_BUCKETS]; + } + + if (this.numTablesMetricsHistBreakpoints == null) { + this.numTablesMetricsHistBreakpoints = new long[HISTOGRAM_BUCKETS]; + } + } + + private void checkClosed() throws SQLException { + if (this.isClosed) { + StringBuffer messageBuf = new StringBuffer( + "No operations allowed after connection closed."); + + if (this.forcedClosedLocation != null || this.forceClosedReason != null) { + messageBuf + .append("Connection was implicitly closed "); + } + + if (this.forcedClosedLocation != null) { + messageBuf.append("\n\n"); + messageBuf + .append(" at (stack trace):\n"); + messageBuf.append(Util + .stackTraceToString(this.forcedClosedLocation)); + } + + if (this.forceClosedReason != null) { + if (this.forcedClosedLocation != null) { + messageBuf.append("\n\nDue "); + } else { + messageBuf.append("due "); + } + + messageBuf.append("to underlying exception/error:\n"); + messageBuf.append(Util + .stackTraceToString(this.forceClosedReason)); + } + + throw SQLError.createSQLException(messageBuf.toString(), + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); + } + } + + /** + * If useUnicode flag is set and explicit client character encoding isn't + * specified then assign encoding from server if any. + * + * @throws SQLException + * DOCUMENT ME! + */ + private void checkServerEncoding() throws SQLException { + if (getUseUnicode() && (getEncoding() != null)) { + // spec'd by client, don't map + return; + } + + String serverEncoding = (String) this.serverVariables + .get("character_set"); + + if (serverEncoding == null) { + // must be 4.1.1 or newer? + serverEncoding = (String) this.serverVariables + .get("character_set_server"); + } + + String mappedServerEncoding = null; + + if (serverEncoding != null) { + mappedServerEncoding = CharsetMapping + .getJavaEncodingForMysqlEncoding(serverEncoding + .toUpperCase(Locale.ENGLISH), this); + } + + // + // First check if we can do the encoding ourselves + // + if (!getUseUnicode() && (mappedServerEncoding != null)) { + SingleByteCharsetConverter converter = getCharsetConverter(mappedServerEncoding); + + if (converter != null) { // we know how to convert this ourselves + setUseUnicode(true); // force the issue + setEncoding(mappedServerEncoding); + + return; + } + } + + // + // Now, try and find a Java I/O converter that can do + // the encoding for us + // + if (serverEncoding != null) { + if (mappedServerEncoding == null) { + // We don't have a mapping for it, so try + // and canonicalize the name.... + if (Character.isLowerCase(serverEncoding.charAt(0))) { + char[] ach = serverEncoding.toCharArray(); + ach[0] = Character.toUpperCase(serverEncoding.charAt(0)); + setEncoding(new String(ach)); + } + } + + if (mappedServerEncoding == null) { + throw SQLError.createSQLException("Unknown character encoding on server '" + + serverEncoding + + "', use 'characterEncoding=' property " + + " to provide correct mapping", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + + // + // Attempt to use the encoding, and bail out if it + // can't be used + // + try { + "abc".getBytes(mappedServerEncoding); + setEncoding(mappedServerEncoding); + setUseUnicode(true); + } catch (UnsupportedEncodingException UE) { + throw SQLError.createSQLException( + "The driver can not map the character encoding '" + + getEncoding() + + "' that your server is using " + + "to a character encoding your JVM understands. You " + + "can specify this mapping manually by adding \"useUnicode=true\" " + + "as well as \"characterEncoding=[an_encoding_your_jvm_understands]\" " + + "to your JDBC URL.", "0S100"); + } + } + } + + /** + * Set transaction isolation level to the value received from server if any. + * Is called by connectionInit(...) + * + * @throws SQLException + * DOCUMENT ME! + */ + private void checkTransactionIsolationLevel() throws SQLException { + String txIsolationName = null; + + if (versionMeetsMinimum(4, 0, 3)) { + txIsolationName = "tx_isolation"; + } else { + txIsolationName = "transaction_isolation"; + } + + String s = (String) this.serverVariables.get(txIsolationName); + + if (s != null) { + Integer intTI = (Integer) mapTransIsolationNameToValue.get(s); + + if (intTI != null) { + this.isolationLevel = intTI.intValue(); + } + } + } + + /** + * Destroys this connection and any underlying resources + * + * @param fromWhere + * DOCUMENT ME! + * @param whyCleanedUp + * DOCUMENT ME! + */ + private void cleanup(Throwable whyCleanedUp) { + try { + if ((this.io != null) && !isClosed()) { + realClose(false, false, false, whyCleanedUp); + } else if (this.io != null) { + this.io.forceClose(); + } + } catch (SQLException sqlEx) { + // ignore, we're going away. + ; + } + + this.isClosed = true; + } + + /** + * After this call, getWarnings returns null until a new warning is reported + * for this connection. + * + * @exception SQLException + * if a database access error occurs + */ + public void clearWarnings() throws SQLException { + // firstWarning = null; + } + + /** + * DOCUMENT ME! + * + * @param sql + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public PreparedStatement clientPrepareStatement(String sql) + throws SQLException { + return clientPrepareStatement(sql, + java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, + java.sql.ResultSet.CONCUR_READ_ONLY); + } + + /** + * @see Connection#prepareStatement(String, int) + */ + public java.sql.PreparedStatement clientPrepareStatement(String sql, + int autoGenKeyIndex) throws SQLException { + java.sql.PreparedStatement pStmt = clientPrepareStatement(sql); + + ((com.mysql.jdbc.PreparedStatement) pStmt) + .setRetrieveGeneratedKeys(autoGenKeyIndex == java.sql.Statement.RETURN_GENERATED_KEYS); + + return pStmt; + } + + /** + * DOCUMENT ME! + * + * @param sql + * DOCUMENT ME! + * @param resultSetType + * DOCUMENT ME! + * @param resultSetConcurrency + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public PreparedStatement clientPrepareStatement(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException { + return clientPrepareStatement(sql, resultSetType, resultSetConcurrency, true); + } + + protected PreparedStatement clientPrepareStatement(String sql, + int resultSetType, int resultSetConcurrency, + boolean processEscapeCodesIfNeeded) throws SQLException { + checkClosed(); + + String nativeSql = processEscapeCodesIfNeeded && getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql; + + PreparedStatement pStmt = null; + + if (getCachePreparedStatements()) { + synchronized (this.cachedPreparedStatementParams) { + PreparedStatement.ParseInfo pStmtInfo = (PreparedStatement.ParseInfo) this.cachedPreparedStatementParams + .get(nativeSql); + + if (pStmtInfo == null) { + pStmt = new com.mysql.jdbc.PreparedStatement(this, nativeSql, + this.database); + + PreparedStatement.ParseInfo parseInfo = pStmt.getParseInfo(); + + if (parseInfo.statementLength < getPreparedStatementCacheSqlLimit()) { + if (this.cachedPreparedStatementParams.size() >= getPreparedStatementCacheSize()) { + Iterator oldestIter = this.cachedPreparedStatementParams + .keySet().iterator(); + long lruTime = Long.MAX_VALUE; + String oldestSql = null; + + while (oldestIter.hasNext()) { + String sqlKey = (String) oldestIter.next(); + PreparedStatement.ParseInfo lruInfo = (PreparedStatement.ParseInfo) this.cachedPreparedStatementParams + .get(sqlKey); + + if (lruInfo.lastUsed < lruTime) { + lruTime = lruInfo.lastUsed; + oldestSql = sqlKey; + } + } + + if (oldestSql != null) { + this.cachedPreparedStatementParams + .remove(oldestSql); + } + } + + this.cachedPreparedStatementParams.put(nativeSql, pStmt + .getParseInfo()); + } + } else { + pStmtInfo.lastUsed = System.currentTimeMillis(); + pStmt = new com.mysql.jdbc.PreparedStatement(this, nativeSql, + this.database, pStmtInfo); + } + } + } else { + pStmt = new com.mysql.jdbc.PreparedStatement(this, nativeSql, + this.database); + } + + pStmt.setResultSetType(resultSetType); + pStmt.setResultSetConcurrency(resultSetConcurrency); + + return pStmt; + } + + + public void close() throws SQLException { + realClose(true, true, false, null); + } + + /** + * Closes all currently open statements. + * + * @throws SQLException + * DOCUMENT ME! + */ + private void closeAllOpenStatements() throws SQLException { + SQLException postponedException = null; + + if (this.openStatements != null) { + List currentlyOpenStatements = new ArrayList(); // we need this to + // avoid + // ConcurrentModificationEx + + for (Iterator iter = this.openStatements.keySet().iterator(); iter + .hasNext();) { + currentlyOpenStatements.add(iter.next()); + } + + int numStmts = currentlyOpenStatements.size(); + + for (int i = 0; i < numStmts; i++) { + Statement stmt = (Statement) currentlyOpenStatements.get(i); + + try { + stmt.realClose(false, true); + } catch (SQLException sqlEx) { + postponedException = sqlEx; // throw it later, cleanup all + // statements first + } + } + + if (postponedException != null) { + throw postponedException; + } + } + } + + private void closeStatement(java.sql.Statement stmt) { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { + ; // ignore + } + + stmt = null; + } + } + + // --------------------------JDBC 2.0----------------------------- + + /** + * The method commit() makes all changes made since the previous + * commit/rollback permanent and releases any database locks currently held + * by the Connection. This method should only be used when auto-commit has + * been disabled. + *

+ * Note: MySQL does not support transactions, so this method is a + * no-op. + *

+ * + * @exception SQLException + * if a database access error occurs + * @see setAutoCommit + */ + public void commit() throws SQLException { + synchronized (getMutex()) { + checkClosed(); + + try { + // no-op if _relaxAutoCommit == true + if (this.autoCommit && !getRelaxAutoCommit()) { + throw SQLError.createSQLException("Can't call commit when autocommit=true"); + } else if (this.transactionsSupported) { + if (getUseLocalSessionState() && versionMeetsMinimum(5, 0, 0)) { + if (!this.io.inTransactionOnServer()) { + return; // effectively a no-op + } + } + + execSQL(null, "commit", -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, + false); + } + } catch (SQLException sqlException) { + if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE + .equals(sqlException.getSQLState())) { + throw SQLError.createSQLException( + "Communications link failure during commit(). Transaction resolution unknown.", + SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN); + } + + throw sqlException; + } finally { + this.needsPing = this.getReconnectAtTxEnd(); + } + + return; + } + } + + /** + * Configures client-side properties for character set information. + * + * @throws SQLException + * if unable to configure the specified character set. + */ + private void configureCharsetProperties() throws SQLException { + if (getEncoding() != null) { + // Attempt to use the encoding, and bail out if it + // can't be used + try { + String testString = "abc"; + testString.getBytes(getEncoding()); + } catch (UnsupportedEncodingException UE) { + // Try the MySQL character encoding, then.... + String oldEncoding = getEncoding(); + + setEncoding(CharsetMapping.getJavaEncodingForMysqlEncoding( + oldEncoding, this)); + + if (getEncoding() == null) { + throw SQLError.createSQLException( + "Java does not support the MySQL character encoding " + + " " + "encoding '" + oldEncoding + "'.", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + + try { + String testString = "abc"; + testString.getBytes(getEncoding()); + } catch (UnsupportedEncodingException encodingEx) { + throw SQLError.createSQLException("Unsupported character " + + "encoding '" + getEncoding() + "'.", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + } + } + } + + /** + * Sets up client character set for MySQL-4.1 and newer if the user This + * must be done before any further communication with the server! + * + * @return true if this routine actually configured the client character + * set, or false if the driver needs to use 'older' methods to + * detect the character set, as it is connected to a MySQL server + * older than 4.1.0 + * @throws SQLException + * if an exception happens while sending 'SET NAMES' to the + * server, or the server sends character set information that + * the client doesn't know about. + */ + private boolean configureClientCharacterSet() throws SQLException { + String realJavaEncoding = getEncoding(); + boolean characterSetAlreadyConfigured = false; + + try { + if (versionMeetsMinimum(4, 1, 0)) { + characterSetAlreadyConfigured = true; + + setUseUnicode(true); + + configureCharsetProperties(); + realJavaEncoding = getEncoding(); // we need to do this again + // to grab this for + // versions > 4.1.0 + + try { + + // Fault injection for testing server character set indices + + if (props != null && props.getProperty("com.mysql.jdbc.faultInjection.serverCharsetIndex") != null) { + this.io.serverCharsetIndex = Integer.parseInt( + props.getProperty( + "com.mysql.jdbc.faultInjection.serverCharsetIndex")); + } + + String serverEncodingToSet = + CharsetMapping.INDEX_TO_CHARSET[this.io.serverCharsetIndex]; + + if (serverEncodingToSet == null || serverEncodingToSet.length() == 0) { + if (realJavaEncoding != null) { + // user knows best, try it + setEncoding(realJavaEncoding); + } else { + throw SQLError.createSQLException( + "Unknown initial character set index '" + + this.io.serverCharsetIndex + + "' received from server. Initial client character set can be forced via the 'characterEncoding' property.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + // "latin1" on MySQL-4.1.0+ is actually CP1252, not ISO8859_1 + if (versionMeetsMinimum(4, 1, 0) && + "ISO8859_1".equalsIgnoreCase(serverEncodingToSet)) { + serverEncodingToSet = "Cp1252"; + } + + setEncoding(serverEncodingToSet); + + } catch (ArrayIndexOutOfBoundsException outOfBoundsEx) { + if (realJavaEncoding != null) { + // user knows best, try it + setEncoding(realJavaEncoding); + } else { + throw SQLError.createSQLException( + "Unknown initial character set index '" + + this.io.serverCharsetIndex + + "' received from server. Initial client character set can be forced via the 'characterEncoding' property.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + if (getEncoding() == null) { + // punt? + setEncoding("ISO8859_1"); + } + + // + // Has the user has 'forced' the character encoding via + // driver properties? + // + if (getUseUnicode()) { + if (realJavaEncoding != null) { + + // + // Now, inform the server what character set we + // will be using from now-on... + // + if (realJavaEncoding.equalsIgnoreCase("UTF-8") + || realJavaEncoding.equalsIgnoreCase("UTF8")) { + // charset names are case-sensitive + + if (!getUseOldUTF8Behavior()) { + if (!characterSetNamesMatches("utf8")) { + execSQL(null, "SET NAMES utf8", -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.database, true, false); + } + } + + setEncoding(realJavaEncoding); + } /* not utf-8 */else { + String mysqlEncodingName = CharsetMapping + .getMysqlEncodingForJavaEncoding( + realJavaEncoding + .toUpperCase(Locale.ENGLISH), + this); + + /* + * if ("koi8_ru".equals(mysqlEncodingName)) { // + * This has a _different_ name in 4.1... + * mysqlEncodingName = "ko18r"; } else if + * ("euc_kr".equals(mysqlEncodingName)) { // + * Different name in 4.1 mysqlEncodingName = + * "euckr"; } + */ + + if (mysqlEncodingName != null) { + + if (!characterSetNamesMatches(mysqlEncodingName)) { + execSQL(null, "SET NAMES " + mysqlEncodingName, + -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.database, true, false); + } + } + + // Switch driver's encoding now, since the server + // knows what we're sending... + // + setEncoding(realJavaEncoding); + } + } else if (getEncoding() != null) { + // Tell the server we'll use the server default charset + // to send our + // queries from now on.... + String mysqlEncodingName = CharsetMapping + .getMysqlEncodingForJavaEncoding(getEncoding() + .toUpperCase(Locale.ENGLISH), this); + + if (!characterSetNamesMatches(mysqlEncodingName)) { + execSQL(null, "SET NAMES " + mysqlEncodingName, -1, + null, java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + } + + realJavaEncoding = getEncoding(); + } + + } + + // + // We know how to deal with any charset coming back from + // the database, so tell the server not to do conversion + // if the user hasn't 'forced' a result-set character set + // + + String onServer = null; + boolean isNullOnServer = false; + + if (this.serverVariables != null) { + onServer = (String)this.serverVariables.get("character_set_results"); + + isNullOnServer = onServer == null || "NULL".equalsIgnoreCase(onServer) || onServer.length() == 0; + } + + if (getCharacterSetResults() == null) { + + // + // Only send if needed, if we're caching server variables + // we -have- to send, because we don't know what it was + // before we cached them. + // + if (!isNullOnServer) { + execSQL(null, "SET character_set_results = NULL", -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, + false); + if (!this.usingCachedConfig) { + this.serverVariables.put(JDBC_LOCAL_CHARACTER_SET_RESULTS, null); + } + } else { + if (!this.usingCachedConfig) { + this.serverVariables.put(JDBC_LOCAL_CHARACTER_SET_RESULTS, onServer); + } + } + } else { + String charsetResults = getCharacterSetResults(); + String mysqlEncodingName = null; + + if ("UTF-8".equalsIgnoreCase(charsetResults) + || "UTF8".equalsIgnoreCase(charsetResults)) { + mysqlEncodingName = "utf8"; + } else { + mysqlEncodingName = CharsetMapping + .getMysqlEncodingForJavaEncoding(charsetResults + .toUpperCase(Locale.ENGLISH), this); + } + + // + // Only change the value if needed + // + + if (!mysqlEncodingName.equalsIgnoreCase( + (String)this.serverVariables.get("character_set_results"))) { + StringBuffer setBuf = new StringBuffer( + "SET character_set_results = ".length() + + mysqlEncodingName.length()); + setBuf.append("SET character_set_results = ").append( + mysqlEncodingName); + + execSQL(null, setBuf.toString(), -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + + if (!this.usingCachedConfig) { + this.serverVariables.put(JDBC_LOCAL_CHARACTER_SET_RESULTS, + mysqlEncodingName); + } + } else { + if (!this.usingCachedConfig) { + this.serverVariables.put(JDBC_LOCAL_CHARACTER_SET_RESULTS, onServer); + } + } + } + + if (getConnectionCollation() != null) { + StringBuffer setBuf = new StringBuffer( + "SET collation_connection = ".length() + + getConnectionCollation().length()); + setBuf.append("SET collation_connection = ").append( + getConnectionCollation()); + + execSQL(null, setBuf.toString(), -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + } + } else { + // Use what the server has specified + realJavaEncoding = getEncoding(); // so we don't get + // swapped out in the finally + // block.... + } + } finally { + // Failsafe, make sure that the driver's notion of character + // encoding matches what the user has specified. + // + setEncoding(realJavaEncoding); + } + + return characterSetAlreadyConfigured; + } + + private boolean characterSetNamesMatches(String mysqlEncodingName) { + // set names is equivalent to character_set_client ..._results and ..._connection, + // but we set _results later, so don't check it here. + + return (mysqlEncodingName != null && + mysqlEncodingName.equalsIgnoreCase((String)this.serverVariables.get("character_set_client")) && + mysqlEncodingName.equalsIgnoreCase((String)this.serverVariables.get("character_set_connection"))); + } + + /** + * Configures the client's timezone if required. + * + * @throws SQLException + * if the timezone the server is configured to use can't be + * mapped to a Java timezone. + */ + private void configureTimezone() throws SQLException { + String configuredTimeZoneOnServer = (String) this.serverVariables + .get("timezone"); + + if (configuredTimeZoneOnServer == null) { + configuredTimeZoneOnServer = (String) this.serverVariables + .get("time_zone"); + + if ("SYSTEM".equalsIgnoreCase(configuredTimeZoneOnServer)) { + configuredTimeZoneOnServer = (String) this.serverVariables + .get("system_time_zone"); + } + } + + if (getUseTimezone() && configuredTimeZoneOnServer != null) { + // user can specify/override as property + String canoncicalTimezone = getServerTimezone(); + + if ((canoncicalTimezone == null) + || (canoncicalTimezone.length() == 0)) { + String serverTimezoneStr = configuredTimeZoneOnServer; + + try { + canoncicalTimezone = TimeUtil + .getCanoncialTimezone(serverTimezoneStr); + + if (canoncicalTimezone == null) { + throw SQLError.createSQLException("Can't map timezone '" + + serverTimezoneStr + "' to " + + " canonical timezone.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (IllegalArgumentException iae) { + throw SQLError.createSQLException(iae.getMessage(), + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + this.serverTimezoneTZ = TimeZone.getTimeZone(canoncicalTimezone); + + // + // The Calendar class has the behavior of mapping + // unknown timezones to 'GMT' instead of throwing an + // exception, so we must check for this... + // + if (!canoncicalTimezone.equalsIgnoreCase("GMT") + && this.serverTimezoneTZ.getID().equals("GMT")) { + throw SQLError.createSQLException("No timezone mapping entry for '" + + canoncicalTimezone + "'", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if ("GMT".equalsIgnoreCase(this.serverTimezoneTZ.getID())) { + this.isServerTzUTC = true; + } else { + this.isServerTzUTC = false; + } + } + } + + private void createInitialHistogram(long[] breakpoints, + long lowerBound, long upperBound) { + + double bucketSize = (((double) upperBound - (double) lowerBound) / HISTOGRAM_BUCKETS) * 1.25; + + if (bucketSize < 1) { + bucketSize = 1; + } + + for (int i = 0; i < HISTOGRAM_BUCKETS; i++) { + breakpoints[i] = lowerBound; + lowerBound += bucketSize; + } + } + + /** + * Creates an IO channel to the server + * + * @param isForReconnect + * is this request for a re-connect + * @return a new MysqlIO instance connected to a server + * @throws SQLException + * if a database access error occurs + * @throws CommunicationsException + * DOCUMENT ME! + */ + protected com.mysql.jdbc.MysqlIO createNewIO(boolean isForReconnect) + throws SQLException { + MysqlIO newIo = null; + + Properties mergedProps = new Properties(); + + mergedProps = exposeAsProperties(this.props); + + long queriesIssuedFailedOverCopy = this.queriesIssuedFailedOver; + this.queriesIssuedFailedOver = 0; + + try { + if (!getHighAvailability() && !this.failedOver) { + boolean connectionGood = false; + Exception connectionNotEstablishedBecause = null; + + int hostIndex = 0; + + // + // TODO: Eventually, when there's enough metadata + // on the server to support it, we should come up + // with a smarter way to pick what server to connect + // to...perhaps even making it 'pluggable' + // + if (getRoundRobinLoadBalance()) { + hostIndex = getNextRoundRobinHostIndex(getURL(), + this.hostList); + } + + for (; hostIndex < this.hostListSize; hostIndex++) { + + if (hostIndex == 0) { + this.hasTriedMasterFlag = true; + } + + try { + String newHostPortPair = (String) this.hostList + .get(hostIndex); + + int newPort = 3306; + + String[] hostPortPair = NonRegisteringDriver + .parseHostPortPair(newHostPortPair); + String newHost = hostPortPair[NonRegisteringDriver.HOST_NAME_INDEX]; + + if (newHost == null || newHost.trim().length() == 0) { + newHost = "localhost"; + } + + if (hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX] != null) { + try { + newPort = Integer + .parseInt(hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX]); + } catch (NumberFormatException nfe) { + throw SQLError.createSQLException( + "Illegal connection port value '" + + hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX] + + "'", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + } + + this.io = new MysqlIO(newHost, newPort, mergedProps, + getSocketFactoryClassName(), this, + getSocketTimeout()); + + this.io.doHandshake(this.user, this.password, + this.database); + this.connectionId = this.io.getThreadId(); + this.isClosed = false; + + // save state from old connection + boolean oldAutoCommit = getAutoCommit(); + int oldIsolationLevel = this.isolationLevel; + boolean oldReadOnly = isReadOnly(); + String oldCatalog = getCatalog(); + + // Server properties might be different + // from previous connection, so initialize + // again... + initializePropsFromServer(); + + if (isForReconnect) { + // Restore state from old connection + setAutoCommit(oldAutoCommit); + + if (this.hasIsolationLevels) { + setTransactionIsolation(oldIsolationLevel); + } + + setCatalog(oldCatalog); + } + + if (hostIndex != 0) { + setFailedOverState(); + queriesIssuedFailedOverCopy = 0; + } else { + this.failedOver = false; + queriesIssuedFailedOverCopy = 0; + + if (this.hostListSize > 1) { + setReadOnlyInternal(false); + } else { + setReadOnlyInternal(oldReadOnly); + } + } + + connectionGood = true; + + break; // low-level connection succeeded + } catch (Exception EEE) { + if (this.io != null) { + this.io.forceClose(); + } + + connectionNotEstablishedBecause = EEE; + + connectionGood = false; + + if (EEE instanceof SQLException) { + SQLException sqlEx = (SQLException)EEE; + + String sqlState = sqlEx.getSQLState(); + + // If this isn't a communications failure, it will probably never succeed, so + // give up right here and now .... + if ((sqlState == null) + || !sqlState + .equals(SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE)) { + throw sqlEx; + } + } + + // Check next host, it might be up... + if (getRoundRobinLoadBalance()) { + hostIndex = getNextRoundRobinHostIndex(getURL(), + this.hostList) - 1 /* incremented by for loop next time around */; + } else if ((this.hostListSize - 1) == hostIndex) { + throw new CommunicationsException(this, + (this.io != null) ? this.io + .getLastPacketSentTimeMs() : 0, + EEE); + } + } + } + + if (!connectionGood) { + // We've really failed! + throw SQLError.createSQLException( + "Could not create connection to database server due to underlying exception: '" + + connectionNotEstablishedBecause + + "'." + + (getParanoid() ? "" + : Util + .stackTraceToString(connectionNotEstablishedBecause)), + SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE); + } + } else { + double timeout = getInitialTimeout(); + boolean connectionGood = false; + + Exception connectionException = null; + + int hostIndex = 0; + + if (getRoundRobinLoadBalance()) { + hostIndex = getNextRoundRobinHostIndex(getURL(), + this.hostList); + } + + for (; (hostIndex < this.hostListSize) && !connectionGood; hostIndex++) { + if (hostIndex == 0) { + this.hasTriedMasterFlag = true; + } + + if (this.preferSlaveDuringFailover && hostIndex == 0) { + hostIndex++; + } + + for (int attemptCount = 0; (attemptCount < getMaxReconnects()) + && !connectionGood; attemptCount++) { + try { + if (this.io != null) { + this.io.forceClose(); + } + + String newHostPortPair = (String) this.hostList + .get(hostIndex); + + int newPort = 3306; + + String[] hostPortPair = NonRegisteringDriver + .parseHostPortPair(newHostPortPair); + String newHost = hostPortPair[NonRegisteringDriver.HOST_NAME_INDEX]; + + if (newHost == null || newHost.trim().length() == 0) { + newHost = "localhost"; + } + + if (hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX] != null) { + try { + newPort = Integer + .parseInt(hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX]); + } catch (NumberFormatException nfe) { + throw SQLError.createSQLException( + "Illegal connection port value '" + + hostPortPair[NonRegisteringDriver.PORT_NUMBER_INDEX] + + "'", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + } + + this.io = new MysqlIO(newHost, newPort, + mergedProps, getSocketFactoryClassName(), + this, getSocketTimeout()); + this.io.doHandshake(this.user, this.password, + this.database); + + pingInternal(false); + this.connectionId = this.io.getThreadId(); + this.isClosed = false; + + // save state from old connection + boolean oldAutoCommit = getAutoCommit(); + int oldIsolationLevel = this.isolationLevel; + boolean oldReadOnly = isReadOnly(); + String oldCatalog = getCatalog(); + + // Server properties might be different + // from previous connection, so initialize + // again... + initializePropsFromServer(); + + if (isForReconnect) { + // Restore state from old connection + setAutoCommit(oldAutoCommit); + + if (this.hasIsolationLevels) { + setTransactionIsolation(oldIsolationLevel); + } + + setCatalog(oldCatalog); + } + + connectionGood = true; + + if (hostIndex != 0) { + setFailedOverState(); + queriesIssuedFailedOverCopy = 0; + } else { + this.failedOver = false; + queriesIssuedFailedOverCopy = 0; + + if (this.hostListSize > 1) { + setReadOnlyInternal(false); + } else { + setReadOnlyInternal(oldReadOnly); + } + } + + break; + } catch (Exception EEE) { + connectionException = EEE; + connectionGood = false; + + // Check next host, it might be up... + if (getRoundRobinLoadBalance()) { + hostIndex = getNextRoundRobinHostIndex(getURL(), + this.hostList) - 1 /* incremented by for loop next time around */; + } + } + + if (connectionGood) { + break; + } + + if (attemptCount > 0) { + try { + Thread.sleep((long) timeout * 1000); + } catch (InterruptedException IE) { + ; + } + } + } // end attempts for a single host + } // end iterator for list of hosts + + if (!connectionGood) { + // We've really failed! + throw SQLError.createSQLException( + "Server connection failure during transaction. Due to underlying exception: '" + + connectionException + + "'." + + (getParanoid() ? "" + : Util + .stackTraceToString(connectionException)) + + "\nAttempted reconnect " + + getMaxReconnects() + " times. Giving up.", + SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE); + } + } + + if (getParanoid() && !getHighAvailability() + && (this.hostListSize <= 1)) { + this.password = null; + this.user = null; + } + + if (isForReconnect) { + // + // Retrieve any 'lost' prepared statements if re-connecting + // + Iterator statementIter = this.openStatements.values() + .iterator(); + + // + // We build a list of these outside the map of open statements, + // because + // in the process of re-preparing, we might end up having to + // close + // a prepared statement, thus removing it from the map, and + // generating + // a ConcurrentModificationException + // + Stack serverPreparedStatements = null; + + while (statementIter.hasNext()) { + Object statementObj = statementIter.next(); + + if (statementObj instanceof ServerPreparedStatement) { + if (serverPreparedStatements == null) { + serverPreparedStatements = new Stack(); + } + + serverPreparedStatements.add(statementObj); + } + } + + if (serverPreparedStatements != null) { + while (!serverPreparedStatements.isEmpty()) { + ((ServerPreparedStatement) serverPreparedStatements + .pop()).rePrepare(); + } + } + } + + return newIo; + } finally { + this.queriesIssuedFailedOver = queriesIssuedFailedOverCopy; + } + } + + private void createPreparedStatementCaches() { + int cacheSize = getPreparedStatementCacheSize(); + + this.cachedPreparedStatementParams = new HashMap(cacheSize); + + this.serverSideStatementCheckCache = new LRUCache(cacheSize); + + this.serverSideStatementCache = new LRUCache(cacheSize) { + protected boolean removeEldestEntry(java.util.Map.Entry eldest) { + if (this.maxElements <= 1) { + return false; + } + + boolean removeIt = super.removeEldestEntry(eldest); + + if (removeIt) { + ServerPreparedStatement ps = + (ServerPreparedStatement)eldest.getValue(); + ps.isCached = false; + ps.setClosed(false); + + try { + ps.close(); + } catch (SQLException sqlEx) { + // punt + } + } + + return removeIt; + } + }; + } + + /** + * SQL statements without parameters are normally executed using Statement + * objects. If the same SQL statement is executed many times, it is more + * efficient to use a PreparedStatement + * + * @return a new Statement object + * @throws SQLException + * passed through from the constructor + */ + public java.sql.Statement createStatement() throws SQLException { + return createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY); + } + + /** + * JDBC 2.0 Same as createStatement() above, but allows the default result + * set type and result set concurrency type to be overridden. + * + * @param resultSetType + * a result set type, see ResultSet.TYPE_XXX + * @param resultSetConcurrency + * a concurrency type, see ResultSet.CONCUR_XXX + * @return a new Statement object + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.Statement createStatement(int resultSetType, + int resultSetConcurrency) throws SQLException { + checkClosed(); + + Statement stmt = new com.mysql.jdbc.Statement(this, this.database); + stmt.setResultSetType(resultSetType); + stmt.setResultSetConcurrency(resultSetConcurrency); + + return stmt; + } + + /** + * @see Connection#createStatement(int, int, int) + */ + public java.sql.Statement createStatement(int resultSetType, + int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + if (getPedantic()) { + if (resultSetHoldability != java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT) { + throw SQLError.createSQLException( + "HOLD_CUSRORS_OVER_COMMIT is only supported holdability level", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + return createStatement(resultSetType, resultSetConcurrency); + } + + protected void dumpTestcaseQuery(String query) { + System.err.println(query); + } + + protected Connection duplicate() throws SQLException { + return new Connection( this.origHostToConnectTo, + this.origPortToConnectTo, + this.props, + this.origDatabaseToConnectTo, + this.myURL); + } + + /** + * Send a query to the server. Returns one of the ResultSet objects. This is + * synchronized, so Statement's queries will be serialized. + * + * @param callingStatement + * DOCUMENT ME! + * @param sql + * the SQL statement to be executed + * @param maxRows + * DOCUMENT ME! + * @param packet + * DOCUMENT ME! + * @param resultSetType + * DOCUMENT ME! + * @param resultSetConcurrency + * DOCUMENT ME! + * @param streamResults + * DOCUMENT ME! + * @param queryIsSelectOnly + * DOCUMENT ME! + * @param catalog + * DOCUMENT ME! + * @param unpackFields + * DOCUMENT ME! + * @return a ResultSet holding the results + * @exception SQLException + * if a database error occurs + */ + + // ResultSet execSQL(Statement callingStatement, String sql, + // int maxRowsToRetreive, String catalog) throws SQLException { + // return execSQL(callingStatement, sql, maxRowsToRetreive, null, + // java.sql.ResultSet.TYPE_FORWARD_ONLY, + // java.sql.ResultSet.CONCUR_READ_ONLY, catalog); + // } + // ResultSet execSQL(Statement callingStatement, String sql, int maxRows, + // int resultSetType, int resultSetConcurrency, boolean streamResults, + // boolean queryIsSelectOnly, String catalog, boolean unpackFields) throws + // SQLException { + // return execSQL(callingStatement, sql, maxRows, null, resultSetType, + // resultSetConcurrency, streamResults, queryIsSelectOnly, catalog, + // unpackFields); + // } + ResultSet execSQL(Statement callingStatement, String sql, int maxRows, + Buffer packet, int resultSetType, int resultSetConcurrency, + boolean streamResults, String catalog, + boolean unpackFields) throws SQLException { + return execSQL(callingStatement, sql, maxRows, packet, resultSetType, + resultSetConcurrency, streamResults, + catalog, unpackFields, false); + } + + ResultSet execSQL(Statement callingStatement, String sql, int maxRows, + Buffer packet, int resultSetType, int resultSetConcurrency, + boolean streamResults, String catalog, + boolean unpackFields, + boolean isBatch) throws SQLException { + // + // Fall-back if the master is back online if we've + // issued queriesBeforeRetryMaster queries since + // we failed over + // + synchronized (this.mutex) { + long queryStartTime = 0; + + int endOfQueryPacketPosition = 0; + + if (packet != null) { + endOfQueryPacketPosition = packet.getPosition(); + } + + if (getGatherPerformanceMetrics()) { + queryStartTime = System.currentTimeMillis(); + } + + this.lastQueryFinishedTime = 0; // we're busy! + + if (this.failedOver && this.autoCommit && !isBatch) { + if (shouldFallBack() && !this.executingFailoverReconnect) { + try { + this.executingFailoverReconnect = true; + + createNewIO(true); + + String connectedHost = this.io.getHost(); + + if ((connectedHost != null) + && this.hostList.get(0).equals(connectedHost)) { + this.failedOver = false; + this.queriesIssuedFailedOver = 0; + setReadOnlyInternal(false); + } + } finally { + this.executingFailoverReconnect = false; + } + } + } + + if ((getHighAvailability() || this.failedOver) + && (this.autoCommit || getAutoReconnectForPools()) + && this.needsPing && !isBatch) { + try { + pingInternal(false); + + this.needsPing = false; + } catch (Exception Ex) { + createNewIO(true); + } + } + + try { + if (packet == null) { + String encoding = null; + + if (getUseUnicode()) { + encoding = getEncoding(); + } + + return this.io.sqlQueryDirect(callingStatement, sql, + encoding, null, maxRows, this, resultSetType, + resultSetConcurrency, streamResults, catalog, + unpackFields); + } + + return this.io.sqlQueryDirect(callingStatement, null, null, + packet, maxRows, this, resultSetType, + resultSetConcurrency, streamResults, catalog, + unpackFields); + } catch (java.sql.SQLException sqlE) { + // don't clobber SQL exceptions + + if (getDumpQueriesOnException()) { + String extractedSql = extractSqlFromPacket(sql, packet, + endOfQueryPacketPosition); + StringBuffer messageBuf = new StringBuffer(extractedSql + .length() + 32); + messageBuf + .append("\n\nQuery being executed when exception was thrown:\n\n"); + messageBuf.append(extractedSql); + + sqlE = appendMessageToException(sqlE, messageBuf.toString()); + } + + if ((getHighAvailability() || this.failedOver)) { + this.needsPing = true; + } else { + String sqlState = sqlE.getSQLState(); + + if ((sqlState != null) + && sqlState + .equals(SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE)) { + cleanup(sqlE); + } + } + + throw sqlE; + } catch (Exception ex) { + if ((getHighAvailability() || this.failedOver)) { + this.needsPing = true; + } else if (ex instanceof IOException) { + cleanup(ex); + } + + String exceptionType = ex.getClass().getName(); + String exceptionMessage = ex.getMessage(); + + if (!getParanoid()) { + exceptionMessage += "\n\nNested Stack Trace:\n"; + exceptionMessage += Util.stackTraceToString(ex); + } + + throw new java.sql.SQLException( + "Error during query: Unexpected Exception: " + + exceptionType + " message given: " + + exceptionMessage, + SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + if (getMaintainTimeStats()) { + this.lastQueryFinishedTime = System.currentTimeMillis(); + } + + if (this.failedOver) { + this.queriesIssuedFailedOver++; + } + + if (getGatherPerformanceMetrics()) { + long queryTime = System.currentTimeMillis() + - queryStartTime; + + registerQueryExecutionTime(queryTime); + } + } + } + } + + protected String extractSqlFromPacket(String possibleSqlQuery, + Buffer queryPacket, int endOfQueryPacketPosition) + throws SQLException { + + String extractedSql = null; + + if (possibleSqlQuery != null) { + if (possibleSqlQuery.length() > getMaxQuerySizeToLog()) { + StringBuffer truncatedQueryBuf = new StringBuffer( + possibleSqlQuery.substring(0, getMaxQuerySizeToLog())); + truncatedQueryBuf.append(Messages.getString("MysqlIO.25")); + extractedSql = truncatedQueryBuf.toString(); + } else { + extractedSql = possibleSqlQuery; + } + } + + if (extractedSql == null) { + // This is probably from a client-side prepared + // statement + + int extractPosition = endOfQueryPacketPosition; + + boolean truncated = false; + + if (endOfQueryPacketPosition > getMaxQuerySizeToLog()) { + extractPosition = getMaxQuerySizeToLog(); + truncated = true; + } + + extractedSql = new String(queryPacket.getByteBuffer(), 5, + (extractPosition - 5)); + + if (truncated) { + extractedSql += Messages.getString("MysqlIO.25"); //$NON-NLS-1$ + } + } + + return extractedSql; + + } + + /** + * DOCUMENT ME! + * + * @throws Throwable + * DOCUMENT ME! + */ + protected void finalize() throws Throwable { + cleanup(null); + } + + protected StringBuffer generateConnectionCommentBlock(StringBuffer buf) { + buf.append("/* conn id "); + buf.append(getId()); + buf.append(" */ "); + + return buf; + } + + public int getActiveStatementCount() { + // Might not have one of these if + // not tracking open resources + if (this.openStatements != null) { + synchronized (this.openStatements) { + return this.openStatements.size(); + } + } + + return 0; + } + + /** + * Gets the current auto-commit state + * + * @return Current state of auto-commit + * @exception SQLException + * if an error occurs + * @see setAutoCommit + */ + public boolean getAutoCommit() throws SQLException { + return this.autoCommit; + } + + /** + * Optimization to only use one calendar per-session, or calculate it for + * each call, depending on user configuration + */ + protected Calendar getCalendarInstanceForSessionOrNew() { + if (getDynamicCalendars()) { + return Calendar.getInstance(); + } + + return getSessionLockedCalendar(); + } + + /** + * Return the connections current catalog name, or null if no catalog name + * is set, or we dont support catalogs. + *

+ * Note: MySQL's notion of catalogs are individual databases. + *

+ * + * @return the current catalog name or null + * @exception SQLException + * if a database access error occurs + */ + public String getCatalog() throws SQLException { + return this.database; + } + + /** + * @return Returns the characterSetMetadata. + */ + protected String getCharacterSetMetadata() { + return characterSetMetadata; + } + + /** + * Returns the locally mapped instance of a charset converter (to avoid + * overhead of static synchronization). + * + * @param javaEncodingName + * the encoding name to retrieve + * @return a character converter, or null if one couldn't be mapped. + */ + SingleByteCharsetConverter getCharsetConverter( + String javaEncodingName) throws SQLException { + if (javaEncodingName == null) { + return null; + } + + if (this.usePlatformCharsetConverters) { + return null; // we'll use Java's built-in routines for this + // they're finally fast enough + } + + SingleByteCharsetConverter converter = null; + + synchronized (this.charsetConverterMap) { + Object asObject = this.charsetConverterMap + .get(javaEncodingName); + + if (asObject == CHARSET_CONVERTER_NOT_AVAILABLE_MARKER) { + return null; + } + + converter = (SingleByteCharsetConverter)asObject; + + if (converter == null) { + try { + converter = SingleByteCharsetConverter.getInstance( + javaEncodingName, this); + + if (converter == null) { + this.charsetConverterMap.put(javaEncodingName, + CHARSET_CONVERTER_NOT_AVAILABLE_MARKER); + } else { + this.charsetConverterMap.put(javaEncodingName, converter); + } + } catch (UnsupportedEncodingException unsupEncEx) { + this.charsetConverterMap.put(javaEncodingName, + CHARSET_CONVERTER_NOT_AVAILABLE_MARKER); + + converter = null; + } + } + } + + return converter; + } + + /** + * Returns the Java character encoding name for the given MySQL server + * charset index + * + * @param charsetIndex + * @return the Java character encoding name for the given MySQL server + * charset index + * @throws SQLException + * if the character set index isn't known by the driver + */ + protected String getCharsetNameForIndex(int charsetIndex) + throws SQLException { + String charsetName = null; + + if (getUseOldUTF8Behavior()) { + return getEncoding(); + } + + if (charsetIndex != MysqlDefs.NO_CHARSET_INFO) { + try { + charsetName = this.indexToCharsetMapping[charsetIndex]; + + if ("sjis".equalsIgnoreCase(charsetName) || + "MS932".equalsIgnoreCase(charsetName) /* for JDK6 */) { + // Use our encoding so that code pages like Cp932 work + if (CharsetMapping.isAliasForSjis(getEncoding())) { + charsetName = getEncoding(); + } + } + } catch (ArrayIndexOutOfBoundsException outOfBoundsEx) { + throw SQLError.createSQLException( + "Unknown character set index for field '" + + charsetIndex + "' received from server.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + // Punt + if (charsetName == null) { + charsetName = getEncoding(); + } + } else { + charsetName = getEncoding(); + } + + return charsetName; + } + + /** + * DOCUMENT ME! + * + * @return Returns the defaultTimeZone. + */ + protected TimeZone getDefaultTimeZone() { + return this.defaultTimeZone; + } + + /** + * @see Connection#getHoldability() + */ + public int getHoldability() throws SQLException { + return java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT; + } + + long getId() { + return this.connectionId; + } + + /** + * NOT JDBC-Compliant, but clients can use this method to determine how long + * this connection has been idle. This time (reported in milliseconds) is + * updated once a query has completed. + * + * @return number of ms that this connection has been idle, 0 if the driver + * is busy retrieving results. + */ + public long getIdleFor() { + if (this.lastQueryFinishedTime == 0) { + return 0; + } + + long now = System.currentTimeMillis(); + long idleTime = now - this.lastQueryFinishedTime; + + return idleTime; + } + + /** + * Returns the IO channel to the server + * + * @return the IO channel to the server + * @throws SQLException + * if the connection is closed. + */ + protected MysqlIO getIO() throws SQLException { + if ((this.io == null) || this.isClosed) { + throw SQLError.createSQLException( + "Operation not allowed on closed connection", + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); + } + + return this.io; + } + + /** + * Returns the log mechanism that should be used to log information from/for + * this Connection. + * + * @return the Log instance to use for logging messages. + * @throws SQLException + * if an error occurs + */ + public Log getLog() throws SQLException { + return this.log; + } + + /** + * Returns the maximum packet size the MySQL server will accept + * + * @return DOCUMENT ME! + */ + int getMaxAllowedPacket() { + return this.maxAllowedPacket; + } + + protected int getMaxBytesPerChar(String javaCharsetName) + throws SQLException { + // TODO: Check if we can actually run this query at this point in time + String charset = CharsetMapping.getMysqlEncodingForJavaEncoding( + javaCharsetName, this); + + if (versionMeetsMinimum(4, 1, 0)) { + Map mapToCheck = null; + + if (!getUseDynamicCharsetInfo()) { + mapToCheck = CharsetMapping.STATIC_CHARSET_TO_NUM_BYTES_MAP; + } else { + mapToCheck = this.charsetToNumBytesMap; + + synchronized (this.charsetToNumBytesMap) { + if (this.charsetToNumBytesMap.isEmpty()) { + + java.sql.Statement stmt = null; + java.sql.ResultSet rs = null; + + try { + stmt = getMetadataSafeStatement(); + + rs = stmt.executeQuery("SHOW CHARACTER SET"); + + while (rs.next()) { + this.charsetToNumBytesMap.put(rs.getString("Charset"), + new Integer(rs.getInt("Maxlen"))); + } + + rs.close(); + rs = null; + + stmt.close(); + + stmt = null; + } finally { + if (rs != null) { + rs.close(); + rs = null; + } + + if (stmt != null) { + stmt.close(); + stmt = null; + } + } + } + } + } + + Integer mbPerChar = (Integer) mapToCheck.get(charset); + + if (mbPerChar != null) { + return mbPerChar.intValue(); + } + + return 1; // we don't know + } + + return 1; // we don't know + } + + /** + * A connection's database is able to provide information describing its + * tables, its supported SQL grammar, its stored procedures, the + * capabilities of this connection, etc. This information is made available + * through a DatabaseMetaData object. + * + * @return a DatabaseMetaData object for this connection + * @exception SQLException + * if a database access error occurs + */ + public java.sql.DatabaseMetaData getMetaData() throws SQLException { + checkClosed(); + + if (getUseInformationSchema() && + this.versionMeetsMinimum(5, 0, 7)) { + return new DatabaseMetaDataUsingInfoSchema(this, this.database); + } + + return new DatabaseMetaData(this, this.database); + } + + protected java.sql.Statement getMetadataSafeStatement() throws SQLException { + java.sql.Statement stmt = createStatement(); + + if (stmt.getMaxRows() != 0) { + stmt.setMaxRows(0); + } + + stmt.setEscapeProcessing(false); + + return stmt; + } + + /** + * Returns the Mutex all queries are locked against + * + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + Object getMutex() throws SQLException { + if (this.io == null) { + throw SQLError.createSQLException( + "Connection.close() has already been called. Invalid operation in this state.", + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); + } + + reportMetricsIfNeeded(); + + return this.mutex; + } + + /** + * Returns the packet buffer size the MySQL server reported upon connection + * + * @return DOCUMENT ME! + */ + int getNetBufferLength() { + return this.netBufferLength; + } + + /** + * Returns the server's character set + * + * @return the server's character set. + */ + protected String getServerCharacterEncoding() { + if (this.io.versionMeetsMinimum(4, 1, 0)) { + return (String) this.serverVariables.get("character_set_server"); + } else { + return (String) this.serverVariables.get("character_set"); + } + } + + int getServerMajorVersion() { + return this.io.getServerMajorVersion(); + } + + int getServerMinorVersion() { + return this.io.getServerMinorVersion(); + } + + int getServerSubMinorVersion() { + return this.io.getServerSubMinorVersion(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public TimeZone getServerTimezoneTZ() { + return this.serverTimezoneTZ; + } + + String getServerVariable(String variableName) { + if (this.serverVariables != null) { + return (String) this.serverVariables.get(variableName); + } + + return null; + } + + String getServerVersion() { + return this.io.getServerVersion(); + } + + protected Calendar getSessionLockedCalendar() { + + return this.sessionCalendar; + } + + + /** + * Get this Connection's current transaction isolation mode. + * + * @return the current TRANSACTION_ mode value + * @exception SQLException + * if a database access error occurs + */ + public int getTransactionIsolation() throws SQLException { + + if (this.hasIsolationLevels && !getUseLocalSessionState()) { + java.sql.Statement stmt = null; + java.sql.ResultSet rs = null; + + try { + stmt = getMetadataSafeStatement(); + + String query = null; + + int offset = 0; + + if (versionMeetsMinimum(4, 0, 3)) { + query = "SELECT @@session.tx_isolation"; + offset = 1; + } else { + query = "SHOW VARIABLES LIKE 'transaction_isolation'"; + offset = 2; + } + + rs = stmt.executeQuery(query); + + if (rs.next()) { + String s = rs.getString(offset); + + if (s != null) { + Integer intTI = (Integer) mapTransIsolationNameToValue + .get(s); + + if (intTI != null) { + return intTI.intValue(); + } + } + + throw SQLError.createSQLException( + "Could not map transaction isolation '" + s + + " to a valid JDBC level.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + throw SQLError.createSQLException( + "Could not retrieve transaction isolation level from server", + SQLError.SQL_STATE_GENERAL_ERROR); + + } finally { + if (rs != null) { + try { + rs.close(); + } catch (Exception ex) { + // ignore + ; + } + + rs = null; + } + + if (stmt != null) { + try { + stmt.close(); + } catch (Exception ex) { + // ignore + ; + } + + stmt = null; + } + } + } + + return this.isolationLevel; + } + + /** + * JDBC 2.0 Get the type-map object associated with this connection. By + * default, the map returned is empty. + * + * @return the type map + * @throws SQLException + * if a database error occurs + */ + public synchronized java.util.Map getTypeMap() throws SQLException { + if (this.typeMap == null) { + this.typeMap = new HashMap(); + } + + return this.typeMap; + } + + String getURL() { + return this.myURL; + } + + String getUser() { + return this.user; + } + + protected Calendar getUtcCalendar() { + return this.utcCalendar; + } + + /** + * The first warning reported by calls on this Connection is returned. + * Note: Sebsequent warnings will be changed to this + * java.sql.SQLWarning + * + * @return the first java.sql.SQLWarning or null + * @exception SQLException + * if a database access error occurs + */ + public SQLWarning getWarnings() throws SQLException { + return null; + } + + public boolean hasSameProperties(Connection c) { + return this.props.equals(c.props); + } + + protected void incrementNumberOfPreparedExecutes() { + if (getGatherPerformanceMetrics()) { + this.numberOfPreparedExecutes++; + + // We need to increment this, because + // server-side prepared statements bypass + // any execution by the connection itself... + this.numberOfQueriesIssued++; + } + } + + protected void incrementNumberOfPrepares() { + if (getGatherPerformanceMetrics()) { + this.numberOfPrepares++; + } + } + + protected void incrementNumberOfResultSetsCreated() { + if (getGatherPerformanceMetrics()) { + this.numberOfResultSetsCreated++; + } + } + + /** + * Initializes driver properties that come from URL or properties passed to + * the driver manager. + * + * @param info + * DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + private void initializeDriverProperties(Properties info) + throws SQLException { + initializeProperties(info); + + this.usePlatformCharsetConverters = getUseJvmCharsetConverters(); + + this.log = LogFactory.getLogger(getLogger(), LOGGER_INSTANCE_NAME); + + if (getProfileSql() || getUseUsageAdvisor()) { + this.eventSink = ProfileEventSink.getInstance(this); + } + + if (getCachePreparedStatements()) { + createPreparedStatementCaches(); + } + + if (getNoDatetimeStringSync() && getUseTimezone()) { + throw SQLError.createSQLException( + "Can't enable noDatetimeSync and useTimezone configuration " + + "properties at the same time", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + + if (getCacheCallableStatements()) { + this.parsedCallableStatementCache = new LRUCache( + getCallableStatementCacheSize()); + } + + if (getAllowMultiQueries()) { + setCacheResultSetMetadata(false); // we don't handle this yet + } + + if (getCacheResultSetMetadata()) { + this.resultSetMetadataCache = new LRUCache( + getMetadataCacheSize()); + } + } + + /** + * Sets varying properties that depend on server information. Called once we + * have connected to the server. + * + * @param info + * DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + private void initializePropsFromServer() throws SQLException { + setSessionVariables(); + + // + // the "boolean" type didn't come along until MySQL-4.1 + // + + if (!versionMeetsMinimum(4, 1, 0)) { + setTransformedBitIsBoolean(false); + } + + this.parserKnowsUnicode = versionMeetsMinimum(4, 1, 0); + + // + // Users can turn off detection of server-side prepared statements + // + if (getUseServerPreparedStmts() && versionMeetsMinimum(4, 1, 0)) { + this.useServerPreparedStmts = true; + + if (versionMeetsMinimum(5, 0, 0) && !versionMeetsMinimum(5, 0, 3)) { + this.useServerPreparedStmts = false; // 4.1.2+ style prepared + // statements + // don't work on these versions + } + } + + this.serverVariables.clear(); + + // + // If version is greater than 3.21.22 get the server + // variables. + if (versionMeetsMinimum(3, 21, 22)) { + loadServerVariables(); + + buildCollationMapping(); + + LicenseConfiguration.checkLicenseType(this.serverVariables); + + String lowerCaseTables = (String) this.serverVariables + .get("lower_case_table_names"); + + this.lowerCaseTableNames = "on".equalsIgnoreCase(lowerCaseTables) + || "1".equalsIgnoreCase(lowerCaseTables) + || "2".equalsIgnoreCase(lowerCaseTables); + + configureTimezone(); + + if (this.serverVariables.containsKey("max_allowed_packet")) { + this.maxAllowedPacket = getServerVariableAsInt("max_allowed_packet", 1024 * 1024); + + int preferredBlobSendChunkSize = getBlobSendChunkSize(); + + int allowedBlobSendChunkSize = Math.min(preferredBlobSendChunkSize, + this.maxAllowedPacket) - + ServerPreparedStatement.BLOB_STREAM_READ_BUF_SIZE + - 11 /* LONG_DATA and MySQLIO packet header size */; + + setBlobSendChunkSize(String.valueOf(allowedBlobSendChunkSize)); + } + + if (this.serverVariables.containsKey("net_buffer_length")) { + this.netBufferLength = getServerVariableAsInt("net_buffer_length", 16 * 1024); + } + + checkTransactionIsolationLevel(); + + if (!versionMeetsMinimum(4, 1, 0)) { + checkServerEncoding(); + } + + this.io.checkForCharsetMismatch(); + + if (this.serverVariables.containsKey("sql_mode")) { + int sqlMode = 0; + + String sqlModeAsString = (String) this.serverVariables + .get("sql_mode"); + try { + sqlMode = Integer.parseInt(sqlModeAsString); + } catch (NumberFormatException nfe) { + // newer versions of the server has this as a string-y + // list... + sqlMode = 0; + + if (sqlModeAsString != null) { + if (sqlModeAsString.indexOf("ANSI_QUOTES") != -1) { + sqlMode |= 4; + } + + if (sqlModeAsString.indexOf("NO_BACKSLASH_ESCAPES") != -1) { + this.noBackslashEscapes = true; + } + } + } + + if ((sqlMode & 4) > 0) { + this.useAnsiQuotes = true; + } else { + this.useAnsiQuotes = false; + } + } + } + + this.errorMessageEncoding = + CharsetMapping.getCharacterEncodingForErrorMessages(this); + + + boolean overrideDefaultAutocommit = isAutoCommitNonDefaultOnServer(); + + configureClientCharacterSet(); + + if (versionMeetsMinimum(3, 23, 15)) { + this.transactionsSupported = true; + + if (!overrideDefaultAutocommit) { + setAutoCommit(true); // to override anything + // the server is set to...reqd + // by JDBC spec. + } + } else { + this.transactionsSupported = false; + } + + + if (versionMeetsMinimum(3, 23, 36)) { + this.hasIsolationLevels = true; + } else { + this.hasIsolationLevels = false; + } + + this.hasQuotedIdentifiers = versionMeetsMinimum(3, 23, 6); + + this.io.resetMaxBuf(); + + // + // If we're using MySQL 4.1.0 or newer, we need to figure + // out what character set metadata will be returned in, + // and then map that to a Java encoding name. + // + // We've already set it, and it might be different than what + // was originally on the server, which is why we use the + // "special" key to retrieve it + if (this.io.versionMeetsMinimum(4, 1, 0)) { + String characterSetResultsOnServerMysql = (String) this.serverVariables + .get(JDBC_LOCAL_CHARACTER_SET_RESULTS); + + if (characterSetResultsOnServerMysql == null + || StringUtils.startsWithIgnoreCaseAndWs( + characterSetResultsOnServerMysql, "NULL") + || characterSetResultsOnServerMysql.length() == 0) { + String defaultMetadataCharsetMysql = (String) this.serverVariables + .get("character_set_system"); + String defaultMetadataCharset = null; + + if (defaultMetadataCharsetMysql != null) { + defaultMetadataCharset = CharsetMapping + .getJavaEncodingForMysqlEncoding( + defaultMetadataCharsetMysql, this); + } else { + defaultMetadataCharset = "UTF-8"; + } + + this.characterSetMetadata = defaultMetadataCharset; + } else { + this.characterSetResultsOnServer = CharsetMapping + .getJavaEncodingForMysqlEncoding( + characterSetResultsOnServerMysql, this); + this.characterSetMetadata = this.characterSetResultsOnServer; + } + } + + // + // Query cache is broken wrt. multi-statements before MySQL-4.1.10 + // + + if (this.versionMeetsMinimum(4, 1, 0) + && !this.versionMeetsMinimum(4, 1, 10) + && getAllowMultiQueries()) { + if ("ON".equalsIgnoreCase((String) this.serverVariables + .get("query_cache_type")) + && !"0".equalsIgnoreCase((String) this.serverVariables + .get("query_cache_size"))) { + setAllowMultiQueries(false); + } + } + + // + // Server can do this more efficiently for us + // + + setupServerForTruncationChecks(); + } + + private int getServerVariableAsInt(String variableName, int fallbackValue) + throws SQLException { + try { + return Integer.parseInt((String) this.serverVariables + .get(variableName)); + } catch (NumberFormatException nfe) { + getLog().logWarn(Messages.getString("Connection.BadValueInServerVariables", new Object[] {variableName, + this.serverVariables.get(variableName), new Integer(fallbackValue)})); + + return fallbackValue; + } + } + + /** + * Has the default autocommit value of 0 been changed on the server + * via init_connect? + * + * @return true if autocommit is not the default of '0' on the server. + * + * @throws SQLException + */ + private boolean isAutoCommitNonDefaultOnServer() throws SQLException { + boolean overrideDefaultAutocommit = false; + + String initConnectValue = (String) this.serverVariables + .get("init_connect"); + + if (versionMeetsMinimum(4, 1, 2) && initConnectValue != null + && initConnectValue.length() > 0) { + if (!getElideSetAutoCommits()) { + // auto-commit might have changed + java.sql.ResultSet rs = null; + java.sql.Statement stmt = null; + + try { + stmt = getMetadataSafeStatement(); + + rs = stmt.executeQuery("SELECT @@session.autocommit"); + + if (rs.next()) { + this.autoCommit = rs.getBoolean(1); + if (this.autoCommit != true) { + overrideDefaultAutocommit = true; + } + } + + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException sqlEx) { + // do nothing + } + } + + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { + // do nothing + } + } + } + } else { + if (this.getIO().isSetNeededForAutoCommitMode(true)) { + // we're not in standard autocommit=true mode + this.autoCommit = false; + overrideDefaultAutocommit = true; + } + } + } + + return overrideDefaultAutocommit; + } + + private void setupServerForTruncationChecks() throws SQLException { + if (getJdbcCompliantTruncation()) { + if (versionMeetsMinimum(5, 0, 2)) { + + String currentSqlMode = + (String)this.serverVariables.get("sql_mode"); + + boolean strictTransTablesIsSet = StringUtils.indexOfIgnoreCase(currentSqlMode, "STRICT_TRANS_TABLES") != -1; + + if (currentSqlMode == null || + currentSqlMode.length() == 0 || !strictTransTablesIsSet) { + StringBuffer commandBuf = new StringBuffer("SET sql_mode='"); + + if (currentSqlMode != null && currentSqlMode.length() > 0) { + commandBuf.append(currentSqlMode); + commandBuf.append(","); + } + + commandBuf.append("STRICT_TRANS_TABLES'"); + + execSQL(null, commandBuf.toString(), -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + + setJdbcCompliantTruncation(false); // server's handling this for us now + } else if (strictTransTablesIsSet) { + // We didn't set it, but someone did, so we piggy back on it + setJdbcCompliantTruncation(false); // server's handling this for us now + } + + } + } + } + + protected boolean isClientTzUTC() { + return this.isClientTzUTC; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isClosed() { + return this.isClosed; + } + + protected boolean isCursorFetchEnabled() throws SQLException { + return (versionMeetsMinimum(5, 0, 2) && getUseCursorFetch()); + } + + public boolean isInGlobalTx() { + return this.isInGlobalTx; + } + + /** + * Is this connection connected to the first host in the list if + * there is a list of servers in the URL? + * + * @return true if this connection is connected to the first in + * the list. + */ + public synchronized boolean isMasterConnection() { + return !this.failedOver; + } + + /** + * Is the server in a sql_mode that doesn't allow us to use \\ to escape + * things? + * + * @return Returns the noBackslashEscapes. + */ + public boolean isNoBackslashEscapesSet() { + return this.noBackslashEscapes; + } + + boolean isReadInfoMsgEnabled() { + return this.readInfoMsg; + } + + /** + * Tests to see if the connection is in Read Only Mode. Note that we cannot + * really put the database in read only mode, but we pretend we can by + * returning the value of the readOnly flag + * + * @return true if the connection is read only + * @exception SQLException + * if a database access error occurs + */ + public boolean isReadOnly() throws SQLException { + return this.readOnly; + } + + protected boolean isRunningOnJDK13() { + return this.isRunningOnJDK13; + } + + public synchronized boolean isSameResource(Connection otherConnection) { + if (otherConnection == null) { + return false; + } + + boolean directCompare = true; + + String otherHost = otherConnection.origHostToConnectTo; + String otherOrigDatabase = otherConnection.origDatabaseToConnectTo; + String otherCurrentCatalog = otherConnection.database; + + if (!nullSafeCompare(otherHost, this.origHostToConnectTo)) { + directCompare = false; + } else if (otherHost != null && otherHost.indexOf(",") == -1 && + otherHost.indexOf(":") == -1) { + // need to check port numbers + directCompare = (otherConnection.origPortToConnectTo == + this.origPortToConnectTo); + } + + if (directCompare) { + if (!nullSafeCompare(otherOrigDatabase, this.origDatabaseToConnectTo)) { directCompare = false; + directCompare = false; + } else if (!nullSafeCompare(otherCurrentCatalog, this.database)) { + directCompare = false; + } + } + + if (directCompare) { + return true; + } + + // Has the user explicitly set a resourceId? + String otherResourceId = otherConnection.getResourceId(); + String myResourceId = getResourceId(); + + if (otherResourceId != null || myResourceId != null) { + directCompare = nullSafeCompare(otherResourceId, myResourceId); + + if (directCompare) { + return true; + } + } + + return false; + } + + protected boolean isServerTzUTC() { + return this.isServerTzUTC; + } + + private boolean usingCachedConfig = false; + + /** + * Loads the result of 'SHOW VARIABLES' into the serverVariables field so + * that the driver can configure itself. + * + * @throws SQLException + * if the 'SHOW VARIABLES' query fails for any reason. + */ + private void loadServerVariables() throws SQLException { + + if (getCacheServerConfiguration()) { + synchronized (serverConfigByUrl) { + Map cachedVariableMap = (Map) serverConfigByUrl.get(getURL()); + + if (cachedVariableMap != null) { + this.serverVariables = cachedVariableMap; + this.usingCachedConfig = true; + + return; + } + } + } + + com.mysql.jdbc.Statement stmt = null; + com.mysql.jdbc.ResultSet results = null; + + try { + stmt = (com.mysql.jdbc.Statement) createStatement(); + stmt.setEscapeProcessing(false); + + results = (com.mysql.jdbc.ResultSet) stmt + .executeQuery("SHOW SESSION VARIABLES"); + + while (results.next()) { + this.serverVariables.put(results.getString(1), results + .getString(2)); + } + + if (getCacheServerConfiguration()) { + synchronized (serverConfigByUrl) { + serverConfigByUrl.put(getURL(), this.serverVariables); + } + } + } catch (SQLException e) { + throw e; + } finally { + if (results != null) { + try { + results.close(); + } catch (SQLException sqlE) { + ; + } + } + + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlE) { + ; + } + } + } + } + + /** + * Is the server configured to use lower-case table names only? + * + * @return true if lower_case_table_names is 'on' + */ + public boolean lowerCaseTableNames() { + return this.lowerCaseTableNames; + } + + /** + * Has the maxRows value changed? + * + * @param stmt + * DOCUMENT ME! + */ + void maxRowsChanged(Statement stmt) { + synchronized (this.mutex) { + if (this.statementsUsingMaxRows == null) { + this.statementsUsingMaxRows = new HashMap(); + } + + this.statementsUsingMaxRows.put(stmt, stmt); + + this.maxRowsChanged = true; + } + } + + /** + * A driver may convert the JDBC sql grammar into its system's native SQL + * grammar prior to sending it; nativeSQL returns the native form of the + * statement that the driver would have sent. + * + * @param sql + * a SQL statement that may contain one or more '?' parameter + * placeholders + * @return the native form of this statement + * @exception SQLException + * if a database access error occurs + */ + public String nativeSQL(String sql) throws SQLException { + if (sql == null) { + return null; + } + + Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, + serverSupportsConvertFn(), + this); + + if (escapedSqlResult instanceof String) { + return (String) escapedSqlResult; + } + + return ((EscapeProcessorResult) escapedSqlResult).escapedSql; + } + + private CallableStatement parseCallableStatement(String sql) + throws SQLException { + Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, + serverSupportsConvertFn(), this); + + boolean isFunctionCall = false; + String parsedSql = null; + + if (escapedSqlResult instanceof EscapeProcessorResult) { + parsedSql = ((EscapeProcessorResult) escapedSqlResult).escapedSql; + isFunctionCall = ((EscapeProcessorResult) escapedSqlResult).callingStoredFunction; + } else { + parsedSql = (String) escapedSqlResult; + isFunctionCall = false; + } + + return new CallableStatement(this, parsedSql, this.database, + isFunctionCall); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean parserKnowsUnicode() { + return this.parserKnowsUnicode; + } + + /** + * Detect if the connection is still good + * + * @throws SQLException + * if the ping fails + */ + public void ping() throws SQLException { + pingInternal(true); + } + + private void pingInternal(boolean checkForClosedConnection) + throws SQLException { + if (checkForClosedConnection) { + checkClosed(); + } + + // Need MySQL-3.22.1, but who uses anything older!? + this.io.sendCommand(MysqlDefs.PING, null, null, false, null); + } + + /** + * DOCUMENT ME! + * + * @param sql + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.CallableStatement prepareCall(String sql) + throws SQLException { + if (this.getUseUltraDevWorkAround()) { + return new UltraDevWorkAround(prepareStatement(sql)); + } + + return prepareCall(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY); + } + + /** + * JDBC 2.0 Same as prepareCall() above, but allows the default result set + * type and result set concurrency type to be overridden. + * + * @param sql + * the SQL representing the callable statement + * @param resultSetType + * a result set type, see ResultSet.TYPE_XXX + * @param resultSetConcurrency + * a concurrency type, see ResultSet.CONCUR_XXX + * @return a new CallableStatement object containing the pre-compiled SQL + * statement + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.CallableStatement prepareCall(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException { + if (versionMeetsMinimum(5, 0, 0)) { + CallableStatement cStmt = null; + + if (!getCacheCallableStatements()) { + + cStmt = parseCallableStatement(sql); + } else { + synchronized (this.parsedCallableStatementCache) { + CompoundCacheKey key = new CompoundCacheKey(getCatalog(), sql); + + CallableStatement.CallableStatementParamInfo cachedParamInfo = (CallableStatement.CallableStatementParamInfo) this.parsedCallableStatementCache + .get(key); + + if (cachedParamInfo != null) { + cStmt = new CallableStatement(this, cachedParamInfo); + } else { + cStmt = parseCallableStatement(sql); + + cachedParamInfo = cStmt.paramInfo; + + this.parsedCallableStatementCache.put(key, cachedParamInfo); + } + } + } + + cStmt.setResultSetType(resultSetType); + cStmt.setResultSetConcurrency(resultSetConcurrency); + + return cStmt; + } + + throw SQLError.createSQLException("Callable statements not " + "supported.", + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } + + /** + * @see Connection#prepareCall(String, int, int, int) + */ + public java.sql.CallableStatement prepareCall(String sql, + int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + if (getPedantic()) { + if (resultSetHoldability != java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT) { + throw SQLError.createSQLException( + "HOLD_CUSRORS_OVER_COMMIT is only supported holdability level", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + CallableStatement cStmt = (com.mysql.jdbc.CallableStatement) prepareCall( + sql, resultSetType, resultSetConcurrency); + + return cStmt; + } + + /** + * A SQL statement with or without IN parameters can be pre-compiled and + * stored in a PreparedStatement object. This object can then be used to + * efficiently execute this statement multiple times. + *

+ * Note: This method is optimized for handling parametric SQL + * statements that benefit from precompilation if the driver supports + * precompilation. In this case, the statement is not sent to the database + * until the PreparedStatement is executed. This has no direct effect on + * users; however it does affect which method throws certain + * java.sql.SQLExceptions + *

+ *

+ * MySQL does not support precompilation of statements, so they are handled + * by the driver. + *

+ * + * @param sql + * a SQL statement that may contain one or more '?' IN parameter + * placeholders + * @return a new PreparedStatement object containing the pre-compiled + * statement. + * @exception SQLException + * if a database access error occurs. + */ + public java.sql.PreparedStatement prepareStatement(String sql) + throws SQLException { + return prepareStatement(sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY); + } + + /** + * @see Connection#prepareStatement(String, int) + */ + public java.sql.PreparedStatement prepareStatement(String sql, + int autoGenKeyIndex) throws SQLException { + java.sql.PreparedStatement pStmt = prepareStatement(sql); + + ((com.mysql.jdbc.PreparedStatement) pStmt) + .setRetrieveGeneratedKeys(autoGenKeyIndex == java.sql.Statement.RETURN_GENERATED_KEYS); + + return pStmt; + } + + /** + * JDBC 2.0 Same as prepareStatement() above, but allows the default result + * set type and result set concurrency type to be overridden. + * + * @param sql + * the SQL query containing place holders + * @param resultSetType + * a result set type, see ResultSet.TYPE_XXX + * @param resultSetConcurrency + * a concurrency type, see ResultSet.CONCUR_XXX + * @return a new PreparedStatement object containing the pre-compiled SQL + * statement + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.PreparedStatement prepareStatement(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException { + checkClosed(); + + // + // FIXME: Create warnings if can't create results of the given + // type or concurrency + // + PreparedStatement pStmt = null; + + boolean canServerPrepare = true; + + String nativeSql = getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql; + + if (getEmulateUnsupportedPstmts()) { + canServerPrepare = canHandleAsServerPreparedStatement(nativeSql); + } + + if (this.useServerPreparedStmts && canServerPrepare) { + if (this.getCachePreparedStatements()) { + synchronized (this.serverSideStatementCache) { + pStmt = (com.mysql.jdbc.ServerPreparedStatement)this.serverSideStatementCache.remove(sql); + + if (pStmt != null) { + ((com.mysql.jdbc.ServerPreparedStatement)pStmt).setClosed(false); + pStmt.clearParameters(); + } + + if (pStmt == null) { + try { + pStmt = new com.mysql.jdbc.ServerPreparedStatement(this, nativeSql, + this.database, resultSetType, resultSetConcurrency); + if (sql.length() < getPreparedStatementCacheSqlLimit()) { + ((com.mysql.jdbc.ServerPreparedStatement)pStmt).isCached = true; + } + } catch (SQLException sqlEx) { + // Punt, if necessary + if (getEmulateUnsupportedPstmts()) { + pStmt = clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false); + + if (sql.length() < getPreparedStatementCacheSqlLimit()) { + this.serverSideStatementCheckCache.put(sql, Boolean.FALSE); + } + } else { + throw sqlEx; + } + } + } + } + } else { + try { + pStmt = new com.mysql.jdbc.ServerPreparedStatement(this, nativeSql, + this.database, resultSetType, resultSetConcurrency); + } catch (SQLException sqlEx) { + // Punt, if necessary + if (getEmulateUnsupportedPstmts()) { + pStmt = clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false); + } else { + throw sqlEx; + } + } + } + } else { + pStmt = clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false); + } + + return pStmt; + } + + /** + * @see Connection#prepareStatement(String, int, int, int) + */ + public java.sql.PreparedStatement prepareStatement(String sql, + int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + if (getPedantic()) { + if (resultSetHoldability != java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT) { + throw SQLError.createSQLException( + "HOLD_CUSRORS_OVER_COMMIT is only supported holdability level", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + return prepareStatement(sql, resultSetType, resultSetConcurrency); + } + + /** + * @see Connection#prepareStatement(String, int[]) + */ + public java.sql.PreparedStatement prepareStatement(String sql, + int[] autoGenKeyIndexes) throws SQLException { + java.sql.PreparedStatement pStmt = prepareStatement(sql); + + ((com.mysql.jdbc.PreparedStatement) pStmt) + .setRetrieveGeneratedKeys((autoGenKeyIndexes != null) + && (autoGenKeyIndexes.length > 0)); + + return pStmt; + } + + /** + * @see Connection#prepareStatement(String, String[]) + */ + public java.sql.PreparedStatement prepareStatement(String sql, + String[] autoGenKeyColNames) throws SQLException { + java.sql.PreparedStatement pStmt = prepareStatement(sql); + + ((com.mysql.jdbc.PreparedStatement) pStmt) + .setRetrieveGeneratedKeys((autoGenKeyColNames != null) + && (autoGenKeyColNames.length > 0)); + + return pStmt; + } + + /** + * Closes connection and frees resources. + * + * @param calledExplicitly + * is this being called from close() + * @param issueRollback + * should a rollback() be issued? + * @throws SQLException + * if an error occurs + */ + protected void realClose(boolean calledExplicitly, boolean issueRollback, + boolean skipLocalTeardown, Throwable reason) throws SQLException { + SQLException sqlEx = null; + + if (this.isClosed()) { + return; + } + + this.forceClosedReason = reason; + + try { + if (!skipLocalTeardown) { + if (!getAutoCommit() && issueRollback) { + try { + rollback(); + } catch (SQLException ex) { + sqlEx = ex; + } + } + + reportMetrics(); + + if (getUseUsageAdvisor()) { + if (!calledExplicitly) { + String message = "Connection implicitly closed by Driver. You should call Connection.close() from your code to free resources more efficiently and avoid resource leaks."; + + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, "", //$NON-NLS-1$ + this.getCatalog(), this.getId(), -1, -1, System + .currentTimeMillis(), 0, Constants.MILLIS_I18N, + null, + this.pointOfOrigin, message)); + } + + long connectionLifeTime = System.currentTimeMillis() + - this.connectionCreationTimeMillis; + + if (connectionLifeTime < 500) { + String message = "Connection lifetime of < .5 seconds. You might be un-necessarily creating short-lived connections and should investigate connection pooling to be more efficient."; + + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, "", //$NON-NLS-1$ + this.getCatalog(), this.getId(), -1, -1, System + .currentTimeMillis(), 0, Constants.MILLIS_I18N, + null, + this.pointOfOrigin, message)); + } + } + + try { + closeAllOpenStatements(); + } catch (SQLException ex) { + sqlEx = ex; + } + + if (this.io != null) { + try { + this.io.quit(); + } catch (Exception e) { + ; + } + + } + } else { + this.io.forceClose(); + } + } finally { + this.openStatements = null; + this.io = null; + ProfileEventSink.removeInstance(this); + this.isClosed = true; + } + + if (sqlEx != null) { + throw sqlEx; + } + + } + + protected void recachePreparedStatement(ServerPreparedStatement pstmt) { + synchronized (this.serverSideStatementCache) { + this.serverSideStatementCache.put(pstmt.originalSql, pstmt); + } + } + + /** + * DOCUMENT ME! + * + * @param queryTimeMs + */ + protected void registerQueryExecutionTime(long queryTimeMs) { + if (queryTimeMs > this.longestQueryTimeMs) { + this.longestQueryTimeMs = queryTimeMs; + + repartitionPerformanceHistogram(); + } + + addToPerformanceHistogram(queryTimeMs, 1); + + if (queryTimeMs < this.shortestQueryTimeMs) { + this.shortestQueryTimeMs = (queryTimeMs == 0) ? 1 : queryTimeMs; + } + + this.numberOfQueriesIssued++; + + this.totalQueryTimeMs += queryTimeMs; + } + + /** + * Register a Statement instance as open. + * + * @param stmt + * the Statement instance to remove + */ + void registerStatement(Statement stmt) { + synchronized (this.openStatements) { + this.openStatements.put(stmt, stmt); + } + } + + /** + * @see Connection#releaseSavepoint(Savepoint) + */ + public void releaseSavepoint(Savepoint arg0) throws SQLException { + // this is a no-op + } + + private void repartitionHistogram(int[] histCounts, long[] histBreakpoints, + long currentLowerBound, long currentUpperBound) { + + if (oldHistCounts == null) { + oldHistCounts = new int[histCounts.length]; + oldHistBreakpoints = new long[histBreakpoints.length]; + } + + for (int i = 0; i < histCounts.length; i++) { + oldHistCounts[i] = histCounts[i]; + } + + for (int i = 0; i < oldHistBreakpoints.length; i++) { + oldHistBreakpoints[i] = histBreakpoints[i]; + } + + createInitialHistogram(histBreakpoints, currentLowerBound, + currentUpperBound); + + for (int i = 0; i < HISTOGRAM_BUCKETS; i++) { + addToHistogram(histCounts, histBreakpoints, oldHistBreakpoints[i], + oldHistCounts[i], currentLowerBound, currentUpperBound); + } + } + + private void repartitionPerformanceHistogram() { + checkAndCreatePerformanceHistogram(); + + repartitionHistogram(this.perfMetricsHistCounts, + this.perfMetricsHistBreakpoints, + this.shortestQueryTimeMs == Long.MAX_VALUE ? 0 + : this.shortestQueryTimeMs, this.longestQueryTimeMs); + } + + private void repartitionTablesAccessedHistogram() { + checkAndCreateTablesAccessedHistogram(); + + repartitionHistogram(this.numTablesMetricsHistCounts, + this.numTablesMetricsHistBreakpoints, + this.minimumNumberTablesAccessed == Long.MAX_VALUE ? 0 + : this.minimumNumberTablesAccessed, + this.maximumNumberTablesAccessed); + } + + private void reportMetrics() { + if (getGatherPerformanceMetrics()) { + StringBuffer logMessage = new StringBuffer(256); + + logMessage.append("** Performance Metrics Report **\n"); + logMessage.append("\nLongest reported query: " + + this.longestQueryTimeMs + " ms"); + logMessage.append("\nShortest reported query: " + + this.shortestQueryTimeMs + " ms"); + logMessage + .append("\nAverage query execution time: " + + (this.totalQueryTimeMs / this.numberOfQueriesIssued) + + " ms"); + logMessage.append("\nNumber of statements executed: " + + this.numberOfQueriesIssued); + logMessage.append("\nNumber of result sets created: " + + this.numberOfResultSetsCreated); + logMessage.append("\nNumber of statements prepared: " + + this.numberOfPrepares); + logMessage.append("\nNumber of prepared statement executions: " + + this.numberOfPreparedExecutes); + + if (this.perfMetricsHistBreakpoints != null) { + logMessage.append("\n\n\tTiming Histogram:\n"); + int maxNumPoints = 20; + int highestCount = Integer.MIN_VALUE; + + for (int i = 0; i < (HISTOGRAM_BUCKETS); i++) { + if (this.perfMetricsHistCounts[i] > highestCount) { + highestCount = this.perfMetricsHistCounts[i]; + } + } + + if (highestCount == 0) { + highestCount = 1; // avoid DIV/0 + } + + for (int i = 0; i < (HISTOGRAM_BUCKETS - 1); i++) { + + if (i == 0) { + logMessage.append("\n\tless than " + + this.perfMetricsHistBreakpoints[i + 1] + + " ms: \t" + this.perfMetricsHistCounts[i]); + } else { + logMessage.append("\n\tbetween " + + this.perfMetricsHistBreakpoints[i] + " and " + + this.perfMetricsHistBreakpoints[i + 1] + + " ms: \t" + this.perfMetricsHistCounts[i]); + } + + logMessage.append("\t"); + + int numPointsToGraph = (int) (maxNumPoints * ((double) this.perfMetricsHistCounts[i] / (double) highestCount)); + + for (int j = 0; j < numPointsToGraph; j++) { + logMessage.append("*"); + } + + if (this.longestQueryTimeMs < this.perfMetricsHistCounts[i + 1]) { + break; + } + } + + if (this.perfMetricsHistBreakpoints[HISTOGRAM_BUCKETS - 2] < this.longestQueryTimeMs) { + logMessage.append("\n\tbetween "); + logMessage + .append(this.perfMetricsHistBreakpoints[HISTOGRAM_BUCKETS - 2]); + logMessage.append(" and "); + logMessage + .append(this.perfMetricsHistBreakpoints[HISTOGRAM_BUCKETS - 1]); + logMessage.append(" ms: \t"); + logMessage + .append(this.perfMetricsHistCounts[HISTOGRAM_BUCKETS - 1]); + } + } + + if (this.numTablesMetricsHistBreakpoints != null) { + logMessage.append("\n\n\tTable Join Histogram:\n"); + int maxNumPoints = 20; + int highestCount = Integer.MIN_VALUE; + + for (int i = 0; i < (HISTOGRAM_BUCKETS); i++) { + if (this.numTablesMetricsHistCounts[i] > highestCount) { + highestCount = this.numTablesMetricsHistCounts[i]; + } + } + + if (highestCount == 0) { + highestCount = 1; // avoid DIV/0 + } + + for (int i = 0; i < (HISTOGRAM_BUCKETS - 1); i++) { + + if (i == 0) { + logMessage.append("\n\t" + + this.numTablesMetricsHistBreakpoints[i + 1] + + " tables or less: \t\t" + + this.numTablesMetricsHistCounts[i]); + } else { + logMessage.append("\n\tbetween " + + this.numTablesMetricsHistBreakpoints[i] + + " and " + + this.numTablesMetricsHistBreakpoints[i + 1] + + " tables: \t" + + this.numTablesMetricsHistCounts[i]); + } + + logMessage.append("\t"); + + int numPointsToGraph = (int) (maxNumPoints * ((double) this.numTablesMetricsHistCounts[i] / (double) highestCount)); + + for (int j = 0; j < numPointsToGraph; j++) { + logMessage.append("*"); + } + + if (this.maximumNumberTablesAccessed < this.numTablesMetricsHistBreakpoints[i + 1]) { + break; + } + } + + if (this.numTablesMetricsHistBreakpoints[HISTOGRAM_BUCKETS - 2] < this.maximumNumberTablesAccessed) { + logMessage.append("\n\tbetween "); + logMessage + .append(this.numTablesMetricsHistBreakpoints[HISTOGRAM_BUCKETS - 2]); + logMessage.append(" and "); + logMessage + .append(this.numTablesMetricsHistBreakpoints[HISTOGRAM_BUCKETS - 1]); + logMessage.append(" tables: "); + logMessage + .append(this.numTablesMetricsHistCounts[HISTOGRAM_BUCKETS - 1]); + } + } + + this.log.logInfo(logMessage); + + this.metricsLastReportedMs = System.currentTimeMillis(); + } + } + + /** + * Reports currently collected metrics if this feature is enabled and the + * timeout has passed. + */ + private void reportMetricsIfNeeded() { + if (getGatherPerformanceMetrics()) { + if ((System.currentTimeMillis() - this.metricsLastReportedMs) > getReportMetricsIntervalMillis()) { + reportMetrics(); + } + } + } + + protected void reportNumberOfTablesAccessed(int numTablesAccessed) { + if (numTablesAccessed < this.minimumNumberTablesAccessed) { + this.minimumNumberTablesAccessed = numTablesAccessed; + } + + if (numTablesAccessed > this.maximumNumberTablesAccessed) { + this.maximumNumberTablesAccessed = numTablesAccessed; + + repartitionTablesAccessedHistogram(); + } + + addToTablesAccessedHistogram(numTablesAccessed, 1); + } + + /** + * Resets the server-side state of this connection. Doesn't work for MySQL + * versions older than 4.0.6 or if isParanoid() is set (it will become a + * no-op in these cases). Usually only used from connection pooling code. + * + * @throws SQLException + * if the operation fails while resetting server state. + */ + public void resetServerState() throws SQLException { + if (!getParanoid() + && ((this.io != null) && versionMeetsMinimum(4, 0, 6))) { + changeUser(this.user, this.password); + } + } + + /** + * The method rollback() drops all changes made since the previous + * commit/rollback and releases any database locks currently held by the + * Connection. + * + * @exception SQLException + * if a database access error occurs + * @see commit + */ + public void rollback() throws SQLException { + synchronized (getMutex()) { + checkClosed(); + + try { + // no-op if _relaxAutoCommit == true + if (this.autoCommit && !getRelaxAutoCommit()) { + throw SQLError.createSQLException( + "Can't call rollback when autocommit=true", + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); + } else if (this.transactionsSupported) { + try { + rollbackNoChecks(); + } catch (SQLException sqlEx) { + // We ignore non-transactional tables if told to do so + if (getIgnoreNonTxTables() + && (sqlEx.getErrorCode() != SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) { + throw sqlEx; + } + } + } + } catch (SQLException sqlException) { + if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE + .equals(sqlException.getSQLState())) { + throw SQLError.createSQLException( + "Communications link failure during rollback(). Transaction resolution unknown.", + SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN); + } + + throw sqlException; + } finally { + this.needsPing = this.getReconnectAtTxEnd(); + } + } + } + + /** + * @see Connection#rollback(Savepoint) + */ + public void rollback(Savepoint savepoint) throws SQLException { + + if (versionMeetsMinimum(4, 0, 14) || versionMeetsMinimum(4, 1, 1)) { + synchronized (getMutex()) { + checkClosed(); + + try { + StringBuffer rollbackQuery = new StringBuffer( + "ROLLBACK TO SAVEPOINT "); + rollbackQuery.append('`'); + rollbackQuery.append(savepoint.getSavepointName()); + rollbackQuery.append('`'); + + java.sql.Statement stmt = null; + + try { + stmt = createStatement(); + + stmt.executeUpdate(rollbackQuery.toString()); + } catch (SQLException sqlEx) { + int errno = sqlEx.getErrorCode(); + + if (errno == 1181) { + String msg = sqlEx.getMessage(); + + if (msg != null) { + int indexOfError153 = msg.indexOf("153"); + + if (indexOfError153 != -1) { + throw SQLError.createSQLException("Savepoint '" + + savepoint.getSavepointName() + + "' does not exist", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT, + errno); + } + } + } + + // We ignore non-transactional tables if told to do so + if (getIgnoreNonTxTables() + && (sqlEx.getErrorCode() != SQLError.ER_WARNING_NOT_COMPLETE_ROLLBACK)) { + throw sqlEx; + } + + if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE + .equals(sqlEx.getSQLState())) { + throw SQLError.createSQLException( + "Communications link failure during rollback(). Transaction resolution unknown.", + SQLError.SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN); + } + + throw sqlEx; + } finally { + closeStatement(stmt); + } + } finally { + this.needsPing = this.getReconnectAtTxEnd(); + } + } + } else { + throw new NotImplemented(); + } + } + + private void rollbackNoChecks() throws SQLException { + if (getUseLocalSessionState() && versionMeetsMinimum(5, 0, 0)) { + if (!this.io.inTransactionOnServer()) { + return; // effectively a no-op + } + } + + execSQL(null, "rollback", -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + } + + /** + * DOCUMENT ME! + * + * @param sql + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public ServerPreparedStatement serverPrepare(String sql) + throws SQLException { + + String nativeSql = getProcessEscapeCodesForPrepStmts() ? nativeSQL(sql): sql; + + return new ServerPreparedStatement(this, nativeSql, this.getCatalog(), + java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, + java.sql.ResultSet.CONCUR_READ_ONLY); + } + + protected boolean serverSupportsConvertFn() throws SQLException { + return versionMeetsMinimum(4, 0, 2); + } + + /** + * If a connection is in auto-commit mode, than all its SQL statements will + * be executed and committed as individual transactions. Otherwise, its SQL + * statements are grouped into transactions that are terminated by either + * commit() or rollback(). By default, new connections are in auto- commit + * mode. The commit occurs when the statement completes or the next execute + * occurs, whichever comes first. In the case of statements returning a + * ResultSet, the statement completes when the last row of the ResultSet has + * been retrieved or the ResultSet has been closed. In advanced cases, a + * single statement may return multiple results as well as output parameter + * values. Here the commit occurs when all results and output param values + * have been retrieved. + *

+ * Note: MySQL does not support transactions, so this method is a + * no-op. + *

+ * + * @param autoCommitFlag - + * true enables auto-commit; false disables it + * @exception SQLException + * if a database access error occurs + */ + public void setAutoCommit(boolean autoCommitFlag) throws SQLException { + synchronized (getMutex()) { + checkClosed(); + + if (getAutoReconnectForPools()) { + setHighAvailability(true); + } + + try { + if (this.transactionsSupported) { + + boolean needsSetOnServer = true; + + if (this.getUseLocalSessionState() + && this.autoCommit == autoCommitFlag) { + needsSetOnServer = false; + } else if (!this.getHighAvailability()) { + needsSetOnServer = this.getIO() + .isSetNeededForAutoCommitMode(autoCommitFlag); + } + + // this internal value must be set first as failover depends on + // it + // being set to true to fail over (which is done by most + // app servers and connection pools at the end of + // a transaction), and the driver issues an implicit set + // based on this value when it (re)-connects to a server + // so the value holds across connections + this.autoCommit = autoCommitFlag; + + if (needsSetOnServer) { + execSQL(null, autoCommitFlag ? "SET autocommit=1" + : "SET autocommit=0", -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + } + + } else { + if ((autoCommitFlag == false) && !getRelaxAutoCommit()) { + throw SQLError.createSQLException("MySQL Versions Older than 3.23.15 " + + "do not support transactions", + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); + } + + this.autoCommit = autoCommitFlag; + } + } finally { + if (this.getAutoReconnectForPools()) { + setHighAvailability(false); + } + } + + return; + } + } + + /** + * A sub-space of this Connection's database may be selected by setting a + * catalog name. If the driver does not support catalogs, it will silently + * ignore this request + *

+ * Note: MySQL's notion of catalogs are individual databases. + *

+ * + * @param catalog + * the database for this connection to use + * @throws SQLException + * if a database access error occurs + */ + public void setCatalog(String catalog) throws SQLException { + synchronized (getMutex()) { + checkClosed(); + + if (catalog == null) { + throw SQLError.createSQLException("Catalog can not be null", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (getUseLocalSessionState()) { + if (this.lowerCaseTableNames) { + if (this.database.equalsIgnoreCase(catalog)) { + return; + } + } else { + if (this.database.equals(catalog)) { + return; + } + } + } + + String quotedId = this.dbmd.getIdentifierQuoteString(); + + if ((quotedId == null) || quotedId.equals(" ")) { + quotedId = ""; + } + + StringBuffer query = new StringBuffer("USE "); + query.append(quotedId); + query.append(catalog); + query.append(quotedId); + + execSQL(null, query.toString(), -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + + this.database = catalog; + } + } + + /** + * @param failedOver + * The failedOver to set. + */ + public synchronized void setFailedOver(boolean flag) { + this.failedOver = flag; + } + + /** + * Sets state for a failed-over connection + * + * @throws SQLException + * DOCUMENT ME! + */ + private void setFailedOverState() throws SQLException { + if (getFailOverReadOnly()) { + setReadOnlyInternal(true); + } + + this.queriesIssuedFailedOver = 0; + this.failedOver = true; + this.masterFailTimeMillis = System.currentTimeMillis(); + } + + /** + * @see Connection#setHoldability(int) + */ + public void setHoldability(int arg0) throws SQLException { + // do nothing + } + + public void setInGlobalTx(boolean flag) { + this.isInGlobalTx = flag; + } + + // exposed for testing + /** + * @param preferSlaveDuringFailover + * The preferSlaveDuringFailover to set. + */ + public void setPreferSlaveDuringFailover(boolean flag) { + this.preferSlaveDuringFailover = flag; + } + + void setReadInfoMsgEnabled(boolean flag) { + this.readInfoMsg = flag; + } + + /** + * You can put a connection in read-only mode as a hint to enable database + * optimizations Note: setReadOnly cannot be called while in the + * middle of a transaction + * + * @param readOnlyFlag - + * true enables read-only mode; false disables it + * @exception SQLException + * if a database access error occurs + */ + public void setReadOnly(boolean readOnlyFlag) throws SQLException { + checkClosed(); + + // Ignore calls to this method if we're failed over and + // we're configured to fail over read-only. + if (this.failedOver && getFailOverReadOnly() && !readOnlyFlag) { + return; + } + + setReadOnlyInternal(readOnlyFlag); + } + + protected void setReadOnlyInternal(boolean readOnlyFlag) throws SQLException { + this.readOnly = readOnlyFlag; + } + + /** + * @see Connection#setSavepoint() + */ + public java.sql.Savepoint setSavepoint() throws SQLException { + MysqlSavepoint savepoint = new MysqlSavepoint(); + + setSavepoint(savepoint); + + return savepoint; + } + + private void setSavepoint(MysqlSavepoint savepoint) throws SQLException { + + if (versionMeetsMinimum(4, 0, 14) || versionMeetsMinimum(4, 1, 1)) { + synchronized (getMutex()) { + checkClosed(); + + StringBuffer savePointQuery = new StringBuffer("SAVEPOINT "); + savePointQuery.append('`'); + savePointQuery.append(savepoint.getSavepointName()); + savePointQuery.append('`'); + + java.sql.Statement stmt = null; + + try { + stmt = createStatement(); + + stmt.executeUpdate(savePointQuery.toString()); + } finally { + closeStatement(stmt); + } + } + } else { + throw new NotImplemented(); + } + } + + /** + * @see Connection#setSavepoint(String) + */ + public synchronized java.sql.Savepoint setSavepoint(String name) throws SQLException { + MysqlSavepoint savepoint = new MysqlSavepoint(name); + + setSavepoint(savepoint); + + return savepoint; + } + + /** + * + */ + private void setSessionVariables() throws SQLException { + if (this.versionMeetsMinimum(4, 0, 0) && getSessionVariables() != null) { + List variablesToSet = StringUtils.split(getSessionVariables(), ",", "\"'", "\"'", + false); + + int numVariablesToSet = variablesToSet.size(); + + java.sql.Statement stmt = null; + + try { + stmt = getMetadataSafeStatement(); + + for (int i = 0; i < numVariablesToSet; i++) { + String variableValuePair = (String) variablesToSet.get(i); + + if (variableValuePair.startsWith("@")) { + stmt.executeUpdate("SET " + variableValuePair); + } else { + stmt.executeUpdate("SET SESSION " + variableValuePair); + } + } + } finally { + if (stmt != null) { + stmt.close(); + } + } + } + + } + + /** + * Attempts to change the transaction isolation level for this + * Connection object to the one given. + * The constants defined in the interface Connection + * are the possible transaction isolation levels. + *

+ * Note: If this method is called during a transaction, the result + * is implementation-defined. + * + * @param level one of the following Connection constants: + * Connection.TRANSACTION_READ_UNCOMMITTED, + * Connection.TRANSACTION_READ_COMMITTED, + * Connection.TRANSACTION_REPEATABLE_READ, or + * Connection.TRANSACTION_SERIALIZABLE. + * (Note that Connection.TRANSACTION_NONE cannot be used + * because it specifies that transactions are not supported.) + * @exception SQLException if a database access error occurs + * or the given parameter is not one of the Connection + * constants + * @see DatabaseMetaData#supportsTransactionIsolationLevel + * @see #getTransactionIsolation + */ + public synchronized void setTransactionIsolation(int level) throws SQLException { + checkClosed(); + + if (this.hasIsolationLevels) { + String sql = null; + + boolean shouldSendSet = false; + + if (getAlwaysSendSetIsolation()) { + shouldSendSet = true; + } else { + if (level != this.isolationLevel) { + shouldSendSet = true; + } + } + + if (getUseLocalSessionState()) { + shouldSendSet = this.isolationLevel != level; + } + + if (shouldSendSet) { + switch (level) { + case java.sql.Connection.TRANSACTION_NONE: + throw SQLError.createSQLException("Transaction isolation level " + + "NONE not supported by MySQL"); + + case java.sql.Connection.TRANSACTION_READ_COMMITTED: + sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED"; + + break; + + case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED: + sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"; + + break; + + case java.sql.Connection.TRANSACTION_REPEATABLE_READ: + sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ"; + + break; + + case java.sql.Connection.TRANSACTION_SERIALIZABLE: + sql = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE"; + + break; + + default: + throw SQLError.createSQLException("Unsupported transaction " + + "isolation level '" + level + "'", + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } + + execSQL(null, sql, -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY,false, + this.database, true, false); + + this.isolationLevel = level; + } + } else { + throw SQLError.createSQLException("Transaction Isolation Levels are " + + "not supported on MySQL versions older than 3.23.36.", + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } + } + + /** + * JDBC 2.0 Install a type-map object as the default type-map for this + * connection + * + * @param map + * the type mapping + * @throws SQLException + * if a database error occurs. + */ + public synchronized void setTypeMap(java.util.Map map) throws SQLException { + this.typeMap = map; + } + + /** + * Should we try to connect back to the master? We try when we've been + * failed over >= this.secondsBeforeRetryMaster _or_ we've issued > + * this.queriesIssuedFailedOver + * + * @return DOCUMENT ME! + */ + private boolean shouldFallBack() { + long secondsSinceFailedOver = (System.currentTimeMillis() - this.masterFailTimeMillis) / 1000; + + // Done this way so we can set a condition in the debugger + boolean tryFallback = ((secondsSinceFailedOver >= getSecondsBeforeRetryMaster()) || (this.queriesIssuedFailedOver >= getQueriesBeforeRetryMaster())); + + return tryFallback; + } + + /** + * Used by MiniAdmin to shutdown a MySQL server + * + * @throws SQLException + * if the command can not be issued. + */ + public void shutdownServer() throws SQLException { + try { + this.io.sendCommand(MysqlDefs.SHUTDOWN, null, null, false, null); + } catch (Exception ex) { + throw SQLError.createSQLException("Unhandled exception '" + ex.toString() + + "'", SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean supportsIsolationLevel() { + return this.hasIsolationLevels; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean supportsQuotedIdentifiers() { + return this.hasQuotedIdentifiers; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean supportsTransactions() { + return this.transactionsSupported; + } + + /** + * Remove the given statement from the list of open statements + * + * @param stmt + * the Statement instance to remove + */ + void unregisterStatement(Statement stmt) { + if (this.openStatements != null) { + synchronized (this.openStatements) { + this.openStatements.remove(stmt); + } + } + } + + /** + * Called by statements on their .close() to let the connection know when it + * is safe to set the connection back to 'default' row limits. + * + * @param stmt + * the statement releasing it's max-rows requirement + * @throws SQLException + * if a database error occurs issuing the statement that sets + * the limit default. + */ + void unsetMaxRows(Statement stmt) throws SQLException { + synchronized (this.mutex) { + if (this.statementsUsingMaxRows != null) { + Object found = this.statementsUsingMaxRows.remove(stmt); + + if ((found != null) + && (this.statementsUsingMaxRows.size() == 0)) { + execSQL(null, "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, + null, java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.database, true, false); + + this.maxRowsChanged = false; + } + } + } + } + + boolean useAnsiQuotedIdentifiers() { + return this.useAnsiQuotes; + } + + /** + * Has maxRows() been set? + * + * @return DOCUMENT ME! + */ + boolean useMaxRows() { + synchronized (this.mutex) { + return this.maxRowsChanged; + } + } + + public boolean versionMeetsMinimum(int major, int minor, int subminor) + throws SQLException { + checkClosed(); + + return this.io.versionMeetsMinimum(major, minor, subminor); + } + + protected String getErrorMessageEncoding() { + return errorMessageEncoding; + } + + /* + * For testing failover scenarios + */ + private boolean hasTriedMasterFlag = false; + + public void clearHasTriedMaster() { + this.hasTriedMasterFlag = false; + } + + public boolean hasTriedMaster() { + return this.hasTriedMasterFlag; + } + + /** + * Returns cached metadata (or null if not cached) for the given query, + * which must match _exactly_. + * + * This method is synchronized by the caller on getMutex(), so if + * calling this method from internal code in the driver, make sure it's + * synchronized on the mutex that guards communication with the server. + * + * @param sql + * the query that is the key to the cache + * + * @return metadata cached for the given SQL, or none if it doesn't + * exist. + */ + protected CachedResultSetMetaData getCachedMetaData(String sql) { + if (this.resultSetMetadataCache != null) { + synchronized (this.resultSetMetadataCache) { + return (CachedResultSetMetaData) this.resultSetMetadataCache + .get(sql); + } + } + + return null; // no cache exists + } + + /** + * Caches CachedResultSetMetaData that has been placed in the cache using + * the given SQL as a key. + * + * This method is synchronized by the caller on getMutex(), so if + * calling this method from internal code in the driver, make sure it's + * synchronized on the mutex that guards communication with the server. + * + * @param sql the query that the metadata pertains too. + * @param cachedMetaData metadata (if it exists) to populate the cache. + * @param resultSet the result set to retreive metadata from, or apply to. + * + * @throws SQLException + */ + protected void initializeResultsMetadataFromCache(String sql, + CachedResultSetMetaData cachedMetaData, ResultSet resultSet) + throws SQLException { + + if (cachedMetaData == null) { + + // read from results + cachedMetaData = new CachedResultSetMetaData(); + cachedMetaData.fields = resultSet.fields; + + // assume that users will use named-based + // lookups + resultSet.buildIndexMapping(); + resultSet.initializeWithMetadata(); + + if (resultSet instanceof UpdatableResultSet) { + ((UpdatableResultSet)resultSet).checkUpdatability(); + } + + cachedMetaData.columnNameToIndex = resultSet.columnNameToIndex; + cachedMetaData.fullColumnNameToIndex = resultSet.fullColumnNameToIndex; + + cachedMetaData.metadata = resultSet.getMetaData(); + + this.resultSetMetadataCache.put(sql, cachedMetaData); + } else { + // initialize results from cached data + resultSet.fields = cachedMetaData.fields; + resultSet.columnNameToIndex = cachedMetaData.columnNameToIndex; + resultSet.fullColumnNameToIndex = cachedMetaData.fullColumnNameToIndex; + resultSet.hasBuiltIndexMapping = true; + resultSet.initializeWithMetadata(); + + if (resultSet instanceof UpdatableResultSet) { + ((UpdatableResultSet)resultSet).checkUpdatability(); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionFeatureNotAvailableException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionFeatureNotAvailableException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionFeatureNotAvailableException.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,67 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Thrown when a client requests a connection-level feature that isn't available + * for this particular distribution of Connector/J (currently only used by code + * that is export-controlled). + * + * @author Mark Matthews + * + * @version $Id: ConnectionFeatureNotAvailableException.java,v 1.1.2.1 + * 2005/05/13 18:58:38 mmatthews Exp $ + */ +public class ConnectionFeatureNotAvailableException extends + CommunicationsException { + + /** + * @param conn + * @param lastPacketSentTimeMs + * @param underlyingException + */ + public ConnectionFeatureNotAvailableException(Connection conn, + long lastPacketSentTimeMs, Exception underlyingException) { + super(conn, lastPacketSentTimeMs, underlyingException); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Throwable#getMessage() + */ + public String getMessage() { + return "Feature not available in this distribution of Connector/J"; + } + + /* + * (non-Javadoc) + * + * @see java.sql.SQLException#getSQLState() + */ + public String getSQLState() { + return SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionProperties.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionProperties.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionProperties.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,4184 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import com.mysql.jdbc.log.Jdk14Logger; +import com.mysql.jdbc.log.Log; +import com.mysql.jdbc.log.StandardLogger; + +import java.io.Serializable; +import java.io.UnsupportedEncodingException; + +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; + +import javax.naming.RefAddr; +import javax.naming.Reference; +import javax.naming.StringRefAddr; + +/** + * Represents configurable properties for Connections and DataSources. Can also + * expose properties as JDBC DriverPropertyInfo if required as well. + * + * @author Mark Matthews + * @version $Id: ConnectionProperties.java,v 1.1.2.2 2005/05/17 14:58:56 + * mmatthews Exp $ + */ +public class ConnectionProperties implements Serializable { + + private static final long serialVersionUID = 4257801713007640580L; + + class BooleanConnectionProperty extends ConnectionProperty implements Serializable { + + private static final long serialVersionUID = 2540132501709159404L; + + /** + * DOCUMENT ME! + * + * @param propertyNameToSet + * @param defaultValueToSet + * @param descriptionToSet + * DOCUMENT ME! + * @param sinceVersionToSet + * DOCUMENT ME! + */ + BooleanConnectionProperty(String propertyNameToSet, + boolean defaultValueToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + super(propertyNameToSet, new Boolean(defaultValueToSet), null, 0, + 0, descriptionToSet, sinceVersionToSet, category, + orderInCategory); + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#getAllowableValues() + */ + String[] getAllowableValues() { + return new String[] { "true", "false", "yes", "no" }; + } + + boolean getValueAsBoolean() { + return ((Boolean) this.valueAsObject).booleanValue(); + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#hasValueConstraints() + */ + boolean hasValueConstraints() { + return true; + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#initializeFrom(java.util.Properties) + */ + void initializeFrom(String extractedValue) throws SQLException { + if (extractedValue != null) { + validateStringValues(extractedValue); + + this.valueAsObject = new Boolean(extractedValue + .equalsIgnoreCase("TRUE") + || extractedValue.equalsIgnoreCase("YES")); + } else { + this.valueAsObject = this.defaultValue; + } + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#isRangeBased() + */ + boolean isRangeBased() { + return false; + } + + void setValue(boolean valueFlag) { + this.valueAsObject = new Boolean(valueFlag); + } + } + + abstract class ConnectionProperty implements Serializable { + String[] allowableValues; + + String categoryName; + + Object defaultValue; + + int lowerBound; + + int order; + + String propertyName; + + String sinceVersion; + + int upperBound; + + Object valueAsObject; + + boolean required; + + String description; + + public ConnectionProperty() {} + + ConnectionProperty(String propertyNameToSet, Object defaultValueToSet, + String[] allowableValuesToSet, int lowerBoundToSet, + int upperBoundToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + + this.description = descriptionToSet; + this.propertyName = propertyNameToSet; + this.defaultValue = defaultValueToSet; + this.valueAsObject = defaultValueToSet; + this.allowableValues = allowableValuesToSet; + this.lowerBound = lowerBoundToSet; + this.upperBound = upperBoundToSet; + this.required = false; + this.sinceVersion = sinceVersionToSet; + this.categoryName = category; + this.order = orderInCategory; + } + + String[] getAllowableValues() { + return this.allowableValues; + } + + /** + * @return Returns the categoryName. + */ + String getCategoryName() { + return this.categoryName; + } + + Object getDefaultValue() { + return this.defaultValue; + } + + int getLowerBound() { + return this.lowerBound; + } + + /** + * @return Returns the order. + */ + int getOrder() { + return this.order; + } + + String getPropertyName() { + return this.propertyName; + } + + int getUpperBound() { + return this.upperBound; + } + + Object getValueAsObject() { + return this.valueAsObject; + } + + abstract boolean hasValueConstraints(); + + void initializeFrom(Properties extractFrom) throws SQLException { + String extractedValue = extractFrom.getProperty(getPropertyName()); + extractFrom.remove(getPropertyName()); + initializeFrom(extractedValue); + } + + void initializeFrom(Reference ref) throws SQLException { + RefAddr refAddr = ref.get(getPropertyName()); + + if (refAddr != null) { + String refContentAsString = (String) refAddr.getContent(); + + initializeFrom(refContentAsString); + } + } + + abstract void initializeFrom(String extractedValue) throws SQLException; + + abstract boolean isRangeBased(); + + /** + * @param categoryName + * The categoryName to set. + */ + void setCategoryName(String categoryName) { + this.categoryName = categoryName; + } + + /** + * @param order + * The order to set. + */ + void setOrder(int order) { + this.order = order; + } + + void setValueAsObject(Object obj) { + this.valueAsObject = obj; + } + + void storeTo(Reference ref) { + if (getValueAsObject() != null) { + ref.add(new StringRefAddr(getPropertyName(), getValueAsObject() + .toString())); + } + } + + DriverPropertyInfo getAsDriverPropertyInfo() { + DriverPropertyInfo dpi = new DriverPropertyInfo(this.propertyName, null); + dpi.choices = getAllowableValues(); + dpi.value = (this.valueAsObject != null) ? this.valueAsObject.toString() : null; + dpi.required = this.required; + dpi.description = this.description; + + return dpi; + } + + + void validateStringValues(String valueToValidate) throws SQLException { + String[] validateAgainst = getAllowableValues(); + + if (valueToValidate == null) { + return; + } + + if ((validateAgainst == null) || (validateAgainst.length == 0)) { + return; + } + + for (int i = 0; i < validateAgainst.length; i++) { + if ((validateAgainst[i] != null) + && validateAgainst[i].equalsIgnoreCase(valueToValidate)) { + return; + } + } + + StringBuffer errorMessageBuf = new StringBuffer(); + + errorMessageBuf.append("The connection property '"); + errorMessageBuf.append(getPropertyName()); + errorMessageBuf.append("' only accepts values of the form: "); + + if (validateAgainst.length != 0) { + errorMessageBuf.append("'"); + errorMessageBuf.append(validateAgainst[0]); + errorMessageBuf.append("'"); + + for (int i = 1; i < (validateAgainst.length - 1); i++) { + errorMessageBuf.append(", "); + errorMessageBuf.append("'"); + errorMessageBuf.append(validateAgainst[i]); + errorMessageBuf.append("'"); + } + + errorMessageBuf.append(" or '"); + errorMessageBuf + .append(validateAgainst[validateAgainst.length - 1]); + errorMessageBuf.append("'"); + } + + errorMessageBuf.append(". The value '"); + errorMessageBuf.append(valueToValidate); + errorMessageBuf.append("' is not in this set."); + + throw SQLError.createSQLException(errorMessageBuf.toString(), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + class IntegerConnectionProperty extends ConnectionProperty implements Serializable { + + private static final long serialVersionUID = -3004305481796850832L; + + public IntegerConnectionProperty(String propertyNameToSet, + Object defaultValueToSet, String[] allowableValuesToSet, + int lowerBoundToSet, int upperBoundToSet, + String descriptionToSet, String sinceVersionToSet, + String category, int orderInCategory) { + super(propertyNameToSet, defaultValueToSet, allowableValuesToSet, + lowerBoundToSet, upperBoundToSet, descriptionToSet, sinceVersionToSet, + category, orderInCategory); + } + + int multiplier = 1; + + IntegerConnectionProperty(String propertyNameToSet, + int defaultValueToSet, int lowerBoundToSet, + int upperBoundToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + super(propertyNameToSet, new Integer(defaultValueToSet), null, + lowerBoundToSet, upperBoundToSet, descriptionToSet, + sinceVersionToSet, category, orderInCategory); + } + + /** + * DOCUMENT ME! + * + * @param propertyNameToSet + * @param defaultValueToSet + * @param descriptionToSet + * @param sinceVersionToSet + * DOCUMENT ME! + */ + + IntegerConnectionProperty(String propertyNameToSet, + int defaultValueToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + this(propertyNameToSet, defaultValueToSet, 0, 0, descriptionToSet, + sinceVersionToSet, category, orderInCategory); + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#getAllowableValues() + */ + String[] getAllowableValues() { + return null; + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#getLowerBound() + */ + int getLowerBound() { + return this.lowerBound; + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#getUpperBound() + */ + int getUpperBound() { + return this.upperBound; + } + + int getValueAsInt() { + return ((Integer) this.valueAsObject).intValue(); + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#hasValueConstraints() + */ + boolean hasValueConstraints() { + return false; + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#initializeFrom(java.lang.String) + */ + void initializeFrom(String extractedValue) throws SQLException { + if (extractedValue != null) { + try { + // Parse decimals, too + int intValue = Double.valueOf(extractedValue).intValue(); + + /* + * if (isRangeBased()) { if ((intValue < getLowerBound()) || + * (intValue > getUpperBound())) { throw new + * SQLException("The connection property '" + + * getPropertyName() + "' only accepts integer values in the + * range of " + getLowerBound() + " - " + getUpperBound() + ", + * the value '" + extractedValue + "' exceeds this range.", + * SQLError.SQL_STATE_ILLEGAL_ARGUMENT); } } + */ + this.valueAsObject = new Integer(intValue * multiplier); + } catch (NumberFormatException nfe) { + throw SQLError.createSQLException("The connection property '" + + getPropertyName() + + "' only accepts integer values. The value '" + + extractedValue + + "' can not be converted to an integer.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } else { + this.valueAsObject = this.defaultValue; + } + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#isRangeBased() + */ + boolean isRangeBased() { + return getUpperBound() != getLowerBound(); + } + + void setValue(int valueFlag) { + this.valueAsObject = new Integer(valueFlag); + } + } + + public class LongConnectionProperty extends IntegerConnectionProperty { + + private static final long serialVersionUID = 6068572984340480895L; + + LongConnectionProperty(String propertyNameToSet, + long defaultValueToSet, long lowerBoundToSet, + long upperBoundToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + super(propertyNameToSet, new Long(defaultValueToSet), null, + (int)lowerBoundToSet, (int)upperBoundToSet, descriptionToSet, + sinceVersionToSet, category, orderInCategory); + } + + + LongConnectionProperty(String propertyNameToSet, + long defaultValueToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + this(propertyNameToSet, + defaultValueToSet, 0, + 0, descriptionToSet, + sinceVersionToSet, category, orderInCategory); + } + + void setValue(long value) { + this.valueAsObject = new Long(value); + } + + long getValueAsLong() { + return ((Long) this.valueAsObject).longValue(); + } + + void initializeFrom(String extractedValue) throws SQLException { + if (extractedValue != null) { + try { + // Parse decimals, too + long longValue = Double.valueOf(extractedValue).longValue(); + + this.valueAsObject = new Long(longValue); + } catch (NumberFormatException nfe) { + throw SQLError.createSQLException("The connection property '" + + getPropertyName() + + "' only accepts long integer values. The value '" + + extractedValue + + "' can not be converted to a long integer.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } else { + this.valueAsObject = this.defaultValue; + } + } + } + + class MemorySizeConnectionProperty extends IntegerConnectionProperty implements Serializable { + + private static final long serialVersionUID = 7351065128998572656L; + + MemorySizeConnectionProperty(String propertyNameToSet, + int defaultValueToSet, int lowerBoundToSet, + int upperBoundToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + super(propertyNameToSet, defaultValueToSet, lowerBoundToSet, + upperBoundToSet, descriptionToSet, sinceVersionToSet, + category, orderInCategory); + // TODO Auto-generated constructor stub + } + + void initializeFrom(String extractedValue) throws SQLException { + if (extractedValue != null) { + if (extractedValue.endsWith("k") + || extractedValue.endsWith("K") + || extractedValue.endsWith("kb") + || extractedValue.endsWith("Kb") + || extractedValue.endsWith("kB")) { + multiplier = 1024; + int indexOfK = StringUtils.indexOfIgnoreCase( + extractedValue, "k"); + extractedValue = extractedValue.substring(0, indexOfK); + } else if (extractedValue.endsWith("m") + || extractedValue.endsWith("M") + || extractedValue.endsWith("G") + || extractedValue.endsWith("mb") + || extractedValue.endsWith("Mb") + || extractedValue.endsWith("mB")) { + multiplier = 1024 * 1024; + int indexOfM = StringUtils.indexOfIgnoreCase( + extractedValue, "m"); + extractedValue = extractedValue.substring(0, indexOfM); + } else if (extractedValue.endsWith("g") + || extractedValue.endsWith("G") + || extractedValue.endsWith("gb") + || extractedValue.endsWith("Gb") + || extractedValue.endsWith("gB")) { + multiplier = 1024 * 1024 * 1024; + int indexOfG = StringUtils.indexOfIgnoreCase( + extractedValue, "g"); + extractedValue = extractedValue.substring(0, indexOfG); + } + } + + super.initializeFrom(extractedValue); + } + + void setValue(String value) throws SQLException { + initializeFrom(value); + } + } + + class StringConnectionProperty extends ConnectionProperty implements Serializable { + + private static final long serialVersionUID = 5432127962785948272L; + + StringConnectionProperty(String propertyNameToSet, + String defaultValueToSet, String descriptionToSet, + String sinceVersionToSet, String category, int orderInCategory) { + this(propertyNameToSet, defaultValueToSet, null, descriptionToSet, + sinceVersionToSet, category, orderInCategory); + } + + /** + * DOCUMENT ME! + * + * @param propertyNameToSet + * @param defaultValueToSet + * @param allowableValuesToSet + * @param descriptionToSet + * @param sinceVersionToSet + * DOCUMENT ME! + */ + StringConnectionProperty(String propertyNameToSet, + String defaultValueToSet, String[] allowableValuesToSet, + String descriptionToSet, String sinceVersionToSet, + String category, int orderInCategory) { + super(propertyNameToSet, defaultValueToSet, allowableValuesToSet, + 0, 0, descriptionToSet, sinceVersionToSet, category, + orderInCategory); + } + + String getValueAsString() { + return (String) this.valueAsObject; + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#hasValueConstraints() + */ + boolean hasValueConstraints() { + return (this.allowableValues != null) + && (this.allowableValues.length > 0); + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#initializeFrom(java.util.Properties) + */ + void initializeFrom(String extractedValue) throws SQLException { + if (extractedValue != null) { + validateStringValues(extractedValue); + + this.valueAsObject = extractedValue; + } else { + this.valueAsObject = this.defaultValue; + } + } + + /** + * @see com.mysql.jdbc.ConnectionProperties.ConnectionProperty#isRangeBased() + */ + boolean isRangeBased() { + return false; + } + + void setValue(String valueFlag) { + this.valueAsObject = valueFlag; + } + } + + private static final String CONNECTION_AND_AUTH_CATEGORY = "Connection/Authentication"; + + private static final String NETWORK_CATEGORY = "Networking"; + + private static final String DEBUGING_PROFILING_CATEGORY = "Debuging/Profiling"; + + private static final String HA_CATEGORY = "High Availability and Clustering"; + + private static final String MISC_CATEGORY = "Miscellaneous"; + + private static final String PERFORMANCE_CATEGORY = "Performance Extensions"; + + private static final String SECURITY_CATEGORY = "Security"; + + private static final String[] PROPERTY_CATEGORIES = new String[] { + CONNECTION_AND_AUTH_CATEGORY, NETWORK_CATEGORY, + HA_CATEGORY, SECURITY_CATEGORY, + PERFORMANCE_CATEGORY, DEBUGING_PROFILING_CATEGORY, MISC_CATEGORY }; + + private static final ArrayList PROPERTY_LIST = new ArrayList(); + + private static final String STANDARD_LOGGER_NAME = StandardLogger.class.getName(); + + protected static final String ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL = "convertToNull"; + + protected static final String ZERO_DATETIME_BEHAVIOR_EXCEPTION = "exception"; + + protected static final String ZERO_DATETIME_BEHAVIOR_ROUND = "round"; + + static { + try { + java.lang.reflect.Field[] declaredFields = ConnectionProperties.class + .getDeclaredFields(); + + for (int i = 0; i < declaredFields.length; i++) { + if (ConnectionProperties.ConnectionProperty.class + .isAssignableFrom(declaredFields[i].getType())) { + PROPERTY_LIST.add(declaredFields[i]); + } + } + } catch (Exception ex) { + throw new RuntimeException(ex.toString()); + } + } + + /** + * Exposes all ConnectionPropertyInfo instances as DriverPropertyInfo + * + * @param info + * the properties to load into these ConnectionPropertyInfo + * instances + * @param slotsToReserve + * the number of DPI slots to reserve for 'standard' DPI + * properties (user, host, password, etc) + * @return a list of all ConnectionPropertyInfo instances, as + * DriverPropertyInfo + * @throws SQLException + * if an error occurs + */ + protected static DriverPropertyInfo[] exposeAsDriverPropertyInfo( + Properties info, int slotsToReserve) throws SQLException { + return (new ConnectionProperties() { + }).exposeAsDriverPropertyInfoInternal(info, slotsToReserve); + } + + private BooleanConnectionProperty allowLoadLocalInfile = new BooleanConnectionProperty( + "allowLoadLocalInfile", + true, + "Should the driver allow use of 'LOAD DATA LOCAL INFILE...' (defaults to 'true').", + "3.0.3", SECURITY_CATEGORY, Integer.MAX_VALUE); + + private BooleanConnectionProperty allowMultiQueries = new BooleanConnectionProperty( + "allowMultiQueries", + false, + "Allow the use of ';' to delimit multiple queries during one statement (true/false), defaults to 'false'", + "3.1.1", SECURITY_CATEGORY, 1); + + private BooleanConnectionProperty allowNanAndInf = new BooleanConnectionProperty( + "allowNanAndInf", + false, + "Should the driver allow NaN or +/- INF values in PreparedStatement.setDouble()?", + "3.1.5", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty allowUrlInLocalInfile = new BooleanConnectionProperty( + "allowUrlInLocalInfile", + false, + "Should the driver allow URLs in 'LOAD DATA LOCAL INFILE' statements?", + "3.1.4", SECURITY_CATEGORY, Integer.MAX_VALUE); + + private BooleanConnectionProperty alwaysSendSetIsolation = new BooleanConnectionProperty( + "alwaysSendSetIsolation", + true, + "Should the driver always communicate with the database when " + + " Connection.setTransactionIsolation() is called? " + + "If set to false, the driver will only communicate with the " + + "database when the requested transaction isolation is different " + + "than the whichever is newer, the last value that was set via " + + "Connection.setTransactionIsolation(), or the value that was read from " + + "the server when the connection was established.", + "3.1.7", PERFORMANCE_CATEGORY, Integer.MAX_VALUE); + + private BooleanConnectionProperty autoClosePStmtStreams = new BooleanConnectionProperty( + "autoClosePStmtStreams", + false, + "Should the driver automatically call .close() on streams/readers passed as " + + "arguments via set*() methods?", + "3.1.12", + MISC_CATEGORY, + Integer.MIN_VALUE); + + private BooleanConnectionProperty autoDeserialize = new BooleanConnectionProperty( + "autoDeserialize", + false, + "Should the driver automatically detect and de-serialize objects stored in BLOB fields?", + "3.1.5", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty autoGenerateTestcaseScript = new BooleanConnectionProperty( + "autoGenerateTestcaseScript", false, + "Should the driver dump the SQL it is executing, including server-side " + + "prepared statements to STDERR?", "3.1.9", + DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private boolean autoGenerateTestcaseScriptAsBoolean = false; + + private BooleanConnectionProperty autoReconnect = new BooleanConnectionProperty( + "autoReconnect", + false, + "Should the driver try to re-establish stale and/or dead connections? " + + " If enabled the driver will throw an exception for a queries issued on a stale or dead connection, " + + " which belong to the current transaction, but will attempt reconnect before the next query issued on the " + + "connection in a new transaction. The use of this feature " + + "is not recommended, because it has side effects related to session state and data consistency when applications don't" + + "handle SQLExceptions properly, and is only designed to be used " + + "when you are unable to configure your application to handle SQLExceptions resulting from dead and" + + "stale connections properly. Alternatively, investigate setting the MySQL server variable \"wait_timeout\"" + + "to some high value rather than the default of 8 hours.", + "1.1", HA_CATEGORY, 0); + + private BooleanConnectionProperty autoReconnectForPools = new BooleanConnectionProperty( + "autoReconnectForPools", + false, + "Use a reconnection strategy appropriate for connection pools (defaults to 'false')", + "3.1.3", HA_CATEGORY, 1); + + private boolean autoReconnectForPoolsAsBoolean = false; + + private MemorySizeConnectionProperty blobSendChunkSize = new MemorySizeConnectionProperty( + "blobSendChunkSize", + 1024 * 1024, + 1, + Integer.MAX_VALUE, + "Chunk to use when sending BLOB/CLOBs via ServerPreparedStatements", + "3.1.9", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty blobsAreStrings = new BooleanConnectionProperty( + "blobsAreStrings", false, + "Should the driver always treat BLOBs as Strings - specifically to work around dubious metadata " + + "returned by the server for GROUP BY clauses?", + "5.0.8", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty functionsNeverReturnBlobs = new BooleanConnectionProperty( + "functionsNeverReturnBlobs", false, + "Should the driver always treat data from functions returning BLOBs as Strings - specifically to work around dubious metadata " + + "returned by the server for GROUP BY clauses?", + "5.0.8", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty cacheCallableStatements = new BooleanConnectionProperty( + "cacheCallableStmts", false, + "Should the driver cache the parsing stage of CallableStatements", + "3.1.2", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty cachePreparedStatements = new BooleanConnectionProperty( + "cachePrepStmts", + false, + "Should the driver cache the parsing stage of PreparedStatements of client-side " + + "prepared statements, the \"check\" for suitability of server-side prepared " + + " and server-side prepared statements themselves?", + "3.0.10", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty cacheResultSetMetadata = new BooleanConnectionProperty( + "cacheResultSetMetadata", + false, + "Should the driver cache ResultSetMetaData for Statements and PreparedStatements? (Req. JDK-1.4+, true/false, default 'false')", + "3.1.1", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private boolean cacheResultSetMetaDataAsBoolean; + + private BooleanConnectionProperty cacheServerConfiguration = new BooleanConnectionProperty( + "cacheServerConfiguration", + false, + "Should the driver cache the results of " + + "'SHOW VARIABLES' and 'SHOW COLLATION' on a per-URL basis?", + "3.1.5", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty callableStatementCacheSize = new IntegerConnectionProperty( + "callableStmtCacheSize", + 100, + 0, + Integer.MAX_VALUE, + "If 'cacheCallableStmts' is enabled, how many callable statements should be cached?", + "3.1.2", PERFORMANCE_CATEGORY, 5); + + private BooleanConnectionProperty capitalizeTypeNames = new BooleanConnectionProperty( + "capitalizeTypeNames", + true, + "Capitalize type names in DatabaseMetaData? (usually only useful when using WebObjects, true/false, defaults to 'false')", + "2.0.7", MISC_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty characterEncoding = new StringConnectionProperty( + "characterEncoding", + null, + "If 'useUnicode' is set to true, what character encoding should the driver use when dealing with strings? (defaults is to 'autodetect')", + "1.1g", MISC_CATEGORY, 5); + + private String characterEncodingAsString = null; + + private StringConnectionProperty characterSetResults = new StringConnectionProperty( + "characterSetResults", null, + "Character set to tell the server to return results as.", "3.0.13", + MISC_CATEGORY, 6); + + private BooleanConnectionProperty clobberStreamingResults = new BooleanConnectionProperty( + "clobberStreamingResults", + false, + "This will cause a 'streaming' ResultSet to be automatically closed, " + + "and any outstanding data still streaming from the server to be discarded if another query is executed " + + "before all the data has been read from the server.", + "3.0.9", MISC_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty clobCharacterEncoding = new StringConnectionProperty( + "clobCharacterEncoding", + null, + "The character encoding to use for sending and retrieving TEXT, MEDIUMTEXT " + + "and LONGTEXT values instead of the configured connection characterEncoding", + "5.0.0", MISC_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty connectionCollation = new StringConnectionProperty( + "connectionCollation", + null, + "If set, tells the server to use this collation via 'set collation_connection'", + "3.0.13", MISC_CATEGORY, 7); + + private IntegerConnectionProperty connectTimeout = new IntegerConnectionProperty( + "connectTimeout", 0, 0, Integer.MAX_VALUE, + "Timeout for socket connect (in milliseconds), with 0 being no timeout. " + + "Only works on JDK-1.4 or newer. Defaults to '0'.", + "3.0.1", CONNECTION_AND_AUTH_CATEGORY, 9); + + private BooleanConnectionProperty continueBatchOnError = new BooleanConnectionProperty( + "continueBatchOnError", + true, + "Should the driver continue processing batch commands if " + + "one statement fails. The JDBC spec allows either way (defaults to 'true').", + "3.0.3", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty createDatabaseIfNotExist = new BooleanConnectionProperty( + "createDatabaseIfNotExist", + false, + "Creates the database given in the URL if it doesn't yet exist. Assumes " + + " the configured user has permissions to create databases.", + "3.1.9", MISC_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty defaultFetchSize = new IntegerConnectionProperty("defaultFetchSize", 0, "The driver will call setFetchSize(n) with this value on all newly-created Statements", "3.1.9", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty detectServerPreparedStmts = new BooleanConnectionProperty( + "useServerPrepStmts", + false, + "Use server-side prepared statements if the server supports them?", + "3.1.0", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty dontTrackOpenResources = new BooleanConnectionProperty( + "dontTrackOpenResources", + false, + "The JDBC specification requires the driver to automatically track and close resources, " + + "however if your application doesn't do a good job of " + + "explicitly calling close() on statements or result sets, " + + "this can cause memory leakage. Setting this property to true " + + "relaxes this constraint, and can be more memory efficient for " + + "some applications.", "3.1.7", PERFORMANCE_CATEGORY, + Integer.MIN_VALUE); + + private BooleanConnectionProperty dumpQueriesOnException = new BooleanConnectionProperty( + "dumpQueriesOnException", + false, + "Should the driver dump the contents of the query sent to the server in the message for SQLExceptions?", + "3.1.3", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty dynamicCalendars = new BooleanConnectionProperty( + "dynamicCalendars", + false, + "Should the driver retrieve the default" + + " calendar when required, or cache it per connection/session?", + "3.1.5", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty elideSetAutoCommits = new BooleanConnectionProperty( + "elideSetAutoCommits", + false, + "If using MySQL-4.1 or newer, should the driver only issue 'set autocommit=n' queries when the server's state doesn't match the requested state by Connection.setAutoCommit(boolean)?", + "3.1.3", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty emptyStringsConvertToZero = new BooleanConnectionProperty( + "emptyStringsConvertToZero", true, + "Should the driver allow conversions from empty string " + + "fields to numeric values of '0'?", "3.1.8", + MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty emulateLocators = new BooleanConnectionProperty( + "emulateLocators", false, "N/A", "3.1.0", MISC_CATEGORY, + Integer.MIN_VALUE); + + private BooleanConnectionProperty emulateUnsupportedPstmts = new BooleanConnectionProperty( + "emulateUnsupportedPstmts", + true, + "Should the driver detect prepared statements that are not supported by the server, and " + + "replace them with client-side emulated versions?", + "3.1.7", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty enablePacketDebug = new BooleanConnectionProperty( + "enablePacketDebug", + false, + "When enabled, a ring-buffer of 'packetDebugBufferSize' packets will be kept, and dumped when exceptions are thrown in key areas in the driver's code", + "3.1.3", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty enableQueryTimeouts = new BooleanConnectionProperty( + "enableQueryTimeouts", + true, + "When enabled, query timeouts set via Statement.setQueryTimeout() use a shared " + + "java.util.Timer instance for scheduling. Even if the timeout doesn't expire before the query is processed, there will be " + + "memory used by the TimerTask for the given timeout which won't be reclaimed until " + + "the time the timeout would have expired if it hadn't been cancelled by the driver. High-load environments " + + "might want to consider disabling this functionality.", + "5.0.6", + PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty explainSlowQueries = new BooleanConnectionProperty( + "explainSlowQueries", + false, + "If 'logSlowQueries' is enabled, should the driver automatically issue an 'EXPLAIN' on the" + + " server and send the results to the configured log at a WARN level?", + "3.1.2", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + /** When failed-over, set connection to read-only? */ + private BooleanConnectionProperty failOverReadOnly = new BooleanConnectionProperty( + "failOverReadOnly", + true, + "When failing over in autoReconnect mode, should the connection be set to 'read-only'?", + "3.0.12", HA_CATEGORY, 2); + + private BooleanConnectionProperty gatherPerformanceMetrics = new BooleanConnectionProperty( + "gatherPerfMetrics", + false, + "Should the driver gather performance metrics, and report them via the configured logger every 'reportMetricsIntervalMillis' milliseconds?", + "3.1.2", DEBUGING_PROFILING_CATEGORY, 1); + + private BooleanConnectionProperty generateSimpleParameterMetadata = new BooleanConnectionProperty( + "generateSimpleParameterMetadata", false, "Should the driver generate simplified parameter metadata for PreparedStatements when " + + "no metadata is available either because the server couldn't support preparing the statement, or server-side prepared statements" + + " are disabled?" + , "5.0.5", MISC_CATEGORY, Integer.MIN_VALUE); + + private boolean highAvailabilityAsBoolean = false; + + private BooleanConnectionProperty holdResultsOpenOverStatementClose = new BooleanConnectionProperty( + "holdResultsOpenOverStatementClose", + false, + "Should the driver close result sets on Statement.close() as required by the JDBC specification?", + "3.1.7", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty includeInnodbStatusInDeadlockExceptions = new BooleanConnectionProperty( + "includeInnodbStatusInDeadlockExceptions", + false, + "Include the output of \"SHOW ENGINE INNODB STATUS\" in exception messages when deadlock exceptions are detected?", + "5.0.7", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty ignoreNonTxTables = new BooleanConnectionProperty( + "ignoreNonTxTables", + false, + "Ignore non-transactional table warning for rollback? (defaults to 'false').", + "3.0.9", MISC_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty initialTimeout = new IntegerConnectionProperty( + "initialTimeout", 2, 1, Integer.MAX_VALUE, + "If autoReconnect is enabled, the" + + " initial time to wait between" + + " re-connect attempts (in seconds, defaults to '2').", + "1.1", HA_CATEGORY, 5); + + private BooleanConnectionProperty isInteractiveClient = new BooleanConnectionProperty( + "interactiveClient", + false, + "Set the CLIENT_INTERACTIVE flag, which tells MySQL " + + "to timeout connections based on INTERACTIVE_TIMEOUT instead of WAIT_TIMEOUT", + "3.1.0", CONNECTION_AND_AUTH_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty jdbcCompliantTruncation = new BooleanConnectionProperty( + "jdbcCompliantTruncation", + true, + "Should the driver throw java.sql.DataTruncation" + + " exceptions when data is truncated as is required by the JDBC specification when connected to a server that supports warnings" + + "(MySQL 4.1.0 and newer)?", "3.1.2", MISC_CATEGORY, + Integer.MIN_VALUE); + + private boolean jdbcCompliantTruncationForReads = + this.jdbcCompliantTruncation.getValueAsBoolean(); + + private StringConnectionProperty loadBalanceStrategy = new StringConnectionProperty( + "loadBalanceStrategy", + "random", + new String[] {"random", "bestResponseTime"}, + "If using a load-balanced connection to connect to SQL nodes in a MySQL Cluster/NDB configuration" + + "(by using the URL prefix \"jdbc:mysql:loadbalance://\"), which load balancin algorithm should the driver " + + "use: (1) \"random\" - the driver will pick a random host for each request. This tends " + + "to work better than round-robin, as the randomness will somewhat account for " + + "spreading loads where requests vary in response time, while round-robin " + + "can sometimes lead to overloaded nodes if there are variations in response times " + + "across the workload. (2) \"bestResponseTime\" - the driver will route the request to the host that had " + + "the best response time for the previous transaction.", + "5.0.6", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty localSocketAddress = new StringConnectionProperty("localSocketAddress", + null, "Hostname or IP address given to explicitly configure the interface that " + + "the driver will bind the client side of the TCP/IP connection to when connecting.", + "5.0.5", CONNECTION_AND_AUTH_CATEGORY, Integer.MIN_VALUE); + + private MemorySizeConnectionProperty locatorFetchBufferSize = new MemorySizeConnectionProperty( + "locatorFetchBufferSize", + 1024 * 1024, + 0, + Integer.MAX_VALUE, + "If 'emulateLocators' is configured to 'true', what size " + + " buffer should be used when fetching BLOB data for getBinaryInputStream?", + "3.2.1", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty loggerClassName = new StringConnectionProperty( + "logger", STANDARD_LOGGER_NAME, + "The name of a class that implements '" + Log.class.getName() + + "' that will be used to log messages to." + + "(default is '" + STANDARD_LOGGER_NAME + "', which " + + "logs to STDERR)", "3.1.1", DEBUGING_PROFILING_CATEGORY, + 0); + + private BooleanConnectionProperty logSlowQueries = new BooleanConnectionProperty( + "logSlowQueries", + false, + "Should queries that take longer than 'slowQueryThresholdMillis' be logged?", + "3.1.2", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty logXaCommands = new BooleanConnectionProperty( + "logXaCommands", + false, + "Should the driver log XA commands sent by MysqlXaConnection to the server," + + " at the DEBUG level of logging?", + "5.0.5", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty maintainTimeStats = new BooleanConnectionProperty( + "maintainTimeStats", + true, + "Should the driver maintain various internal timers to enable " + + "idle time calculations as well as more verbose error messages when " + + "the connection to the server fails? Setting this property to " + + "false removes at least two calls to System.getCurrentTimeMillis() " + + "per query.", "3.1.9", PERFORMANCE_CATEGORY, + Integer.MAX_VALUE); + + private boolean maintainTimeStatsAsBoolean = true; + + private IntegerConnectionProperty maxQuerySizeToLog = new IntegerConnectionProperty( + "maxQuerySizeToLog", + 2048, + 0, + Integer.MAX_VALUE, + "Controls the maximum length/size of a query that will get logged when profiling or tracing", + "3.1.3", DEBUGING_PROFILING_CATEGORY, 4); + + private IntegerConnectionProperty maxReconnects = new IntegerConnectionProperty( + "maxReconnects", + 3, + 1, + Integer.MAX_VALUE, + "Maximum number of reconnects to attempt if autoReconnect is true, default is '3'.", + "1.1", HA_CATEGORY, 4); + + private IntegerConnectionProperty maxRows = new IntegerConnectionProperty( + "maxRows", -1, -1, Integer.MAX_VALUE, + "The maximum number of rows to return " + + " (0, the default means return all rows).", + "all versions", MISC_CATEGORY, Integer.MIN_VALUE); + + private int maxRowsAsInt = -1; + + private IntegerConnectionProperty metadataCacheSize = new IntegerConnectionProperty( + "metadataCacheSize", + 50, + 1, + Integer.MAX_VALUE, + "The number of queries to cache" + + "ResultSetMetadata for if cacheResultSetMetaData is set to 'true' (default 50)", + "3.1.1", PERFORMANCE_CATEGORY, 5); + + private BooleanConnectionProperty noAccessToProcedureBodies = new BooleanConnectionProperty( + "noAccessToProcedureBodies", + false, + "When determining procedure parameter types for CallableStatements, and the connected user " + + " can't access procedure bodies through \"SHOW CREATE PROCEDURE\" or select on mysql.proc " + + " should the driver instead create basic metadata (all parameters reported as IN VARCHARs," + + " but allowing registerOutParameter() to be called on them anyway) instead " + + " of throwing an exception?", + "5.0.3", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty noDatetimeStringSync = new BooleanConnectionProperty( + "noDatetimeStringSync", + false, + "Don't ensure that ResultSet.getDatetimeType().toString().equals(ResultSet.getString())", + "3.1.7", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty noTimezoneConversionForTimeType = new BooleanConnectionProperty( + "noTimezoneConversionForTimeType", + false, + "Don't convert TIME values using the server timezone if 'useTimezone'='true'", + "5.0.0", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty nullCatalogMeansCurrent = new BooleanConnectionProperty( + "nullCatalogMeansCurrent", + true, + "When DatabaseMetadataMethods ask for a 'catalog' parameter, does the value null mean use the current catalog? " + + "(this is not JDBC-compliant, but follows legacy behavior from earlier versions of the driver)", + "3.1.8", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty nullNamePatternMatchesAll = new BooleanConnectionProperty( + "nullNamePatternMatchesAll", + true, + "Should DatabaseMetaData methods that accept *pattern parameters treat null the same as '%' " + + " (this is not JDBC-compliant, however older versions of the driver accepted this departure from the specification)", + "3.1.8", MISC_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty packetDebugBufferSize = new IntegerConnectionProperty( + "packetDebugBufferSize", + 20, + 0, + Integer.MAX_VALUE, + "The maximum number of packets to retain when 'enablePacketDebug' is true", + "3.1.3", DEBUGING_PROFILING_CATEGORY, 7); + + private BooleanConnectionProperty padCharsWithSpace = new BooleanConnectionProperty( + "padCharsWithSpace", + false, + "If a result set column has the CHAR type and the value does not fill the " + + "amount of characters specified in the DDL for the column, should the driver " + + "pad the remaining characters with space (for ANSI compliance)?", + "5.0.6", + MISC_CATEGORY, + Integer.MIN_VALUE); + + private BooleanConnectionProperty paranoid = new BooleanConnectionProperty( + "paranoid", + false, + "Take measures to prevent exposure sensitive information in error messages and clear " + + "data structures holding sensitive data when possible? (defaults to 'false')", + "3.0.1", SECURITY_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty pedantic = new BooleanConnectionProperty( + "pedantic", false, "Follow the JDBC spec to the letter.", "3.0.0", + MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty pinGlobalTxToPhysicalConnection = new BooleanConnectionProperty( + "pinGlobalTxToPhysicalConnection", false, "When using XAConnections, should the driver ensure that " + + " operations on a given XID are always routed to the same physical connection? This allows the XAConnection" + + " to support \"XA START ... JOIN\" after \"XA END\" has been called", + "5.0.1", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty populateInsertRowWithDefaultValues = new BooleanConnectionProperty( + "populateInsertRowWithDefaultValues", false, + "When using ResultSets that are CONCUR_UPDATABLE, should the driver pre-poulate " + + "the \"insert\" row with default values from the DDL for the table used in the query " + + " so those values are immediately available for ResultSet accessors? This functionality requires a " + + " call to the database for metadata each time a result set of this type is created. " + + " If disabled (the default), the default values will be populated by the an internal" + + " call to refreshRow() which pulls back default values and/or values changed by triggers.", + "5.0.5", MISC_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty preparedStatementCacheSize = new IntegerConnectionProperty( + "prepStmtCacheSize", 25, 0, Integer.MAX_VALUE, + "If prepared statement caching is enabled, " + + "how many prepared statements should be cached?", + "3.0.10", PERFORMANCE_CATEGORY, 10); + + private IntegerConnectionProperty preparedStatementCacheSqlLimit = new IntegerConnectionProperty( + "prepStmtCacheSqlLimit", + 256, + 1, + Integer.MAX_VALUE, + "If prepared statement caching is enabled, " + + "what's the largest SQL the driver will cache the parsing for?", + "3.0.10", PERFORMANCE_CATEGORY, 11); + + private BooleanConnectionProperty processEscapeCodesForPrepStmts = + new BooleanConnectionProperty("processEscapeCodesForPrepStmts", + true, + "Should the driver process escape codes in queries that are prepared?", + "3.1.12", + MISC_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty profileSql = new StringConnectionProperty( + "profileSql", + null, + "Deprecated, use 'profileSQL' instead. Trace queries and their execution/fetch times on STDERR (true/false) defaults to 'false'", + "2.0.14", DEBUGING_PROFILING_CATEGORY, 3); + + private BooleanConnectionProperty profileSQL = new BooleanConnectionProperty( + "profileSQL", + false, + "Trace queries and their execution/fetch times to the configured logger (true/false) defaults to 'false'", + "3.1.0", DEBUGING_PROFILING_CATEGORY, 1); + + private boolean profileSQLAsBoolean = false; + + private StringConnectionProperty propertiesTransform = new StringConnectionProperty( + NonRegisteringDriver.PROPERTIES_TRANSFORM_KEY, + null, + "An implementation of com.mysql.jdbc.ConnectionPropertiesTransform that the driver will use to modify URL properties passed to the driver before attempting a connection", + "3.1.4", CONNECTION_AND_AUTH_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty queriesBeforeRetryMaster = new IntegerConnectionProperty( + "queriesBeforeRetryMaster", + 50, + 1, + Integer.MAX_VALUE, + "Number of queries to issue before falling back to master when failed over " + + "(when using multi-host failover). Whichever condition is met first, " + + "'queriesBeforeRetryMaster' or 'secondsBeforeRetryMaster' will cause an " + + "attempt to be made to reconnect to the master. Defaults to 50.", + "3.0.2", HA_CATEGORY, 7); + + private BooleanConnectionProperty reconnectAtTxEnd = new BooleanConnectionProperty( + "reconnectAtTxEnd", false, + "If autoReconnect is set to true, should the driver attempt reconnections" + + "at the end of every transaction?", "3.0.10", + HA_CATEGORY, 4); + + private boolean reconnectTxAtEndAsBoolean = false; + + private BooleanConnectionProperty relaxAutoCommit = new BooleanConnectionProperty( + "relaxAutoCommit", + false, + "If the version of MySQL the driver connects to does not support transactions, still allow calls to commit(), rollback() and setAutoCommit() (true/false, defaults to 'false')?", + "2.0.13", MISC_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty reportMetricsIntervalMillis = new IntegerConnectionProperty( + "reportMetricsIntervalMillis", + 30000, + 0, + Integer.MAX_VALUE, + "If 'gatherPerfMetrics' is enabled, how often should they be logged (in ms)?", + "3.1.2", DEBUGING_PROFILING_CATEGORY, 3); + + private BooleanConnectionProperty requireSSL = new BooleanConnectionProperty( + "requireSSL", false, + "Require SSL connection if useSSL=true? (defaults to 'false').", + "3.1.0", SECURITY_CATEGORY, 3); + + private StringConnectionProperty resourceId = new StringConnectionProperty( + "resourceId", + null, "A globally unique name that identifies the resource that this datasource or connection is " + + "connected to, used for XAResource.isSameRM() when the driver can't determine this value based on " + + "hostnames used in the URL", + "5.0.1", + HA_CATEGORY, + Integer.MIN_VALUE); + + private IntegerConnectionProperty resultSetSizeThreshold = new IntegerConnectionProperty("resultSetSizeThreshold", 100, + "If the usage advisor is enabled, how many rows should a result set contain before the driver warns that it " + + " is suspiciously large?", "5.0.5", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty retainStatementAfterResultSetClose = new BooleanConnectionProperty( + "retainStatementAfterResultSetClose", + false, + "Should the driver retain the Statement reference in a ResultSet after ResultSet.close()" + + " has been called. This is not JDBC-compliant after JDBC-4.0.", + "3.1.11", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty rewriteBatchedStatements = new BooleanConnectionProperty( + "rewriteBatchedStatements", + false, + "Should the driver use multiqueries (irregardless of the setting of \"allowMultiQueries\") as well as " + + "rewriting of prepared statements for INSERT and REPLACE into multi-value inserts/replaces when executeBatch() is called? Notice that this has the potential " + + "for SQL injection if using plain java.sql.Statements and your code doesn't sanitize input correctly.\n\n" + + "Notice that if you don't specify stream lengths when using PreparedStatement.set*Stream()," + + "the driver won't be able to determine the optimium number of parameters per batch and you might receive " + + "an error from the driver that the resultant packet is too large.\n\n" + + "Statement.getGeneratedKeys() for these rewritten statements only works when the entire " + + "batch includes INSERT statements.", + "3.1.13", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty rollbackOnPooledClose = new BooleanConnectionProperty( + "rollbackOnPooledClose", + true, + "Should the driver issue a rollback() when the logical connection in a pool is closed?", + "3.0.15", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty roundRobinLoadBalance = new BooleanConnectionProperty( + "roundRobinLoadBalance", + false, + "When autoReconnect is enabled, and failoverReadonly is false, should we pick hosts to connect to on a round-robin basis?", + "3.1.2", HA_CATEGORY, 5); + + private BooleanConnectionProperty runningCTS13 = new BooleanConnectionProperty( + "runningCTS13", + false, + "Enables workarounds for bugs in Sun's JDBC compliance testsuite version 1.3", + "3.1.7", MISC_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty secondsBeforeRetryMaster = new IntegerConnectionProperty( + "secondsBeforeRetryMaster", + 30, + 1, + Integer.MAX_VALUE, + "How long should the driver wait, when failed over, before attempting " + + "to reconnect to the master server? Whichever condition is met first, " + + "'queriesBeforeRetryMaster' or 'secondsBeforeRetryMaster' will cause an " + + "attempt to be made to reconnect to the master. Time in seconds, defaults to 30", + "3.0.2", HA_CATEGORY, 8); + + private StringConnectionProperty serverTimezone = new StringConnectionProperty( + "serverTimezone", + null, + "Override detection/mapping of timezone. Used when timezone from server doesn't map to Java timezone", + "3.0.2", MISC_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty sessionVariables = new StringConnectionProperty( + "sessionVariables", null, + "A comma-separated list of name/value pairs to be sent as SET SESSION ... to " + + " the server when the driver connects.", "3.1.8", + MISC_CATEGORY, Integer.MAX_VALUE); + + private IntegerConnectionProperty slowQueryThresholdMillis = new IntegerConnectionProperty( + "slowQueryThresholdMillis", + 2000, + 0, + Integer.MAX_VALUE, + "If 'logSlowQueries' is enabled, how long should a query (in ms) before it is logged as 'slow'?", + "3.1.2", DEBUGING_PROFILING_CATEGORY, 9); + + private LongConnectionProperty slowQueryThresholdNanos = new LongConnectionProperty( + "slowQueryThresholdNanos", + 0, + "If 'useNanosForElapsedTime' is set to true, and this property is set to a non-zero value," + + " the driver will use this threshold (in nanosecond units) to determine if a query was slow.", + "5.0.7", + DEBUGING_PROFILING_CATEGORY, + 10); + + private StringConnectionProperty socketFactoryClassName = new StringConnectionProperty( + "socketFactory", + StandardSocketFactory.class.getName(), + "The name of the class that the driver should use for creating socket connections to the server. This class must implement the interface 'com.mysql.jdbc.SocketFactory' and have public no-args constructor.", + "3.0.3", CONNECTION_AND_AUTH_CATEGORY, 4); + + private IntegerConnectionProperty socketTimeout = new IntegerConnectionProperty( + "socketTimeout", + 0, + 0, + Integer.MAX_VALUE, + "Timeout on network socket operations (0, the default means no timeout).", + "3.0.1", CONNECTION_AND_AUTH_CATEGORY, 10); + + private BooleanConnectionProperty strictFloatingPoint = new BooleanConnectionProperty( + "strictFloatingPoint", false, + "Used only in older versions of compliance test", "3.0.0", + MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty strictUpdates = new BooleanConnectionProperty( + "strictUpdates", + true, + "Should the driver do strict checking (all primary keys selected) of updatable result sets (true, false, defaults to 'true')?", + "3.0.4", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty overrideSupportsIntegrityEnhancementFacility = + new BooleanConnectionProperty("overrideSupportsIntegrityEnhancementFacility", + false, + "Should the driver return \"true\" for DatabaseMetaData.supportsIntegrityEnhancementFacility() " + + "even if the database doesn't support it to workaround applications that require this method to return " + + "\"true\" to signal support of foreign keys, even though the SQL specification states that this facility " + + "contains much more than just foreign key support (one such application being OpenOffice)?", + "3.1.12", MISC_CATEGORY, Integer.MIN_VALUE); + private BooleanConnectionProperty tcpNoDelay = new BooleanConnectionProperty( + StandardSocketFactory.TCP_NO_DELAY_PROPERTY_NAME, + Boolean.valueOf(StandardSocketFactory.TCP_NO_DELAY_DEFAULT_VALUE).booleanValue(), + "If connecting using TCP/IP, should the driver set SO_TCP_NODELAY (disabling the Nagle Algorithm)?", + "5.0.7", NETWORK_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty tcpKeepAlive = new BooleanConnectionProperty( + StandardSocketFactory.TCP_KEEP_ALIVE_PROPERTY_NAME, + Boolean.valueOf(StandardSocketFactory.TCP_KEEP_ALIVE_DEFAULT_VALUE).booleanValue(), + "If connecting using TCP/IP, should the driver set SO_KEEPALIVE?", + "5.0.7", NETWORK_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty tcpRcvBuf = new IntegerConnectionProperty( + StandardSocketFactory.TCP_RCV_BUF_PROPERTY_NAME, + Integer.parseInt(StandardSocketFactory.TCP_RCV_BUF_DEFAULT_VALUE), + 0, Integer.MAX_VALUE, + "If connecting using TCP/IP, should the driver set SO_RCV_BUF to the given value? " + + "The default value of '0', means use the platform default value for this property)", + "5.0.7", NETWORK_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty tcpSndBuf = new IntegerConnectionProperty( + StandardSocketFactory.TCP_SND_BUF_PROPERTY_NAME, + Integer.parseInt(StandardSocketFactory.TCP_SND_BUF_DEFAULT_VALUE), + 0, Integer.MAX_VALUE, + "If connecting using TCP/IP, shuold the driver set SO_SND_BUF to the given value? " + + "The default value of '0', means use the platform default value for this property)", + "5.0.7", NETWORK_CATEGORY, Integer.MIN_VALUE); + + private IntegerConnectionProperty tcpTrafficClass = new IntegerConnectionProperty( + StandardSocketFactory.TCP_TRAFFIC_CLASS_PROPERTY_NAME, + Integer.parseInt(StandardSocketFactory.TCP_TRAFFIC_CLASS_DEFAULT_VALUE), + 0, 255, + "If connecting using TCP/IP, should the driver set traffic class or type-of-service fields ?" + + " See the documentation for java.net.Socket.setTrafficClass() for more information.", + "5.0.7", NETWORK_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty tinyInt1isBit = new BooleanConnectionProperty( + "tinyInt1isBit", + true, + "Should the driver treat the datatype TINYINT(1) as the BIT type " + + "(because the server silently converts BIT -> TINYINT(1) when creating tables)?", + "3.0.16", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty traceProtocol = new BooleanConnectionProperty( + "traceProtocol", false, + "Should trace-level network protocol be logged?", "3.1.2", + DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty treatUtilDateAsTimestamp = new BooleanConnectionProperty( + "treatUtilDateAsTimestamp", true, + "Should the driver treat java.util.Date as a TIMESTAMP for the purposes of PreparedStatement.setObject()?", + "5.0.5", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty transformedBitIsBoolean = new BooleanConnectionProperty( + "transformedBitIsBoolean", + false, + "If the driver converts TINYINT(1) to a different type, should it use BOOLEAN instead of BIT " + + " for future compatibility with MySQL-5.0, as MySQL-5.0 has a BIT type?", + "3.1.9", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useCompression = new BooleanConnectionProperty( + "useCompression", + false, + "Use zlib compression when communicating with the server (true/false)? Defaults to 'false'.", + "3.0.17", CONNECTION_AND_AUTH_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty useConfigs = new StringConnectionProperty( + "useConfigs", + null, + "Load the comma-delimited list of configuration properties before parsing the " + + "URL or applying user-specified properties. These configurations are explained in the 'Configurations' of the documentation.", + "3.1.5", CONNECTION_AND_AUTH_CATEGORY, Integer.MAX_VALUE); + + private BooleanConnectionProperty useCursorFetch = new BooleanConnectionProperty( + "useCursorFetch", + false, + "If connected to MySQL > 5.0.2, and setFetchSize() > 0 on a statement, should " + + " that statement use cursor-based fetching to retrieve rows?", + "5.0.0", PERFORMANCE_CATEGORY, Integer.MAX_VALUE); + + private BooleanConnectionProperty useDynamicCharsetInfo = new BooleanConnectionProperty( + "useDynamicCharsetInfo", + true, + "Should the driver use a per-connection cache of character set information queried from the " + + " server when necessary, or use a built-in static mapping that is more efficient, but isn't " + + " aware of custom character sets or character sets implemented after the release of the JDBC driver?" + + "(this only affects the \"padCharsWithSpace\" configuration property and the " + + "ResultSetMetaData.getColumnDisplayWidth() method)." + , "5.0.6", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useFastIntParsing = new BooleanConnectionProperty( + "useFastIntParsing", + true, + "Use internal String->Integer conversion routines to avoid excessive object creation?", + "3.1.4", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useFastDateParsing = new BooleanConnectionProperty( + "useFastDateParsing", + true, + "Use internal String->Date/Time/Teimstamp conversion routines to avoid excessive object creation?", + "5.0.5", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useHostsInPrivileges = new BooleanConnectionProperty( + "useHostsInPrivileges", + true, + "Add '@hostname' to users in DatabaseMetaData.getColumn/TablePrivileges() (true/false), defaults to 'true'.", + "3.0.2", MISC_CATEGORY, Integer.MIN_VALUE); + private BooleanConnectionProperty useInformationSchema = new BooleanConnectionProperty( + "useInformationSchema", + false, + "When connected to MySQL-5.0.7 or newer, should the driver use the INFORMATION_SCHEMA to " + + " derive information used by DatabaseMetaData?", + "5.0.0", MISC_CATEGORY, Integer.MIN_VALUE); + private BooleanConnectionProperty useJDBCCompliantTimezoneShift = new BooleanConnectionProperty( + "useJDBCCompliantTimezoneShift", + false, + "Should the driver use JDBC-compliant rules when converting TIME/TIMESTAMP/DATETIME values' timezone information " + + "for those JDBC arguments which take a java.util.Calendar argument? (Notice that this " + + "option is exclusive of the \"useTimezone=true\" configuration option.)", + "5.0.0", + MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useLocalSessionState = new BooleanConnectionProperty( + "useLocalSessionState", + false, + "Should the driver refer to the internal values of autocommit and transaction isolation that are set " + + "by Connection.setAutoCommit() and Connection.setTransactionIsolation() and transaction state " + + "as maintained by the protocol, rather than querying the database or blindly " + + "sending commands to the database for commit() or rollback() method calls?", + "3.1.7", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useNanosForElapsedTime = new BooleanConnectionProperty( + "useNanosForElapsedTime", + false, + "For profiling/debugging functionality that measures elapsed time, should the driver " + + "try to use nanoseconds resolution if available (JDK >= 1.5)?", + "5.0.7", + DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useOldAliasMetadataBehavior = new BooleanConnectionProperty( + "useOldAliasMetadataBehavior", + true, + "Should the driver use the legacy behavior for \"AS\" clauses on columns and tables, and only " + + "return aliases (if any) for ResultSetMetaData.getColumnName() or ResultSetMetaData.getTableName() " + + "rather than the original column/table name?", + "5.0.4", + MISC_CATEGORY, + Integer.MIN_VALUE); + + private BooleanConnectionProperty useOldUTF8Behavior = new BooleanConnectionProperty( + "useOldUTF8Behavior", + false, + "Use the UTF-8 behavior the driver did when communicating with 4.0 and older servers", + "3.1.6", MISC_CATEGORY, Integer.MIN_VALUE); + + private boolean useOldUTF8BehaviorAsBoolean = false; + + private BooleanConnectionProperty useOnlyServerErrorMessages = new BooleanConnectionProperty( + "useOnlyServerErrorMessages", + true, + "Don't prepend 'standard' SQLState error messages to error messages returned by the server.", + "3.0.15", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useReadAheadInput = new BooleanConnectionProperty( + "useReadAheadInput", + true, + "Use newer, optimized non-blocking, buffered input stream when reading from the server?", + "3.1.5", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useSqlStateCodes = new BooleanConnectionProperty( + "useSqlStateCodes", + true, + "Use SQL Standard state codes instead of 'legacy' X/Open/SQL state codes (true/false), default is 'true'", + "3.1.3", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useSSL = new BooleanConnectionProperty( + "useSSL", + false, + "Use SSL when communicating with the server (true/false), defaults to 'false'", + "3.0.2", SECURITY_CATEGORY, 2); + + private BooleanConnectionProperty useSSPSCompatibleTimezoneShift = new BooleanConnectionProperty( + "useSSPSCompatibleTimezoneShift", + false, + "If migrating from an environment that was using server-side prepared statements, and the" + + " configuration property \"useJDBCCompliantTimeZoneShift\" set to \"true\", use compatible behavior" + + " when not using server-side prepared statements when sending TIMESTAMP values to the MySQL server.", + "5.0.5", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useStreamLengthsInPrepStmts = new BooleanConnectionProperty( + "useStreamLengthsInPrepStmts", + true, + "Honor stream length parameter in " + + "PreparedStatement/ResultSet.setXXXStream() method calls (true/false, defaults to 'true')?", + "3.0.2", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useTimezone = new BooleanConnectionProperty( + "useTimezone", + false, + "Convert time/date types between client and server timezones (true/false, defaults to 'false')?", + "3.0.2", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useUltraDevWorkAround = new BooleanConnectionProperty( + "ultraDevHack", + false, + "Create PreparedStatements for prepareCall() when required, because UltraDev " + + " is broken and issues a prepareCall() for _all_ statements? (true/false, defaults to 'false')", + "2.0.3", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useUnbufferedInput = new BooleanConnectionProperty( + "useUnbufferedInput", true, + "Don't use BufferedInputStream for reading data from the server", + "3.0.11", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useUnicode = new BooleanConnectionProperty( + "useUnicode", + true, + "Should the driver use Unicode character encodings when handling strings? Should only be used when the driver can't determine the character set mapping, or you are trying to 'force' the driver to use a character set that MySQL either doesn't natively support (such as UTF-8), true/false, defaults to 'true'", + "1.1g", MISC_CATEGORY, 0); + + // Cache these values, they are 'hot' + private boolean useUnicodeAsBoolean = true; + + private BooleanConnectionProperty useUsageAdvisor = new BooleanConnectionProperty( + "useUsageAdvisor", + false, + "Should the driver issue 'usage' warnings advising proper and efficient usage of JDBC and MySQL Connector/J to the log (true/false, defaults to 'false')?", + "3.1.1", DEBUGING_PROFILING_CATEGORY, 10); + + private boolean useUsageAdvisorAsBoolean = false; + + private BooleanConnectionProperty yearIsDateType = new BooleanConnectionProperty( + "yearIsDateType", + true, + "Should the JDBC driver treat the MySQL type \"YEAR\" as a java.sql.Date, or as a SHORT?", + "3.1.9", MISC_CATEGORY, Integer.MIN_VALUE); + + private StringConnectionProperty zeroDateTimeBehavior = new StringConnectionProperty( + "zeroDateTimeBehavior", + ZERO_DATETIME_BEHAVIOR_EXCEPTION, + new String[] { ZERO_DATETIME_BEHAVIOR_EXCEPTION, + ZERO_DATETIME_BEHAVIOR_ROUND, + ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL }, + "What should happen when the driver encounters DATETIME values that are composed " + + "entirely of zeroes (used by MySQL to represent invalid dates)? " + + "Valid values are '" + + ZERO_DATETIME_BEHAVIOR_EXCEPTION + + "', '" + + ZERO_DATETIME_BEHAVIOR_ROUND + + "' and '" + + ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + "'.", "3.1.4", + MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useJvmCharsetConverters = new BooleanConnectionProperty("useJvmCharsetConverters", + false, "Always use the character encoding routines built into the JVM, rather than using " + + "lookup tables for single-byte character sets?", "5.0.1", PERFORMANCE_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty useGmtMillisForDatetimes = new BooleanConnectionProperty("useGmtMillisForDatetimes", false, "Convert between session timezone and GMT before creating Date and Timestamp instances (value of \"false\" is legacy behavior, \"true\" leads to more JDBC-compliant behavior.", "3.1.12", MISC_CATEGORY, Integer.MIN_VALUE); + + private BooleanConnectionProperty dumpMetadataOnColumnNotFound = new BooleanConnectionProperty("dumpMetadataOnColumnNotFound", false, "Should the driver dump the field-level metadata of a result set into " + "the exception message when ResultSet.findColumn() fails?", "3.1.13", DEBUGING_PROFILING_CATEGORY, Integer.MIN_VALUE); + + protected DriverPropertyInfo[] exposeAsDriverPropertyInfoInternal( + Properties info, int slotsToReserve) throws SQLException { + initializeProperties(info); + + int numProperties = PROPERTY_LIST.size(); + + int listSize = numProperties + slotsToReserve; + + DriverPropertyInfo[] driverProperties = new DriverPropertyInfo[listSize]; + + for (int i = slotsToReserve; i < listSize; i++) { + java.lang.reflect.Field propertyField = (java.lang.reflect.Field) PROPERTY_LIST + .get(i - slotsToReserve); + + try { + ConnectionProperty propToExpose = (ConnectionProperty) propertyField + .get(this); + + if (info != null) { + propToExpose.initializeFrom(info); + } + + + driverProperties[i] = propToExpose.getAsDriverPropertyInfo(); + } catch (IllegalAccessException iae) { + throw SQLError.createSQLException("Internal properties failure", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + return driverProperties; + } + + protected Properties exposeAsProperties(Properties info) + throws SQLException { + if (info == null) { + info = new Properties(); + } + + int numPropertiesToSet = PROPERTY_LIST.size(); + + for (int i = 0; i < numPropertiesToSet; i++) { + java.lang.reflect.Field propertyField = (java.lang.reflect.Field) PROPERTY_LIST + .get(i); + + try { + ConnectionProperty propToGet = (ConnectionProperty) propertyField + .get(this); + + Object propValue = propToGet.getValueAsObject(); + + if (propValue != null) { + info.setProperty(propToGet.getPropertyName(), propValue + .toString()); + } + } catch (IllegalAccessException iae) { + throw SQLError.createSQLException("Internal properties failure", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + return info; + } + + /** + * Returns a description of the connection properties as an XML document. + * + * @return the connection properties as an XML document. + * @throws SQLException + * if an error occurs. + */ + public String exposeAsXml() throws SQLException { + StringBuffer xmlBuf = new StringBuffer(); + xmlBuf.append(""); + + int numPropertiesToSet = PROPERTY_LIST.size(); + + int numCategories = PROPERTY_CATEGORIES.length; + + Map propertyListByCategory = new HashMap(); + + for (int i = 0; i < numCategories; i++) { + propertyListByCategory.put(PROPERTY_CATEGORIES[i], new Map[] { + new TreeMap(), new TreeMap() }); + } + + // + // The following properties are not exposed as 'normal' properties, but + // they are + // settable nonetheless, so we need to have them documented, make sure + // that they sort 'first' as #1 and #2 in the category + // + StringConnectionProperty userProp = new StringConnectionProperty( + NonRegisteringDriver.USER_PROPERTY_KEY, null, + "The user to connect as", "all", CONNECTION_AND_AUTH_CATEGORY, + Integer.MIN_VALUE + 1); + StringConnectionProperty passwordProp = new StringConnectionProperty( + NonRegisteringDriver.PASSWORD_PROPERTY_KEY, null, + "The password to use when connecting", "all", + CONNECTION_AND_AUTH_CATEGORY, Integer.MIN_VALUE + 2); + + Map[] connectionSortMaps = (Map[]) propertyListByCategory + .get(CONNECTION_AND_AUTH_CATEGORY); + TreeMap userMap = new TreeMap(); + userMap.put(userProp.getPropertyName(), userProp); + + connectionSortMaps[0].put(new Integer(userProp.getOrder()), userMap); + + TreeMap passwordMap = new TreeMap(); + passwordMap.put(passwordProp.getPropertyName(), passwordProp); + + connectionSortMaps[0] + .put(new Integer(passwordProp.getOrder()), passwordMap); + + try { + for (int i = 0; i < numPropertiesToSet; i++) { + java.lang.reflect.Field propertyField = (java.lang.reflect.Field) PROPERTY_LIST + .get(i); + ConnectionProperty propToGet = (ConnectionProperty) propertyField + .get(this); + Map[] sortMaps = (Map[]) propertyListByCategory.get(propToGet + .getCategoryName()); + int orderInCategory = propToGet.getOrder(); + + if (orderInCategory == Integer.MIN_VALUE) { + sortMaps[1].put(propToGet.getPropertyName(), propToGet); + } else { + Integer order = new Integer(orderInCategory); + + Map orderMap = (Map)sortMaps[0].get(order); + + if (orderMap == null) { + orderMap = new TreeMap(); + sortMaps[0].put(order, orderMap); + } + + orderMap.put(propToGet.getPropertyName(), propToGet); + } + } + + for (int j = 0; j < numCategories; j++) { + Map[] sortMaps = (Map[]) propertyListByCategory + .get(PROPERTY_CATEGORIES[j]); + Iterator orderedIter = sortMaps[0].values().iterator(); + Iterator alphaIter = sortMaps[1].values().iterator(); + + xmlBuf.append("\n "); + + while (orderedIter.hasNext()) { + Iterator orderedAlphaIter = ((Map)orderedIter.next()).values().iterator(); + + while (orderedAlphaIter.hasNext()) { + ConnectionProperty propToGet = (ConnectionProperty) orderedAlphaIter + .next(); + + xmlBuf.append("\n \n"); + xmlBuf.append(" "); + xmlBuf.append(propToGet.description); + xmlBuf.append("\n "); + } + } + + while (alphaIter.hasNext()) { + ConnectionProperty propToGet = (ConnectionProperty) alphaIter + .next(); + + xmlBuf.append("\n \n"); + xmlBuf.append(" "); + xmlBuf.append(propToGet.description); + xmlBuf.append("\n "); + } + + xmlBuf.append("\n "); + } + } catch (IllegalAccessException iae) { + throw SQLError.createSQLException("Internal properties failure", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + xmlBuf.append("\n"); + + return xmlBuf.toString(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getAllowLoadLocalInfile() { + return this.allowLoadLocalInfile.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getAllowMultiQueries() { + return this.allowMultiQueries.getValueAsBoolean(); + } + + /** + * @return Returns the allowNanAndInf. + */ + public boolean getAllowNanAndInf() { + return allowNanAndInf.getValueAsBoolean(); + } + + /** + * @return Returns the allowUrlInLocalInfile. + */ + public boolean getAllowUrlInLocalInfile() { + return this.allowUrlInLocalInfile.getValueAsBoolean(); + } + + /** + * @return Returns the alwaysSendSetIsolation. + */ + public boolean getAlwaysSendSetIsolation() { + return this.alwaysSendSetIsolation.getValueAsBoolean(); + } + + /** + * @return Returns the autoDeserialize. + */ + public boolean getAutoDeserialize() { + return autoDeserialize.getValueAsBoolean(); + } + + public boolean getAutoGenerateTestcaseScript() { + return this.autoGenerateTestcaseScriptAsBoolean; + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getAutoReconnectForPools() { + return this.autoReconnectForPoolsAsBoolean; + } + + /** + * @return Returns the blobSendChunkSize. + */ + public int getBlobSendChunkSize() { + return blobSendChunkSize.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return Returns if cacheCallableStatements is enabled + */ + public boolean getCacheCallableStatements() { + return this.cacheCallableStatements.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the cachePreparedStatements. + */ + public boolean getCachePreparedStatements() { + return ((Boolean) this.cachePreparedStatements.getValueAsObject()) + .booleanValue(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean getCacheResultSetMetadata() { + return this.cacheResultSetMetaDataAsBoolean; + } + + /** + * @return Returns the cacheServerConfiguration. + */ + public boolean getCacheServerConfiguration() { + return cacheServerConfiguration.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the callableStatementCacheSize. + */ + public int getCallableStatementCacheSize() { + return this.callableStatementCacheSize.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getCapitalizeTypeNames() { + return this.capitalizeTypeNames.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the characterSetResults. + */ + public String getCharacterSetResults() { + return this.characterSetResults.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the clobberStreamingResults. + */ + public boolean getClobberStreamingResults() { + return this.clobberStreamingResults.getValueAsBoolean(); + } + + public String getClobCharacterEncoding() { + return this.clobCharacterEncoding.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the connectionCollation. + */ + public String getConnectionCollation() { + return this.connectionCollation.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public int getConnectTimeout() { + return this.connectTimeout.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getContinueBatchOnError() { + return this.continueBatchOnError.getValueAsBoolean(); + } + + public boolean getCreateDatabaseIfNotExist() { + return this.createDatabaseIfNotExist.getValueAsBoolean(); + } + + public int getDefaultFetchSize() { + return this.defaultFetchSize.getValueAsInt(); + } + + /** + * @return Returns the dontTrackOpenResources. + */ + public boolean getDontTrackOpenResources() { + return this.dontTrackOpenResources.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the dumpQueriesOnException. + */ + public boolean getDumpQueriesOnException() { + return this.dumpQueriesOnException.getValueAsBoolean(); + } + + /** + * @return Returns the dynamicCalendars. + */ + public boolean getDynamicCalendars() { + return this.dynamicCalendars.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the elideSetAutoCommits. + */ + public boolean getElideSetAutoCommits() { + return this.elideSetAutoCommits.getValueAsBoolean(); + } + + public boolean getEmptyStringsConvertToZero() { + return this.emptyStringsConvertToZero.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getEmulateLocators() { + return this.emulateLocators.getValueAsBoolean(); + } + + /** + * @return Returns the emulateUnsupportedPstmts. + */ + public boolean getEmulateUnsupportedPstmts() { + return this.emulateUnsupportedPstmts.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the enablePacketDebug. + */ + public boolean getEnablePacketDebug() { + return this.enablePacketDebug.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public String getEncoding() { + return this.characterEncodingAsString; + } + + /** + * DOCUMENT ME! + * + * @return Returns the explainSlowQueries. + */ + public boolean getExplainSlowQueries() { + return this.explainSlowQueries.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the failOverReadOnly. + */ + public boolean getFailOverReadOnly() { + return this.failOverReadOnly.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the gatherPerformanceMetrics. + */ + public boolean getGatherPerformanceMetrics() { + return this.gatherPerformanceMetrics.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + protected boolean getHighAvailability() { + return this.highAvailabilityAsBoolean; + } + + /** + * @return Returns the holdResultsOpenOverStatementClose. + */ + public boolean getHoldResultsOpenOverStatementClose() { + return holdResultsOpenOverStatementClose.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getIgnoreNonTxTables() { + return this.ignoreNonTxTables.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public int getInitialTimeout() { + return this.initialTimeout.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getInteractiveClient() { + return this.isInteractiveClient.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the isInteractiveClient. + */ + public boolean getIsInteractiveClient() { + return this.isInteractiveClient.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the jdbcCompliantTruncation. + */ + public boolean getJdbcCompliantTruncation() { + return this.jdbcCompliantTruncation.getValueAsBoolean(); + } + + /** + * @return Returns the dontTrackOpenResources. + */ + public int getLocatorFetchBufferSize() { + return this.locatorFetchBufferSize.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public String getLogger() { + return this.loggerClassName.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the loggerClassName. + */ + public String getLoggerClassName() { + return this.loggerClassName.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the logSlowQueries. + */ + public boolean getLogSlowQueries() { + return this.logSlowQueries.getValueAsBoolean(); + } + + public boolean getMaintainTimeStats() { + return maintainTimeStatsAsBoolean; + } + + /** + * DOCUMENT ME! + * + * @return Returns the maxQuerySizeToLog. + */ + public int getMaxQuerySizeToLog() { + return this.maxQuerySizeToLog.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public int getMaxReconnects() { + return this.maxReconnects.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public int getMaxRows() { + return this.maxRowsAsInt; + } + + /** + * Returns the number of queries that metadata can be cached if caching is + * enabled. + * + * @return the number of queries to cache metadata for. + */ + public int getMetadataCacheSize() { + return this.metadataCacheSize.getValueAsInt(); + } + + /** + * @return Returns the noDatetimeStringSync. + */ + public boolean getNoDatetimeStringSync() { + return this.noDatetimeStringSync.getValueAsBoolean(); + } + + public boolean getNullCatalogMeansCurrent() { + return this.nullCatalogMeansCurrent.getValueAsBoolean(); + } + + public boolean getNullNamePatternMatchesAll() { + return this.nullNamePatternMatchesAll.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the packetDebugBufferSize. + */ + public int getPacketDebugBufferSize() { + return this.packetDebugBufferSize.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getParanoid() { + return this.paranoid.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getPedantic() { + return this.pedantic.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the preparedStatementCacheSize. + */ + public int getPreparedStatementCacheSize() { + return ((Integer) this.preparedStatementCacheSize.getValueAsObject()) + .intValue(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the preparedStatementCacheSqlLimit. + */ + public int getPreparedStatementCacheSqlLimit() { + return ((Integer) this.preparedStatementCacheSqlLimit + .getValueAsObject()).intValue(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getProfileSql() { + return this.profileSQLAsBoolean; + } + + /** + * DOCUMENT ME! + * + * @return Returns the profileSQL flag + */ + public boolean getProfileSQL() { + return this.profileSQL.getValueAsBoolean(); + } + + /** + * @return Returns the propertiesTransform. + */ + public String getPropertiesTransform() { + return this.propertiesTransform.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public int getQueriesBeforeRetryMaster() { + return this.queriesBeforeRetryMaster.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getReconnectAtTxEnd() { + return this.reconnectTxAtEndAsBoolean; + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getRelaxAutoCommit() { + return this.relaxAutoCommit.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the reportMetricsIntervalMillis. + */ + public int getReportMetricsIntervalMillis() { + return this.reportMetricsIntervalMillis.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getRequireSSL() { + return this.requireSSL.getValueAsBoolean(); + } + + public boolean getRetainStatementAfterResultSetClose() { + return this.retainStatementAfterResultSetClose.getValueAsBoolean(); + } + + /** + * @return Returns the rollbackOnPooledClose. + */ + public boolean getRollbackOnPooledClose() { + return this.rollbackOnPooledClose.getValueAsBoolean(); + } + + /** + * Returns whether or not hosts will be picked in a round-robin fashion. + * + * @return Returns the roundRobinLoadBalance property. + */ + public boolean getRoundRobinLoadBalance() { + return this.roundRobinLoadBalance.getValueAsBoolean(); + } + + /** + * @return Returns the runningCTS13. + */ + public boolean getRunningCTS13() { + return this.runningCTS13.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public int getSecondsBeforeRetryMaster() { + return this.secondsBeforeRetryMaster.getValueAsInt(); + } + + /** + * Returns the 'serverTimezone' property. + * + * @return the configured server timezone property. + */ + public String getServerTimezone() { + return this.serverTimezone.getValueAsString(); + } + + /** + * @return Returns the sessionVariables. + */ + public String getSessionVariables() { + return sessionVariables.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the slowQueryThresholdMillis. + */ + public int getSlowQueryThresholdMillis() { + return this.slowQueryThresholdMillis.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public String getSocketFactoryClassName() { + return this.socketFactoryClassName.getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public int getSocketTimeout() { + return this.socketTimeout.getValueAsInt(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getStrictFloatingPoint() { + return this.strictFloatingPoint.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getStrictUpdates() { + return this.strictUpdates.getValueAsBoolean(); + } + + /** + * @return Returns the tinyInt1isBit. + */ + public boolean getTinyInt1isBit() { + return this.tinyInt1isBit.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the logProtocol. + */ + public boolean getTraceProtocol() { + return this.traceProtocol.getValueAsBoolean(); + } + + public boolean getTransformedBitIsBoolean() { + return this.transformedBitIsBoolean.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseCompression() { + return this.useCompression.getValueAsBoolean(); + } + + /** + * @return Returns the useFastIntParsing. + */ + public boolean getUseFastIntParsing() { + return this.useFastIntParsing.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseHostsInPrivileges() { + return this.useHostsInPrivileges.getValueAsBoolean(); + } + + public boolean getUseInformationSchema() { + return this.useInformationSchema.getValueAsBoolean(); + } + + /** + * @return Returns the useLocalSessionState. + */ + public boolean getUseLocalSessionState() { + return this.useLocalSessionState.getValueAsBoolean(); + } + + /** + * @return Returns the useOldUTF8Behavior. + */ + public boolean getUseOldUTF8Behavior() { + return this.useOldUTF8BehaviorAsBoolean; + } + + /** + * @return Returns the useOnlyServerErrorMessages. + */ + public boolean getUseOnlyServerErrorMessages() { + return this.useOnlyServerErrorMessages.getValueAsBoolean(); + } + + /** + * @return Returns the useReadAheadInput. + */ + public boolean getUseReadAheadInput() { + return this.useReadAheadInput.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseServerPreparedStmts() { + return this.detectServerPreparedStmts.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the useSqlStateCodes state. + */ + public boolean getUseSqlStateCodes() { + return this.useSqlStateCodes.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseSSL() { + return this.useSSL.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseStreamLengthsInPrepStmts() { + return this.useStreamLengthsInPrepStmts.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseTimezone() { + return this.useTimezone.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseUltraDevWorkAround() { + return this.useUltraDevWorkAround.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return Returns the useUnbufferedInput. + */ + public boolean getUseUnbufferedInput() { + return this.useUnbufferedInput.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @return + */ + public boolean getUseUnicode() { + return this.useUnicodeAsBoolean; + } + + /** + * Returns whether or not the driver advises of proper usage. + * + * @return the value of useUsageAdvisor + */ + public boolean getUseUsageAdvisor() { + return this.useUsageAdvisorAsBoolean; + } + + public boolean getYearIsDateType() { + return this.yearIsDateType.getValueAsBoolean(); + } + + /** + * @return Returns the zeroDateTimeBehavior. + */ + public String getZeroDateTimeBehavior() { + return this.zeroDateTimeBehavior.getValueAsString(); + } + + /** + * Initializes driver properties that come from a JNDI reference (in the + * case of a javax.sql.DataSource bound into some name service that doesn't + * handle Java objects directly). + * + * @param ref + * The JNDI Reference that holds RefAddrs for all properties + * @throws SQLException + * DOCUMENT ME! + */ + protected void initializeFromRef(Reference ref) throws SQLException { + int numPropertiesToSet = PROPERTY_LIST.size(); + + for (int i = 0; i < numPropertiesToSet; i++) { + java.lang.reflect.Field propertyField = (java.lang.reflect.Field) PROPERTY_LIST + .get(i); + + try { + ConnectionProperty propToSet = (ConnectionProperty) propertyField + .get(this); + + if (ref != null) { + propToSet.initializeFrom(ref); + } + } catch (IllegalAccessException iae) { + throw SQLError.createSQLException("Internal properties failure", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + postInitialization(); + } + + /** + * Initializes driver properties that come from URL or properties passed to + * the driver manager. + * + * @param info + * DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + protected void initializeProperties(Properties info) throws SQLException { + if (info != null) { + // For backwards-compatibility + String profileSqlLc = info.getProperty("profileSql"); + + if (profileSqlLc != null) { + info.put("profileSQL", profileSqlLc); + } + + Properties infoCopy = (Properties) info.clone(); + + infoCopy.remove(NonRegisteringDriver.HOST_PROPERTY_KEY); + infoCopy.remove(NonRegisteringDriver.USER_PROPERTY_KEY); + infoCopy.remove(NonRegisteringDriver.PASSWORD_PROPERTY_KEY); + infoCopy.remove(NonRegisteringDriver.DBNAME_PROPERTY_KEY); + infoCopy.remove(NonRegisteringDriver.PORT_PROPERTY_KEY); + infoCopy.remove("profileSql"); + + int numPropertiesToSet = PROPERTY_LIST.size(); + + for (int i = 0; i < numPropertiesToSet; i++) { + java.lang.reflect.Field propertyField = (java.lang.reflect.Field) PROPERTY_LIST + .get(i); + + try { + ConnectionProperty propToSet = (ConnectionProperty) propertyField + .get(this); + + propToSet.initializeFrom(infoCopy); + } catch (IllegalAccessException iae) { + throw SQLError.createSQLException( + "Unable to initialize driver properties due to " + + iae.toString(), + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + // TODO -- Not yet + /* + * int numUnknownProperties = infoCopy.size(); if + * (numUnknownProperties > 0) { StringBuffer errorMessageBuf = new + * StringBuffer( "Unknown connection "); + * errorMessageBuf.append((numUnknownProperties == 1) ? "property " : + * "properties "); Iterator propNamesItor = + * infoCopy.keySet().iterator(); errorMessageBuf.append("'"); + * errorMessageBuf.append(propNamesItor.next().toString()); + * errorMessageBuf.append("'"); while (propNamesItor.hasNext()) { + * errorMessageBuf.append(", '"); + * errorMessageBuf.append(propNamesItor.next().toString()); + * errorMessageBuf.append("'"); } throw new + * SQLException(errorMessageBuf.toString(), + * SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); } + */ + postInitialization(); + } + } + + protected void postInitialization() throws SQLException { + + // Support 'old' profileSql capitalization + if (this.profileSql.getValueAsObject() != null) { + this.profileSQL.initializeFrom(this.profileSql.getValueAsObject() + .toString()); + } + + this.reconnectTxAtEndAsBoolean = ((Boolean) this.reconnectAtTxEnd + .getValueAsObject()).booleanValue(); + + // Adjust max rows + if (this.getMaxRows() == 0) { + // adjust so that it will become MysqlDefs.MAX_ROWS + // in execSQL() + this.maxRows.setValueAsObject(new Integer(-1)); + } + + // + // Check character encoding + // + String testEncoding = this.getEncoding(); + + if (testEncoding != null) { + // Attempt to use the encoding, and bail out if it + // can't be used + try { + String testString = "abc"; + testString.getBytes(testEncoding); + } catch (UnsupportedEncodingException UE) { + throw SQLError.createSQLException("Unsupported character " + "encoding '" + + testEncoding + "'.", "0S100"); + } + } + + // Metadata caching is only supported on JDK-1.4 and newer + // because it relies on LinkedHashMap being present. + // Check (and disable) if not supported + if (((Boolean) this.cacheResultSetMetadata.getValueAsObject()) + .booleanValue()) { + try { + Class.forName("java.util.LinkedHashMap"); + } catch (ClassNotFoundException cnfe) { + this.cacheResultSetMetadata.setValue(false); + } + } + + this.cacheResultSetMetaDataAsBoolean = this.cacheResultSetMetadata + .getValueAsBoolean(); + this.useUnicodeAsBoolean = this.useUnicode.getValueAsBoolean(); + this.characterEncodingAsString = ((String) this.characterEncoding + .getValueAsObject()); + this.highAvailabilityAsBoolean = this.autoReconnect.getValueAsBoolean(); + this.autoReconnectForPoolsAsBoolean = this.autoReconnectForPools + .getValueAsBoolean(); + this.maxRowsAsInt = ((Integer) this.maxRows.getValueAsObject()) + .intValue(); + this.profileSQLAsBoolean = this.profileSQL.getValueAsBoolean(); + this.useUsageAdvisorAsBoolean = this.useUsageAdvisor + .getValueAsBoolean(); + this.useOldUTF8BehaviorAsBoolean = this.useOldUTF8Behavior + .getValueAsBoolean(); + this.autoGenerateTestcaseScriptAsBoolean = this.autoGenerateTestcaseScript + .getValueAsBoolean(); + this.maintainTimeStatsAsBoolean = this.maintainTimeStats + .getValueAsBoolean(); + this.jdbcCompliantTruncationForReads = getJdbcCompliantTruncation(); + + if (getUseCursorFetch()) { + // assume they want to use server-side prepared statements + // because they're required for this functionality + setDetectServerPreparedStmts(true); + } + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setAllowLoadLocalInfile(boolean property) { + this.allowLoadLocalInfile.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setAllowMultiQueries(boolean property) { + this.allowMultiQueries.setValue(property); + } + + /** + * @param allowNanAndInf + * The allowNanAndInf to set. + */ + public void setAllowNanAndInf(boolean flag) { + this.allowNanAndInf.setValue(flag); + } + + /** + * @param allowUrlInLocalInfile + * The allowUrlInLocalInfile to set. + */ + public void setAllowUrlInLocalInfile(boolean flag) { + this.allowUrlInLocalInfile.setValue(flag); + } + + /** + * @param alwaysSendSetIsolation + * The alwaysSendSetIsolation to set. + */ + public void setAlwaysSendSetIsolation(boolean flag) { + this.alwaysSendSetIsolation.setValue(flag); + } + + /** + * @param autoDeserialize + * The autoDeserialize to set. + */ + public void setAutoDeserialize(boolean flag) { + this.autoDeserialize.setValue(flag); + } + + public void setAutoGenerateTestcaseScript(boolean flag) { + this.autoGenerateTestcaseScript.setValue(flag); + this.autoGenerateTestcaseScriptAsBoolean = this.autoGenerateTestcaseScript + .getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The autoReconnect to set. + */ + public void setAutoReconnect(boolean flag) { + this.autoReconnect.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setAutoReconnectForConnectionPools(boolean property) { + this.autoReconnectForPools.setValue(property); + this.autoReconnectForPoolsAsBoolean = this.autoReconnectForPools + .getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The autoReconnectForPools to set. + */ + public void setAutoReconnectForPools(boolean flag) { + this.autoReconnectForPools.setValue(flag); + } + + /** + * @param blobSendChunkSize + * The blobSendChunkSize to set. + */ + public void setBlobSendChunkSize(String value) throws SQLException { + this.blobSendChunkSize.setValue(value); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The cacheCallableStatements to set. + */ + public void setCacheCallableStatements(boolean flag) { + this.cacheCallableStatements.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The cachePreparedStatements to set. + */ + public void setCachePreparedStatements(boolean flag) { + this.cachePreparedStatements.setValue(flag); + } + + /** + * Sets whether or not we should cache result set metadata. + * + * @param property + */ + public void setCacheResultSetMetadata(boolean property) { + this.cacheResultSetMetadata.setValue(property); + this.cacheResultSetMetaDataAsBoolean = this.cacheResultSetMetadata + .getValueAsBoolean(); + } + + /** + * @param cacheServerConfiguration + * The cacheServerConfiguration to set. + */ + public void setCacheServerConfiguration(boolean flag) { + this.cacheServerConfiguration.setValue(flag); + } + + /** + * Configures the number of callable statements to cache. (this is + * configurable during the life of the connection). + * + * @param size + * The callableStatementCacheSize to set. + */ + public void setCallableStatementCacheSize(int size) { + this.callableStatementCacheSize.setValue(size); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setCapitalizeDBMDTypes(boolean property) { + this.capitalizeTypeNames.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The capitalizeTypeNames to set. + */ + public void setCapitalizeTypeNames(boolean flag) { + this.capitalizeTypeNames.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param encoding + * The characterEncoding to set. + */ + public void setCharacterEncoding(String encoding) { + this.characterEncoding.setValue(encoding); + } + + /** + * DOCUMENT ME! + * + * @param characterSet + * The characterSetResults to set. + */ + public void setCharacterSetResults(String characterSet) { + this.characterSetResults.setValue(characterSet); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The clobberStreamingResults to set. + */ + public void setClobberStreamingResults(boolean flag) { + this.clobberStreamingResults.setValue(flag); + } + + public void setClobCharacterEncoding(String encoding) { + this.clobCharacterEncoding.setValue(encoding); + } + + /** + * DOCUMENT ME! + * + * @param collation + * The connectionCollation to set. + */ + public void setConnectionCollation(String collation) { + this.connectionCollation.setValue(collation); + } + + /** + * DOCUMENT ME! + * + * @param timeoutMs + */ + public void setConnectTimeout(int timeoutMs) { + this.connectTimeout.setValue(timeoutMs); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setContinueBatchOnError(boolean property) { + this.continueBatchOnError.setValue(property); + } + + public void setCreateDatabaseIfNotExist(boolean flag) { + this.createDatabaseIfNotExist.setValue(flag); + } + + public void setDefaultFetchSize(int n) { + this.defaultFetchSize.setValue(n); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setDetectServerPreparedStmts(boolean property) { + this.detectServerPreparedStmts.setValue(property); + } + + /** + * @param dontTrackOpenResources + * The dontTrackOpenResources to set. + */ + public void setDontTrackOpenResources(boolean flag) { + this.dontTrackOpenResources.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The dumpQueriesOnException to set. + */ + public void setDumpQueriesOnException(boolean flag) { + this.dumpQueriesOnException.setValue(flag); + } + + /** + * @param dynamicCalendars + * The dynamicCalendars to set. + */ + public void setDynamicCalendars(boolean flag) { + this.dynamicCalendars.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The elideSetAutoCommits to set. + */ + public void setElideSetAutoCommits(boolean flag) { + this.elideSetAutoCommits.setValue(flag); + } + + public void setEmptyStringsConvertToZero(boolean flag) { + this.emptyStringsConvertToZero.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setEmulateLocators(boolean property) { + this.emulateLocators.setValue(property); + } + + /** + * @param emulateUnsupportedPstmts + * The emulateUnsupportedPstmts to set. + */ + public void setEmulateUnsupportedPstmts(boolean flag) { + this.emulateUnsupportedPstmts.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The enablePacketDebug to set. + */ + public void setEnablePacketDebug(boolean flag) { + this.enablePacketDebug.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setEncoding(String property) { + this.characterEncoding.setValue(property); + this.characterEncodingAsString = this.characterEncoding + .getValueAsString(); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The explainSlowQueries to set. + */ + public void setExplainSlowQueries(boolean flag) { + this.explainSlowQueries.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The failOverReadOnly to set. + */ + public void setFailOverReadOnly(boolean flag) { + this.failOverReadOnly.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The gatherPerformanceMetrics to set. + */ + public void setGatherPerformanceMetrics(boolean flag) { + this.gatherPerformanceMetrics.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + protected void setHighAvailability(boolean property) { + this.autoReconnect.setValue(property); + this.highAvailabilityAsBoolean = this.autoReconnect.getValueAsBoolean(); + } + + /** + * @param holdResultsOpenOverStatementClose + * The holdResultsOpenOverStatementClose to set. + */ + public void setHoldResultsOpenOverStatementClose(boolean flag) { + this.holdResultsOpenOverStatementClose.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setIgnoreNonTxTables(boolean property) { + this.ignoreNonTxTables.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setInitialTimeout(int property) { + this.initialTimeout.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setIsInteractiveClient(boolean property) { + this.isInteractiveClient.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The jdbcCompliantTruncation to set. + */ + public void setJdbcCompliantTruncation(boolean flag) { + this.jdbcCompliantTruncation.setValue(flag); + } + + /** + * @param locatorFetchBufferSize + * The locatorFetchBufferSize to set. + */ + public void setLocatorFetchBufferSize(String value) throws SQLException { + this.locatorFetchBufferSize.setValue(value); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setLogger(String property) { + this.loggerClassName.setValueAsObject(property); + } + + /** + * DOCUMENT ME! + * + * @param className + * The loggerClassName to set. + */ + public void setLoggerClassName(String className) { + this.loggerClassName.setValue(className); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The logSlowQueries to set. + */ + public void setLogSlowQueries(boolean flag) { + this.logSlowQueries.setValue(flag); + } + + public void setMaintainTimeStats(boolean flag) { + this.maintainTimeStats.setValue(flag); + this.maintainTimeStatsAsBoolean = this.maintainTimeStats + .getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @param sizeInBytes + * The maxQuerySizeToLog to set. + */ + public void setMaxQuerySizeToLog(int sizeInBytes) { + this.maxQuerySizeToLog.setValue(sizeInBytes); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setMaxReconnects(int property) { + this.maxReconnects.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setMaxRows(int property) { + this.maxRows.setValue(property); + this.maxRowsAsInt = this.maxRows.getValueAsInt(); + } + + /** + * Sets the number of queries that metadata can be cached if caching is + * enabled. + * + * @param value + * the number of queries to cache metadata for. + */ + public void setMetadataCacheSize(int value) { + this.metadataCacheSize.setValue(value); + } + + /** + * @param noDatetimeStringSync + * The noDatetimeStringSync to set. + */ + public void setNoDatetimeStringSync(boolean flag) { + this.noDatetimeStringSync.setValue(flag); + } + + public void setNullCatalogMeansCurrent(boolean value) { + this.nullCatalogMeansCurrent.setValue(value); + } + + public void setNullNamePatternMatchesAll(boolean value) { + this.nullNamePatternMatchesAll.setValue(value); + } + + /** + * DOCUMENT ME! + * + * @param size + * The packetDebugBufferSize to set. + */ + public void setPacketDebugBufferSize(int size) { + this.packetDebugBufferSize.setValue(size); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setParanoid(boolean property) { + this.paranoid.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setPedantic(boolean property) { + this.pedantic.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param cacheSize + * The preparedStatementCacheSize to set. + */ + public void setPreparedStatementCacheSize(int cacheSize) { + this.preparedStatementCacheSize.setValue(cacheSize); + } + + /** + * DOCUMENT ME! + * + * @param cacheSqlLimit + * The preparedStatementCacheSqlLimit to set. + */ + public void setPreparedStatementCacheSqlLimit(int cacheSqlLimit) { + this.preparedStatementCacheSqlLimit.setValue(cacheSqlLimit); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setProfileSql(boolean property) { + this.profileSQL.setValue(property); + this.profileSQLAsBoolean = this.profileSQL.getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The profileSQL to set. + */ + public void setProfileSQL(boolean flag) { + this.profileSQL.setValue(flag); + } + + /** + * @param propertiesTransform + * The propertiesTransform to set. + */ + public void setPropertiesTransform(String value) { + this.propertiesTransform.setValue(value); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setQueriesBeforeRetryMaster(int property) { + this.queriesBeforeRetryMaster.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setReconnectAtTxEnd(boolean property) { + this.reconnectAtTxEnd.setValue(property); + this.reconnectTxAtEndAsBoolean = this.reconnectAtTxEnd + .getValueAsBoolean(); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setRelaxAutoCommit(boolean property) { + this.relaxAutoCommit.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param millis + * The reportMetricsIntervalMillis to set. + */ + public void setReportMetricsIntervalMillis(int millis) { + this.reportMetricsIntervalMillis.setValue(millis); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setRequireSSL(boolean property) { + this.requireSSL.setValue(property); + } + + public void setRetainStatementAfterResultSetClose(boolean flag) { + this.retainStatementAfterResultSetClose.setValue(flag); + } + + /** + * @param rollbackOnPooledClose + * The rollbackOnPooledClose to set. + */ + public void setRollbackOnPooledClose(boolean flag) { + this.rollbackOnPooledClose.setValue(flag); + } + + /** + * Sets whether or not hosts will be picked in a round-robin fashion. + * + * @param flag + * The roundRobinLoadBalance property to set. + */ + public void setRoundRobinLoadBalance(boolean flag) { + this.roundRobinLoadBalance.setValue(flag); + } + + /** + * @param runningCTS13 + * The runningCTS13 to set. + */ + public void setRunningCTS13(boolean flag) { + this.runningCTS13.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setSecondsBeforeRetryMaster(int property) { + this.secondsBeforeRetryMaster.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + * DOCUMENT ME! + */ + public void setServerTimezone(String property) { + this.serverTimezone.setValue(property); + } + + /** + * @param sessionVariables + * The sessionVariables to set. + */ + public void setSessionVariables(String variables) { + this.sessionVariables.setValue(variables); + } + + /** + * DOCUMENT ME! + * + * @param millis + * The slowQueryThresholdMillis to set. + */ + public void setSlowQueryThresholdMillis(int millis) { + this.slowQueryThresholdMillis.setValue(millis); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setSocketFactoryClassName(String property) { + this.socketFactoryClassName.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setSocketTimeout(int property) { + this.socketTimeout.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setStrictFloatingPoint(boolean property) { + this.strictFloatingPoint.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setStrictUpdates(boolean property) { + this.strictUpdates.setValue(property); + } + + /** + * @param tinyInt1isBit + * The tinyInt1isBit to set. + */ + public void setTinyInt1isBit(boolean flag) { + this.tinyInt1isBit.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The logProtocol to set. + */ + public void setTraceProtocol(boolean flag) { + this.traceProtocol.setValue(flag); + } + + public void setTransformedBitIsBoolean(boolean flag) { + this.transformedBitIsBoolean.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setUseCompression(boolean property) { + this.useCompression.setValue(property); + } + + /** + * @param useFastIntParsing + * The useFastIntParsing to set. + */ + public void setUseFastIntParsing(boolean flag) { + this.useFastIntParsing.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setUseHostsInPrivileges(boolean property) { + this.useHostsInPrivileges.setValue(property); + } + + public void setUseInformationSchema(boolean flag) { + this.useInformationSchema.setValue(flag); + } + + /** + * @param useLocalSessionState + * The useLocalSessionState to set. + */ + public void setUseLocalSessionState(boolean flag) { + this.useLocalSessionState.setValue(flag); + } + + /** + * @param useOldUTF8Behavior + * The useOldUTF8Behavior to set. + */ + public void setUseOldUTF8Behavior(boolean flag) { + this.useOldUTF8Behavior.setValue(flag); + this.useOldUTF8BehaviorAsBoolean = this.useOldUTF8Behavior + .getValueAsBoolean(); + } + + /** + * @param useOnlyServerErrorMessages + * The useOnlyServerErrorMessages to set. + */ + public void setUseOnlyServerErrorMessages(boolean flag) { + this.useOnlyServerErrorMessages.setValue(flag); + } + + /** + * @param useReadAheadInput + * The useReadAheadInput to set. + */ + public void setUseReadAheadInput(boolean flag) { + this.useReadAheadInput.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The detectServerPreparedStmts to set. + */ + public void setUseServerPreparedStmts(boolean flag) { + this.detectServerPreparedStmts.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The useSqlStateCodes to set. + */ + public void setUseSqlStateCodes(boolean flag) { + this.useSqlStateCodes.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setUseSSL(boolean property) { + this.useSSL.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setUseStreamLengthsInPrepStmts(boolean property) { + this.useStreamLengthsInPrepStmts.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setUseTimezone(boolean property) { + this.useTimezone.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param property + */ + public void setUseUltraDevWorkAround(boolean property) { + this.useUltraDevWorkAround.setValue(property); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The useUnbufferedInput to set. + */ + public void setUseUnbufferedInput(boolean flag) { + this.useUnbufferedInput.setValue(flag); + } + + /** + * DOCUMENT ME! + * + * @param flag + * The useUnicode to set. + */ + public void setUseUnicode(boolean flag) { + this.useUnicode.setValue(flag); + this.useUnicodeAsBoolean = this.useUnicode.getValueAsBoolean(); + } + + /** + * Sets whether or not the driver advises of proper usage. + * + * @param useUsageAdvisorFlag + * whether or not the driver advises of proper usage. + */ + public void setUseUsageAdvisor(boolean useUsageAdvisorFlag) { + this.useUsageAdvisor.setValue(useUsageAdvisorFlag); + this.useUsageAdvisorAsBoolean = this.useUsageAdvisor + .getValueAsBoolean(); + } + + public void setYearIsDateType(boolean flag) { + this.yearIsDateType.setValue(flag); + } + + /** + * @param zeroDateTimeBehavior + * The zeroDateTimeBehavior to set. + */ + public void setZeroDateTimeBehavior(String behavior) { + this.zeroDateTimeBehavior.setValue(behavior); + } + + protected void storeToRef(Reference ref) throws SQLException { + int numPropertiesToSet = PROPERTY_LIST.size(); + + for (int i = 0; i < numPropertiesToSet; i++) { + java.lang.reflect.Field propertyField = (java.lang.reflect.Field) PROPERTY_LIST + .get(i); + + try { + ConnectionProperty propToStore = (ConnectionProperty) propertyField + .get(this); + + if (ref != null) { + propToStore.storeTo(ref); + } + } catch (IllegalAccessException iae) { + throw SQLError.createSQLException("Huh?"); + } + } + } + + /** + * DOCUMENT ME! + * + * @return Returns the useUnbufferedInput. + */ + public boolean useUnbufferedInput() { + return this.useUnbufferedInput.getValueAsBoolean(); + } + + public boolean getUseCursorFetch() { + return this.useCursorFetch.getValueAsBoolean(); + } + + public void setUseCursorFetch(boolean flag) { + this.useCursorFetch.setValue(flag); + } + + public boolean getOverrideSupportsIntegrityEnhancementFacility() { + return this.overrideSupportsIntegrityEnhancementFacility.getValueAsBoolean(); + } + + public void setOverrideSupportsIntegrityEnhancementFacility(boolean flag) { + this.overrideSupportsIntegrityEnhancementFacility.setValue(flag); + } + + public boolean getNoTimezoneConversionForTimeType() { + return this.noTimezoneConversionForTimeType.getValueAsBoolean(); + } + + public void setNoTimezoneConversionForTimeType(boolean flag) { + this.noTimezoneConversionForTimeType.setValue(flag); + } + + public boolean getUseJDBCCompliantTimezoneShift() { + return this.useJDBCCompliantTimezoneShift.getValueAsBoolean(); + } + + public void setUseJDBCCompliantTimezoneShift(boolean flag) { + this.useJDBCCompliantTimezoneShift.setValue(flag); + } + + public boolean getAutoClosePStmtStreams() { + return this.autoClosePStmtStreams.getValueAsBoolean(); + } + + public void setAutoClosePStmtStreams(boolean flag) { + this.autoClosePStmtStreams.setValue(flag); + } + + public boolean getProcessEscapeCodesForPrepStmts() { + return this.processEscapeCodesForPrepStmts.getValueAsBoolean(); + } + + public void setProcessEscapeCodesForPrepStmts(boolean flag) { + this.processEscapeCodesForPrepStmts.setValue(flag); + } + + public boolean getUseGmtMillisForDatetimes() { + return this.useGmtMillisForDatetimes.getValueAsBoolean(); + } + + public void setUseGmtMillisForDatetimes(boolean flag) { + this.useGmtMillisForDatetimes.setValue(flag); + } + + public boolean getDumpMetadataOnColumnNotFound() { + return this.dumpMetadataOnColumnNotFound.getValueAsBoolean(); + } + + public void setDumpMetadataOnColumnNotFound(boolean flag) { + this.dumpMetadataOnColumnNotFound.setValue(flag); + } + + public String getResourceId() { + return this.resourceId.getValueAsString(); + } + + public void setResourceId(String resourceId) { + this.resourceId.setValue(resourceId); + } + + public boolean getRewriteBatchedStatements() { + return this.rewriteBatchedStatements.getValueAsBoolean(); + } + + public void setRewriteBatchedStatements(boolean flag) { + this.rewriteBatchedStatements.setValue(flag); + } + + public boolean getJdbcCompliantTruncationForReads() { + return this.jdbcCompliantTruncationForReads; + } + + public void setJdbcCompliantTruncationForReads( + boolean jdbcCompliantTruncationForReads) { + this.jdbcCompliantTruncationForReads = jdbcCompliantTruncationForReads; + } + + public boolean getUseJvmCharsetConverters() { + return this.useJvmCharsetConverters.getValueAsBoolean(); + } + + public void setUseJvmCharsetConverters(boolean flag) { + this.useJvmCharsetConverters.setValue(flag); + } + + public boolean getPinGlobalTxToPhysicalConnection() { + return this.pinGlobalTxToPhysicalConnection.getValueAsBoolean(); + } + + public void setPinGlobalTxToPhysicalConnection(boolean flag) { + this.pinGlobalTxToPhysicalConnection.setValue(flag); + } + + /* + * "Aliases" which match the property names to make using + * from datasources easier. + */ + + public void setGatherPerfMetrics(boolean flag) { + setGatherPerformanceMetrics(flag); + } + + public boolean getGatherPerfMetrics() { + return getGatherPerformanceMetrics(); + } + + public void setUltraDevHack(boolean flag) { + setUseUltraDevWorkAround(flag); + } + + public boolean getUltraDevHack() { + return getUseUltraDevWorkAround(); + } + + public void setInteractiveClient(boolean property) { + setIsInteractiveClient(property); + } + + public void setSocketFactory(String name) { + setSocketFactoryClassName(name); + } + + public String getSocketFactory() { + return getSocketFactoryClassName(); + } + + public void setUseServerPrepStmts(boolean flag) { + setUseServerPreparedStmts(flag); + } + + public boolean getUseServerPrepStmts() { + return getUseServerPreparedStmts(); + } + + public void setCacheCallableStmts(boolean flag) { + setCacheCallableStatements(flag); + } + + public boolean getCacheCallableStmts() { + return getCacheCallableStatements(); + } + + public void setCachePrepStmts(boolean flag) { + setCachePreparedStatements(flag); + } + + public boolean getCachePrepStmts() { + return getCachePreparedStatements(); + } + + public void setCallableStmtCacheSize(int cacheSize) { + setCallableStatementCacheSize(cacheSize); + } + + public int getCallableStmtCacheSize() { + return getCallableStatementCacheSize(); + } + + public void setPrepStmtCacheSize(int cacheSize) { + setPreparedStatementCacheSize(cacheSize); + } + + public int getPrepStmtCacheSize() { + return getPreparedStatementCacheSize(); + } + + public void setPrepStmtCacheSqlLimit(int sqlLimit) { + setPreparedStatementCacheSqlLimit(sqlLimit); + } + + public int getPrepStmtCacheSqlLimit() { + return getPreparedStatementCacheSqlLimit(); + } + + public boolean getNoAccessToProcedureBodies() { + return this.noAccessToProcedureBodies.getValueAsBoolean(); + } + + public void setNoAccessToProcedureBodies(boolean flag) { + this.noAccessToProcedureBodies.setValue(flag); + } + + public boolean getUseOldAliasMetadataBehavior() { + return this.useOldAliasMetadataBehavior.getValueAsBoolean(); + } + + public void setUseOldAliasMetadataBehavior(boolean flag) { + this.useOldAliasMetadataBehavior.setValue(flag); + } + + public boolean getUseSSPSCompatibleTimezoneShift() { + return this.useSSPSCompatibleTimezoneShift.getValueAsBoolean(); + } + + public void setUseSSPSCompatibleTimezoneShift(boolean flag) { + this.useSSPSCompatibleTimezoneShift.setValue(flag); + } + + public boolean getTreatUtilDateAsTimestamp() { + return this.treatUtilDateAsTimestamp.getValueAsBoolean(); + } + + public void setTreatUtilDateAsTimestamp(boolean flag) { + this.treatUtilDateAsTimestamp.setValue(flag); + } + + public boolean getUseFastDateParsing() { + return this.useFastDateParsing.getValueAsBoolean(); + } + + public void setUseFastDateParsing(boolean flag) { + this.useFastDateParsing.setValue(flag); + } + + public String getLocalSocketAddress() { + return this.localSocketAddress.getValueAsString(); + } + + public void setLocalSocketAddress(String address) { + this.localSocketAddress.setValue(address); + } + + public void setUseConfigs(String configs) { + this.useConfigs.setValue(configs); + } + + public String getUseConfigs() { + return this.useConfigs.getValueAsString(); + } + + public boolean getGenerateSimpleParameterMetadata() { + return this.generateSimpleParameterMetadata.getValueAsBoolean(); + } + + public void setGenerateSimpleParameterMetadata(boolean flag) { + this.generateSimpleParameterMetadata.setValue(flag); + } + + public boolean getLogXaCommands() { + return this.logXaCommands.getValueAsBoolean(); + } + + public void setLogXaCommands(boolean flag) { + this.logXaCommands.setValue(flag); + } + + public int getResultSetSizeThreshold() { + return this.resultSetSizeThreshold.getValueAsInt(); + } + + public void setResultSetSizeThreshold(int threshold) { + this.resultSetSizeThreshold.setValue(threshold); + } + + public boolean getEnableQueryTimeouts() { + return this.enableQueryTimeouts.getValueAsBoolean(); + } + + public void setEnableQueryTimeouts(boolean flag) { + this.enableQueryTimeouts.setValue(flag); + } + + public boolean getPadCharsWithSpace() { + return this.padCharsWithSpace.getValueAsBoolean(); + } + + public void setPadCharsWithSpace(boolean flag) { + this.padCharsWithSpace.setValue(flag); + } + + public boolean getUseDynamicCharsetInfo() { + return this.useDynamicCharsetInfo.getValueAsBoolean(); + } + + public void setUseDynamicCharsetInfo(boolean flag) { + this.useDynamicCharsetInfo.setValue(flag); + } + + public boolean getPopulateInsertRowWithDefaultValues() { + return this.populateInsertRowWithDefaultValues.getValueAsBoolean(); + } + + public void setPopulateInsertRowWithDefaultValues(boolean flag) { + this.populateInsertRowWithDefaultValues.setValue(flag); + } + + public String getLoadBalanceStrategy() { + return this.loadBalanceStrategy.getValueAsString(); + } + + public void setLoadBalanceStrategy(String strategy) { + this.loadBalanceStrategy.setValue(strategy); + } + + public boolean getUseNanosForElapsedTime() { + return this.useNanosForElapsedTime.getValueAsBoolean(); + } + + public void setUseNanosForElapsedTime(boolean flag) { + this.useNanosForElapsedTime.setValue(flag); + } + + public long getSlowQueryThresholdNanos() { + return this.slowQueryThresholdNanos.getValueAsLong(); + } + + public void setSlowQueryThresholdNanos(long nanos) { + this.slowQueryThresholdNanos.setValue(nanos); + } + + public boolean getTcpNoDelay() { + return this.tcpNoDelay.getValueAsBoolean(); + } + + public void setTcpNoDelay(boolean flag) { + this.tcpNoDelay.setValue(flag); + } + + public boolean getTcpKeepAlive() { + return this.tcpKeepAlive.getValueAsBoolean(); + } + + public void setTcpKeepAlive(boolean flag) { + this.tcpKeepAlive.setValue(flag); + } + + public int getTcpRcvBuf() { + return this.tcpRcvBuf.getValueAsInt(); + } + + public void setTcpRcvBuf(int bufSize) { + this.tcpRcvBuf.setValue(bufSize); + } + + public int getTcpSndBuf() { + return this.tcpSndBuf.getValueAsInt(); + } + + public void setTcpSndBuf(int bufSize) { + this.tcpSndBuf.setValue(bufSize); + } + + public int getTcpTrafficClass() { + return this.tcpTrafficClass.getValueAsInt(); + } + + public void setTcpTrafficClass(int classFlags) { + this.tcpTrafficClass.setValue(classFlags); + } + + public boolean getIncludeInnodbStatusInDeadlockExceptions() { + return this.includeInnodbStatusInDeadlockExceptions.getValueAsBoolean(); + } + + public void setIncludeInnodbStatusInDeadlockExceptions(boolean flag) { + this.includeInnodbStatusInDeadlockExceptions.setValue(flag); + } + + public boolean getBlobsAreStrings() { + return this.blobsAreStrings.getValueAsBoolean(); + } + + public void setBlobsAreStrings(boolean flag) { + this.blobsAreStrings.setValue(flag); + } + + public boolean getFunctionsNeverReturnBlobs() { + return this.functionsNeverReturnBlobs.getValueAsBoolean(); + } + + public void setFunctionsNeverReturnBlobs(boolean flag) { + this.functionsNeverReturnBlobs.setValue(flag); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionPropertiesTransform.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionPropertiesTransform.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ConnectionPropertiesTransform.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,55 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; +import java.util.Properties; + +/** + * Implement this interface, and pass the class name as the + * 'propertiesTransform' property in your JDBC URL, and the driver will pass the + * properties it has parsed to your transform implementation so that you can + * modify/substitute/add any that you desire. + * + * @author Mark Matthews + * + * @version $Id: ConnectionPropertiesTransform.java,v 1.1.2.1 2005/05/13 + * 18:58:37 mmatthews Exp $ + */ +public interface ConnectionPropertiesTransform { + /** + * The JDBC driver will call this method if the user has loaded your + * implementation of this interface by specifying the 'propertiesTransform' + * property in their JDBC URL. + * + * @param props + * the properties as passed by the driver (never null) + * + * @return the same properties with any transformations that your + * implementation has made + * + * @throws SQLException + * if a transform can not be made for any reason. + */ + public Properties transformProperties(Properties props) throws SQLException; +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Constants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Constants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Constants.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,50 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Represents various constants used in the driver. + * + * @author Mark Matthews + * + * @version $Id: Constants.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + */ +class Constants { + /** + * Avoids allocation of empty byte[] when representing 0-length strings. + */ + public final static byte[] EMPTY_BYTE_ARRAY = new byte[0]; + + /** + * I18N'd representation of the abbreviation for "ms" + */ + public final static String MILLIS_I18N = Messages.getString("Milliseconds"); + + /** + * Prevents instantiation + */ + private Constants() { + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/CursorRowProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Attic/CursorRowProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/CursorRowProvider.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,461 @@ +/* + Copyright (C) 2002-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +package com.mysql.jdbc; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * Model for result set data backed by a cursor. Only works for forward-only + * result sets (but still works with updatable concurrency). + * + * @version $Id: CursorRowProvider.java,v 1.1.2.1 2005/05/19 18:31:49 mmatthews + * Exp $ + */ +public class CursorRowProvider implements RowData { + + private final static int BEFORE_START_OF_ROWS = -1; + + /** + * The cache of rows we have retrieved from the server. + */ + private List fetchedRows; + + /** + * Where we are positionaly in the entire result set, used mostly to + * facilitate easy 'isBeforeFirst()' and 'isFirst()' methods. + */ + private int currentPositionInEntireResult = BEFORE_START_OF_ROWS; + + /** + * Position in cache of rows, used to determine if we need to fetch more + * rows from the server to satisfy a request for the next row. + */ + private int currentPositionInFetchedRows = BEFORE_START_OF_ROWS; + + /** + * The result set that we 'belong' to. + */ + private ResultSet owner; + + /** + * Have we been told from the server that we have seen the last row? + */ + private boolean lastRowFetched = false; + + /** + * Field-level metadata from the server. We need this, because it is not + * sent for each batch of rows, but we need the metadata to unpack the + * results for each field. + */ + private Field[] fields; + + /** + * Communications channel to the server + */ + private MysqlIO mysql; + + /** + * Identifier for the statement that created this cursor. + */ + private long statementIdOnServer; + + /** + * The prepared statement that created this cursor. + */ + private ServerPreparedStatement prepStmt; + + /** + * The server status for 'last-row-sent'...This might belong in mysqldefs, + * but it it only ever referenced from here. + */ + private static final int SERVER_STATUS_LAST_ROW_SENT = 128; + + /** + * Have we attempted to fetch any rows yet? + */ + private boolean firstFetchCompleted = false; + + private boolean wasEmpty = false; + + /** + * Creates a new cursor-backed row provider. + * + * @param ioChannel + * connection to the server. + * @param creatingStatement + * statement that opened the cursor. + * @param metadata + * field-level metadata for the results that this cursor covers. + */ + public CursorRowProvider(MysqlIO ioChannel, + ServerPreparedStatement creatingStatement, Field[] metadata) { + this.currentPositionInEntireResult = BEFORE_START_OF_ROWS; + this.fields = metadata; + this.mysql = ioChannel; + this.statementIdOnServer = creatingStatement.getServerStatementId(); + this.prepStmt = creatingStatement; + } + + /** + * Returns true if we got the last element. + * + * @return DOCUMENT ME! + */ + public boolean isAfterLast() { + return lastRowFetched + && this.currentPositionInFetchedRows > this.fetchedRows.size(); + } + + /** + * Only works on non dynamic result sets. + * + * @param index + * row number to get at + * @return row data at index + * @throws SQLException + * if a database error occurs + */ + public Object[] getAt(int ind) throws SQLException { + notSupported(); + + return null; + } + + /** + * Returns if iteration has not occured yet. + * + * @return true if before first row + * @throws SQLException + * if a database error occurs + */ + public boolean isBeforeFirst() throws SQLException { + return this.currentPositionInEntireResult < 0; + } + + /** + * Moves the current position in the result set to the given row number. + * + * @param rowNumber + * row to move to + * @throws SQLException + * if a database error occurs + */ + public void setCurrentRow(int rowNumber) throws SQLException { + notSupported(); + } + + /** + * Returns the current position in the result set as a row number. + * + * @return the current row number + * @throws SQLException + * if a database error occurs + */ + public int getCurrentRowNumber() throws SQLException { + return this.currentPositionInEntireResult + 1; + } + + /** + * Returns true if the result set is dynamic. + * + * This means that move back and move forward won't work because we do not + * hold on to the records. + * + * @return true if this result set is streaming from the server + */ + public boolean isDynamic() { + return true; + } + + /** + * Has no records. + * + * @return true if no records + * @throws SQLException + * if a database error occurs + */ + public boolean isEmpty() throws SQLException { + return this.isBeforeFirst() && this.isAfterLast(); + } + + /** + * Are we on the first row of the result set? + * + * @return true if on first row + * @throws SQLException + * if a database error occurs + */ + public boolean isFirst() throws SQLException { + return this.currentPositionInEntireResult == 0; + } + + /** + * Are we on the last row of the result set? + * + * @return true if on last row + * @throws SQLException + * if a database error occurs + */ + public boolean isLast() throws SQLException { + return this.lastRowFetched + && this.currentPositionInFetchedRows == (this.fetchedRows + .size() - 1); + } + + /** + * Adds a row to this row data. + * + * @param row + * the row to add + * @throws SQLException + * if a database error occurs + */ + public void addRow(byte[][] row) throws SQLException { + notSupported(); + } + + /** + * Moves to after last. + * + * @throws SQLException + * if a database error occurs + */ + public void afterLast() throws SQLException { + notSupported(); + } + + /** + * Moves to before first. + * + * @throws SQLException + * if a database error occurs + */ + public void beforeFirst() throws SQLException { + notSupported(); + } + + /** + * Moves to before last so next el is the last el. + * + * @throws SQLException + * if a database error occurs + */ + public void beforeLast() throws SQLException { + notSupported(); + } + + /** + * We're done. + * + * @throws SQLException + * if a database error occurs + */ + public void close() throws SQLException { + + this.fields = null; + this.owner = null; + } + + /** + * Returns true if another row exists. + * + * @return true if more rows + * @throws SQLException + * if a database error occurs + */ + public boolean hasNext() throws SQLException { + + if (this.fetchedRows != null && this.fetchedRows.size() == 0) { + return false; + } + + if (this.owner != null && this.owner.owningStatement != null) { + int maxRows = this.owner.owningStatement.maxRows; + + if (maxRows != -1 && this.currentPositionInEntireResult + 1 > maxRows) { + return false; + } + } + + if (this.currentPositionInEntireResult != BEFORE_START_OF_ROWS) { + // Case, we've fetched some rows, but are not at end of fetched + // block + if (this.currentPositionInFetchedRows < (this.fetchedRows.size() - 1)) { + return true; + } else if (this.currentPositionInFetchedRows == this.fetchedRows + .size() + && this.lastRowFetched) { + return false; + } else { + // need to fetch to determine + fetchMoreRows(); + + return (this.fetchedRows.size() > 0); + } + } + + // Okay, no rows _yet_, so fetch 'em + + fetchMoreRows(); + + return this.fetchedRows.size() > 0; + } + + /** + * Moves the current position relative 'rows' from the current position. + * + * @param rows + * the relative number of rows to move + * @throws SQLException + * if a database error occurs + */ + public void moveRowRelative(int rows) throws SQLException { + notSupported(); + } + + /** + * Returns the next row. + * + * @return the next row value + * @throws SQLException + * if a database error occurs + */ + public Object[] next() throws SQLException { + + this.currentPositionInEntireResult++; + this.currentPositionInFetchedRows++; + + + // Catch the forced scroll-passed-end + if (this.fetchedRows != null && this.fetchedRows.size() == 0) { + return null; + } + + if (this.currentPositionInFetchedRows > (this.fetchedRows.size() - 1)) { + fetchMoreRows(); + this.currentPositionInFetchedRows = 0; + } + + Object[] row = (Object[]) this.fetchedRows + .get(this.currentPositionInFetchedRows); + + return row; + } + + /** + * + */ + private void fetchMoreRows() throws SQLException { + if (this.lastRowFetched) { + this.fetchedRows = new ArrayList(0); + return; + } + + synchronized (this.owner.connection.getMutex()) { + boolean oldFirstFetchCompleted = this.firstFetchCompleted; + + if (!this.firstFetchCompleted) { + this.firstFetchCompleted = true; + } + + int numRowsToFetch = this.owner.getFetchSize(); + + if (numRowsToFetch == 0) { + numRowsToFetch = this.prepStmt.getFetchSize(); + } + + if (numRowsToFetch == Integer.MIN_VALUE) { + // Handle the case where the user used 'old' + // streaming result sets + + numRowsToFetch = 1; + } + + this.fetchedRows = this.mysql.fetchRowsViaCursor(this.fetchedRows, + this.statementIdOnServer, this.fields, numRowsToFetch); + this.currentPositionInFetchedRows = BEFORE_START_OF_ROWS; + + if ((this.mysql.getServerStatus() & SERVER_STATUS_LAST_ROW_SENT) != 0) { + this.lastRowFetched = true; + + if (!oldFirstFetchCompleted && this.fetchedRows.size() == 0) { + this.wasEmpty = true; + } + } + } + } + + /** + * Removes the row at the given index. + * + * @param index + * the row to move to + * @throws SQLException + * if a database error occurs + */ + public void removeRow(int ind) throws SQLException { + notSupported(); + } + + /** + * Only works on non dynamic result sets. + * + * @return the size of this row data + */ + public int size() { + return RESULT_SET_SIZE_UNKNOWN; + } + + private void nextRecord() throws SQLException { + + } + + private void notSupported() throws SQLException { + throw new OperationNotSupportedException(); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.RowProvider#setOwner(com.mysql.jdbc.ResultSet) + */ + public void setOwner(ResultSet rs) { + this.owner = rs; + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.RowProvider#getOwner() + */ + public ResultSet getOwner() { + return this.owner; + } + + public boolean wasEmpty() { + return this.wasEmpty; + } + +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/DatabaseMetaData.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/DatabaseMetaData.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/DatabaseMetaData.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,7940 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.UnsupportedEncodingException; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TreeMap; + +/** + * JDBC Interface to Mysql functions + *

+ * This class provides information about the database as a whole. + *

+ *

+ * Many of the methods here return lists of information in ResultSets. You can + * use the normal ResultSet methods such as getString and getInt to retrieve the + * data from these ResultSets. If a given form of metadata is not available, + * these methods show throw a SQLException. + *

+ *

+ * Some of these methods take arguments that are String patterns. These methods + * all have names such as fooPattern. Within a pattern String "%" means match + * any substring of 0 or more characters and "_" means match any one character. + *

+ * + * @author Mark Matthews + * @version $Id: DatabaseMetaData.java,v 1.27.4.66 2005/05/03 18:40:39 mmatthews + * Exp $ + */ +public class DatabaseMetaData implements java.sql.DatabaseMetaData { + protected abstract class IterateBlock { + IteratorWithCleanup iterator; + + IterateBlock(IteratorWithCleanup i) { + iterator = i; + } + + public void doForAll() throws SQLException { + try { + while (iterator.hasNext()) { + forEach(iterator.next()); + } + } finally { + iterator.close(); + } + } + + abstract void forEach(Object each) throws SQLException; + } + + protected abstract class IteratorWithCleanup { + abstract void close() throws SQLException; + + abstract boolean hasNext() throws SQLException; + + abstract Object next() throws SQLException; + } + + class LocalAndReferencedColumns { + String constraintName; + + List localColumnsList; + + String referencedCatalog; + + List referencedColumnsList; + + String referencedTable; + + LocalAndReferencedColumns(List localColumns, List refColumns, + String constName, String refCatalog, String refTable) { + this.localColumnsList = localColumns; + this.referencedColumnsList = refColumns; + this.constraintName = constName; + this.referencedTable = refTable; + this.referencedCatalog = refCatalog; + } + } + + protected class ResultSetIterator extends IteratorWithCleanup { + int colIndex; + + ResultSet resultSet; + + ResultSetIterator(ResultSet rs, int index) { + resultSet = rs; + colIndex = index; + } + + void close() throws SQLException { + resultSet.close(); + } + + boolean hasNext() throws SQLException { + return resultSet.next(); + } + + Object next() throws SQLException { + return resultSet.getObject(colIndex); + } + } + + protected class SingleStringIterator extends IteratorWithCleanup { + boolean onFirst = true; + + String value; + + SingleStringIterator(String s) { + value = s; + } + + void close() throws SQLException { + // not needed + + } + + boolean hasNext() throws SQLException { + return onFirst; + } + + Object next() throws SQLException { + onFirst = false; + return value; + } + } + + /** + * Parses and represents common data type information used by various + * column/parameter methods. + */ + class TypeDescriptor { + int bufferLength; + + int charOctetLength; + + Integer columnSize; + + short dataType; + + Integer decimalDigits; + + String isNullable; + + int nullability; + + int numPrecRadix = 10; + + String typeName; + + TypeDescriptor(String typeInfo, String nullabilityInfo) + throws SQLException { + String mysqlType = ""; + String fullMysqlType = null; + + if (typeInfo.indexOf("(") != -1) { + mysqlType = typeInfo.substring(0, typeInfo.indexOf("(")); + } else { + mysqlType = typeInfo; + } + + int indexOfUnsignedInMysqlType = StringUtils.indexOfIgnoreCase( + mysqlType, "unsigned"); + + if (indexOfUnsignedInMysqlType != -1) { + mysqlType = mysqlType.substring(0, + (indexOfUnsignedInMysqlType - 1)); + } + + // Add unsigned to typename reported to enduser as 'native type', if + // present + + boolean isUnsigned = false; + + if (StringUtils.indexOfIgnoreCase(typeInfo, "unsigned") != -1) { + fullMysqlType = mysqlType + " unsigned"; + isUnsigned = true; + } else { + fullMysqlType = mysqlType; + } + + if (conn.getCapitalizeTypeNames()) { + fullMysqlType = fullMysqlType.toUpperCase(Locale.ENGLISH); + } + + this.dataType = (short) MysqlDefs.mysqlToJavaType(mysqlType); + + this.typeName = fullMysqlType; + + // Figure Out the Size + if (typeInfo != null) { + if (StringUtils.startsWithIgnoreCase(typeInfo, "enum")) { + String temp = typeInfo.substring(typeInfo.indexOf("("), + typeInfo.lastIndexOf(")")); + java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( + temp, ","); + int maxLength = 0; + + while (tokenizer.hasMoreTokens()) { + maxLength = Math.max(maxLength, (tokenizer.nextToken() + .length() - 2)); + } + + this.columnSize = new Integer(maxLength); + this.decimalDigits = null; + } else if (StringUtils.startsWithIgnoreCase(typeInfo, "set")) { + String temp = typeInfo.substring(typeInfo.indexOf("("), + typeInfo.lastIndexOf(")")); + java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( + temp, ","); + int maxLength = 0; + + while (tokenizer.hasMoreTokens()) { + String setMember = tokenizer.nextToken().trim(); + + if (setMember.startsWith("'") + && setMember.endsWith("'")) { + maxLength += setMember.length() - 2; + } else { + maxLength += setMember.length(); + } + } + + this.columnSize = new Integer(maxLength); + this.decimalDigits = null; + } else if (typeInfo.indexOf(",") != -1) { + // Numeric with decimals + this.columnSize = new Integer(typeInfo.substring((typeInfo + .indexOf("(") + 1), (typeInfo.indexOf(","))).trim()); + this.decimalDigits = new Integer(typeInfo.substring( + (typeInfo.indexOf(",") + 1), + (typeInfo.indexOf(")"))).trim()); + } else { + this.columnSize = null; + this.decimalDigits = null; + + /* If the size is specified with the DDL, use that */ + if ((StringUtils.indexOfIgnoreCase(typeInfo, "char") != -1 + || StringUtils.indexOfIgnoreCase(typeInfo, "text") != -1 + || StringUtils.indexOfIgnoreCase(typeInfo, "blob") != -1 + || StringUtils + .indexOfIgnoreCase(typeInfo, "binary") != -1 || StringUtils + .indexOfIgnoreCase(typeInfo, "bit") != -1) + && typeInfo.indexOf("(") != -1) { + int endParenIndex = typeInfo.indexOf(")"); + + if (endParenIndex == -1) { + endParenIndex = typeInfo.length(); + } + + this.columnSize = new Integer(typeInfo.substring( + (typeInfo.indexOf("(") + 1), endParenIndex).trim()); + + // Adjust for pseudo-boolean + if (conn.getTinyInt1isBit() + && this.columnSize.intValue() == 1 + && StringUtils.startsWithIgnoreCase(typeInfo, + 0, "tinyint")) { + if (conn.getTransformedBitIsBoolean()) { + this.dataType = Types.BOOLEAN; + this.typeName = "BOOLEAN"; + } else { + this.dataType = Types.BIT; + this.typeName = "BIT"; + } + } + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "tinyint")) { + if (conn.getTinyInt1isBit() && typeInfo.indexOf("(1)") != -1) { + if (conn.getTransformedBitIsBoolean()) { + this.dataType = Types.BOOLEAN; + this.typeName = "BOOLEAN"; + } else { + this.dataType = Types.BIT; + this.typeName = "BIT"; + } + } else { + this.columnSize = new Integer(3); + this.decimalDigits = new Integer(0); + } + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "smallint")) { + this.columnSize = new Integer(5); + this.decimalDigits = new Integer(0); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "mediumint")) { + this.columnSize = new Integer(isUnsigned ? 8 : 7); + this.decimalDigits = new Integer(0); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "int")) { + this.columnSize = new Integer(10); + this.decimalDigits = new Integer(0); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "integer")) { + this.columnSize = new Integer(10); + this.decimalDigits = new Integer(0); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "bigint")) { + this.columnSize = new Integer(isUnsigned ? 20 : 19); + this.decimalDigits = new Integer(0); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "int24")) { + this.columnSize = new Integer(19); + this.decimalDigits = new Integer(0); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "real")) { + this.columnSize = new Integer(12); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "float")) { + this.columnSize = new Integer(12); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "decimal")) { + this.columnSize = new Integer(12); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "numeric")) { + this.columnSize = new Integer(12); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "double")) { + this.columnSize = new Integer(22); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "char")) { + this.columnSize = new Integer(1); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "varchar")) { + this.columnSize = new Integer(255); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "date")) { + this.columnSize = null; + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "time")) { + this.columnSize = null; + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "timestamp")) { + this.columnSize = null; + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "datetime")) { + this.columnSize = null; + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "tinyblob")) { + this.columnSize = new Integer(255); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "blob")) { + this.columnSize = new Integer(65535); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "mediumblob")) { + this.columnSize = new Integer(16777215); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "longblob")) { + this.columnSize = new Integer(Integer.MAX_VALUE); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "tinytext")) { + this.columnSize = new Integer(255); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "text")) { + this.columnSize = new Integer(65535); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "mediumtext")) { + this.columnSize = new Integer(16777215); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "longtext")) { + this.columnSize = new Integer(Integer.MAX_VALUE); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "enum")) { + this.columnSize = new Integer(255); + } else if (StringUtils.startsWithIgnoreCaseAndWs(typeInfo, + "set")) { + this.columnSize = new Integer(255); + } + + } + } else { + this.decimalDigits = null; + this.columnSize = null; + } + + // BUFFER_LENGTH + this.bufferLength = MysqlIO.getMaxBuf(); + + // NUM_PREC_RADIX (is this right for char?) + this.numPrecRadix = 10; + + // Nullable? + if (nullabilityInfo != null) { + if (nullabilityInfo.equals("YES")) { + this.nullability = java.sql.DatabaseMetaData.columnNullable; + this.isNullable = "YES"; + + // IS_NULLABLE + } else { + this.nullability = java.sql.DatabaseMetaData.columnNoNulls; + this.isNullable = "NO"; + } + } else { + this.nullability = java.sql.DatabaseMetaData.columnNoNulls; + this.isNullable = "NO"; + } + } + } + + private static String mysqlKeywordsThatArentSQL92; + + private static final int DEFERRABILITY = 13; + + private static final int DELETE_RULE = 10; + + private static final int FK_NAME = 11; + + private static final int FKCOLUMN_NAME = 7; + + private static final int FKTABLE_CAT = 4; + + private static final int FKTABLE_NAME = 6; + + private static final int FKTABLE_SCHEM = 5; + + private static final int KEY_SEQ = 8; + + private static final int PK_NAME = 12; + + private static final int PKCOLUMN_NAME = 3; + + // + // Column indexes used by all DBMD foreign key + // ResultSets + // + private static final int PKTABLE_CAT = 0; + + private static final int PKTABLE_NAME = 2; + + private static final int PKTABLE_SCHEM = 1; + + /** The table type for generic tables that support foreign keys. */ + private static final String SUPPORTS_FK = "SUPPORTS_FK"; + + private static final byte[] TABLE_AS_BYTES = "TABLE".getBytes(); + + private static final int UPDATE_RULE = 9; + + private static final byte[] VIEW_AS_BYTES = "VIEW".getBytes(); + + static { + // Current as-of MySQL-5.1.16 + String[] allMySQLKeywords = new String[] { "ACCESSIBLE", "ADD", "ALL", + "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE", "BEFORE", + "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOTH", "BY", "CALL", + "CASCADE", "CASE", "CHANGE", "CHAR", "CHARACTER", "CHECK", + "COLLATE", "COLUMN", "CONDITION", "CONNECTION", "CONSTRAINT", + "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT_DATE", + "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", + "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MICROSECOND", + "DAY_MINUTE", "DAY_SECOND", "DEC", "DECIMAL", "DECLARE", + "DEFAULT", "DELAYED", "DELETE", "DESC", "DESCRIBE", + "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE", + "DROP", "DUAL", "EACH", "ELSE", "ELSEIF", "ENCLOSED", + "ESCAPED", "EXISTS", "EXIT", "EXPLAIN", "FALSE", "FETCH", + "FLOAT", "FLOAT4", "FLOAT8", "FOR", "FORCE", "FOREIGN", "FROM", + "FULLTEXT", "GRANT", "GROUP", "HAVING", "HIGH_PRIORITY", + "HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IF", + "IGNORE", "IN", "INDEX", "INFILE", "INNER", "INOUT", + "INSENSITIVE", "INSERT", "INT", "INT1", "INT2", "INT3", "INT4", + "INT8", "INTEGER", "INTERVAL", "INTO", "IS", "ITERATE", "JOIN", + "KEY", "KEYS", "KILL", "LEADING", "LEAVE", "LEFT", "LIKE", + "LIMIT", "LINEAR", "LINES", "LOAD", "LOCALTIME", + "LOCALTIMESTAMP", "LOCK", "LONG", "LONGBLOB", "LONGTEXT", + "LOOP", "LOW_PRIORITY", "MATCH", "MEDIUMBLOB", "MEDIUMINT", + "MEDIUMTEXT", "MIDDLEINT", "MINUTE_MICROSECOND", + "MINUTE_SECOND", "MOD", "MODIFIES", "NATURAL", "NOT", + "NO_WRITE_TO_BINLOG", "NULL", "NUMERIC", "ON", "OPTIMIZE", + "OPTION", "OPTIONALLY", "OR", "ORDER", "OUT", "OUTER", + "OUTFILE", "PRECISION", "PRIMARY", "PROCEDURE", "PURGE", + "RANGE", "READ", "READS", "READ_ONLY", "READ_WRITE", "REAL", + "REFERENCES", "REGEXP", "RELEASE", "RENAME", "REPEAT", + "REPLACE", "REQUIRE", "RESTRICT", "RETURN", "REVOKE", "RIGHT", + "RLIKE", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", + "SENSITIVE", "SEPARATOR", "SET", "SHOW", "SMALLINT", "SPATIAL", + "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", + "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", + "SSL", "STARTING", "STRAIGHT_JOIN", "TABLE", "TERMINATED", + "THEN", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", + "TRIGGER", "TRUE", "UNDO", "UNION", "UNIQUE", "UNLOCK", + "UNSIGNED", "UPDATE", "USAGE", "USE", "USING", "UTC_DATE", + "UTC_TIME", "UTC_TIMESTAMP", "VALUES", "VARBINARY", "VARCHAR", + "VARCHARACTER", "VARYING", "WHEN", "WHERE", "WHILE", "WITH", + "WRITE", "X509", "XOR", "YEAR_MONTH", "ZEROFILL" }; + + String[] sql92Keywords = new String[] { "ABSOLUTE", "EXEC", "OVERLAPS", + "ACTION", "EXECUTE", "PAD", "ADA", "EXISTS", "PARTIAL", "ADD", + "EXTERNAL", "PASCAL", "ALL", "EXTRACT", "POSITION", "ALLOCATE", + "FALSE", "PRECISION", "ALTER", "FETCH", "PREPARE", "AND", + "FIRST", "PRESERVE", "ANY", "FLOAT", "PRIMARY", "ARE", "FOR", + "PRIOR", "AS", "FOREIGN", "PRIVILEGES", "ASC", "FORTRAN", + "PROCEDURE", "ASSERTION", "FOUND", "PUBLIC", "AT", "FROM", + "READ", "AUTHORIZATION", "FULL", "REAL", "AVG", "GET", + "REFERENCES", "BEGIN", "GLOBAL", "RELATIVE", "BETWEEN", "GO", + "RESTRICT", "BIT", "GOTO", "REVOKE", "BIT_LENGTH", "GRANT", + "RIGHT", "BOTH", "GROUP", "ROLLBACK", "BY", "HAVING", "ROWS", + "CASCADE", "HOUR", "SCHEMA", "CASCADED", "IDENTITY", "SCROLL", + "CASE", "IMMEDIATE", "SECOND", "CAST", "IN", "SECTION", + "CATALOG", "INCLUDE", "SELECT", "CHAR", "INDEX", "SESSION", + "CHAR_LENGTH", "INDICATOR", "SESSION_USER", "CHARACTER", + "INITIALLY", "SET", "CHARACTER_LENGTH", "INNER", "SIZE", + "CHECK", "INPUT", "SMALLINT", "CLOSE", "INSENSITIVE", "SOME", + "COALESCE", "INSERT", "SPACE", "COLLATE", "INT", "SQL", + "COLLATION", "INTEGER", "SQLCA", "COLUMN", "INTERSECT", + "SQLCODE", "COMMIT", "INTERVAL", "SQLERROR", "CONNECT", "INTO", + "SQLSTATE", "CONNECTION", "IS", "SQLWARNING", "CONSTRAINT", + "ISOLATION", "SUBSTRING", "CONSTRAINTS", "JOIN", "SUM", + "CONTINUE", "KEY", "SYSTEM_USER", "CONVERT", "LANGUAGE", + "TABLE", "CORRESPONDING", "LAST", "TEMPORARY", "COUNT", + "LEADING", "THEN", "CREATE", "LEFT", "TIME", "CROSS", "LEVEL", + "TIMESTAMP", "CURRENT", "LIKE", "TIMEZONE_HOUR", + "CURRENT_DATE", "LOCAL", "TIMEZONE_MINUTE", "CURRENT_TIME", + "LOWER", "TO", "CURRENT_TIMESTAMP", "MATCH", "TRAILING", + "CURRENT_USER", "MAX", "TRANSACTION", "CURSOR", "MIN", + "TRANSLATE", "DATE", "MINUTE", "TRANSLATION", "DAY", "MODULE", + "TRIM", "DEALLOCATE", "MONTH", "TRUE", "DEC", "NAMES", "UNION", + "DECIMAL", "NATIONAL", "UNIQUE", "DECLARE", "NATURAL", + "UNKNOWN", "DEFAULT", "NCHAR", "UPDATE", "DEFERRABLE", "NEXT", + "UPPER", "DEFERRED", "NO", "USAGE", "DELETE", "NONE", "USER", + "DESC", "NOT", "USING", "DESCRIBE", "NULL", "VALUE", + "DESCRIPTOR", "NULLIF", "VALUES", "DIAGNOSTICS", "NUMERIC", + "VARCHAR", "DISCONNECT", "OCTET_LENGTH", "VARYING", "DISTINCT", + "OF", "VIEW", "DOMAIN", "ON", "WHEN", "DOUBLE", "ONLY", + "WHENEVER", "DROP", "OPEN", "WHERE", "ELSE", "OPTION", "WITH", + "END", "OR", "WORK", "END-EXEC", "ORDER", "WRITE", "ESCAPE", + "OUTER", "YEAR", "EXCEPT", "OUTPUT", "ZONE", "EXCEPTION" }; + + TreeMap mySQLKeywordMap = new TreeMap(); + + for (int i = 0; i < allMySQLKeywords.length; i++) { + mySQLKeywordMap.put(allMySQLKeywords[i], null); + } + + HashMap sql92KeywordMap = new HashMap(sql92Keywords.length); + + for (int i = 0; i < sql92Keywords.length; i++) { + sql92KeywordMap.put(sql92Keywords[i], null); + } + + Iterator it = sql92KeywordMap.keySet().iterator(); + + while (it.hasNext()) { + mySQLKeywordMap.remove(it.next()); + } + + StringBuffer keywordBuf = new StringBuffer(); + + it = mySQLKeywordMap.keySet().iterator(); + + if (it.hasNext()) { + keywordBuf.append(it.next().toString()); + } + + while (it.hasNext()) { + keywordBuf.append(","); + keywordBuf.append(it.next().toString()); + } + + mysqlKeywordsThatArentSQL92 = keywordBuf.toString(); + } + + static java.sql.ResultSet buildResultSet(com.mysql.jdbc.Field[] fields, + java.util.ArrayList rows, Connection c) throws SQLException { + int fieldsLength = fields.length; + + for (int i = 0; i < fieldsLength; i++) { + fields[i].setConnection(c); + fields[i].setUseOldNameMetadata(true); + } + + return new com.mysql.jdbc.ResultSet(c.getCatalog(), fields, + new RowDataStatic(rows), c, null); + } + + /** The connection to the database */ + protected Connection conn; + + /** The 'current' database name being used */ + protected String database = null; + + /** What character to use when quoting identifiers */ + protected String quotedId = null; + + /** + * Creates a new DatabaseMetaData object. + * + * @param connToSet + * DOCUMENT ME! + * @param databaseToSet + * DOCUMENT ME! + */ + public DatabaseMetaData(Connection connToSet, String databaseToSet) { + this.conn = connToSet; + this.database = databaseToSet; + + try { + this.quotedId = this.conn.supportsQuotedIdentifiers() ? getIdentifierQuoteString() + : ""; + } catch (SQLException sqlEx) { + // Forced by API, never thrown from getIdentifierQuoteString() in + // this + // implementation. + AssertionFailedException.shouldNotHappen(sqlEx); + } + } + + /** + * Can all the procedures returned by getProcedures be called by the current + * user? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean allProceduresAreCallable() throws SQLException { + return false; + } + + /** + * Can all the tables returned by getTable be SELECTed by the current user? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean allTablesAreSelectable() throws SQLException { + return false; + } + + private java.sql.ResultSet buildResultSet(com.mysql.jdbc.Field[] fields, + java.util.ArrayList rows) throws SQLException { + return buildResultSet(fields, rows, this.conn); + } + + private void convertToJdbcFunctionList(String catalog, + ResultSet proceduresRs, boolean needsClientFiltering, String db, + Map procedureRowsOrderedByName, int nameIndex) throws SQLException { + while (proceduresRs.next()) { + boolean shouldAdd = true; + + if (needsClientFiltering) { + shouldAdd = false; + + String procDb = proceduresRs.getString(1); + + if (db == null && procDb == null) { + shouldAdd = true; + } else if (db != null && db.equals(procDb)) { + shouldAdd = true; + } + } + + if (shouldAdd) { + String functionName = proceduresRs.getString(nameIndex); + byte[][] rowData = new byte[8][]; + rowData[0] = catalog == null ? null : s2b(catalog); + rowData[1] = null; + rowData[2] = s2b(functionName); + rowData[3] = null; + rowData[4] = null; + rowData[5] = null; + rowData[6] = null; + rowData[7] = s2b(Integer.toString(procedureReturnsResult)); + + procedureRowsOrderedByName.put(functionName, rowData); + } + } + } + + private void convertToJdbcProcedureList(boolean fromSelect, String catalog, + ResultSet proceduresRs, boolean needsClientFiltering, String db, + Map procedureRowsOrderedByName, int nameIndex) throws SQLException { + while (proceduresRs.next()) { + boolean shouldAdd = true; + + if (needsClientFiltering) { + shouldAdd = false; + + String procDb = proceduresRs.getString(1); + + if (db == null && procDb == null) { + shouldAdd = true; + } else if (db != null && db.equals(procDb)) { + shouldAdd = true; + } + } + + if (shouldAdd) { + String procedureName = proceduresRs.getString(nameIndex); + byte[][] rowData = new byte[8][]; + rowData[0] = catalog == null ? null : s2b(catalog); + rowData[1] = null; + rowData[2] = s2b(procedureName); + rowData[3] = null; + rowData[4] = null; + rowData[5] = null; + rowData[6] = null; + + boolean isFunction = fromSelect ? "FUNCTION" + .equalsIgnoreCase(proceduresRs.getString("type")) + : false; + rowData[7] = s2b(isFunction ? Integer + .toString(procedureReturnsResult) : Integer + .toString(procedureResultUnknown)); + + procedureRowsOrderedByName.put(procedureName, rowData); + } + } + } + + private byte[][] convertTypeDescriptorToProcedureRow( + byte[] procNameAsBytes, String paramName, boolean isOutParam, + boolean isInParam, boolean isReturnParam, TypeDescriptor typeDesc) + throws SQLException { + byte[][] row = new byte[14][]; + row[0] = null; // PROCEDURE_CAT + row[1] = null; // PROCEDURE_SCHEM + row[2] = procNameAsBytes; // PROCEDURE/NAME + row[3] = s2b(paramName); // COLUMN_NAME + // COLUMN_TYPE + if (isInParam && isOutParam) { + row[4] = s2b(String.valueOf(procedureColumnInOut)); + } else if (isInParam) { + row[4] = s2b(String.valueOf(procedureColumnIn)); + } else if (isOutParam) { + row[4] = s2b(String.valueOf(procedureColumnOut)); + } else if (isReturnParam) { + row[4] = s2b(String.valueOf(procedureColumnReturn)); + } else { + row[4] = s2b(String.valueOf(procedureColumnUnknown)); + } + row[5] = s2b(Short.toString(typeDesc.dataType)); // DATA_TYPE + row[6] = s2b(typeDesc.typeName); // TYPE_NAME + row[7] = typeDesc.columnSize == null ? null : s2b(typeDesc.columnSize + .toString()); // PRECISION + row[8] = s2b(Integer.toString(typeDesc.bufferLength)); // LENGTH + row[9] = typeDesc.decimalDigits == null ? null + : s2b(typeDesc.decimalDigits.toString()); // SCALE + row[10] = s2b(Integer.toString(typeDesc.numPrecRadix)); // RADIX + // Map 'column****' to 'procedure****' + switch (typeDesc.nullability) { + case columnNoNulls: + row[11] = s2b(Integer.toString(procedureNoNulls)); // NULLABLE + + break; + + case columnNullable: + row[11] = s2b(Integer.toString(procedureNullable)); // NULLABLE + + break; + + case columnNullableUnknown: + row[11] = s2b(Integer.toString(procedureNullableUnknown)); // nullable + + break; + + default: + throw SQLError + .createSQLException( + "Internal error while parsing callable statement metadata (unknown nullability value fount)", + SQLError.SQL_STATE_GENERAL_ERROR); + } + row[12] = null; + return row; + } + + /** + * Does a data definition statement within a transaction force the + * transaction to commit? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean dataDefinitionCausesTransactionCommit() throws SQLException { + return true; + } + + /** + * Is a data definition statement within a transaction ignored? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean dataDefinitionIgnoredInTransactions() throws SQLException { + return false; + } + + /** + * JDBC 2.0 Determine whether or not a visible row delete can be detected by + * calling ResultSet.rowDeleted(). If deletesAreDetected() returns false, + * then deleted rows are removed from the result set. + * + * @param type + * set type, i.e. ResultSet.TYPE_XXX + * @return true if changes are detected by the resultset type + * @exception SQLException + * if a database-access error occurs. + */ + public boolean deletesAreDetected(int type) throws SQLException { + return false; + } + + // ---------------------------------------------------------------------- + + /** + * Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY blobs? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { + return true; + } + + /** + * Finds the end of the parameter declaration from the output of "SHOW + * CREATE PROCEDURE". + * + * @param beginIndex + * should be the index of the procedure body that contains the + * first "(". + * @param procedureDef + * the procedure body + * @param quoteChar + * the identifier quote character in use + * @return the ending index of the parameter declaration, not including the + * closing ")" + * @throws SQLException + * if a parse error occurs. + */ + private int endPositionOfParameterDeclaration(int beginIndex, + String procedureDef, String quoteChar) throws SQLException { + int currentPos = beginIndex + 1; + int parenDepth = 1; // counting the first openParen + + while (parenDepth > 0 && currentPos < procedureDef.length()) { + int closedParenIndex = StringUtils.indexOfIgnoreCaseRespectQuotes( + currentPos, procedureDef, ")", quoteChar.charAt(0), + !this.conn.isNoBackslashEscapesSet()); + + if (closedParenIndex != -1) { + int nextOpenParenIndex = StringUtils + .indexOfIgnoreCaseRespectQuotes(currentPos, + procedureDef, "(", quoteChar.charAt(0), + !this.conn.isNoBackslashEscapesSet()); + + if (nextOpenParenIndex != -1 + && nextOpenParenIndex < closedParenIndex) { + parenDepth++; + currentPos = closedParenIndex + 1; // set after closed + // paren that increases + // depth + } else { + parenDepth--; + currentPos = closedParenIndex; // start search from same + // position + } + } else { + // we should always get closed paren of some sort + throw SQLError + .createSQLException( + "Internal error when parsing callable statement metadata", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + return currentPos; + } + + /** + * Extracts foreign key info for one table. + * + * @param rows + * the list of rows to add to + * @param rs + * the result set from 'SHOW CREATE TABLE' + * @param catalog + * the database name + * @return the list of rows with new rows added + * @throws SQLException + * if a database access error occurs + */ + public List extractForeignKeyForTable(ArrayList rows, + java.sql.ResultSet rs, String catalog) throws SQLException { + byte[][] row = new byte[3][]; + row[0] = rs.getBytes(1); + row[1] = s2b(SUPPORTS_FK); + + String createTableString = rs.getString(2); + StringTokenizer lineTokenizer = new StringTokenizer(createTableString, + "\n"); + StringBuffer commentBuf = new StringBuffer("comment; "); + boolean firstTime = true; + + String quoteChar = getIdentifierQuoteString(); + + if (quoteChar == null) { + quoteChar = "`"; + } + + while (lineTokenizer.hasMoreTokens()) { + String line = lineTokenizer.nextToken().trim(); + + String constraintName = null; + + if (StringUtils.startsWithIgnoreCase(line, "CONSTRAINT")) { + boolean usingBackTicks = true; + int beginPos = line.indexOf(quoteChar); + + if (beginPos == -1) { + beginPos = line.indexOf("\""); + usingBackTicks = false; + } + + if (beginPos != -1) { + int endPos = -1; + + if (usingBackTicks) { + endPos = line.indexOf(quoteChar, beginPos + 1); + } else { + endPos = line.indexOf("\"", beginPos + 1); + } + + if (endPos != -1) { + constraintName = line.substring(beginPos + 1, endPos); + line = line.substring(endPos + 1, line.length()).trim(); + } + } + } + + if (line.startsWith("FOREIGN KEY")) { + if (line.endsWith(",")) { + line = line.substring(0, line.length() - 1); + } + + char quote = this.quotedId.charAt(0); + + int indexOfFK = line.indexOf("FOREIGN KEY"); + + String localColumnName = null; + String referencedCatalogName = this.quotedId + catalog + + this.quotedId; + String referencedTableName = null; + String referencedColumnName = null; + + if (indexOfFK != -1) { + int afterFk = indexOfFK + "FOREIGN KEY".length(); + + int indexOfRef = StringUtils + .indexOfIgnoreCaseRespectQuotes(afterFk, line, + "REFERENCES", quote, true); + + if (indexOfRef != -1) { + + int indexOfParenOpen = line.indexOf('(', afterFk); + int indexOfParenClose = StringUtils + .indexOfIgnoreCaseRespectQuotes( + indexOfParenOpen, line, ")", quote, + true); + + if (indexOfParenOpen == -1 || indexOfParenClose == -1) { + // throw SQLError.createSQLException(); + } + + localColumnName = line.substring(indexOfParenOpen + 1, + indexOfParenClose); + + int afterRef = indexOfRef + "REFERENCES".length(); + + int referencedColumnBegin = StringUtils + .indexOfIgnoreCaseRespectQuotes(afterRef, line, + "(", quote, true); + + if (referencedColumnBegin != -1) { + referencedTableName = line.substring(afterRef, + referencedColumnBegin); + + int referencedColumnEnd = StringUtils + .indexOfIgnoreCaseRespectQuotes( + referencedColumnBegin + 1, line, + ")", quote, true); + + if (referencedColumnEnd != -1) { + referencedColumnName = line.substring( + referencedColumnBegin + 1, + referencedColumnEnd); + } + + int indexOfCatalogSep = StringUtils + .indexOfIgnoreCaseRespectQuotes(0, + referencedTableName, ".", quote, + true); + + if (indexOfCatalogSep != -1) { + referencedCatalogName = referencedTableName + .substring(0, indexOfCatalogSep); + referencedTableName = referencedTableName + .substring(indexOfCatalogSep + 1); + } + } + } + } + + if (!firstTime) { + commentBuf.append("; "); + } else { + firstTime = false; + } + + if (constraintName != null) { + commentBuf.append(constraintName); + } else { + commentBuf.append("not_available"); + } + + commentBuf.append("("); + commentBuf.append(localColumnName); + commentBuf.append(") REFER "); + commentBuf.append(referencedCatalogName); + commentBuf.append("/"); + commentBuf.append(referencedTableName); + commentBuf.append("("); + commentBuf.append(referencedColumnName); + commentBuf.append(")"); + + int lastParenIndex = line.lastIndexOf(")"); + + if (lastParenIndex != (line.length() - 1)) { + String cascadeOptions = cascadeOptions = line + .substring(lastParenIndex + 1); + commentBuf.append(" "); + commentBuf.append(cascadeOptions); + } + } + } + + row[2] = s2b(commentBuf.toString()); + rows.add(row); + + return rows; + } + + /** + * Creates a result set similar enough to 'SHOW TABLE STATUS' to allow the + * same code to work on extracting the foreign key data + * + * @param connToUse + * the database connection to use + * @param metadata + * the DatabaseMetaData instance calling this method + * @param catalog + * the database name to extract foreign key info for + * @param tableName + * the table to extract foreign key info for + * @return A result set that has the structure of 'show table status' + * @throws SQLException + * if a database access error occurs. + */ + public ResultSet extractForeignKeyFromCreateTable(String catalog, + String tableName) throws SQLException { + ArrayList tableList = new ArrayList(); + java.sql.ResultSet rs = null; + java.sql.Statement stmt = null; + + if (tableName != null) { + tableList.add(tableName); + } else { + try { + rs = getTables(catalog, "", "%", new String[] { "TABLE" }); + + while (rs.next()) { + tableList.add(rs.getString("TABLE_NAME")); + } + } finally { + if (rs != null) { + rs.close(); + } + + rs = null; + } + } + + ArrayList rows = new ArrayList(); + Field[] fields = new Field[3]; + fields[0] = new Field("", "Name", Types.CHAR, Integer.MAX_VALUE); + fields[1] = new Field("", "Type", Types.CHAR, 255); + fields[2] = new Field("", "Comment", Types.CHAR, Integer.MAX_VALUE); + + int numTables = tableList.size(); + stmt = this.conn.getMetadataSafeStatement(); + + String quoteChar = getIdentifierQuoteString(); + + if (quoteChar == null) { + quoteChar = "`"; + } + + try { + for (int i = 0; i < numTables; i++) { + String tableToExtract = (String) tableList.get(i); + + String query = new StringBuffer("SHOW CREATE TABLE ").append( + quoteChar).append(catalog).append(quoteChar) + .append(".").append(quoteChar).append(tableToExtract) + .append(quoteChar).toString(); + try { + rs = stmt.executeQuery(query); + } catch (SQLException sqlEx) { + // Table might've disappeared on us, not really an error + String sqlState = sqlEx.getSQLState(); + + if (!"42S02".equals(sqlState) && + sqlEx.getErrorCode() != MysqlErrorNumbers.ER_NO_SUCH_TABLE) { + throw sqlEx; + } + + continue; + } + + while (rs.next()) { + extractForeignKeyForTable(rows, rs, catalog); + } + } + } finally { + if (rs != null) { + rs.close(); + } + + rs = null; + + if (stmt != null) { + stmt.close(); + } + + stmt = null; + } + + return buildResultSet(fields, rows); + } + + /** + * Finds the end of the RETURNS clause for SQL Functions by using any of the + * keywords allowed after the RETURNS clause, or a label. + * + * @param procedureDefn + * the function body containing the definition of the function + * @param quoteChar + * the identifier quote string in use + * @param positionOfReturnKeyword + * the position of "RETRUNS" in the definition + * @return the end of the returns clause + * @throws SQLException + * if a parse error occurs + */ + private int findEndOfReturnsClause(String procedureDefn, String quoteChar, + int positionOfReturnKeyword) throws SQLException { + /* + * characteristic: LANGUAGE SQL | [NOT] DETERMINISTIC | { CONTAINS SQL | + * NO SQL | READS SQL DATA | MODIFIES SQL DATA } | SQL SECURITY { + * DEFINER | INVOKER } | COMMENT 'string' + */ + + String[] tokens = new String[] { "LANGUAGE", "NOT", "DETERMINISTIC", + "CONTAINS", "NO", "READ", "MODIFIES", "SQL", "COMMENT", "BEGIN", + "RETURN" }; + + int startLookingAt = positionOfReturnKeyword + "RETURNS".length() + 1; + + for (int i = 0; i < tokens.length; i++) { + int endOfReturn = StringUtils.indexOfIgnoreCaseRespectQuotes( + startLookingAt, procedureDefn, tokens[i], quoteChar + .charAt(0), !this.conn.isNoBackslashEscapesSet()); + + if (endOfReturn != -1) { + return endOfReturn; + } + } + + // Label? + int endOfReturn = StringUtils.indexOfIgnoreCaseRespectQuotes( + startLookingAt, procedureDefn, ":", quoteChar.charAt(0), + !this.conn.isNoBackslashEscapesSet()); + + if (endOfReturn != -1) { + // seek back until whitespace + for (int i = endOfReturn; i > 0; i--) { + if (Character.isWhitespace(procedureDefn.charAt(i))) { + return i; + } + } + } + + // We can't parse it. + + throw SQLError.createSQLException( + "Internal error when parsing callable statement metadata", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + /** + * @see DatabaseMetaData#getAttributes(String, String, String, String) + */ + public java.sql.ResultSet getAttributes(String arg0, String arg1, + String arg2, String arg3) throws SQLException { + Field[] fields = new Field[21]; + fields[0] = new Field("", "TYPE_CAT", Types.CHAR, 32); + fields[1] = new Field("", "TYPE_SCHEM", Types.CHAR, 32); + fields[2] = new Field("", "TYPE_NAME", Types.CHAR, 32); + fields[3] = new Field("", "ATTR_NAME", Types.CHAR, 32); + fields[4] = new Field("", "DATA_TYPE", Types.SMALLINT, 32); + fields[5] = new Field("", "ATTR_TYPE_NAME", Types.CHAR, 32); + fields[6] = new Field("", "ATTR_SIZE", Types.INTEGER, 32); + fields[7] = new Field("", "DECIMAL_DIGITS", Types.INTEGER, 32); + fields[8] = new Field("", "NUM_PREC_RADIX", Types.INTEGER, 32); + fields[9] = new Field("", "NULLABLE ", Types.INTEGER, 32); + fields[10] = new Field("", "REMARKS", Types.CHAR, 32); + fields[11] = new Field("", "ATTR_DEF", Types.CHAR, 32); + fields[12] = new Field("", "SQL_DATA_TYPE", Types.INTEGER, 32); + fields[13] = new Field("", "SQL_DATETIME_SUB", Types.INTEGER, 32); + fields[14] = new Field("", "CHAR_OCTET_LENGTH", Types.INTEGER, 32); + fields[15] = new Field("", "ORDINAL_POSITION", Types.INTEGER, 32); + fields[16] = new Field("", "IS_NULLABLE", Types.CHAR, 32); + fields[17] = new Field("", "SCOPE_CATALOG", Types.CHAR, 32); + fields[18] = new Field("", "SCOPE_SCHEMA", Types.CHAR, 32); + fields[19] = new Field("", "SCOPE_TABLE", Types.CHAR, 32); + fields[20] = new Field("", "SOURCE_DATA_TYPE", Types.SMALLINT, 32); + + return buildResultSet(fields, new ArrayList()); + } + + /** + * Get a description of a table's optimal set of columns that uniquely + * identifies a row. They are ordered by SCOPE. + *

+ * Each column description has the following columns: + *

    + *
  1. SCOPE short => actual scope of result + *
      + *
    • bestRowTemporary - very temporary, while using row
    • + *
    • bestRowTransaction - valid for remainder of current transaction + *
    • + *
    • bestRowSession - valid for remainder of current session
    • + *
    + *
  2. + *
  3. COLUMN_NAME String => column name
  4. + *
  5. DATA_TYPE short => SQL data type from java.sql.Types
  6. + *
  7. TYPE_NAME String => Data source dependent type name
  8. + *
  9. COLUMN_SIZE int => precision
  10. + *
  11. BUFFER_LENGTH int => not used
  12. + *
  13. DECIMAL_DIGITS short => scale
  14. + *
  15. PSEUDO_COLUMN short => is this a pseudo column like an + * Oracle ROWID + *
      + *
    • bestRowUnknown - may or may not be pseudo column
    • + *
    • bestRowNotPseudo - is NOT a pseudo column
    • + *
    • bestRowPseudo - is a pseudo column
    • + *
    + *
  16. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name; "" retrieves those without a schema + * @param table + * a table name + * @param scope + * the scope of interest; use same values as SCOPE + * @param nullable + * include columns that are nullable? + * @return ResultSet each row is a column description + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getBestRowIdentifier(String catalog, + String schema, final String table, int scope, boolean nullable) + throws SQLException { + if (table == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + Field[] fields = new Field[8]; + fields[0] = new Field("", "SCOPE", Types.SMALLINT, 5); + fields[1] = new Field("", "COLUMN_NAME", Types.CHAR, 32); + fields[2] = new Field("", "DATA_TYPE", Types.SMALLINT, 32); + fields[3] = new Field("", "TYPE_NAME", Types.CHAR, 32); + fields[4] = new Field("", "COLUMN_SIZE", Types.INTEGER, 10); + fields[5] = new Field("", "BUFFER_LENGTH", Types.INTEGER, 10); + fields[6] = new Field("", "DECIMAL_DIGITS", Types.INTEGER, 10); + fields[7] = new Field("", "PSEUDO_COLUMN", Types.SMALLINT, 5); + + final ArrayList rows = new ArrayList(); + final Statement stmt = this.conn.getMetadataSafeStatement(); + + try { + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + ResultSet results = null; + + try { + StringBuffer queryBuf = new StringBuffer( + "SHOW COLUMNS FROM "); + queryBuf.append(quotedId); + queryBuf.append(table); + queryBuf.append(quotedId); + queryBuf.append(" FROM "); + queryBuf.append(quotedId); + queryBuf.append(catalogStr.toString()); + queryBuf.append(quotedId); + + results = stmt.executeQuery(queryBuf.toString()); + + while (results.next()) { + String keyType = results.getString("Key"); + + if (keyType != null) { + if (StringUtils.startsWithIgnoreCase(keyType, + "PRI")) { + byte[][] rowVal = new byte[8][]; + rowVal[0] = Integer + .toString( + java.sql.DatabaseMetaData.bestRowSession) + .getBytes(); + rowVal[1] = results.getBytes("Field"); + + String type = results.getString("Type"); + int size = MysqlIO.getMaxBuf(); + int decimals = 0; + + /* + * Parse the Type column from MySQL + */ + if (type.indexOf("enum") != -1) { + String temp = type.substring(type + .indexOf("("), type + .indexOf(")")); + java.util.StringTokenizer tokenizer = new java.util.StringTokenizer( + temp, ","); + int maxLength = 0; + + while (tokenizer.hasMoreTokens()) { + maxLength = Math.max(maxLength, + (tokenizer.nextToken() + .length() - 2)); + } + + size = maxLength; + decimals = 0; + type = "enum"; + } else if (type.indexOf("(") != -1) { + if (type.indexOf(",") != -1) { + size = Integer.parseInt(type + .substring(type + .indexOf("(") + 1, + type.indexOf(","))); + decimals = Integer.parseInt(type + .substring(type + .indexOf(",") + 1, + type.indexOf(")"))); + } else { + size = Integer.parseInt(type + .substring(type + .indexOf("(") + 1, + type.indexOf(")"))); + } + + type = type.substring(0, type + .indexOf("(")); + } + + rowVal[2] = s2b(String.valueOf(MysqlDefs + .mysqlToJavaType(type))); + rowVal[3] = s2b(type); + rowVal[4] = Integer.toString( + size + decimals).getBytes(); + rowVal[5] = Integer.toString( + size + decimals).getBytes(); + rowVal[6] = Integer.toString(decimals) + .getBytes(); + rowVal[7] = Integer + .toString( + java.sql.DatabaseMetaData.bestRowNotPseudo) + .getBytes(); + + rows.add(rowVal); + } + } + } + + } finally { + if (results != null) { + try { + results.close(); + } catch (Exception ex) { + ; + } + + results = null; + } + } + } + }.doForAll(); + } finally { + if (stmt != null) { + stmt.close(); + } + } + + java.sql.ResultSet results = buildResultSet(fields, rows); + + return results; + + } + + /* + * * Each row in the ResultSet is a parameter desription or column + * description with the following fields:
  1. PROCEDURE_CAT + * String => procedure catalog (may be null)
  2. PROCEDURE_SCHEM + * String => procedure schema (may be null)
  3. PROCEDURE_NAME + * String => procedure name
  4. COLUMN_NAME String => + * column/parameter name
  5. COLUMN_TYPE Short => kind of + * column/parameter:
    • procedureColumnUnknown - nobody knows
    • + *
    • procedureColumnIn - IN parameter
    • procedureColumnInOut - + * INOUT parameter
    • procedureColumnOut - OUT parameter
    • + * procedureColumnReturn - procedure return value
    • + * procedureColumnResult - result column in ResultSet
  6. + * DATA_TYPE short => SQL type from java.sql.Types
  7. + * TYPE_NAME String => SQL type name
  8. PRECISION + * int => precision
  9. LENGTH int => length in bytes of data + *
  10. SCALE short => scale
  11. RADIX short => + * radix
  12. NULLABLE short => can it contain NULL?
    • + * procedureNoNulls - does not allow NULL values
    • + * procedureNullable - allows NULL values
    • + * procedureNullableUnknown - nullability unknown
  13. + * REMARKS String => comment describing parameter/column
+ *

Note: Some databases may not return the column + * descriptions for a procedure. Additional columns beyond REMARKS can be + * defined by the database.

@param catalog a catalog name; "" retrieves + * those without a catalog @param schemaPattern a schema name pattern; "" + * retrieves those without a schema @param procedureNamePattern a procedure + * name pattern @param columnNamePattern a column name pattern @return + * ResultSet each row is a stored procedure parameter or column description + * @throws SQLException if a database access error occurs + * + * @see #getSearchStringEscape + */ + private void getCallStmtParameterTypes(String catalog, String procName, + String parameterNamePattern, List resultRows) throws SQLException { + java.sql.Statement paramRetrievalStmt = null; + java.sql.ResultSet paramRetrievalRs = null; + + if (parameterNamePattern == null) { + if (this.conn.getNullNamePatternMatchesAll()) { + parameterNamePattern = "%"; + } else { + throw SQLError + .createSQLException( + "Parameter/Column name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + byte[] procNameAsBytes = null; + + try { + procNameAsBytes = procName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException ueEx) { + procNameAsBytes = s2b(procName); + } + + String quoteChar = getIdentifierQuoteString(); + + String parameterDef = null; + + boolean isProcedureInAnsiMode = false; + String storageDefnDelims = null; + String storageDefnClosures = null; + + try { + paramRetrievalStmt = this.conn.getMetadataSafeStatement(); + + if (this.conn.lowerCaseTableNames() && catalog != null + && catalog.length() != 0) { + // Workaround for bug in server wrt. to + // SHOW CREATE PROCEDURE not respecting + // lower-case table names + + String oldCatalog = this.conn.getCatalog(); + ResultSet rs = null; + + try { + this.conn.setCatalog(catalog); + rs = paramRetrievalStmt.executeQuery("SELECT DATABASE()"); + rs.next(); + + catalog = rs.getString(1); + + } finally { + + this.conn.setCatalog(oldCatalog); + + if (rs != null) { + rs.close(); + } + } + } + + if (paramRetrievalStmt.getMaxRows() != 0) { + paramRetrievalStmt.setMaxRows(0); + } + + int dotIndex = -1; + + if (!" ".equals(quoteChar)) { + dotIndex = StringUtils.indexOfIgnoreCaseRespectQuotes(0, + procName, ".", quoteChar.charAt(0), !this.conn + .isNoBackslashEscapesSet()); + } else { + dotIndex = procName.indexOf("."); + } + + String dbName = null; + + if (dotIndex != -1 && (dotIndex + 1) < procName.length()) { + dbName = procName.substring(0, dotIndex); + procName = procName.substring(dotIndex + 1); + } else { + dbName = catalog; + } + + StringBuffer procNameBuf = new StringBuffer(); + + if (dbName != null) { + if (!" ".equals(quoteChar) && !dbName.startsWith(quoteChar)) { + procNameBuf.append(quoteChar); + } + + procNameBuf.append(dbName); + + if (!" ".equals(quoteChar) && !dbName.startsWith(quoteChar)) { + procNameBuf.append(quoteChar); + } + + procNameBuf.append("."); + } + + boolean procNameIsNotQuoted = !procName.startsWith(quoteChar); + + if (!" ".equals(quoteChar) && procNameIsNotQuoted) { + procNameBuf.append(quoteChar); + } + + procNameBuf.append(procName); + + if (!" ".equals(quoteChar) && procNameIsNotQuoted) { + procNameBuf.append(quoteChar); + } + + boolean parsingFunction = false; + + try { + paramRetrievalRs = paramRetrievalStmt + .executeQuery("SHOW CREATE PROCEDURE " + + procNameBuf.toString()); + parsingFunction = false; + } catch (SQLException sqlEx) { + paramRetrievalRs = paramRetrievalStmt + .executeQuery("SHOW CREATE FUNCTION " + + procNameBuf.toString()); + parsingFunction = true; + } + + if (paramRetrievalRs.next()) { + String procedureDef = parsingFunction ? paramRetrievalRs + .getString("Create Function") : paramRetrievalRs + .getString("Create Procedure"); + + if (procedureDef == null || procedureDef.length() == 0) { + throw SQLError + .createSQLException( + "User does not have access to metadata required to determine " + + "stored procedure parameter types. If rights can not be granted, configure connection with \"noAccessToProcedureBodies=true\" " + + "to have driver generate parameters that represent INOUT strings irregardless of actual parameter types.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + try { + String sqlMode = paramRetrievalRs.getString("sql_mode"); + + if (StringUtils.indexOfIgnoreCase(sqlMode, "ANSI") != -1) { + isProcedureInAnsiMode = true; + } + } catch (SQLException sqlEx) { + // doesn't exist + } + + String identifierMarkers = isProcedureInAnsiMode ? "`\"" : "`"; + String identifierAndStringMarkers = "'" + identifierMarkers; + storageDefnDelims = "(" + identifierMarkers; + storageDefnClosures = ")" + identifierMarkers; + + // sanitize/normalize by stripping out comments + procedureDef = StringUtils.stripComments(procedureDef, + identifierAndStringMarkers, identifierAndStringMarkers, true, false, true, true); + + int openParenIndex = StringUtils + .indexOfIgnoreCaseRespectQuotes(0, procedureDef, "(", + quoteChar.charAt(0), !this.conn + .isNoBackslashEscapesSet()); + int endOfParamDeclarationIndex = 0; + + endOfParamDeclarationIndex = endPositionOfParameterDeclaration( + openParenIndex, procedureDef, quoteChar); + + if (parsingFunction) { + + // Grab the return column since it needs + // to go first in the output result set + int returnsIndex = StringUtils + .indexOfIgnoreCaseRespectQuotes(0, procedureDef, + " RETURNS ", quoteChar.charAt(0), + !this.conn.isNoBackslashEscapesSet()); + + int endReturnsDef = findEndOfReturnsClause(procedureDef, + quoteChar, returnsIndex); + + // Trim off whitespace after "RETURNS" + + int declarationStart = returnsIndex + "RETURNS ".length(); + + while (declarationStart < procedureDef.length()) { + if (Character.isWhitespace(procedureDef.charAt(declarationStart))) { + declarationStart++; + } else { + break; + } + } + + String returnsDefn = procedureDef.substring(declarationStart, endReturnsDef).trim(); + TypeDescriptor returnDescriptor = new TypeDescriptor( + returnsDefn, null); + + resultRows.add(convertTypeDescriptorToProcedureRow( + procNameAsBytes, "", false, false, true, + returnDescriptor)); + } + + if ((openParenIndex == -1) + || (endOfParamDeclarationIndex == -1)) { + // parse error? + throw SQLError + .createSQLException( + "Internal error when parsing callable statement metadata", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + parameterDef = procedureDef.substring(openParenIndex + 1, + endOfParamDeclarationIndex); + } + } finally { + SQLException sqlExRethrow = null; + + if (paramRetrievalRs != null) { + try { + paramRetrievalRs.close(); + } catch (SQLException sqlEx) { + sqlExRethrow = sqlEx; + } + + paramRetrievalRs = null; + } + + if (paramRetrievalStmt != null) { + try { + paramRetrievalStmt.close(); + } catch (SQLException sqlEx) { + sqlExRethrow = sqlEx; + } + + paramRetrievalStmt = null; + } + + if (sqlExRethrow != null) { + throw sqlExRethrow; + } + } + + if (parameterDef != null) { + + List parseList = StringUtils.split(parameterDef, ",", + storageDefnDelims, storageDefnClosures, true); + + int parseListLen = parseList.size(); + + for (int i = 0; i < parseListLen; i++) { + String declaration = (String) parseList.get(i); + + if (declaration.trim().length() == 0) { + break; // no parameters actually declared, but whitespace + // spans lines + } + + StringTokenizer declarationTok = new StringTokenizer( + declaration, " \t"); + + String paramName = null; + boolean isOutParam = false; + boolean isInParam = false; + + if (declarationTok.hasMoreTokens()) { + String possibleParamName = declarationTok.nextToken(); + + if (possibleParamName.equalsIgnoreCase("OUT")) { + isOutParam = true; + + if (declarationTok.hasMoreTokens()) { + paramName = declarationTok.nextToken(); + } else { + throw SQLError + .createSQLException( + "Internal error when parsing callable statement metadata (missing parameter name)", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } else if (possibleParamName.equalsIgnoreCase("INOUT")) { + isOutParam = true; + isInParam = true; + + if (declarationTok.hasMoreTokens()) { + paramName = declarationTok.nextToken(); + } else { + throw SQLError + .createSQLException( + "Internal error when parsing callable statement metadata (missing parameter name)", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } else if (possibleParamName.equalsIgnoreCase("IN")) { + isOutParam = false; + isInParam = true; + + if (declarationTok.hasMoreTokens()) { + paramName = declarationTok.nextToken(); + } else { + throw SQLError + .createSQLException( + "Internal error when parsing callable statement metadata (missing parameter name)", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } else { + isOutParam = false; + isInParam = true; + + paramName = possibleParamName; + } + + TypeDescriptor typeDesc = null; + + if (declarationTok.hasMoreTokens()) { + StringBuffer typeInfoBuf = new StringBuffer( + declarationTok.nextToken()); + + while (declarationTok.hasMoreTokens()) { + typeInfoBuf.append(" "); + typeInfoBuf.append(declarationTok.nextToken()); + } + + String typeInfo = typeInfoBuf.toString(); + + typeDesc = new TypeDescriptor(typeInfo, null); + } else { + throw SQLError + .createSQLException( + "Internal error when parsing callable statement metadata (missing parameter type)", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + if ((paramName.startsWith("`") && paramName.endsWith("`")) || + (isProcedureInAnsiMode && paramName.startsWith("\"") && paramName.endsWith("\""))) { + paramName = paramName.substring(1, paramName.length() - 1); + } + + int wildCompareRes = StringUtils.wildCompare(paramName, + parameterNamePattern); + + if (wildCompareRes != StringUtils.WILD_COMPARE_NO_MATCH) { + byte[][] row = convertTypeDescriptorToProcedureRow( + procNameAsBytes, paramName, isOutParam, + isInParam, false, typeDesc); + + resultRows.add(row); + } + } else { + throw SQLError + .createSQLException( + "Internal error when parsing callable statement metadata (unknown output from 'SHOW CREATE PROCEDURE')", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + } else { + // Is this an error? JDBC spec doesn't make it clear if stored + // procedure doesn't + // exist, is it an error.... + } + } + + /** + * Parses the cascade option string and returns the DBMD constant that + * represents it (for deletes) + * + * @param cascadeOptions + * the comment from 'SHOW TABLE STATUS' + * @return the DBMD constant that represents the cascade option + */ + private int getCascadeDeleteOption(String cascadeOptions) { + int onDeletePos = cascadeOptions.indexOf("ON DELETE"); + + if (onDeletePos != -1) { + String deleteOptions = cascadeOptions.substring(onDeletePos, + cascadeOptions.length()); + + if (deleteOptions.startsWith("ON DELETE CASCADE")) { + return java.sql.DatabaseMetaData.importedKeyCascade; + } else if (deleteOptions.startsWith("ON DELETE SET NULL")) { + return java.sql.DatabaseMetaData.importedKeySetNull; + } else if (deleteOptions.startsWith("ON DELETE RESTRICT")) { + return java.sql.DatabaseMetaData.importedKeyRestrict; + } else if (deleteOptions.startsWith("ON DELETE NO ACTION")) { + return java.sql.DatabaseMetaData.importedKeyNoAction; + } + } + + return java.sql.DatabaseMetaData.importedKeyNoAction; + } + + /** + * Parses the cascade option string and returns the DBMD constant that + * represents it (for Updates) + * + * @param cascadeOptions + * the comment from 'SHOW TABLE STATUS' + * @return the DBMD constant that represents the cascade option + */ + private int getCascadeUpdateOption(String cascadeOptions) { + int onUpdatePos = cascadeOptions.indexOf("ON UPDATE"); + + if (onUpdatePos != -1) { + String updateOptions = cascadeOptions.substring(onUpdatePos, + cascadeOptions.length()); + + if (updateOptions.startsWith("ON UPDATE CASCADE")) { + return java.sql.DatabaseMetaData.importedKeyCascade; + } else if (updateOptions.startsWith("ON UPDATE SET NULL")) { + return java.sql.DatabaseMetaData.importedKeySetNull; + } else if (updateOptions.startsWith("ON UPDATE RESTRICT")) { + return java.sql.DatabaseMetaData.importedKeyRestrict; + } else if (updateOptions.startsWith("ON UPDATE NO ACTION")) { + return java.sql.DatabaseMetaData.importedKeyNoAction; + } + } + + return java.sql.DatabaseMetaData.importedKeyNoAction; + } + + protected IteratorWithCleanup getCatalogIterator(String catalogSpec) + throws SQLException { + IteratorWithCleanup allCatalogsIter; + if (catalogSpec != null) { + if (!catalogSpec.equals("")) { + allCatalogsIter = new SingleStringIterator(catalogSpec); + } else { + // legacy mode of operation + allCatalogsIter = new SingleStringIterator(this.database); + } + } else if (this.conn.getNullCatalogMeansCurrent()) { + allCatalogsIter = new SingleStringIterator(this.database); + } else { + allCatalogsIter = new ResultSetIterator(getCatalogs(), 1); + } + + return allCatalogsIter; + } + + /** + * Get the catalog names available in this database. The results are ordered + * by catalog name. + *

+ * The catalog column is: + *

    + *
  1. TABLE_CAT String => catalog name
  2. + *
+ *

+ * + * @return ResultSet each row has a single String column that is a catalog + * name + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getCatalogs() throws SQLException { + java.sql.ResultSet results = null; + java.sql.Statement stmt = null; + + try { + stmt = this.conn.createStatement(); + stmt.setEscapeProcessing(false); + results = stmt.executeQuery("SHOW DATABASES"); + + java.sql.ResultSetMetaData resultsMD = results.getMetaData(); + Field[] fields = new Field[1]; + fields[0] = new Field("", "TABLE_CAT", Types.VARCHAR, resultsMD + .getColumnDisplaySize(1)); + + ArrayList tuples = new ArrayList(); + + while (results.next()) { + byte[][] rowVal = new byte[1][]; + rowVal[0] = results.getBytes(1); + tuples.add(rowVal); + } + + return buildResultSet(fields, tuples); + } finally { + if (results != null) { + try { + results.close(); + } catch (SQLException sqlEx) { + AssertionFailedException.shouldNotHappen(sqlEx); + } + + results = null; + } + + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { + AssertionFailedException.shouldNotHappen(sqlEx); + } + + stmt = null; + } + } + } + + /** + * What's the separator between catalog and table name? + * + * @return the separator string + * @throws SQLException + * DOCUMENT ME! + */ + public String getCatalogSeparator() throws SQLException { + return "."; + } + + // ---------------------------------------------------------------------- + // The following group of methods exposes various limitations + // based on the target database with the current driver. + // Unless otherwise specified, a result of zero means there is no + // limit, or the limit is not known. + + /** + * What's the database vendor's preferred term for "catalog"? + * + * @return the vendor term + * @throws SQLException + * DOCUMENT ME! + */ + public String getCatalogTerm() throws SQLException { + return "database"; + } + + /** + * Get a description of the access rights for a table's columns. + *

+ * Only privileges matching the column name criteria are returned. They are + * ordered by COLUMN_NAME and PRIVILEGE. + *

+ *

+ * Each privilige description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. COLUMN_NAME String => column name
  8. + *
  9. GRANTOR => grantor of access (may be null)
  10. + *
  11. GRANTEE String => grantee of access
  12. + *
  13. PRIVILEGE String => name of access (SELECT, INSERT, UPDATE, + * REFRENCES, ...)
  14. + *
  15. IS_GRANTABLE String => "YES" if grantee is permitted to + * grant to others; "NO" if not; null if unknown
  16. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name; "" retrieves those without a schema + * @param table + * a table name + * @param columnNamePattern + * a column name pattern + * @return ResultSet each row is a column privilege description + * @throws SQLException + * if a database access error occurs + * @see #getSearchStringEscape + */ + public java.sql.ResultSet getColumnPrivileges(String catalog, + String schema, String table, String columnNamePattern) + throws SQLException { + Field[] fields = new Field[8]; + fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 64); + fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 1); + fields[2] = new Field("", "TABLE_NAME", Types.CHAR, 64); + fields[3] = new Field("", "COLUMN_NAME", Types.CHAR, 64); + fields[4] = new Field("", "GRANTOR", Types.CHAR, 77); + fields[5] = new Field("", "GRANTEE", Types.CHAR, 77); + fields[6] = new Field("", "PRIVILEGE", Types.CHAR, 64); + fields[7] = new Field("", "IS_GRANTABLE", Types.CHAR, 3); + + StringBuffer grantQuery = new StringBuffer( + "SELECT c.host, c.db, t.grantor, c.user, " + + "c.table_name, c.column_name, c.column_priv " + + "from mysql.columns_priv c, mysql.tables_priv t " + + "where c.host = t.host and c.db = t.db and " + + "c.table_name = t.table_name "); + + if ((catalog != null) && (catalog.length() != 0)) { + grantQuery.append(" AND c.db='"); + grantQuery.append(catalog); + grantQuery.append("' "); + ; + } + + grantQuery.append(" AND c.table_name ='"); + grantQuery.append(table); + grantQuery.append("' AND c.column_name like '"); + grantQuery.append(columnNamePattern); + grantQuery.append("'"); + + Statement stmt = null; + ResultSet results = null; + ArrayList grantRows = new ArrayList(); + + try { + stmt = this.conn.createStatement(); + stmt.setEscapeProcessing(false); + results = stmt.executeQuery(grantQuery.toString()); + + while (results.next()) { + String host = results.getString(1); + String db = results.getString(2); + String grantor = results.getString(3); + String user = results.getString(4); + + if ((user == null) || (user.length() == 0)) { + user = "%"; + } + + StringBuffer fullUser = new StringBuffer(user); + + if ((host != null) && this.conn.getUseHostsInPrivileges()) { + fullUser.append("@"); + fullUser.append(host); + } + + String columnName = results.getString(6); + String allPrivileges = results.getString(7); + + if (allPrivileges != null) { + allPrivileges = allPrivileges.toUpperCase(Locale.ENGLISH); + + StringTokenizer st = new StringTokenizer(allPrivileges, ","); + + while (st.hasMoreTokens()) { + String privilege = st.nextToken().trim(); + byte[][] tuple = new byte[8][]; + tuple[0] = s2b(db); + tuple[1] = null; + tuple[2] = s2b(table); + tuple[3] = s2b(columnName); + + if (grantor != null) { + tuple[4] = s2b(grantor); + } else { + tuple[4] = null; + } + + tuple[5] = s2b(fullUser.toString()); + tuple[6] = s2b(privilege); + tuple[7] = null; + grantRows.add(tuple); + } + } + } + } finally { + if (results != null) { + try { + results.close(); + } catch (Exception ex) { + ; + } + + results = null; + } + + if (stmt != null) { + try { + stmt.close(); + } catch (Exception ex) { + ; + } + + stmt = null; + } + } + + return buildResultSet(fields, grantRows); + } + + /** + * Get a description of table columns available in a catalog. + *

+ * Only column descriptions matching the catalog, schema, table and column + * name criteria are returned. They are ordered by TABLE_SCHEM, TABLE_NAME + * and ORDINAL_POSITION. + *

+ *

+ * Each column description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. COLUMN_NAME String => column name
  8. + *
  9. DATA_TYPE short => SQL type from java.sql.Types
  10. + *
  11. TYPE_NAME String => Data source dependent type name
  12. + *
  13. COLUMN_SIZE int => column size. For char or date types this + * is the maximum number of characters, for numeric or decimal types this is + * precision.
  14. + *
  15. BUFFER_LENGTH is not used.
  16. + *
  17. DECIMAL_DIGITS int => the number of fractional digits
  18. + *
  19. NUM_PREC_RADIX int => Radix (typically either 10 or 2)
  20. + *
  21. NULLABLE int => is NULL allowed? + *
      + *
    • columnNoNulls - might not allow NULL values
    • + *
    • columnNullable - definitely allows NULL values
    • + *
    • columnNullableUnknown - nullability unknown
    • + *
    + *
  22. + *
  23. REMARKS String => comment describing column (may be null) + *
  24. + *
  25. COLUMN_DEF String => default value (may be null)
  26. + *
  27. SQL_DATA_TYPE int => unused
  28. + *
  29. SQL_DATETIME_SUB int => unused
  30. + *
  31. CHAR_OCTET_LENGTH int => for char types the maximum number + * of bytes in the column
  32. + *
  33. ORDINAL_POSITION int => index of column in table (starting + * at 1)
  34. + *
  35. IS_NULLABLE String => "NO" means column definitely does not + * allow NULL values; "YES" means the column might allow NULL values. An + * empty string means nobody knows.
  36. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param tableNamePattern + * a table name pattern + * @param columnNamePattern + * a column name pattern + * @return ResultSet each row is a column description + * @throws SQLException + * if a database access error occurs + * @see #getSearchStringEscape + */ + public java.sql.ResultSet getColumns(final String catalog, + final String schemaPattern, final String tableNamePattern, + String columnNamePattern) throws SQLException { + + if (columnNamePattern == null) { + if (this.conn.getNullNamePatternMatchesAll()) { + columnNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Column name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + final String colPattern = columnNamePattern; + + Field[] fields = new Field[23]; + fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 255); + fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "TABLE_NAME", Types.CHAR, 255); + fields[3] = new Field("", "COLUMN_NAME", Types.CHAR, 32); + fields[4] = new Field("", "DATA_TYPE", Types.SMALLINT, 5); + fields[5] = new Field("", "TYPE_NAME", Types.CHAR, 16); + fields[6] = new Field("", "COLUMN_SIZE", Types.INTEGER, Integer + .toString(Integer.MAX_VALUE).length()); + fields[7] = new Field("", "BUFFER_LENGTH", Types.INTEGER, 10); + fields[8] = new Field("", "DECIMAL_DIGITS", Types.INTEGER, 10); + fields[9] = new Field("", "NUM_PREC_RADIX", Types.INTEGER, 10); + fields[10] = new Field("", "NULLABLE", Types.INTEGER, 10); + fields[11] = new Field("", "REMARKS", Types.CHAR, 0); + fields[12] = new Field("", "COLUMN_DEF", Types.CHAR, 0); + fields[13] = new Field("", "SQL_DATA_TYPE", Types.INTEGER, 10); + fields[14] = new Field("", "SQL_DATETIME_SUB", Types.INTEGER, 10); + fields[15] = new Field("", "CHAR_OCTET_LENGTH", Types.INTEGER, Integer + .toString(Integer.MAX_VALUE).length()); + fields[16] = new Field("", "ORDINAL_POSITION", Types.INTEGER, 10); + fields[17] = new Field("", "IS_NULLABLE", Types.CHAR, 3); + fields[18] = new Field("", "SCOPE_CATALOG", Types.CHAR, 255); + fields[19] = new Field("", "SCOPE_SCHEMA", Types.CHAR, 255); + fields[20] = new Field("", "SCOPE_TABLE", Types.CHAR, 255); + fields[21] = new Field("", "SOURCE_DATA_TYPE", Types.SMALLINT, 10); + fields[22] = new Field("", "IS_AUTOINCREMENT", Types.CHAR, 3); + + final ArrayList rows = new ArrayList(); + final Statement stmt = this.conn.getMetadataSafeStatement(); + + try { + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + + ArrayList tableNameList = new ArrayList(); + + if (tableNamePattern == null) { + // Select from all tables + java.sql.ResultSet tables = null; + + try { + tables = getTables(catalog, schemaPattern, "%", + new String[0]); + + while (tables.next()) { + String tableNameFromList = tables + .getString("TABLE_NAME"); + tableNameList.add(tableNameFromList); + } + } finally { + if (tables != null) { + try { + tables.close(); + } catch (Exception sqlEx) { + AssertionFailedException + .shouldNotHappen(sqlEx); + } + + tables = null; + } + } + } else { + java.sql.ResultSet tables = null; + + try { + tables = getTables(catalog, schemaPattern, + tableNamePattern, new String[0]); + + while (tables.next()) { + String tableNameFromList = tables + .getString("TABLE_NAME"); + tableNameList.add(tableNameFromList); + } + } finally { + if (tables != null) { + try { + tables.close(); + } catch (SQLException sqlEx) { + AssertionFailedException + .shouldNotHappen(sqlEx); + } + + tables = null; + } + } + } + + java.util.Iterator tableNames = tableNameList.iterator(); + + while (tableNames.hasNext()) { + String tableName = (String) tableNames.next(); + + ResultSet results = null; + + try { + StringBuffer queryBuf = new StringBuffer("SHOW "); + + if (conn.versionMeetsMinimum(4, 1, 0)) { + queryBuf.append("FULL "); + } + + queryBuf.append("COLUMNS FROM "); + queryBuf.append(quotedId); + queryBuf.append(tableName); + queryBuf.append(quotedId); + queryBuf.append(" FROM "); + queryBuf.append(quotedId); + queryBuf.append(catalogStr.toString()); + queryBuf.append(quotedId); + queryBuf.append(" LIKE '"); + queryBuf.append(colPattern); + queryBuf.append("'"); + + // Return correct ordinals if column name pattern is + // not '%' + // Currently, MySQL doesn't show enough data to do + // this, so we do it the 'hard' way...Once _SYSTEM + // tables are in, this should be much easier + boolean fixUpOrdinalsRequired = false; + Map ordinalFixUpMap = null; + + if (!colPattern.equals("%")) { + fixUpOrdinalsRequired = true; + + StringBuffer fullColumnQueryBuf = new StringBuffer( + "SHOW "); + + if (conn.versionMeetsMinimum(4, 1, 0)) { + fullColumnQueryBuf.append("FULL "); + } + + fullColumnQueryBuf.append("COLUMNS FROM "); + fullColumnQueryBuf.append(quotedId); + fullColumnQueryBuf.append(tableName); + fullColumnQueryBuf.append(quotedId); + fullColumnQueryBuf.append(" FROM "); + fullColumnQueryBuf.append(quotedId); + fullColumnQueryBuf + .append(catalogStr.toString()); + fullColumnQueryBuf.append(quotedId); + + results = stmt.executeQuery(fullColumnQueryBuf + .toString()); + + ordinalFixUpMap = new HashMap(); + + int fullOrdinalPos = 1; + + while (results.next()) { + String fullOrdColName = results + .getString("Field"); + + ordinalFixUpMap.put(fullOrdColName, + new Integer(fullOrdinalPos++)); + } + } + + results = stmt.executeQuery(queryBuf.toString()); + + int ordPos = 1; + + while (results.next()) { + byte[][] rowVal = new byte[23][]; + rowVal[0] = s2b(catalog); // TABLE_CAT + rowVal[1] = null; // TABLE_SCHEM (No schemas + // in MySQL) + + rowVal[2] = s2b(tableName); // TABLE_NAME + rowVal[3] = results.getBytes("Field"); + + TypeDescriptor typeDesc = new TypeDescriptor( + results.getString("Type"), results + .getString("Null")); + + rowVal[4] = Short.toString(typeDesc.dataType) + .getBytes(); + + // DATA_TYPE (jdbc) + rowVal[5] = s2b(typeDesc.typeName); // TYPE_NAME + // (native) + rowVal[6] = typeDesc.columnSize == null ? null + : s2b(typeDesc.columnSize.toString()); + rowVal[7] = s2b(Integer + .toString(typeDesc.bufferLength)); + rowVal[8] = typeDesc.decimalDigits == null ? null + : s2b(typeDesc.decimalDigits.toString()); + rowVal[9] = s2b(Integer + .toString(typeDesc.numPrecRadix)); + rowVal[10] = s2b(Integer + .toString(typeDesc.nullability)); + + // + // Doesn't always have this field, depending on + // version + // + // + // REMARK column + // + try { + if (conn.versionMeetsMinimum(4, 1, 0)) { + rowVal[11] = results + .getBytes("Comment"); + } else { + rowVal[11] = results.getBytes("Extra"); + } + } catch (Exception E) { + rowVal[11] = new byte[0]; + } + + // COLUMN_DEF + rowVal[12] = results.getBytes("Default"); + + rowVal[13] = new byte[] { (byte) '0' }; // SQL_DATA_TYPE + rowVal[14] = new byte[] { (byte) '0' }; // SQL_DATE_TIME_SUB + + if (StringUtils.indexOfIgnoreCase( + typeDesc.typeName, "CHAR") != -1 + || StringUtils.indexOfIgnoreCase( + typeDesc.typeName, "BLOB") != -1 + || StringUtils.indexOfIgnoreCase( + typeDesc.typeName, "TEXT") != -1 + || StringUtils.indexOfIgnoreCase( + typeDesc.typeName, "BINARY") != -1) { + rowVal[15] = rowVal[6]; // CHAR_OCTET_LENGTH + } else { + rowVal[15] = null; + } + + // ORDINAL_POSITION + if (!fixUpOrdinalsRequired) { + rowVal[16] = Integer.toString(ordPos++) + .getBytes(); + } else { + String origColName = results + .getString("Field"); + Integer realOrdinal = (Integer) ordinalFixUpMap + .get(origColName); + + if (realOrdinal != null) { + rowVal[16] = realOrdinal.toString() + .getBytes(); + } else { + throw SQLError + .createSQLException( + "Can not find column in full column list to determine true ordinal position.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + rowVal[17] = s2b(typeDesc.isNullable); + + // We don't support REF or DISTINCT types + rowVal[18] = null; + rowVal[19] = null; + rowVal[20] = null; + rowVal[21] = null; + + rowVal[22] = s2b(""); + + String extra = results.getString("Extra"); + + if (extra != null) { + rowVal[22] = s2b(StringUtils + .indexOfIgnoreCase(extra, + "auto_increment") != -1 ? "YES" + : "NO"); + } + + rows.add(rowVal); + } + } finally { + if (results != null) { + try { + results.close(); + } catch (Exception ex) { + ; + } + + results = null; + } + } + } + } + }.doForAll(); + } finally { + if (stmt != null) { + stmt.close(); + } + } + + java.sql.ResultSet results = buildResultSet(fields, rows); + + return results; + } + + /** + * JDBC 2.0 Return the connection that produced this metadata object. + * + * @return the connection that produced this metadata object. + * @throws SQLException + * if a database error occurs + */ + public java.sql.Connection getConnection() throws SQLException { + return this.conn; + } + + /** + * Get a description of the foreign key columns in the foreign key table + * that reference the primary key columns of the primary key table (describe + * how one table imports another's key.) This should normally return a + * single foreign key/primary key pair (most tables only import a foreign + * key from a table once.) They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, + * FKTABLE_NAME, and KEY_SEQ. + *

+ * Each foreign key column description has the following columns: + *

    + *
  1. PKTABLE_CAT String => primary key table catalog (may be + * null)
  2. + *
  3. PKTABLE_SCHEM String => primary key table schema (may be + * null)
  4. + *
  5. PKTABLE_NAME String => primary key table name
  6. + *
  7. PKCOLUMN_NAME String => primary key column name
  8. + *
  9. FKTABLE_CAT String => foreign key table catalog (may be + * null) being exported (may be null)
  10. + *
  11. FKTABLE_SCHEM String => foreign key table schema (may be + * null) being exported (may be null)
  12. + *
  13. FKTABLE_NAME String => foreign key table name being exported + *
  14. + *
  15. FKCOLUMN_NAME String => foreign key column name being + * exported
  16. + *
  17. KEY_SEQ short => sequence number within foreign key
  18. + *
  19. UPDATE_RULE short => What happens to foreign key when + * primary is updated: + *
      + *
    • importedKeyCascade - change imported key to agree with primary key + * update
    • + *
    • importedKeyRestrict - do not allow update of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been updated
    • + *
    + *
  20. + *
  21. DELETE_RULE short => What happens to the foreign key when + * primary is deleted. + *
      + *
    • importedKeyCascade - delete rows that import a deleted key
    • + *
    • importedKeyRestrict - do not allow delete of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been deleted
    • + *
    + *
  22. + *
  23. FK_NAME String => foreign key identifier (may be null)
  24. + *
  25. PK_NAME String => primary key identifier (may be null)
  26. + *
+ *

+ * + * @param primaryCatalog + * a catalog name; "" retrieves those without a catalog + * @param primarySchema + * a schema name pattern; "" retrieves those without a schema + * @param primaryTable + * a table name + * @param foreignCatalog + * a catalog name; "" retrieves those without a catalog + * @param foreignSchema + * a schema name pattern; "" retrieves those without a schema + * @param foreignTable + * a table name + * @return ResultSet each row is a foreign key column description + * @throws SQLException + * if a database access error occurs + */ + public java.sql.ResultSet getCrossReference(final String primaryCatalog, + final String primarySchema, final String primaryTable, + final String foreignCatalog, final String foreignSchema, + final String foreignTable) throws SQLException { + if (primaryTable == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + Field[] fields = new Field[14]; + fields[0] = new Field("", "PKTABLE_CAT", Types.CHAR, 255); + fields[1] = new Field("", "PKTABLE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "PKTABLE_NAME", Types.CHAR, 255); + fields[3] = new Field("", "PKCOLUMN_NAME", Types.CHAR, 32); + fields[4] = new Field("", "FKTABLE_CAT", Types.CHAR, 255); + fields[5] = new Field("", "FKTABLE_SCHEM", Types.CHAR, 0); + fields[6] = new Field("", "FKTABLE_NAME", Types.CHAR, 255); + fields[7] = new Field("", "FKCOLUMN_NAME", Types.CHAR, 32); + fields[8] = new Field("", "KEY_SEQ", Types.SMALLINT, 2); + fields[9] = new Field("", "UPDATE_RULE", Types.SMALLINT, 2); + fields[10] = new Field("", "DELETE_RULE", Types.SMALLINT, 2); + fields[11] = new Field("", "FK_NAME", Types.CHAR, 0); + fields[12] = new Field("", "PK_NAME", Types.CHAR, 0); + fields[13] = new Field("", "DEFERRABILITY", Types.INTEGER, 2); + + final ArrayList tuples = new ArrayList(); + + if (this.conn.versionMeetsMinimum(3, 23, 0)) { + + final Statement stmt = this.conn.getMetadataSafeStatement(); + + try { + + new IterateBlock(getCatalogIterator(foreignCatalog)) { + void forEach(Object catalogStr) throws SQLException { + + ResultSet fkresults = null; + + try { + + /* + * Get foreign key information for table + */ + if (conn.versionMeetsMinimum(3, 23, 50)) { + fkresults = extractForeignKeyFromCreateTable( + catalogStr.toString(), null); + } else { + StringBuffer queryBuf = new StringBuffer( + "SHOW TABLE STATUS FROM "); + queryBuf.append(quotedId); + queryBuf.append(catalogStr.toString()); + queryBuf.append(quotedId); + + fkresults = stmt.executeQuery(queryBuf + .toString()); + } + + String foreignTableWithCase = getTableNameWithCase(foreignTable); + String primaryTableWithCase = getTableNameWithCase(primaryTable); + + /* + * Parse imported foreign key information + */ + + String dummy; + + while (fkresults.next()) { + String tableType = fkresults.getString("Type"); + + if ((tableType != null) + && (tableType + .equalsIgnoreCase("innodb") || tableType + .equalsIgnoreCase(SUPPORTS_FK))) { + String comment = fkresults.getString( + "Comment").trim(); + + if (comment != null) { + StringTokenizer commentTokens = new StringTokenizer( + comment, ";", false); + + if (commentTokens.hasMoreTokens()) { + dummy = commentTokens.nextToken(); + + // Skip InnoDB comment + } + + while (commentTokens.hasMoreTokens()) { + String keys = commentTokens + .nextToken(); + LocalAndReferencedColumns parsedInfo = parseTableStatusIntoLocalAndReferencedColumns(keys); + + int keySeq = 0; + + Iterator referencingColumns = parsedInfo.localColumnsList + .iterator(); + Iterator referencedColumns = parsedInfo.referencedColumnsList + .iterator(); + + while (referencingColumns.hasNext()) { + String referencingColumn = removeQuotedId(referencingColumns + .next().toString()); + + // one tuple for each table + // between + // parenthesis + byte[][] tuple = new byte[14][]; + tuple[4] = ((foreignCatalog == null) ? null + : s2b(foreignCatalog)); + tuple[5] = ((foreignSchema == null) ? null + : s2b(foreignSchema)); + dummy = fkresults + .getString("Name"); // FKTABLE_NAME + + if (dummy + .compareTo(foreignTableWithCase) != 0) { + continue; + } + + tuple[6] = s2b(dummy); + + tuple[7] = s2b(referencingColumn); // FKCOLUMN_NAME + tuple[0] = ((primaryCatalog == null) ? null + : s2b(primaryCatalog)); + tuple[1] = ((primarySchema == null) ? null + : s2b(primarySchema)); + + // Skip foreign key if it + // doesn't refer to + // the right table + if (parsedInfo.referencedTable + .compareTo(primaryTableWithCase) != 0) { + continue; + } + + tuple[2] = s2b(parsedInfo.referencedTable); // PKTABLE_NAME + tuple[3] = s2b(removeQuotedId(referencedColumns + .next().toString())); // PKCOLUMN_NAME + tuple[8] = Integer.toString( + keySeq).getBytes(); // KEY_SEQ + + int[] actions = getForeignKeyActions(keys); + + tuple[9] = Integer.toString( + actions[1]).getBytes(); + tuple[10] = Integer.toString( + actions[0]).getBytes(); + tuple[11] = null; // FK_NAME + tuple[12] = null; // PK_NAME + tuple[13] = Integer + .toString( + java.sql.DatabaseMetaData.importedKeyNotDeferrable) + .getBytes(); + tuples.add(tuple); + keySeq++; + } + } + } + } + } + + } finally { + if (fkresults != null) { + try { + fkresults.close(); + } catch (Exception sqlEx) { + AssertionFailedException + .shouldNotHappen(sqlEx); + } + + fkresults = null; + } + } + } + }.doForAll(); + } finally { + if (stmt != null) { + stmt.close(); + } + } + } + + java.sql.ResultSet results = buildResultSet(fields, tuples); + + return results; + } + + /** + * @see DatabaseMetaData#getDatabaseMajorVersion() + */ + public int getDatabaseMajorVersion() throws SQLException { + return this.conn.getServerMajorVersion(); + } + + /** + * @see DatabaseMetaData#getDatabaseMinorVersion() + */ + public int getDatabaseMinorVersion() throws SQLException { + return this.conn.getServerMinorVersion(); + } + + /** + * What's the name of this database product? + * + * @return database product name + * @throws SQLException + * DOCUMENT ME! + */ + public String getDatabaseProductName() throws SQLException { + return "MySQL"; + } + + /** + * What's the version of this database product? + * + * @return database version + * @throws SQLException + * DOCUMENT ME! + */ + public String getDatabaseProductVersion() throws SQLException { + return this.conn.getServerVersion(); + } + + /** + * What's the database's default transaction isolation level? The values are + * defined in java.sql.Connection. + * + * @return the default isolation level + * @throws SQLException + * if a database access error occurs + * @see Connection + */ + public int getDefaultTransactionIsolation() throws SQLException { + if (this.conn.supportsIsolationLevel()) { + return java.sql.Connection.TRANSACTION_READ_COMMITTED; + } + + return java.sql.Connection.TRANSACTION_NONE; + } + + /** + * What's this JDBC driver's major version number? + * + * @return JDBC driver major version + */ + public int getDriverMajorVersion() { + return NonRegisteringDriver.getMajorVersionInternal(); + } + + /** + * What's this JDBC driver's minor version number? + * + * @return JDBC driver minor version number + */ + public int getDriverMinorVersion() { + return NonRegisteringDriver.getMinorVersionInternal(); + } + + /** + * What's the name of this JDBC driver? + * + * @return JDBC driver name + * @throws SQLException + * DOCUMENT ME! + */ + public String getDriverName() throws SQLException { + return "MySQL-AB JDBC Driver"; + } + + /** + * What's the version of this JDBC driver? + * + * @return JDBC driver version + * @throws java.sql.SQLException + * DOCUMENT ME! + */ + public String getDriverVersion() throws java.sql.SQLException { + return "@MYSQL_CJ_FULL_PROD_NAME@ ( Revision: @MYSQL_CJ_REVISION@ )"; + } + + /** + * Get a description of a foreign key columns that reference a table's + * primary key columns (the foreign keys exported by a table). They are + * ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and KEY_SEQ. + *

+ * Each foreign key column description has the following columns: + *

    + *
  1. PKTABLE_CAT String => primary key table catalog (may be + * null)
  2. + *
  3. PKTABLE_SCHEM String => primary key table schema (may be + * null)
  4. + *
  5. PKTABLE_NAME String => primary key table name
  6. + *
  7. PKCOLUMN_NAME String => primary key column name
  8. + *
  9. FKTABLE_CAT String => foreign key table catalog (may be + * null) being exported (may be null)
  10. + *
  11. FKTABLE_SCHEM String => foreign key table schema (may be + * null) being exported (may be null)
  12. + *
  13. FKTABLE_NAME String => foreign key table name being exported + *
  14. + *
  15. FKCOLUMN_NAME String => foreign key column name being + * exported
  16. + *
  17. KEY_SEQ short => sequence number within foreign key
  18. + *
  19. UPDATE_RULE short => What happens to foreign key when + * primary is updated: + *
      + *
    • importedKeyCascade - change imported key to agree with primary key + * update
    • + *
    • importedKeyRestrict - do not allow update of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been updated
    • + *
    + *
  20. + *
  21. DELETE_RULE short => What happens to the foreign key when + * primary is deleted. + *
      + *
    • importedKeyCascade - delete rows that import a deleted key
    • + *
    • importedKeyRestrict - do not allow delete of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been deleted
    • + *
    + *
  22. + *
  23. FK_NAME String => foreign key identifier (may be null)
  24. + *
  25. PK_NAME String => primary key identifier (may be null)
  26. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @return ResultSet each row is a foreign key column description + * @throws SQLException + * if a database access error occurs + * @see #getImportedKeys + */ + public java.sql.ResultSet getExportedKeys(String catalog, String schema, + final String table) throws SQLException { + if (table == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + Field[] fields = new Field[14]; + fields[0] = new Field("", "PKTABLE_CAT", Types.CHAR, 255); + fields[1] = new Field("", "PKTABLE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "PKTABLE_NAME", Types.CHAR, 255); + fields[3] = new Field("", "PKCOLUMN_NAME", Types.CHAR, 32); + fields[4] = new Field("", "FKTABLE_CAT", Types.CHAR, 255); + fields[5] = new Field("", "FKTABLE_SCHEM", Types.CHAR, 0); + fields[6] = new Field("", "FKTABLE_NAME", Types.CHAR, 255); + fields[7] = new Field("", "FKCOLUMN_NAME", Types.CHAR, 32); + fields[8] = new Field("", "KEY_SEQ", Types.SMALLINT, 2); + fields[9] = new Field("", "UPDATE_RULE", Types.SMALLINT, 2); + fields[10] = new Field("", "DELETE_RULE", Types.SMALLINT, 2); + fields[11] = new Field("", "FK_NAME", Types.CHAR, 255); + fields[12] = new Field("", "PK_NAME", Types.CHAR, 0); + fields[13] = new Field("", "DEFERRABILITY", Types.INTEGER, 2); + + final ArrayList rows = new ArrayList(); + + if (this.conn.versionMeetsMinimum(3, 23, 0)) { + + final Statement stmt = this.conn.getMetadataSafeStatement(); + + try { + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + ResultSet fkresults = null; + + try { + + /* + * Get foreign key information for table + */ + if (conn.versionMeetsMinimum(3, 23, 50)) { + // we can use 'SHOW CREATE TABLE' + + fkresults = extractForeignKeyFromCreateTable( + catalogStr.toString(), null); + } else { + StringBuffer queryBuf = new StringBuffer( + "SHOW TABLE STATUS FROM "); + queryBuf.append(quotedId); + queryBuf.append(catalogStr.toString()); + queryBuf.append(quotedId); + + fkresults = stmt.executeQuery(queryBuf + .toString()); + } + + // lower-case table name might be turned on + String tableNameWithCase = getTableNameWithCase(table); + + /* + * Parse imported foreign key information + */ + + while (fkresults.next()) { + String tableType = fkresults.getString("Type"); + + if ((tableType != null) + && (tableType + .equalsIgnoreCase("innodb") || tableType + .equalsIgnoreCase(SUPPORTS_FK))) { + String comment = fkresults.getString( + "Comment").trim(); + + if (comment != null) { + StringTokenizer commentTokens = new StringTokenizer( + comment, ";", false); + + if (commentTokens.hasMoreTokens()) { + commentTokens.nextToken(); // Skip + // InnoDB + // comment + + while (commentTokens + .hasMoreTokens()) { + String keys = commentTokens + .nextToken(); + getExportKeyResults( + catalogStr.toString(), + tableNameWithCase, + keys, + rows, + fkresults + .getString("Name")); + } + } + } + } + } + + } finally { + if (fkresults != null) { + try { + fkresults.close(); + } catch (SQLException sqlEx) { + AssertionFailedException + .shouldNotHappen(sqlEx); + } + + fkresults = null; + } + } + } + }.doForAll(); + } finally { + if (stmt != null) { + stmt.close(); + } + } + } + + java.sql.ResultSet results = buildResultSet(fields, rows); + + return results; + } + + /** + * Adds to the tuples list the exported keys of exportingTable based on the + * keysComment from the 'show table status' sql command. KeysComment is that + * part of the comment field that follows the "InnoDB free ...;" prefix. + * + * @param catalog + * the database to use + * @param exportingTable + * the table keys are being exported from + * @param keysComment + * the comment from 'show table status' + * @param tuples + * the rows to add results to + * @param fkTableName + * the foreign key table name + * @throws SQLException + * if a database access error occurs + */ + private void getExportKeyResults(String catalog, String exportingTable, + String keysComment, List tuples, String fkTableName) + throws SQLException { + getResultsImpl(catalog, exportingTable, keysComment, tuples, + fkTableName, true); + } + + /** + * Get all the "extra" characters that can be used in unquoted identifier + * names (those beyond a-z, 0-9 and _). + * + * @return the string containing the extra characters + * @throws SQLException + * DOCUMENT ME! + */ + public String getExtraNameCharacters() throws SQLException { + return "#@"; + } + + /** + * Returns the DELETE and UPDATE foreign key actions from the given 'SHOW + * TABLE STATUS' string, with the DELETE action being the first item in the + * array, and the UPDATE action being the second. + * + * @param commentString + * the comment from 'SHOW TABLE STATUS' + * @return int[] [0] = delete action, [1] = update action + */ + private int[] getForeignKeyActions(String commentString) { + int[] actions = new int[] { + java.sql.DatabaseMetaData.importedKeyNoAction, + java.sql.DatabaseMetaData.importedKeyNoAction }; + + int lastParenIndex = commentString.lastIndexOf(")"); + + if (lastParenIndex != (commentString.length() - 1)) { + String cascadeOptions = commentString.substring(lastParenIndex + 1) + .trim().toUpperCase(Locale.ENGLISH); + + actions[0] = getCascadeDeleteOption(cascadeOptions); + actions[1] = getCascadeUpdateOption(cascadeOptions); + } + + return actions; + } + + /** + * What's the string used to quote SQL identifiers? This returns a space " " + * if identifier quoting isn't supported. A JDBC compliant driver always + * uses a double quote character. + * + * @return the quoting string + * @throws SQLException + * DOCUMENT ME! + */ + public String getIdentifierQuoteString() throws SQLException { + if (this.conn.supportsQuotedIdentifiers()) { + if (!this.conn.useAnsiQuotedIdentifiers()) { + return "`"; + } + + return "\""; + } + + return " "; + } + + /** + * Get a description of the primary key columns that are referenced by a + * table's foreign key columns (the primary keys imported by a table). They + * are ordered by PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ. + *

+ * Each primary key column description has the following columns: + *

    + *
  1. PKTABLE_CAT String => primary key table catalog being + * imported (may be null)
  2. + *
  3. PKTABLE_SCHEM String => primary key table schema being + * imported (may be null)
  4. + *
  5. PKTABLE_NAME String => primary key table name being imported + *
  6. + *
  7. PKCOLUMN_NAME String => primary key column name being + * imported
  8. + *
  9. FKTABLE_CAT String => foreign key table catalog (may be + * null)
  10. + *
  11. FKTABLE_SCHEM String => foreign key table schema (may be + * null)
  12. + *
  13. FKTABLE_NAME String => foreign key table name
  14. + *
  15. FKCOLUMN_NAME String => foreign key column name
  16. + *
  17. KEY_SEQ short => sequence number within foreign key
  18. + *
  19. UPDATE_RULE short => What happens to foreign key when + * primary is updated: + *
      + *
    • importedKeyCascade - change imported key to agree with primary key + * update
    • + *
    • importedKeyRestrict - do not allow update of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been updated
    • + *
    + *
  20. + *
  21. DELETE_RULE short => What happens to the foreign key when + * primary is deleted. + *
      + *
    • importedKeyCascade - delete rows that import a deleted key
    • + *
    • importedKeyRestrict - do not allow delete of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been deleted
    • + *
    + *
  22. + *
  23. FK_NAME String => foreign key name (may be null)
  24. + *
  25. PK_NAME String => primary key name (may be null)
  26. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @return ResultSet each row is a primary key column description + * @throws SQLException + * if a database access error occurs + * @see #getExportedKeys + */ + public java.sql.ResultSet getImportedKeys(String catalog, String schema, + final String table) throws SQLException { + if (table == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + Field[] fields = new Field[14]; + fields[0] = new Field("", "PKTABLE_CAT", Types.CHAR, 255); + fields[1] = new Field("", "PKTABLE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "PKTABLE_NAME", Types.CHAR, 255); + fields[3] = new Field("", "PKCOLUMN_NAME", Types.CHAR, 32); + fields[4] = new Field("", "FKTABLE_CAT", Types.CHAR, 255); + fields[5] = new Field("", "FKTABLE_SCHEM", Types.CHAR, 0); + fields[6] = new Field("", "FKTABLE_NAME", Types.CHAR, 255); + fields[7] = new Field("", "FKCOLUMN_NAME", Types.CHAR, 32); + fields[8] = new Field("", "KEY_SEQ", Types.SMALLINT, 2); + fields[9] = new Field("", "UPDATE_RULE", Types.SMALLINT, 2); + fields[10] = new Field("", "DELETE_RULE", Types.SMALLINT, 2); + fields[11] = new Field("", "FK_NAME", Types.CHAR, 255); + fields[12] = new Field("", "PK_NAME", Types.CHAR, 0); + fields[13] = new Field("", "DEFERRABILITY", Types.INTEGER, 2); + + final ArrayList rows = new ArrayList(); + + if (this.conn.versionMeetsMinimum(3, 23, 0)) { + + final Statement stmt = this.conn.getMetadataSafeStatement(); + + try { + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + ResultSet fkresults = null; + + try { + + /* + * Get foreign key information for table + */ + if (conn.versionMeetsMinimum(3, 23, 50)) { + // we can use 'SHOW CREATE TABLE' + + fkresults = extractForeignKeyFromCreateTable( + catalogStr.toString(), table); + } else { + StringBuffer queryBuf = new StringBuffer( + "SHOW TABLE STATUS "); + queryBuf.append(" FROM "); + queryBuf.append(quotedId); + queryBuf.append(catalogStr.toString()); + queryBuf.append(quotedId); + queryBuf.append(" LIKE '"); + queryBuf.append(table); + queryBuf.append("'"); + + fkresults = stmt.executeQuery(queryBuf + .toString()); + } + + /* + * Parse imported foreign key information + */ + + while (fkresults.next()) { + String tableType = fkresults.getString("Type"); + + if ((tableType != null) + && (tableType + .equalsIgnoreCase("innodb") || tableType + .equalsIgnoreCase(SUPPORTS_FK))) { + String comment = fkresults.getString( + "Comment").trim(); + + if (comment != null) { + StringTokenizer commentTokens = new StringTokenizer( + comment, ";", false); + + if (commentTokens.hasMoreTokens()) { + commentTokens.nextToken(); // Skip + // InnoDB + // comment + + while (commentTokens + .hasMoreTokens()) { + String keys = commentTokens + .nextToken(); + getImportKeyResults(catalogStr + .toString(), table, + keys, rows); + } + } + } + } + } + } finally { + if (fkresults != null) { + try { + fkresults.close(); + } catch (SQLException sqlEx) { + AssertionFailedException + .shouldNotHappen(sqlEx); + } + + fkresults = null; + } + } + } + }.doForAll(); + } finally { + if (stmt != null) { + stmt.close(); + } + } + } + + java.sql.ResultSet results = buildResultSet(fields, rows); + + return results; + } + + /** + * Populates the tuples list with the imported keys of importingTable based + * on the keysComment from the 'show table status' sql command. KeysComment + * is that part of the comment field that follows the "InnoDB free ...;" + * prefix. + * + * @param catalog + * the database to use + * @param importingTable + * the table keys are being imported to + * @param keysComment + * the comment from 'show table status' + * @param tuples + * the rows to add results to + * @throws SQLException + * if a database access error occurs + */ + private void getImportKeyResults(String catalog, String importingTable, + String keysComment, List tuples) throws SQLException { + getResultsImpl(catalog, importingTable, keysComment, tuples, null, + false); + } + + /** + * Get a description of a table's indices and statistics. They are ordered + * by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION. + *

+ * Each index column description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. NON_UNIQUE boolean => Can index values be non-unique? false + * when TYPE is tableIndexStatistic
  8. + *
  9. INDEX_QUALIFIER String => index catalog (may be null); null + * when TYPE is tableIndexStatistic
  10. + *
  11. INDEX_NAME String => index name; null when TYPE is + * tableIndexStatistic
  12. + *
  13. TYPE short => index type: + *
      + *
    • tableIndexStatistic - this identifies table statistics that are + * returned in conjuction with a table's index descriptions
    • + *
    • tableIndexClustered - this is a clustered index
    • + *
    • tableIndexHashed - this is a hashed index
    • + *
    • tableIndexOther - this is some other style of index
    • + *
    + *
  14. + *
  15. ORDINAL_POSITION short => column sequence number within + * index; zero when TYPE is tableIndexStatistic
  16. + *
  17. COLUMN_NAME String => column name; null when TYPE is + * tableIndexStatistic
  18. + *
  19. ASC_OR_DESC String => column sort sequence, "A" => + * ascending, "D" => descending, may be null if sort sequence is not + * supported; null when TYPE is tableIndexStatistic
  20. + *
  21. CARDINALITY int => When TYPE is tableIndexStatisic then this + * is the number of rows in the table; otherwise it is the number of unique + * values in the index.
  22. + *
  23. PAGES int => When TYPE is tableIndexStatisic then this is + * the number of pages used for the table, otherwise it is the number of + * pages used for the current index.
  24. + *
  25. FILTER_CONDITION String => Filter condition, if any. (may be + * null)
  26. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @param unique + * when true, return only indices for unique values; when false, + * return indices regardless of whether unique or not + * @param approximate + * when true, result is allowed to reflect approximate or out of + * data values; when false, results are requested to be accurate + * @return ResultSet each row is an index column description + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getIndexInfo(String catalog, String schema, + final String table, final boolean unique, boolean approximate) + throws SQLException { + /* + * MySQL stores index information in the following fields: Table + * Non_unique Key_name Seq_in_index Column_name Collation Cardinality + * Sub_part + */ + + Field[] fields = new Field[13]; + fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 255); + fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "TABLE_NAME", Types.CHAR, 255); + fields[3] = new Field("", "NON_UNIQUE", Types.CHAR, 4); + fields[4] = new Field("", "INDEX_QUALIFIER", Types.CHAR, 1); + fields[5] = new Field("", "INDEX_NAME", Types.CHAR, 32); + fields[6] = new Field("", "TYPE", Types.CHAR, 32); + fields[7] = new Field("", "ORDINAL_POSITION", Types.SMALLINT, 5); + fields[8] = new Field("", "COLUMN_NAME", Types.CHAR, 32); + fields[9] = new Field("", "ASC_OR_DESC", Types.CHAR, 1); + fields[10] = new Field("", "CARDINALITY", Types.INTEGER, 10); + fields[11] = new Field("", "PAGES", Types.INTEGER, 10); + fields[12] = new Field("", "FILTER_CONDITION", Types.CHAR, 32); + + final ArrayList rows = new ArrayList(); + final Statement stmt = this.conn.getMetadataSafeStatement(); + + try { + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + + ResultSet results = null; + + try { + StringBuffer queryBuf = new StringBuffer( + "SHOW INDEX FROM "); + queryBuf.append(quotedId); + queryBuf.append(table); + queryBuf.append(quotedId); + queryBuf.append(" FROM "); + queryBuf.append(quotedId); + queryBuf.append(catalogStr.toString()); + queryBuf.append(quotedId); + + try { + results = stmt.executeQuery(queryBuf.toString()); + } catch (SQLException sqlEx) { + int errorCode = sqlEx.getErrorCode(); + + // If SQLState is 42S02, ignore this SQLException + // it means the table doesn't exist.... + if (!"42S02".equals(sqlEx.getSQLState())) { + // Sometimes not mapped correctly for pre-4.1 + // so use error code instead. + if (errorCode != MysqlErrorNumbers.ER_NO_SUCH_TABLE) { + throw sqlEx; + } + } + } + + while (results != null && results.next()) { + byte[][] row = new byte[14][]; + row[0] = ((catalogStr.toString() == null) ? new byte[0] + : s2b(catalogStr.toString())); + ; + row[1] = null; + row[2] = results.getBytes("Table"); + + boolean indexIsUnique = results + .getInt("Non_unique") == 0; + + row[3] = (!indexIsUnique ? s2b("true") + : s2b("false")); + row[4] = new byte[0]; + row[5] = results.getBytes("Key_name"); + row[6] = Integer.toString( + java.sql.DatabaseMetaData.tableIndexOther) + .getBytes(); + row[7] = results.getBytes("Seq_in_index"); + row[8] = results.getBytes("Column_name"); + row[9] = results.getBytes("Collation"); + row[10] = results.getBytes("Cardinality"); + row[11] = s2b("0"); + row[12] = null; + + if (unique) { + if (indexIsUnique) { + rows.add(row); + } + } else { + // All rows match + rows.add(row); + } + } + } finally { + if (results != null) { + try { + results.close(); + } catch (Exception ex) { + ; + } + + results = null; + } + } + } + }.doForAll(); + + java.sql.ResultSet indexInfo = buildResultSet(fields, rows); + + return indexInfo; + } finally { + if (stmt != null) { + stmt.close(); + } + } + } + + /** + * @see DatabaseMetaData#getJDBCMajorVersion() + */ + public int getJDBCMajorVersion() throws SQLException { + return 3; + } + + /** + * @see DatabaseMetaData#getJDBCMinorVersion() + */ + public int getJDBCMinorVersion() throws SQLException { + return 0; + } + + /** + * How many hex characters can you have in an inline binary literal? + * + * @return max literal length + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxBinaryLiteralLength() throws SQLException { + return 16777208; + } + + /** + * What's the maximum length of a catalog name? + * + * @return max name length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxCatalogNameLength() throws SQLException { + return 32; + } + + /** + * What's the max length for a character literal? + * + * @return max literal length + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxCharLiteralLength() throws SQLException { + return 16777208; + } + + /** + * What's the limit on column name length? + * + * @return max literal length + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxColumnNameLength() throws SQLException { + return 64; + } + + /** + * What's the maximum number of columns in a "GROUP BY" clause? + * + * @return max number of columns + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxColumnsInGroupBy() throws SQLException { + return 64; + } + + /** + * What's the maximum number of columns allowed in an index? + * + * @return max columns + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxColumnsInIndex() throws SQLException { + return 16; + } + + /** + * What's the maximum number of columns in an "ORDER BY" clause? + * + * @return max columns + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxColumnsInOrderBy() throws SQLException { + return 64; + } + + /** + * What's the maximum number of columns in a "SELECT" list? + * + * @return max columns + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxColumnsInSelect() throws SQLException { + return 256; + } + + /** + * What's maximum number of columns in a table? + * + * @return max columns + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxColumnsInTable() throws SQLException { + return 512; + } + + /** + * How many active connections can we have at a time to this database? + * + * @return max connections + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxConnections() throws SQLException { + return 0; + } + + /** + * What's the maximum cursor name length? + * + * @return max cursor name length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxCursorNameLength() throws SQLException { + return 64; + } + + /** + * What's the maximum length of an index (in bytes)? + * + * @return max index length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxIndexLength() throws SQLException { + return 256; + } + + /** + * What's the maximum length of a procedure name? + * + * @return max name length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxProcedureNameLength() throws SQLException { + return 0; + } + + /** + * What's the maximum length of a single row? + * + * @return max row size in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxRowSize() throws SQLException { + return Integer.MAX_VALUE - 8; // Max buffer size - HEADER + } + + /** + * What's the maximum length allowed for a schema name? + * + * @return max name length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxSchemaNameLength() throws SQLException { + return 0; + } + + /** + * What's the maximum length of a SQL statement? + * + * @return max length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxStatementLength() throws SQLException { + return MysqlIO.getMaxBuf() - 4; // Max buffer - header + } + + /** + * How many active statements can we have open at one time to this database? + * + * @return the maximum + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxStatements() throws SQLException { + return 0; + } + + /** + * What's the maximum length of a table name? + * + * @return max name length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxTableNameLength() throws SQLException { + return 64; + } + + /** + * What's the maximum number of tables in a SELECT? + * + * @return the maximum + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxTablesInSelect() throws SQLException { + return 256; + } + + /** + * What's the maximum length of a user name? + * + * @return max name length in bytes + * @throws SQLException + * DOCUMENT ME! + */ + public int getMaxUserNameLength() throws SQLException { + return 16; + } + + /** + * Get a comma separated list of math functions. + * + * @return the list + * @throws SQLException + * DOCUMENT ME! + */ + public String getNumericFunctions() throws SQLException { + return "ABS,ACOS,ASIN,ATAN,ATAN2,BIT_COUNT,CEILING,COS," + + "COT,DEGREES,EXP,FLOOR,LOG,LOG10,MAX,MIN,MOD,PI,POW," + + "POWER,RADIANS,RAND,ROUND,SIN,SQRT,TAN,TRUNCATE"; + } + + /** + * Get a description of a table's primary key columns. They are ordered by + * COLUMN_NAME. + *

+ * Each column description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. COLUMN_NAME String => column name
  8. + *
  9. KEY_SEQ short => sequence number within primary key
  10. + *
  11. PK_NAME String => primary key name (may be null)
  12. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @return ResultSet each row is a primary key column description + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getPrimaryKeys(String catalog, String schema, + final String table) throws SQLException { + Field[] fields = new Field[6]; + fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 255); + fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "TABLE_NAME", Types.CHAR, 255); + fields[3] = new Field("", "COLUMN_NAME", Types.CHAR, 32); + fields[4] = new Field("", "KEY_SEQ", Types.SMALLINT, 5); + fields[5] = new Field("", "PK_NAME", Types.CHAR, 32); + + if (table == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + final ArrayList rows = new ArrayList(); + final Statement stmt = this.conn.getMetadataSafeStatement(); + + try { + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + ResultSet rs = null; + + try { + + StringBuffer queryBuf = new StringBuffer( + "SHOW KEYS FROM "); + queryBuf.append(quotedId); + queryBuf.append(table); + queryBuf.append(quotedId); + queryBuf.append(" FROM "); + queryBuf.append(quotedId); + queryBuf.append(catalogStr.toString()); + queryBuf.append(quotedId); + + rs = stmt.executeQuery(queryBuf.toString()); + + ArrayList tuples = new ArrayList(); + TreeMap sortMap = new TreeMap(); + + while (rs.next()) { + String keyType = rs.getString("Key_name"); + + if (keyType != null) { + if (keyType.equalsIgnoreCase("PRIMARY") + || keyType.equalsIgnoreCase("PRI")) { + byte[][] tuple = new byte[6][]; + tuple[0] = ((catalogStr.toString() == null) ? new byte[0] + : s2b(catalogStr.toString())); + tuple[1] = null; + tuple[2] = s2b(table); + + String columnName = rs + .getString("Column_name"); + tuple[3] = s2b(columnName); + tuple[4] = s2b(rs.getString("Seq_in_index")); + tuple[5] = s2b(keyType); + sortMap.put(columnName, tuple); + } + } + } + + // Now pull out in column name sorted order + Iterator sortedIterator = sortMap.values().iterator(); + + while (sortedIterator.hasNext()) { + rows.add(sortedIterator.next()); + } + + } finally { + if (rs != null) { + try { + rs.close(); + } catch (Exception ex) { + ; + } + + rs = null; + } + } + } + }.doForAll(); + } finally { + if (stmt != null) { + stmt.close(); + } + } + + java.sql.ResultSet results = buildResultSet(fields, rows); + + return results; + } + + /** + * Get a description of a catalog's stored procedure parameters and result + * columns. + *

+ * Only descriptions matching the schema, procedure and parameter name + * criteria are returned. They are ordered by PROCEDURE_SCHEM and + * PROCEDURE_NAME. Within this, the return value, if any, is first. Next are + * the parameter descriptions in call order. The column descriptions follow + * in column number order. + *

+ *

+ * Each row in the ResultSet is a parameter desription or column description + * with the following fields: + *

    + *
  1. PROCEDURE_CAT String => procedure catalog (may be null) + *
  2. + *
  3. PROCEDURE_SCHEM String => procedure schema (may be null) + *
  4. + *
  5. PROCEDURE_NAME String => procedure name
  6. + *
  7. COLUMN_NAME String => column/parameter name
  8. + *
  9. COLUMN_TYPE Short => kind of column/parameter: + *
      + *
    • procedureColumnUnknown - nobody knows
    • + *
    • procedureColumnIn - IN parameter
    • + *
    • procedureColumnInOut - INOUT parameter
    • + *
    • procedureColumnOut - OUT parameter
    • + *
    • procedureColumnReturn - procedure return value
    • + *
    • procedureColumnResult - result column in ResultSet
    • + *
    + *
  10. + *
  11. DATA_TYPE short => SQL type from java.sql.Types
  12. + *
  13. TYPE_NAME String => SQL type name
  14. + *
  15. PRECISION int => precision
  16. + *
  17. LENGTH int => length in bytes of data
  18. + *
  19. SCALE short => scale
  20. + *
  21. RADIX short => radix
  22. + *
  23. NULLABLE short => can it contain NULL? + *
      + *
    • procedureNoNulls - does not allow NULL values
    • + *
    • procedureNullable - allows NULL values
    • + *
    • procedureNullableUnknown - nullability unknown
    • + *
    + *
  24. + *
  25. REMARKS String => comment describing parameter/column
  26. + *
+ *

+ *

+ * Note: Some databases may not return the column descriptions for a + * procedure. Additional columns beyond REMARKS can be defined by the + * database. + *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param procedureNamePattern + * a procedure name pattern + * @param columnNamePattern + * a column name pattern + * @return ResultSet each row is a stored procedure parameter or column + * description + * @throws SQLException + * if a database access error occurs + * @see #getSearchStringEscape + */ + public java.sql.ResultSet getProcedureColumns(String catalog, + String schemaPattern, String procedureNamePattern, + String columnNamePattern) throws SQLException { + + Field[] fields = new Field[13]; + + fields[0] = new Field("", "PROCEDURE_CAT", Types.CHAR, 0); + fields[1] = new Field("", "PROCEDURE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "PROCEDURE_NAME", Types.CHAR, 0); + fields[3] = new Field("", "COLUMN_NAME", Types.CHAR, 0); + fields[4] = new Field("", "COLUMN_TYPE", Types.CHAR, 0); + fields[5] = new Field("", "DATA_TYPE", Types.SMALLINT, 0); + fields[6] = new Field("", "TYPE_NAME", Types.CHAR, 0); + fields[7] = new Field("", "PRECISION", Types.INTEGER, 0); + fields[8] = new Field("", "LENGTH", Types.INTEGER, 0); + fields[9] = new Field("", "SCALE", Types.SMALLINT, 0); + fields[10] = new Field("", "RADIX", Types.SMALLINT, 0); + fields[11] = new Field("", "NULLABLE", Types.SMALLINT, 0); + fields[12] = new Field("", "REMARKS", Types.CHAR, 0); + + List proceduresToExtractList = new ArrayList(); + + if (supportsStoredProcedures()) { + if ((procedureNamePattern.indexOf("%") == -1) + && (procedureNamePattern.indexOf("?") == -1)) { + proceduresToExtractList.add(procedureNamePattern); + } else { + + ResultSet procedureNameRs = null; + + try { + + procedureNameRs = getProcedures(catalog, schemaPattern, + procedureNamePattern); + + while (procedureNameRs.next()) { + proceduresToExtractList.add(procedureNameRs + .getString(3)); + } + + // Required to be sorted in name-order by JDBC spec, + // in 'normal' case getProcedures takes care of this for us, + // but if system tables are inaccessible, we need to sort... + // so just do this to be safe... + Collections.sort(proceduresToExtractList); + } finally { + SQLException rethrowSqlEx = null; + + if (procedureNameRs != null) { + try { + procedureNameRs.close(); + } catch (SQLException sqlEx) { + rethrowSqlEx = sqlEx; + } + } + + if (rethrowSqlEx != null) { + throw rethrowSqlEx; + } + } + } + } + + ArrayList resultRows = new ArrayList(); + + for (Iterator iter = proceduresToExtractList.iterator(); iter.hasNext();) { + String procName = (String) iter.next(); + + getCallStmtParameterTypes(catalog, procName, columnNamePattern, + resultRows); + } + + return buildResultSet(fields, resultRows); + } + + /** + * Get a description of stored procedures available in a catalog. + *

+ * Only procedure descriptions matching the schema and procedure name + * criteria are returned. They are ordered by PROCEDURE_SCHEM, and + * PROCEDURE_NAME. + *

+ *

+ * Each procedure description has the the following columns: + *

    + *
  1. PROCEDURE_CAT String => procedure catalog (may be null) + *
  2. + *
  3. PROCEDURE_SCHEM String => procedure schema (may be null) + *
  4. + *
  5. PROCEDURE_NAME String => procedure name
  6. + *
  7. reserved for future use
  8. + *
  9. reserved for future use
  10. + *
  11. reserved for future use
  12. + *
  13. REMARKS String => explanatory comment on the procedure
  14. + *
  15. PROCEDURE_TYPE short => kind of procedure: + *
      + *
    • procedureResultUnknown - May return a result
    • + *
    • procedureNoResult - Does not return a result
    • + *
    • procedureReturnsResult - Returns a result
    • + *
    + *
  16. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param procedureNamePattern + * a procedure name pattern + * @return ResultSet each row is a procedure description + * @throws SQLException + * if a database access error occurs + * @see #getSearchStringEscape + */ + public java.sql.ResultSet getProcedures(String catalog, + String schemaPattern, String procedureNamePattern) + throws SQLException { + return getProceduresAndOrFunctions(catalog, schemaPattern, + procedureNamePattern, true, true); + } + + protected java.sql.ResultSet getProceduresAndOrFunctions(String catalog, + String schemaPattern, String procedureNamePattern, + final boolean returnProcedures, final boolean returnFunctions) + throws SQLException { + if ((procedureNamePattern == null) + || (procedureNamePattern.length() == 0)) { + if (this.conn.getNullNamePatternMatchesAll()) { + procedureNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Procedure name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + Field[] fields = new Field[8]; + fields[0] = new Field("", "PROCEDURE_CAT", Types.CHAR, 0); + fields[1] = new Field("", "PROCEDURE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "PROCEDURE_NAME", Types.CHAR, 0); + fields[3] = new Field("", "reserved1", Types.CHAR, 0); + fields[4] = new Field("", "reserved2", Types.CHAR, 0); + fields[5] = new Field("", "reserved3", Types.CHAR, 0); + fields[6] = new Field("", "REMARKS", Types.CHAR, 0); + fields[7] = new Field("", "PROCEDURE_TYPE", Types.SMALLINT, 0); + + final ArrayList procedureRows = new ArrayList(); + + if (supportsStoredProcedures()) { + final String procNamePattern = procedureNamePattern; + + final Map procedureRowsOrderedByName = new TreeMap(); + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + String db = catalogStr.toString(); + + boolean fromSelect = false; + ResultSet proceduresRs = null; + boolean needsClientFiltering = true; + PreparedStatement proceduresStmt = conn + .clientPrepareStatement("SELECT name, type FROM mysql.proc WHERE name like ? and db <=> ? ORDER BY name"); + + try { + // + // Try using system tables first, as this is a little + // bit more efficient.... + // + + boolean hasTypeColumn = false; + + if (db != null) { + proceduresStmt.setString(2, db); + } else { + proceduresStmt.setNull(2, Types.VARCHAR); + } + + int nameIndex = 1; + + if (proceduresStmt.getMaxRows() != 0) { + proceduresStmt.setMaxRows(0); + } + + proceduresStmt.setString(1, procNamePattern); + + try { + proceduresRs = proceduresStmt.executeQuery(); + fromSelect = true; + needsClientFiltering = false; + hasTypeColumn = true; + } catch (SQLException sqlEx) { + + // + // Okay, system tables aren't accessible, so use + // 'SHOW + // ....'.... + // + proceduresStmt.close(); + + fromSelect = false; + + if (conn.versionMeetsMinimum(5, 0, 1)) { + nameIndex = 2; + } else { + nameIndex = 1; + } + + proceduresStmt = conn + .clientPrepareStatement("SHOW PROCEDURE STATUS LIKE ?"); + + if (proceduresStmt.getMaxRows() != 0) { + proceduresStmt.setMaxRows(0); + } + + proceduresStmt.setString(1, procNamePattern); + + proceduresRs = proceduresStmt.executeQuery(); + } + + if (returnProcedures) { + convertToJdbcProcedureList(fromSelect, db, + proceduresRs, needsClientFiltering, db, + procedureRowsOrderedByName, nameIndex); + } + + if (!hasTypeColumn) { + // need to go after functions too... + if (proceduresStmt != null) { + proceduresStmt.close(); + } + + proceduresStmt = conn + .clientPrepareStatement("SHOW FUNCTION STATUS LIKE ?"); + + if (proceduresStmt.getMaxRows() != 0) { + proceduresStmt.setMaxRows(0); + } + + proceduresStmt.setString(1, procNamePattern); + + proceduresRs = proceduresStmt.executeQuery(); + + if (returnFunctions) { + convertToJdbcFunctionList(db, proceduresRs, + needsClientFiltering, db, + procedureRowsOrderedByName, nameIndex); + } + } + + // Now, sort them + + Iterator proceduresIter = procedureRowsOrderedByName + .values().iterator(); + + while (proceduresIter.hasNext()) { + procedureRows.add(proceduresIter.next()); + } + } finally { + SQLException rethrowSqlEx = null; + + if (proceduresRs != null) { + try { + proceduresRs.close(); + } catch (SQLException sqlEx) { + rethrowSqlEx = sqlEx; + } + } + + if (proceduresStmt != null) { + try { + proceduresStmt.close(); + } catch (SQLException sqlEx) { + rethrowSqlEx = sqlEx; + } + } + + if (rethrowSqlEx != null) { + throw rethrowSqlEx; + } + } + } + }.doForAll(); + } + + return buildResultSet(fields, procedureRows); + } + + /** + * What's the database vendor's preferred term for "procedure"? + * + * @return the vendor term + * @throws SQLException + * if an error occurs (don't know why it would in this case...) + */ + public String getProcedureTerm() throws SQLException { + return "PROCEDURE"; + } + + /** + * @see DatabaseMetaData#getResultSetHoldability() + */ + public int getResultSetHoldability() throws SQLException { + return ResultSet.HOLD_CURSORS_OVER_COMMIT; + } + + private void getResultsImpl(String catalog, String table, + String keysComment, List tuples, String fkTableName, + boolean isExport) throws SQLException { + + LocalAndReferencedColumns parsedInfo = parseTableStatusIntoLocalAndReferencedColumns(keysComment); + + if (isExport && !parsedInfo.referencedTable.equals(table)) { + return; + } + + if (parsedInfo.localColumnsList.size() != parsedInfo.referencedColumnsList + .size()) { + throw SQLError + .createSQLException( + "Error parsing foreign keys definition," + + "number of local and referenced columns is not the same.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + Iterator localColumnNames = parsedInfo.localColumnsList.iterator(); + Iterator referColumnNames = parsedInfo.referencedColumnsList.iterator(); + + int keySeqIndex = 1; + + while (localColumnNames.hasNext()) { + byte[][] tuple = new byte[14][]; + String lColumnName = removeQuotedId(localColumnNames.next() + .toString()); + String rColumnName = removeQuotedId(referColumnNames.next() + .toString()); + tuple[FKTABLE_CAT] = ((catalog == null) ? new byte[0] + : s2b(catalog)); + tuple[FKTABLE_SCHEM] = null; + tuple[FKTABLE_NAME] = s2b((isExport) ? fkTableName : table); + tuple[FKCOLUMN_NAME] = s2b(lColumnName); + tuple[PKTABLE_CAT] = s2b(parsedInfo.referencedCatalog); + tuple[PKTABLE_SCHEM] = null; + tuple[PKTABLE_NAME] = s2b((isExport) ? table + : parsedInfo.referencedTable); + tuple[PKCOLUMN_NAME] = s2b(rColumnName); + tuple[KEY_SEQ] = s2b(Integer.toString(keySeqIndex++)); + + int[] actions = getForeignKeyActions(keysComment); + + tuple[UPDATE_RULE] = s2b(Integer.toString(actions[1])); + tuple[DELETE_RULE] = s2b(Integer.toString(actions[0])); + tuple[FK_NAME] = s2b(parsedInfo.constraintName); + tuple[PK_NAME] = null; // not available from show table status + tuple[DEFERRABILITY] = s2b(Integer + .toString(java.sql.DatabaseMetaData.importedKeyNotDeferrable)); + tuples.add(tuple); + } + } + + /** + * Get the schema names available in this database. The results are ordered + * by schema name. + *

+ * The schema column is: + *

    + *
  1. TABLE_SCHEM String => schema name
  2. + *
+ *

+ * + * @return ResultSet each row has a single String column that is a schema + * name + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getSchemas() throws SQLException { + Field[] fields = new Field[2]; + fields[0] = new Field("", "TABLE_SCHEM", java.sql.Types.CHAR, 0); + fields[1] = new Field("", "TABLE_CATALOG", java.sql.Types.CHAR, 0); + + ArrayList tuples = new ArrayList(); + java.sql.ResultSet results = buildResultSet(fields, tuples); + + return results; + } + + /** + * What's the database vendor's preferred term for "schema"? + * + * @return the vendor term + * @throws SQLException + * DOCUMENT ME! + */ + public String getSchemaTerm() throws SQLException { + return ""; + } + + /** + * This is the string that can be used to escape '_' or '%' in the string + * pattern style catalog search parameters. + *

+ * The '_' character represents any single character. + *

+ *

+ * The '%' character represents any sequence of zero or more characters. + *

+ * + * @return the string used to escape wildcard characters + * @throws SQLException + * DOCUMENT ME! + */ + public String getSearchStringEscape() throws SQLException { + return "\\"; + } + + /** + * Get a comma separated list of all a database's SQL keywords that are NOT + * also SQL92 keywords. + * + * @return the list + * @throws SQLException + * DOCUMENT ME! + */ + public String getSQLKeywords() throws SQLException { + return mysqlKeywordsThatArentSQL92; + } + + /** + * @see DatabaseMetaData#getSQLStateType() + */ + public int getSQLStateType() throws SQLException { + if (this.conn.versionMeetsMinimum(4, 1, 0)) { + return DatabaseMetaData.sqlStateSQL99; + } + + if (this.conn.getUseSqlStateCodes()) { + return DatabaseMetaData.sqlStateSQL99; + } + + return DatabaseMetaData.sqlStateXOpen; + } + + /** + * Get a comma separated list of string functions. + * + * @return the list + * @throws SQLException + * DOCUMENT ME! + */ + public String getStringFunctions() throws SQLException { + return "ASCII,BIN,BIT_LENGTH,CHAR,CHARACTER_LENGTH,CHAR_LENGTH,CONCAT," + + "CONCAT_WS,CONV,ELT,EXPORT_SET,FIELD,FIND_IN_SET,HEX,INSERT," + + "INSTR,LCASE,LEFT,LENGTH,LOAD_FILE,LOCATE,LOCATE,LOWER,LPAD," + + "LTRIM,MAKE_SET,MATCH,MID,OCT,OCTET_LENGTH,ORD,POSITION," + + "QUOTE,REPEAT,REPLACE,REVERSE,RIGHT,RPAD,RTRIM,SOUNDEX," + + "SPACE,STRCMP,SUBSTRING,SUBSTRING,SUBSTRING,SUBSTRING," + + "SUBSTRING_INDEX,TRIM,UCASE,UPPER"; + } + + /** + * @see DatabaseMetaData#getSuperTables(String, String, String) + */ + public java.sql.ResultSet getSuperTables(String arg0, String arg1, + String arg2) throws SQLException { + Field[] fields = new Field[4]; + fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 32); + fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 32); + fields[2] = new Field("", "TABLE_NAME", Types.CHAR, 32); + fields[3] = new Field("", "SUPERTABLE_NAME", Types.CHAR, 32); + + return buildResultSet(fields, new ArrayList()); + } + + /** + * @see DatabaseMetaData#getSuperTypes(String, String, String) + */ + public java.sql.ResultSet getSuperTypes(String arg0, String arg1, + String arg2) throws SQLException { + Field[] fields = new Field[6]; + fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 32); + fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 32); + fields[2] = new Field("", "TYPE_NAME", Types.CHAR, 32); + fields[3] = new Field("", "SUPERTYPE_CAT", Types.CHAR, 32); + fields[4] = new Field("", "SUPERTYPE_SCHEM", Types.CHAR, 32); + fields[5] = new Field("", "SUPERTYPE_NAME", Types.CHAR, 32); + + return buildResultSet(fields, new ArrayList()); + } + + /** + * Get a comma separated list of system functions. + * + * @return the list + * @throws SQLException + * DOCUMENT ME! + */ + public String getSystemFunctions() throws SQLException { + return "DATABASE,USER,SYSTEM_USER,SESSION_USER,PASSWORD,ENCRYPT,LAST_INSERT_ID,VERSION"; + } + + private String getTableNameWithCase(String table) { + String tableNameWithCase = (this.conn.lowerCaseTableNames() ? table + .toLowerCase() : table); + + return tableNameWithCase; + } + + /** + * Get a description of the access rights for each table available in a + * catalog. + *

+ * Only privileges matching the schema and table name criteria are returned. + * They are ordered by TABLE_SCHEM, TABLE_NAME, and PRIVILEGE. + *

+ *

+ * Each privilige description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. COLUMN_NAME String => column name
  8. + *
  9. GRANTOR => grantor of access (may be null)
  10. + *
  11. GRANTEE String => grantee of access
  12. + *
  13. PRIVILEGE String => name of access (SELECT, INSERT, UPDATE, + * REFRENCES, ...)
  14. + *
  15. IS_GRANTABLE String => "YES" if grantee is permitted to + * grant to others; "NO" if not; null if unknown
  16. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param tableNamePattern + * a table name pattern + * @return ResultSet each row is a table privilege description + * @throws SQLException + * if a database access error occurs + * @see #getSearchStringEscape + */ + public java.sql.ResultSet getTablePrivileges(String catalog, + String schemaPattern, String tableNamePattern) throws SQLException { + + if (tableNamePattern == null) { + if (this.conn.getNullNamePatternMatchesAll()) { + tableNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Table name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + Field[] fields = new Field[7]; + fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 64); + fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 1); + fields[2] = new Field("", "TABLE_NAME", Types.CHAR, 64); + fields[3] = new Field("", "GRANTOR", Types.CHAR, 77); + fields[4] = new Field("", "GRANTEE", Types.CHAR, 77); + fields[5] = new Field("", "PRIVILEGE", Types.CHAR, 64); + fields[6] = new Field("", "IS_GRANTABLE", Types.CHAR, 3); + + StringBuffer grantQuery = new StringBuffer( + "SELECT host,db,table_name,grantor,user,table_priv from mysql.tables_priv "); + grantQuery.append(" WHERE "); + + if ((catalog != null) && (catalog.length() != 0)) { + grantQuery.append(" db='"); + grantQuery.append(catalog); + grantQuery.append("' AND "); + } + + grantQuery.append("table_name like '"); + grantQuery.append(tableNamePattern); + grantQuery.append("'"); + + ResultSet results = null; + ArrayList grantRows = new ArrayList(); + Statement stmt = null; + + try { + stmt = this.conn.createStatement(); + stmt.setEscapeProcessing(false); + + results = stmt.executeQuery(grantQuery.toString()); + + while (results.next()) { + String host = results.getString(1); + String db = results.getString(2); + String table = results.getString(3); + String grantor = results.getString(4); + String user = results.getString(5); + + if ((user == null) || (user.length() == 0)) { + user = "%"; + } + + StringBuffer fullUser = new StringBuffer(user); + + if ((host != null) && this.conn.getUseHostsInPrivileges()) { + fullUser.append("@"); + fullUser.append(host); + } + + String allPrivileges = results.getString(6); + + if (allPrivileges != null) { + allPrivileges = allPrivileges.toUpperCase(Locale.ENGLISH); + + StringTokenizer st = new StringTokenizer(allPrivileges, ","); + + while (st.hasMoreTokens()) { + String privilege = st.nextToken().trim(); + + // Loop through every column in the table + java.sql.ResultSet columnResults = null; + + try { + columnResults = getColumns(catalog, schemaPattern, + table, "%"); + + while (columnResults.next()) { + byte[][] tuple = new byte[8][]; + tuple[0] = s2b(db); + tuple[1] = null; + tuple[2] = s2b(table); + + if (grantor != null) { + tuple[3] = s2b(grantor); + } else { + tuple[3] = null; + } + + tuple[4] = s2b(fullUser.toString()); + tuple[5] = s2b(privilege); + tuple[6] = null; + grantRows.add(tuple); + } + } finally { + if (columnResults != null) { + try { + columnResults.close(); + } catch (Exception ex) { + ; + } + } + } + } + } + } + } finally { + if (results != null) { + try { + results.close(); + } catch (Exception ex) { + ; + } + + results = null; + } + + if (stmt != null) { + try { + stmt.close(); + } catch (Exception ex) { + ; + } + + stmt = null; + } + } + + return buildResultSet(fields, grantRows); + } + + /** + * Get a description of tables available in a catalog. + *

+ * Only table descriptions matching the catalog, schema, table name and type + * criteria are returned. They are ordered by TABLE_TYPE, TABLE_SCHEM and + * TABLE_NAME. + *

+ *

+ * Each table description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. TABLE_TYPE String => table type. Typical types are "TABLE", + * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", + * "SYNONYM".
  8. + *
  9. REMARKS String => explanatory comment on the table
  10. + *
+ *

+ *

+ * Note: Some databases may not return information for all tables. + *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param tableNamePattern + * a table name pattern + * @param types + * a list of table types to include; null returns all types + * @return ResultSet each row is a table description + * @throws SQLException + * DOCUMENT ME! + * @see #getSearchStringEscape + */ + public java.sql.ResultSet getTables(String catalog, String schemaPattern, + String tableNamePattern, final String[] types) throws SQLException { + + if (tableNamePattern == null) { + if (this.conn.getNullNamePatternMatchesAll()) { + tableNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Table name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + Field[] fields = new Field[5]; + fields[0] = new Field("", "TABLE_CAT", java.sql.Types.VARCHAR, 255); + fields[1] = new Field("", "TABLE_SCHEM", java.sql.Types.VARCHAR, 0); + fields[2] = new Field("", "TABLE_NAME", java.sql.Types.VARCHAR, 255); + fields[3] = new Field("", "TABLE_TYPE", java.sql.Types.VARCHAR, 5); + fields[4] = new Field("", "REMARKS", java.sql.Types.VARCHAR, 0); + + final ArrayList tuples = new ArrayList(); + + final Statement stmt = this.conn.getMetadataSafeStatement(); + + final String tableNamePat = tableNamePattern; + + try { + + new IterateBlock(getCatalogIterator(catalog)) { + void forEach(Object catalogStr) throws SQLException { + ResultSet results = null; + + try { + + if (!conn.versionMeetsMinimum(5, 0, 2)) { + try { + results = stmt.executeQuery("SHOW TABLES FROM " + + quotedId + catalogStr.toString() + + quotedId + " LIKE '" + tableNamePat + + "'"); + } catch (SQLException sqlEx) { + if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE + .equals(sqlEx.getSQLState())) { + throw sqlEx; + } + + return; + } + } else { + try { + results = stmt + .executeQuery("SHOW FULL TABLES FROM " + + quotedId + + catalogStr.toString() + + quotedId + " LIKE '" + + tableNamePat + "'"); + } catch (SQLException sqlEx) { + if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE + .equals(sqlEx.getSQLState())) { + throw sqlEx; + } + + return; + } + } + + boolean shouldReportTables = false; + boolean shouldReportViews = false; + + if (types == null || types.length == 0) { + shouldReportTables = true; + shouldReportViews = true; + } else { + for (int i = 0; i < types.length; i++) { + if ("TABLE".equalsIgnoreCase(types[i])) { + shouldReportTables = true; + } + + if ("VIEW".equalsIgnoreCase(types[i])) { + shouldReportViews = true; + } + } + } + + int typeColumnIndex = 0; + boolean hasTableTypes = false; + + if (conn.versionMeetsMinimum(5, 0, 2)) { + try { + // Both column names have been in use in the + // source tree + // so far.... + typeColumnIndex = results + .findColumn("table_type"); + hasTableTypes = true; + } catch (SQLException sqlEx) { + + // We should probably check SQLState here, but + // that + // can change depending on the server version + // and + // user properties, however, we'll get a 'true' + // SQLException when we actually try to find the + // 'Type' column + // + try { + typeColumnIndex = results + .findColumn("Type"); + hasTableTypes = true; + } catch (SQLException sqlEx2) { + hasTableTypes = false; + } + } + } + + TreeMap tablesOrderedByName = null; + TreeMap viewsOrderedByName = null; + + while (results.next()) { + byte[][] row = new byte[5][]; + row[0] = (catalogStr.toString() == null) ? null + : s2b(catalogStr.toString()); + row[1] = null; + row[2] = results.getBytes(1); + row[4] = new byte[0]; + + if (hasTableTypes) { + String tableType = results + .getString(typeColumnIndex); + + if (("table".equalsIgnoreCase(tableType) || "base table" + .equalsIgnoreCase(tableType)) + && shouldReportTables) { + row[3] = TABLE_AS_BYTES; + + if (tablesOrderedByName == null) { + tablesOrderedByName = new TreeMap(); + } + + tablesOrderedByName.put(results + .getString(1), row); + } else if ("view".equalsIgnoreCase(tableType) + && shouldReportViews) { + row[3] = VIEW_AS_BYTES; + + if (viewsOrderedByName == null) { + viewsOrderedByName = new TreeMap(); + } + + viewsOrderedByName.put( + results.getString(1), row); + } else if (!hasTableTypes) { + // punt? + row[3] = TABLE_AS_BYTES; + + if (tablesOrderedByName == null) { + tablesOrderedByName = new TreeMap(); + } + + tablesOrderedByName.put(results + .getString(1), row); + } + } else { + if (shouldReportTables) { + // Pre-MySQL-5.0.1, tables only + row[3] = TABLE_AS_BYTES; + + if (tablesOrderedByName == null) { + tablesOrderedByName = new TreeMap(); + } + + tablesOrderedByName.put(results + .getString(1), row); + } + } + } + + // They are ordered by TABLE_TYPE, + // * TABLE_SCHEM and TABLE_NAME. + + if (tablesOrderedByName != null) { + Iterator tablesIter = tablesOrderedByName.values() + .iterator(); + + while (tablesIter.hasNext()) { + tuples.add(tablesIter.next()); + } + } + + if (viewsOrderedByName != null) { + Iterator viewsIter = viewsOrderedByName.values() + .iterator(); + + while (viewsIter.hasNext()) { + tuples.add(viewsIter.next()); + } + } + + } finally { + if (results != null) { + try { + results.close(); + } catch (Exception ex) { + ; + } + + results = null; + } + + } + } + }.doForAll(); + } finally { + if (stmt != null) { + stmt.close(); + } + } + + java.sql.ResultSet tables = buildResultSet(fields, tuples); + + return tables; + } + + /** + * Get the table types available in this database. The results are ordered + * by table type. + *

+ * The table type is: + *

    + *
  1. TABLE_TYPE String => table type. Typical types are "TABLE", + * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", + * "SYNONYM".
  2. + *
+ *

+ * + * @return ResultSet each row has a single String column that is a table + * type + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getTableTypes() throws SQLException { + ArrayList tuples = new ArrayList(); + Field[] fields = new Field[1]; + fields[0] = new Field("", "TABLE_TYPE", Types.VARCHAR, 5); + + byte[][] tableTypeRow = new byte[1][]; + tableTypeRow[0] = TABLE_AS_BYTES; + tuples.add(tableTypeRow); + + if (this.conn.versionMeetsMinimum(5, 0, 1)) { + byte[][] viewTypeRow = new byte[1][]; + viewTypeRow[0] = VIEW_AS_BYTES; + tuples.add(viewTypeRow); + } + + byte[][] tempTypeRow = new byte[1][]; + tempTypeRow[0] = s2b("LOCAL TEMPORARY"); + tuples.add(tempTypeRow); + + return buildResultSet(fields, tuples); + } + + /** + * Get a comma separated list of time and date functions. + * + * @return the list + * @throws SQLException + * DOCUMENT ME! + */ + public String getTimeDateFunctions() throws SQLException { + return "DAYOFWEEK,WEEKDAY,DAYOFMONTH,DAYOFYEAR,MONTH,DAYNAME," + + "MONTHNAME,QUARTER,WEEK,YEAR,HOUR,MINUTE,SECOND,PERIOD_ADD," + + "PERIOD_DIFF,TO_DAYS,FROM_DAYS,DATE_FORMAT,TIME_FORMAT," + + "CURDATE,CURRENT_DATE,CURTIME,CURRENT_TIME,NOW,SYSDATE," + + "CURRENT_TIMESTAMP,UNIX_TIMESTAMP,FROM_UNIXTIME," + + "SEC_TO_TIME,TIME_TO_SEC"; + } + + /** + * Get a description of all the standard SQL types supported by this + * database. They are ordered by DATA_TYPE and then by how closely the data + * type maps to the corresponding JDBC SQL type. + *

+ * Each type description has the following columns: + *

    + *
  1. TYPE_NAME String => Type name
  2. + *
  3. DATA_TYPE short => SQL data type from java.sql.Types
  4. + *
  5. PRECISION int => maximum precision
  6. + *
  7. LITERAL_PREFIX String => prefix used to quote a literal (may + * be null)
  8. + *
  9. LITERAL_SUFFIX String => suffix used to quote a literal (may + * be null)
  10. + *
  11. CREATE_PARAMS String => parameters used in creating the type + * (may be null)
  12. + *
  13. NULLABLE short => can you use NULL for this type? + *
      + *
    • typeNoNulls - does not allow NULL values
    • + *
    • typeNullable - allows NULL values
    • + *
    • typeNullableUnknown - nullability unknown
    • + *
    + *
  14. + *
  15. CASE_SENSITIVE boolean=> is it case sensitive?
  16. + *
  17. SEARCHABLE short => can you use "WHERE" based on this type: + *
      + *
    • typePredNone - No support
    • + *
    • typePredChar - Only supported with WHERE .. LIKE
    • + *
    • typePredBasic - Supported except for WHERE .. LIKE
    • + *
    • typeSearchable - Supported for all WHERE ..
    • + *
    + *
  18. + *
  19. UNSIGNED_ATTRIBUTE boolean => is it unsigned?
  20. + *
  21. FIXED_PREC_SCALE boolean => can it be a money value?
  22. + *
  23. AUTO_INCREMENT boolean => can it be used for an + * auto-increment value?
  24. + *
  25. LOCAL_TYPE_NAME String => localized version of type name + * (may be null)
  26. + *
  27. MINIMUM_SCALE short => minimum scale supported
  28. + *
  29. MAXIMUM_SCALE short => maximum scale supported
  30. + *
  31. SQL_DATA_TYPE int => unused
  32. + *
  33. SQL_DATETIME_SUB int => unused
  34. + *
  35. NUM_PREC_RADIX int => usually 2 or 10
  36. + *
+ *

+ * + * @return ResultSet each row is a SQL type description + * @throws SQLException + * DOCUMENT ME! + */ + /** + * Get a description of all the standard SQL types supported by this + * database. They are ordered by DATA_TYPE and then by how closely the data + * type maps to the corresponding JDBC SQL type. + *

+ * Each type description has the following columns: + *

    + *
  1. TYPE_NAME String => Type name
  2. + *
  3. DATA_TYPE short => SQL data type from java.sql.Types
  4. + *
  5. PRECISION int => maximum precision
  6. + *
  7. LITERAL_PREFIX String => prefix used to quote a literal (may + * be null)
  8. + *
  9. LITERAL_SUFFIX String => suffix used to quote a literal (may + * be null)
  10. + *
  11. CREATE_PARAMS String => parameters used in creating the type + * (may be null)
  12. + *
  13. NULLABLE short => can you use NULL for this type? + *
      + *
    • typeNoNulls - does not allow NULL values
    • + *
    • typeNullable - allows NULL values
    • + *
    • typeNullableUnknown - nullability unknown
    • + *
    + *
  14. + *
  15. CASE_SENSITIVE boolean=> is it case sensitive?
  16. + *
  17. SEARCHABLE short => can you use "WHERE" based on this type: + *
      + *
    • typePredNone - No support
    • + *
    • typePredChar - Only supported with WHERE .. LIKE
    • + *
    • typePredBasic - Supported except for WHERE .. LIKE
    • + *
    • typeSearchable - Supported for all WHERE ..
    • + *
    + *
  18. + *
  19. UNSIGNED_ATTRIBUTE boolean => is it unsigned?
  20. + *
  21. FIXED_PREC_SCALE boolean => can it be a money value?
  22. + *
  23. AUTO_INCREMENT boolean => can it be used for an + * auto-increment value?
  24. + *
  25. LOCAL_TYPE_NAME String => localized version of type name + * (may be null)
  26. + *
  27. MINIMUM_SCALE short => minimum scale supported
  28. + *
  29. MAXIMUM_SCALE short => maximum scale supported
  30. + *
  31. SQL_DATA_TYPE int => unused
  32. + *
  33. SQL_DATETIME_SUB int => unused
  34. + *
  35. NUM_PREC_RADIX int => usually 2 or 10
  36. + *
+ *

+ * + * @return ResultSet each row is a SQL type description + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getTypeInfo() throws SQLException { + Field[] fields = new Field[18]; + fields[0] = new Field("", "TYPE_NAME", Types.CHAR, 32); + fields[1] = new Field("", "DATA_TYPE", Types.SMALLINT, 5); + fields[2] = new Field("", "PRECISION", Types.INTEGER, 10); + fields[3] = new Field("", "LITERAL_PREFIX", Types.CHAR, 4); + fields[4] = new Field("", "LITERAL_SUFFIX", Types.CHAR, 4); + fields[5] = new Field("", "CREATE_PARAMS", Types.CHAR, 32); + fields[6] = new Field("", "NULLABLE", Types.SMALLINT, 5); + fields[7] = new Field("", "CASE_SENSITIVE", Types.CHAR, 3); + fields[8] = new Field("", "SEARCHABLE", Types.SMALLINT, 3); + fields[9] = new Field("", "UNSIGNED_ATTRIBUTE", Types.CHAR, 3); + fields[10] = new Field("", "FIXED_PREC_SCALE", Types.CHAR, 3); + fields[11] = new Field("", "AUTO_INCREMENT", Types.CHAR, 3); + fields[12] = new Field("", "LOCAL_TYPE_NAME", Types.CHAR, 32); + fields[13] = new Field("", "MINIMUM_SCALE", Types.SMALLINT, 5); + fields[14] = new Field("", "MAXIMUM_SCALE", Types.SMALLINT, 5); + fields[15] = new Field("", "SQL_DATA_TYPE", Types.INTEGER, 10); + fields[16] = new Field("", "SQL_DATETIME_SUB", Types.INTEGER, 10); + fields[17] = new Field("", "NUM_PREC_RADIX", Types.INTEGER, 10); + + byte[][] rowVal = null; + ArrayList tuples = new ArrayList(); + + /* + * The following are ordered by java.sql.Types, and then by how closely + * the MySQL type matches the JDBC Type (per spec) + */ + /* + * MySQL Type: BIT (silently converted to TINYINT(1)) JDBC Type: BIT + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("BIT"); + rowVal[1] = Integer.toString(java.sql.Types.BIT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("1"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("BIT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: BOOL (silently converted to TINYINT(1)) JDBC Type: BIT + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("BOOL"); + rowVal[1] = Integer.toString(java.sql.Types.BIT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("1"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("BOOL"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: TINYINT JDBC Type: TINYINT + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("TINYINT"); + rowVal[1] = Integer.toString(java.sql.Types.TINYINT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("3"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [UNSIGNED] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("TINYINT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + rowVal = new byte[18][]; + rowVal[0] = s2b("TINYINT UNSIGNED"); + rowVal[1] = Integer.toString(java.sql.Types.TINYINT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("3"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [UNSIGNED] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("TINYINT UNSIGNED"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: BIGINT JDBC Type: BIGINT + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("BIGINT"); + rowVal[1] = Integer.toString(java.sql.Types.BIGINT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("19"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [UNSIGNED] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("BIGINT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + rowVal = new byte[18][]; + rowVal[0] = s2b("BIGINT UNSIGNED"); + rowVal[1] = Integer.toString(java.sql.Types.BIGINT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("20"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("BIGINT UNSIGNED"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: LONG VARBINARY JDBC Type: LONGVARBINARY + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("LONG VARBINARY"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARBINARY).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("16777215"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("LONG VARBINARY"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: MEDIUMBLOB JDBC Type: LONGVARBINARY + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("MEDIUMBLOB"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARBINARY).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("16777215"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("MEDIUMBLOB"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: LONGBLOB JDBC Type: LONGVARBINARY + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("LONGBLOB"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARBINARY).getBytes(); + + // JDBC Data type + rowVal[2] = Integer.toString(Integer.MAX_VALUE).getBytes(); + + // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("LONGBLOB"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: BLOB JDBC Type: LONGVARBINARY + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("BLOB"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARBINARY).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("65535"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("BLOB"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: TINYBLOB JDBC Type: LONGVARBINARY + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("TINYBLOB"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARBINARY).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("255"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("TINYBLOB"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: VARBINARY (sliently converted to VARCHAR(M) BINARY) JDBC + * Type: VARBINARY + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("VARBINARY"); + rowVal[1] = Integer.toString(java.sql.Types.VARBINARY).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("255"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b("(M)"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("VARBINARY"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: BINARY (silently converted to CHAR(M) BINARY) JDBC Type: + * BINARY + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("BINARY"); + rowVal[1] = Integer.toString(java.sql.Types.BINARY).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("255"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b("(M)"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("true"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("BINARY"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: LONG VARCHAR JDBC Type: LONGVARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("LONG VARCHAR"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("16777215"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("LONG VARCHAR"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: MEDIUMTEXT JDBC Type: LONGVARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("MEDIUMTEXT"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("16777215"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("MEDIUMTEXT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: LONGTEXT JDBC Type: LONGVARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("LONGTEXT"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = Integer.toString(Integer.MAX_VALUE).getBytes(); + + // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("LONGTEXT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: TEXT JDBC Type: LONGVARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("TEXT"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("65535"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("TEXT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: TINYTEXT JDBC Type: LONGVARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("TINYTEXT"); + rowVal[1] = Integer.toString(java.sql.Types.LONGVARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("255"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("TINYTEXT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: CHAR JDBC Type: CHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("CHAR"); + rowVal[1] = Integer.toString(java.sql.Types.CHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("255"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b("(M)"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("CHAR"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + // The maximum number of digits for DECIMAL or NUMERIC is 65 (64 from MySQL 5.0.3 to 5.0.5). + + int decimalPrecision = 254; + + if (this.conn.versionMeetsMinimum(5,0,3)) { + if (this.conn.versionMeetsMinimum(5, 0, 6)) { + decimalPrecision = 65; + } else { + decimalPrecision = 64; + } + } + + /* + * MySQL Type: NUMERIC (silently converted to DECIMAL) JDBC Type: + * NUMERIC + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("NUMERIC"); + rowVal[1] = Integer.toString(java.sql.Types.NUMERIC).getBytes(); + + // JDBC Data type + rowVal[2] = s2b(String.valueOf(decimalPrecision)); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M[,D])] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("NUMERIC"); // Locale Type Name + rowVal[13] = s2b("-308"); // Minimum Scale + rowVal[14] = s2b("308"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: DECIMAL JDBC Type: DECIMAL + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("DECIMAL"); + rowVal[1] = Integer.toString(java.sql.Types.DECIMAL).getBytes(); + + // JDBC Data type + rowVal[2] = s2b(String.valueOf(decimalPrecision)); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M[,D])] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("DECIMAL"); // Locale Type Name + rowVal[13] = s2b("-308"); // Minimum Scale + rowVal[14] = s2b("308"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: INTEGER JDBC Type: INTEGER + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("INTEGER"); + rowVal[1] = Integer.toString(java.sql.Types.INTEGER).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("10"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [UNSIGNED] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("INTEGER"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + rowVal = new byte[18][]; + rowVal[0] = s2b("INTEGER UNSIGNED"); + rowVal[1] = Integer.toString(java.sql.Types.INTEGER).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("10"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("INTEGER UNSIGNED"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: INT JDBC Type: INTEGER + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("INT"); + rowVal[1] = Integer.toString(java.sql.Types.INTEGER).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("10"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [UNSIGNED] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("INT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + rowVal = new byte[18][]; + rowVal[0] = s2b("INT UNSIGNED"); + rowVal[1] = Integer.toString(java.sql.Types.INTEGER).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("10"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("INT UNSIGNED"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: MEDIUMINT JDBC Type: INTEGER + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("MEDIUMINT"); + rowVal[1] = Integer.toString(java.sql.Types.INTEGER).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("7"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [UNSIGNED] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("MEDIUMINT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + rowVal = new byte[18][]; + rowVal[0] = s2b("MEDIUMINT UNSIGNED"); + rowVal[1] = Integer.toString(java.sql.Types.INTEGER).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("8"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("MEDIUMINT UNSIGNED"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: SMALLINT JDBC Type: SMALLINT + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("SMALLINT"); + rowVal[1] = Integer.toString(java.sql.Types.SMALLINT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("5"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [UNSIGNED] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("SMALLINT"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + rowVal = new byte[18][]; + rowVal[0] = s2b("SMALLINT UNSIGNED"); + rowVal[1] = Integer.toString(java.sql.Types.SMALLINT).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("5"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("true"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("SMALLINT UNSIGNED"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: FLOAT JDBC Type: REAL (this is the SINGLE PERCISION + * floating point type) + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("FLOAT"); + rowVal[1] = Integer.toString(java.sql.Types.REAL).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("10"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M,D)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("FLOAT"); // Locale Type Name + rowVal[13] = s2b("-38"); // Minimum Scale + rowVal[14] = s2b("38"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: DOUBLE JDBC Type: DOUBLE + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("DOUBLE"); + rowVal[1] = Integer.toString(java.sql.Types.DOUBLE).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("17"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M,D)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("DOUBLE"); // Locale Type Name + rowVal[13] = s2b("-308"); // Minimum Scale + rowVal[14] = s2b("308"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: DOUBLE PRECISION JDBC Type: DOUBLE + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("DOUBLE PRECISION"); + rowVal[1] = Integer.toString(java.sql.Types.DOUBLE).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("17"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M,D)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("DOUBLE PRECISION"); // Locale Type Name + rowVal[13] = s2b("-308"); // Minimum Scale + rowVal[14] = s2b("308"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: REAL (does not map to Types.REAL) JDBC Type: DOUBLE + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("REAL"); + rowVal[1] = Integer.toString(java.sql.Types.DOUBLE).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("17"); // Precision + rowVal[3] = s2b(""); // Literal Prefix + rowVal[4] = s2b(""); // Literal Suffix + rowVal[5] = s2b("[(M,D)] [ZEROFILL]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("true"); // Auto Increment + rowVal[12] = s2b("REAL"); // Locale Type Name + rowVal[13] = s2b("-308"); // Minimum Scale + rowVal[14] = s2b("308"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: VARCHAR JDBC Type: VARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("VARCHAR"); + rowVal[1] = Integer.toString(java.sql.Types.VARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("255"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b("(M)"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("VARCHAR"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: ENUM JDBC Type: VARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("ENUM"); + rowVal[1] = Integer.toString(java.sql.Types.VARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("65535"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("ENUM"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: SET JDBC Type: VARCHAR + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("SET"); + rowVal[1] = Integer.toString(java.sql.Types.VARCHAR).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("64"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("SET"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: DATE JDBC Type: DATE + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("DATE"); + rowVal[1] = Integer.toString(java.sql.Types.DATE).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("0"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("DATE"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: TIME JDBC Type: TIME + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("TIME"); + rowVal[1] = Integer.toString(java.sql.Types.TIME).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("0"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("TIME"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: DATETIME JDBC Type: TIMESTAMP + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("DATETIME"); + rowVal[1] = Integer.toString(java.sql.Types.TIMESTAMP).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("0"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b(""); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("DATETIME"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + /* + * MySQL Type: TIMESTAMP JDBC Type: TIMESTAMP + */ + rowVal = new byte[18][]; + rowVal[0] = s2b("TIMESTAMP"); + rowVal[1] = Integer.toString(java.sql.Types.TIMESTAMP).getBytes(); + + // JDBC Data type + rowVal[2] = s2b("0"); // Precision + rowVal[3] = s2b("'"); // Literal Prefix + rowVal[4] = s2b("'"); // Literal Suffix + rowVal[5] = s2b("[(M)]"); // Create Params + rowVal[6] = Integer.toString(java.sql.DatabaseMetaData.typeNullable) + .getBytes(); + + // Nullable + rowVal[7] = s2b("false"); // Case Sensitive + rowVal[8] = Integer.toString(java.sql.DatabaseMetaData.typeSearchable) + .getBytes(); + + // Searchable + rowVal[9] = s2b("false"); // Unsignable + rowVal[10] = s2b("false"); // Fixed Prec Scale + rowVal[11] = s2b("false"); // Auto Increment + rowVal[12] = s2b("TIMESTAMP"); // Locale Type Name + rowVal[13] = s2b("0"); // Minimum Scale + rowVal[14] = s2b("0"); // Maximum Scale + rowVal[15] = s2b("0"); // SQL Data Type (not used) + rowVal[16] = s2b("0"); // SQL DATETIME SUB (not used) + rowVal[17] = s2b("10"); // NUM_PREC_RADIX (2 or 10) + tuples.add(rowVal); + + return buildResultSet(fields, tuples); + } + + /** + * JDBC 2.0 Get a description of the user-defined types defined in a + * particular schema. Schema specific UDTs may have type JAVA_OBJECT, + * STRUCT, or DISTINCT. + *

+ * Only types matching the catalog, schema, type name and type criteria are + * returned. They are ordered by DATA_TYPE, TYPE_SCHEM and TYPE_NAME. The + * type name parameter may be a fully qualified name. In this case, the + * catalog and schemaPattern parameters are ignored. + *

+ *

+ * Each type description has the following columns: + *

    + *
  1. TYPE_CAT String => the type's catalog (may be null)
  2. + *
  3. TYPE_SCHEM String => type's schema (may be null)
  4. + *
  5. TYPE_NAME String => type name
  6. + *
  7. CLASS_NAME String => Java class name
  8. + *
  9. DATA_TYPE String => type value defined in java.sql.Types. + * One of JAVA_OBJECT, STRUCT, or DISTINCT
  10. + *
  11. REMARKS String => explanatory comment on the type
  12. + *
+ *

+ *

+ * Note: If the driver does not support UDTs then an empty result + * set is returned. + *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog; null + * means drop catalog name from the selection criteria + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param typeNamePattern + * a type name pattern; may be a fully qualified name + * @param types + * a list of user-named types to include (JAVA_OBJECT, STRUCT, or + * DISTINCT); null returns all types + * @return ResultSet - each row is a type description + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.ResultSet getUDTs(String catalog, String schemaPattern, + String typeNamePattern, int[] types) throws SQLException { + Field[] fields = new Field[6]; + fields[0] = new Field("", "TYPE_CAT", Types.VARCHAR, 32); + fields[1] = new Field("", "TYPE_SCHEM", Types.VARCHAR, 32); + fields[2] = new Field("", "TYPE_NAME", Types.VARCHAR, 32); + fields[3] = new Field("", "CLASS_NAME", Types.VARCHAR, 32); + fields[4] = new Field("", "DATA_TYPE", Types.VARCHAR, 32); + fields[5] = new Field("", "REMARKS", Types.VARCHAR, 32); + + ArrayList tuples = new ArrayList(); + + return buildResultSet(fields, tuples); + } + + /** + * What's the url for this database? + * + * @return the url or null if it can't be generated + * @throws SQLException + * DOCUMENT ME! + */ + public String getURL() throws SQLException { + return this.conn.getURL(); + } + + /** + * What's our user name as known to the database? + * + * @return our database user name + * @throws SQLException + * DOCUMENT ME! + */ + public String getUserName() throws SQLException { + if (this.conn.getUseHostsInPrivileges()) { + Statement stmt = null; + ResultSet rs = null; + + try { + stmt = this.conn.createStatement(); + stmt.setEscapeProcessing(false); + + rs = stmt.executeQuery("SELECT USER()"); + rs.next(); + + return rs.getString(1); + } finally { + if (rs != null) { + try { + rs.close(); + } catch (Exception ex) { + AssertionFailedException.shouldNotHappen(ex); + } + + rs = null; + } + + if (stmt != null) { + try { + stmt.close(); + } catch (Exception ex) { + AssertionFailedException.shouldNotHappen(ex); + } + + stmt = null; + } + } + } + + return this.conn.getUser(); + } + + /** + * Get a description of a table's columns that are automatically updated + * when any value in a row is updated. They are unordered. + *

+ * Each column description has the following columns: + *

    + *
  1. SCOPE short => is not used
  2. + *
  3. COLUMN_NAME String => column name
  4. + *
  5. DATA_TYPE short => SQL data type from java.sql.Types
  6. + *
  7. TYPE_NAME String => Data source dependent type name
  8. + *
  9. COLUMN_SIZE int => precision
  10. + *
  11. BUFFER_LENGTH int => length of column value in bytes
  12. + *
  13. DECIMAL_DIGITS short => scale
  14. + *
  15. PSEUDO_COLUMN short => is this a pseudo column like an + * Oracle ROWID + *
      + *
    • versionColumnUnknown - may or may not be pseudo column
    • + *
    • versionColumnNotPseudo - is NOT a pseudo column
    • + *
    • versionColumnPseudo - is a pseudo column
    • + *
    + *
  16. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name; "" retrieves those without a schema + * @param table + * a table name + * @return ResultSet each row is a column description + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getVersionColumns(String catalog, String schema, + String table) throws SQLException { + Field[] fields = new Field[8]; + fields[0] = new Field("", "SCOPE", Types.SMALLINT, 5); + fields[1] = new Field("", "COLUMN_NAME", Types.CHAR, 32); + fields[2] = new Field("", "DATA_TYPE", Types.SMALLINT, 5); + fields[3] = new Field("", "TYPE_NAME", Types.CHAR, 16); + fields[4] = new Field("", "COLUMN_SIZE", Types.CHAR, 16); + fields[5] = new Field("", "BUFFER_LENGTH", Types.CHAR, 16); + fields[6] = new Field("", "DECIMAL_DIGITS", Types.CHAR, 16); + fields[7] = new Field("", "PSEUDO_COLUMN", Types.SMALLINT, 5); + + return buildResultSet(fields, new ArrayList()); + + // do TIMESTAMP columns count? + } + + /** + * JDBC 2.0 Determine whether or not a visible row insert can be detected by + * calling ResultSet.rowInserted(). + * + * @param type + * set type, i.e. ResultSet.TYPE_XXX + * @return true if changes are detected by the resultset type + * @exception SQLException + * if a database-access error occurs. + */ + public boolean insertsAreDetected(int type) throws SQLException { + return false; + } + + /** + * Does a catalog appear at the start of a qualified table name? (Otherwise + * it appears at the end) + * + * @return true if it appears at the start + * @throws SQLException + * DOCUMENT ME! + */ + public boolean isCatalogAtStart() throws SQLException { + return true; + } + + /** + * Is the database in read-only mode? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean isReadOnly() throws SQLException { + return false; + } + + /** + * @see DatabaseMetaData#locatorsUpdateCopy() + */ + public boolean locatorsUpdateCopy() throws SQLException { + return !this.conn.getEmulateLocators(); + } + + /** + * Are concatenations between NULL and non-NULL values NULL? A JDBC + * compliant driver always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean nullPlusNonNullIsNull() throws SQLException { + return true; + } + + /** + * Are NULL values sorted at the end regardless of sort order? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean nullsAreSortedAtEnd() throws SQLException { + return false; + } + + /** + * Are NULL values sorted at the start regardless of sort order? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean nullsAreSortedAtStart() throws SQLException { + return (this.conn.versionMeetsMinimum(4, 0, 2) && !this.conn + .versionMeetsMinimum(4, 0, 11)); + } + + /** + * Are NULL values sorted high? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean nullsAreSortedHigh() throws SQLException { + return false; + } + + /** + * Are NULL values sorted low? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean nullsAreSortedLow() throws SQLException { + return !nullsAreSortedHigh(); + } + + /** + * DOCUMENT ME! + * + * @param type + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public boolean othersDeletesAreVisible(int type) throws SQLException { + return false; + } + + /** + * DOCUMENT ME! + * + * @param type + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public boolean othersInsertsAreVisible(int type) throws SQLException { + return false; + } + + /** + * JDBC 2.0 Determine whether changes made by others are visible. + * + * @param type + * set type, i.e. ResultSet.TYPE_XXX + * @return true if changes are visible for the result set type + * @exception SQLException + * if a database-access error occurs. + */ + public boolean othersUpdatesAreVisible(int type) throws SQLException { + return false; + } + + /** + * DOCUMENT ME! + * + * @param type + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public boolean ownDeletesAreVisible(int type) throws SQLException { + return false; + } + + /** + * DOCUMENT ME! + * + * @param type + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public boolean ownInsertsAreVisible(int type) throws SQLException { + return false; + } + + /** + * JDBC 2.0 Determine whether a result set's own changes visible. + * + * @param type + * set type, i.e. ResultSet.TYPE_XXX + * @return true if changes are visible for the result set type + * @exception SQLException + * if a database-access error occurs. + */ + public boolean ownUpdatesAreVisible(int type) throws SQLException { + return false; + } + + private LocalAndReferencedColumns parseTableStatusIntoLocalAndReferencedColumns( + String keysComment) throws SQLException { + // keys will equal something like this: + // (parent_service_id child_service_id) REFER + // ds/subservices(parent_service_id child_service_id) + // + // simple-columned keys: (m) REFER + // airline/tt(a) + // + // multi-columned keys : (m n) REFER + // airline/vv(a b) + // + // parse of the string into three phases: + // 1: parse the opening parentheses to determine how many results there + // will be + // 2: read in the schema name/table name + // 3: parse the closing parentheses + + String columnsDelimitter = ","; // what version did this change in? + + char quoteChar = this.quotedId.length() == 0 ? 0 : this.quotedId + .charAt(0); + + int indexOfOpenParenLocalColumns = StringUtils + .indexOfIgnoreCaseRespectQuotes(0, keysComment, "(", quoteChar, + true); + + if (indexOfOpenParenLocalColumns == -1) { + throw SQLError.createSQLException( + "Error parsing foreign keys definition," + + " couldn't find start of local columns list.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + String constraintName = removeQuotedId(keysComment.substring(0, + indexOfOpenParenLocalColumns).trim()); + keysComment = keysComment.substring(indexOfOpenParenLocalColumns, + keysComment.length()); + + String keysCommentTrimmed = keysComment.trim(); + + int indexOfCloseParenLocalColumns = StringUtils + .indexOfIgnoreCaseRespectQuotes(0, keysCommentTrimmed, ")", + quoteChar, true); + + if (indexOfCloseParenLocalColumns == -1) { + throw SQLError.createSQLException( + "Error parsing foreign keys definition," + + " couldn't find end of local columns list.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + String localColumnNamesString = keysCommentTrimmed.substring(1, + indexOfCloseParenLocalColumns); + + int indexOfRefer = StringUtils.indexOfIgnoreCaseRespectQuotes(0, + keysCommentTrimmed, "REFER ", this.quotedId.charAt(0), true); + + if (indexOfRefer == -1) { + throw SQLError + .createSQLException( + "Error parsing foreign keys definition," + + " couldn't find start of referenced tables list.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + int indexOfOpenParenReferCol = StringUtils + .indexOfIgnoreCaseRespectQuotes(indexOfRefer, + keysCommentTrimmed, "(", quoteChar, false); + + if (indexOfOpenParenReferCol == -1) { + throw SQLError + .createSQLException( + "Error parsing foreign keys definition," + + " couldn't find start of referenced columns list.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + String referCatalogTableString = keysCommentTrimmed.substring( + indexOfRefer + "REFER ".length(), indexOfOpenParenReferCol); + + int indexOfSlash = StringUtils.indexOfIgnoreCaseRespectQuotes(0, + referCatalogTableString, "/", this.quotedId.charAt(0), false); + + if (indexOfSlash == -1) { + throw SQLError.createSQLException( + "Error parsing foreign keys definition," + + " couldn't find name of referenced catalog.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + String referCatalog = removeQuotedId(referCatalogTableString.substring( + 0, indexOfSlash)); + String referTable = removeQuotedId(referCatalogTableString.substring( + indexOfSlash + 1).trim()); + + int indexOfCloseParenRefer = StringUtils + .indexOfIgnoreCaseRespectQuotes(indexOfOpenParenReferCol, + keysCommentTrimmed, ")", quoteChar, true); + + if (indexOfCloseParenRefer == -1) { + throw SQLError.createSQLException( + "Error parsing foreign keys definition," + + " couldn't find end of referenced columns list.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + String referColumnNamesString = keysCommentTrimmed.substring( + indexOfOpenParenReferCol + 1, indexOfCloseParenRefer); + + List referColumnsList = StringUtils.split(referColumnNamesString, + columnsDelimitter, this.quotedId, this.quotedId, false); + List localColumnsList = StringUtils.split(localColumnNamesString, + columnsDelimitter, this.quotedId, this.quotedId, false); + + return new LocalAndReferencedColumns(localColumnsList, + referColumnsList, constraintName, referCatalog, referTable); + } + + private String removeQuotedId(String s) { + if (s == null) { + return null; + } + + if (this.quotedId.equals("")) { + return s; + } + + s = s.trim(); + + int frontOffset = 0; + int backOffset = s.length(); + int quoteLength = this.quotedId.length(); + + if (s.startsWith(this.quotedId)) { + frontOffset = quoteLength; + } + + if (s.endsWith(this.quotedId)) { + backOffset -= quoteLength; + } + + return s.substring(frontOffset, backOffset); + } + + /** + * Converts the given string to bytes, using the connection's character + * encoding, or if not available, the JVM default encoding. + * + * @param s + * DOCUMENT ME! + * @return DOCUMENT ME! + */ + private byte[] s2b(String s) throws SQLException { + return StringUtils.s2b(s, this.conn); + } + + /** + * Does the database store mixed case unquoted SQL identifiers in lower + * case? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean storesLowerCaseIdentifiers() throws SQLException { + return this.conn.lowerCaseTableNames(); + } + + /** + * Does the database store mixed case quoted SQL identifiers in lower case? + * A JDBC compliant driver will always return false. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { + return this.conn.lowerCaseTableNames(); + } + + /** + * Does the database store mixed case unquoted SQL identifiers in mixed + * case? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean storesMixedCaseIdentifiers() throws SQLException { + return !this.conn.lowerCaseTableNames(); + } + + /** + * Does the database store mixed case quoted SQL identifiers in mixed case? + * A JDBC compliant driver will always return false. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { + return !this.conn.lowerCaseTableNames(); + } + + /** + * Does the database store mixed case unquoted SQL identifiers in upper + * case? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean storesUpperCaseIdentifiers() throws SQLException { + return false; + } + + /** + * Does the database store mixed case quoted SQL identifiers in upper case? + * A JDBC compliant driver will always return true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { + return true; // not actually true, but required by JDBC spec!? + } + + /** + * Is "ALTER TABLE" with add column supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsAlterTableWithAddColumn() throws SQLException { + return true; + } + + /** + * Is "ALTER TABLE" with drop column supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsAlterTableWithDropColumn() throws SQLException { + return true; + } + + /** + * Is the ANSI92 entry level SQL grammar supported? All JDBC compliant + * drivers must return true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsANSI92EntryLevelSQL() throws SQLException { + return true; + } + + /** + * Is the ANSI92 full SQL grammar supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsANSI92FullSQL() throws SQLException { + return false; + } + + /** + * Is the ANSI92 intermediate SQL grammar supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsANSI92IntermediateSQL() throws SQLException { + return false; + } + + /** + * JDBC 2.0 Return true if the driver supports batch updates, else return + * false. + * + * @return DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsBatchUpdates() throws SQLException { + return true; + } + + /** + * Can a catalog name be used in a data manipulation statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsCatalogsInDataManipulation() throws SQLException { + // Servers before 3.22 could not do this + return this.conn.versionMeetsMinimum(3, 22, 0); + } + + /** + * Can a catalog name be used in a index definition statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsCatalogsInIndexDefinitions() throws SQLException { + // Servers before 3.22 could not do this + return this.conn.versionMeetsMinimum(3, 22, 0); + } + + /** + * Can a catalog name be used in a privilege definition statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { + // Servers before 3.22 could not do this + return this.conn.versionMeetsMinimum(3, 22, 0); + } + + /** + * Can a catalog name be used in a procedure call statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsCatalogsInProcedureCalls() throws SQLException { + // Servers before 3.22 could not do this + return this.conn.versionMeetsMinimum(3, 22, 0); + } + + /** + * Can a catalog name be used in a table definition statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsCatalogsInTableDefinitions() throws SQLException { + // Servers before 3.22 could not do this + return this.conn.versionMeetsMinimum(3, 22, 0); + } + + /** + * Is column aliasing supported? + *

+ * If so, the SQL AS clause can be used to provide names for computed + * columns or to provide alias names for columns as required. A JDBC + * compliant driver always returns true. + *

+ * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsColumnAliasing() throws SQLException { + return true; + } + + /** + * Is the CONVERT function between SQL types supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsConvert() throws SQLException { + return false; + } + + /** + * Is CONVERT between the given SQL types supported? + * + * @param fromType + * the type to convert from + * @param toType + * the type to convert to + * @return true if so + * @throws SQLException + * if an error occurs + * @see Types + */ + public boolean supportsConvert(int fromType, int toType) + throws SQLException { + switch (fromType) { + /* + * The char/binary types can be converted to pretty much anything. + */ + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + case java.sql.Types.BINARY: + case java.sql.Types.VARBINARY: + case java.sql.Types.LONGVARBINARY: + + switch (toType) { + case java.sql.Types.DECIMAL: + case java.sql.Types.NUMERIC: + case java.sql.Types.REAL: + case java.sql.Types.TINYINT: + case java.sql.Types.SMALLINT: + case java.sql.Types.INTEGER: + case java.sql.Types.BIGINT: + case java.sql.Types.FLOAT: + case java.sql.Types.DOUBLE: + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + case java.sql.Types.BINARY: + case java.sql.Types.VARBINARY: + case java.sql.Types.LONGVARBINARY: + case java.sql.Types.OTHER: + case java.sql.Types.DATE: + case java.sql.Types.TIME: + case java.sql.Types.TIMESTAMP: + return true; + + default: + return false; + } + + /* + * We don't handle the BIT type yet. + */ + case java.sql.Types.BIT: + return false; + + /* + * The numeric types. Basically they can convert among themselves, + * and with char/binary types. + */ + case java.sql.Types.DECIMAL: + case java.sql.Types.NUMERIC: + case java.sql.Types.REAL: + case java.sql.Types.TINYINT: + case java.sql.Types.SMALLINT: + case java.sql.Types.INTEGER: + case java.sql.Types.BIGINT: + case java.sql.Types.FLOAT: + case java.sql.Types.DOUBLE: + + switch (toType) { + case java.sql.Types.DECIMAL: + case java.sql.Types.NUMERIC: + case java.sql.Types.REAL: + case java.sql.Types.TINYINT: + case java.sql.Types.SMALLINT: + case java.sql.Types.INTEGER: + case java.sql.Types.BIGINT: + case java.sql.Types.FLOAT: + case java.sql.Types.DOUBLE: + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + case java.sql.Types.BINARY: + case java.sql.Types.VARBINARY: + case java.sql.Types.LONGVARBINARY: + return true; + + default: + return false; + } + + /* MySQL doesn't support a NULL type. */ + case java.sql.Types.NULL: + return false; + + /* + * With this driver, this will always be a serialized object, so the + * char/binary types will work. + */ + case java.sql.Types.OTHER: + + switch (toType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + case java.sql.Types.BINARY: + case java.sql.Types.VARBINARY: + case java.sql.Types.LONGVARBINARY: + return true; + + default: + return false; + } + + /* Dates can be converted to char/binary types. */ + case java.sql.Types.DATE: + + switch (toType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + case java.sql.Types.BINARY: + case java.sql.Types.VARBINARY: + case java.sql.Types.LONGVARBINARY: + return true; + + default: + return false; + } + + /* Time can be converted to char/binary types */ + case java.sql.Types.TIME: + + switch (toType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + case java.sql.Types.BINARY: + case java.sql.Types.VARBINARY: + case java.sql.Types.LONGVARBINARY: + return true; + + default: + return false; + } + + /* + * Timestamp can be converted to char/binary types and date/time + * types (with loss of precision). + */ + case java.sql.Types.TIMESTAMP: + + switch (toType) { + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + case java.sql.Types.BINARY: + case java.sql.Types.VARBINARY: + case java.sql.Types.LONGVARBINARY: + case java.sql.Types.TIME: + case java.sql.Types.DATE: + return true; + + default: + return false; + } + + /* We shouldn't get here! */ + default: + return false; // not sure + } + } + + /** + * Is the ODBC Core SQL grammar supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsCoreSQLGrammar() throws SQLException { + return true; + } + + /** + * Are correlated subqueries supported? A JDBC compliant driver always + * returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsCorrelatedSubqueries() throws SQLException { + return this.conn.versionMeetsMinimum(4, 1, 0); + } + + /** + * Are both data definition and data manipulation statements within a + * transaction supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsDataDefinitionAndDataManipulationTransactions() + throws SQLException { + return false; + } + + /** + * Are only data manipulation statements within a transaction supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsDataManipulationTransactionsOnly() + throws SQLException { + return false; + } + + /** + * If table correlation names are supported, are they restricted to be + * different from the names of the tables? A JDBC compliant driver always + * returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsDifferentTableCorrelationNames() throws SQLException { + return true; + } + + /** + * Are expressions in "ORDER BY" lists supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsExpressionsInOrderBy() throws SQLException { + return true; + } + + /** + * Is the ODBC Extended SQL grammar supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsExtendedSQLGrammar() throws SQLException { + return false; + } + + /** + * Are full nested outer joins supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsFullOuterJoins() throws SQLException { + return false; + } + + /** + * JDBC 3.0 + * + * @return DOCUMENT ME! + */ + public boolean supportsGetGeneratedKeys() { + return true; + } + + /** + * Is some form of "GROUP BY" clause supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsGroupBy() throws SQLException { + return true; + } + + /** + * Can a "GROUP BY" clause add columns not in the SELECT provided it + * specifies all the columns in the SELECT? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsGroupByBeyondSelect() throws SQLException { + return true; + } + + /** + * Can a "GROUP BY" clause use columns not in the SELECT? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsGroupByUnrelated() throws SQLException { + return true; + } + + /** + * Is the SQL Integrity Enhancement Facility supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsIntegrityEnhancementFacility() throws SQLException { + if (!this.conn.getOverrideSupportsIntegrityEnhancementFacility()) { + return false; + } + + return true; + } + + /** + * Is the escape character in "LIKE" clauses supported? A JDBC compliant + * driver always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsLikeEscapeClause() throws SQLException { + return true; + } + + /** + * Is there limited support for outer joins? (This will be true if + * supportFullOuterJoins is true.) + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsLimitedOuterJoins() throws SQLException { + return true; + } + + /** + * Is the ODBC Minimum SQL grammar supported? All JDBC compliant drivers + * must return true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsMinimumSQLGrammar() throws SQLException { + return true; + } + + /** + * Does the database support mixed case unquoted SQL identifiers? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsMixedCaseIdentifiers() throws SQLException { + return !this.conn.lowerCaseTableNames(); + } + + /** + * Does the database support mixed case quoted SQL identifiers? A JDBC + * compliant driver will always return true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { + return !this.conn.lowerCaseTableNames(); + } + + /** + * @see DatabaseMetaData#supportsMultipleOpenResults() + */ + public boolean supportsMultipleOpenResults() throws SQLException { + return true; + } + + /** + * Are multiple ResultSets from a single execute supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsMultipleResultSets() throws SQLException { + return false; + } + + /** + * Can we have multiple transactions open at once (on different + * connections)? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsMultipleTransactions() throws SQLException { + return true; + } + + /** + * @see DatabaseMetaData#supportsNamedParameters() + */ + public boolean supportsNamedParameters() throws SQLException { + return false; + } + + /** + * Can columns be defined as non-nullable? A JDBC compliant driver always + * returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsNonNullableColumns() throws SQLException { + return true; + } + + /** + * Can cursors remain open across commits? + * + * @return true if so + * @throws SQLException + * if a database access error occurs + * @see Connection#disableAutoClose + */ + public boolean supportsOpenCursorsAcrossCommit() throws SQLException { + return false; + } + + /** + * Can cursors remain open across rollbacks? + * + * @return true if so + * @throws SQLException + * if an error occurs + * @see Connection#disableAutoClose + */ + public boolean supportsOpenCursorsAcrossRollback() throws SQLException { + return false; + } + + /** + * Can statements remain open across commits? + * + * @return true if so + * @throws SQLException + * if an error occurs + * @see Connection#disableAutoClose + */ + public boolean supportsOpenStatementsAcrossCommit() throws SQLException { + return false; + } + + /** + * Can statements remain open across rollbacks? + * + * @return true if so + * @throws SQLException + * if an error occurs + * @see Connection#disableAutoClose + */ + public boolean supportsOpenStatementsAcrossRollback() throws SQLException { + return false; + } + + /** + * Can an "ORDER BY" clause use columns not in the SELECT? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsOrderByUnrelated() throws SQLException { + return false; + } + + /** + * Is some form of outer join supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsOuterJoins() throws SQLException { + return true; + } + + /** + * Is positioned DELETE supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsPositionedDelete() throws SQLException { + return false; + } + + /** + * Is positioned UPDATE supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsPositionedUpdate() throws SQLException { + return false; + } + + /** + * JDBC 2.0 Does the database support the concurrency type in combination + * with the given result set type? + * + * @param type + * defined in java.sql.ResultSet + * @param concurrency + * type defined in java.sql.ResultSet + * @return true if so + * @exception SQLException + * if a database-access error occurs. + * @see Connection + */ + public boolean supportsResultSetConcurrency(int type, int concurrency) + throws SQLException { + switch (type) { + case ResultSet.TYPE_SCROLL_INSENSITIVE: + if ((concurrency == ResultSet.CONCUR_READ_ONLY) + || (concurrency == ResultSet.CONCUR_UPDATABLE)) { + return true; + } else { + throw SQLError.createSQLException( + "Illegal arguments to supportsResultSetConcurrency()", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + case ResultSet.TYPE_FORWARD_ONLY: + if ((concurrency == ResultSet.CONCUR_READ_ONLY) + || (concurrency == ResultSet.CONCUR_UPDATABLE)) { + return true; + } else { + throw SQLError.createSQLException( + "Illegal arguments to supportsResultSetConcurrency()", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + case ResultSet.TYPE_SCROLL_SENSITIVE: + return false; + default: + throw SQLError.createSQLException( + "Illegal arguments to supportsResultSetConcurrency()", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + } + + /** + * @see DatabaseMetaData#supportsResultSetHoldability(int) + */ + public boolean supportsResultSetHoldability(int holdability) + throws SQLException { + return (holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT); + } + + /** + * JDBC 2.0 Does the database support the given result set type? + * + * @param type + * defined in java.sql.ResultSet + * @return true if so + * @exception SQLException + * if a database-access error occurs. + * @see Connection + */ + public boolean supportsResultSetType(int type) throws SQLException { + return (type == ResultSet.TYPE_SCROLL_INSENSITIVE); + } + + /** + * @see DatabaseMetaData#supportsSavepoints() + */ + public boolean supportsSavepoints() throws SQLException { + + return (this.conn.versionMeetsMinimum(4, 0, 14) || this.conn + .versionMeetsMinimum(4, 1, 1)); + } + + /** + * Can a schema name be used in a data manipulation statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSchemasInDataManipulation() throws SQLException { + return false; + } + + /** + * Can a schema name be used in an index definition statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSchemasInIndexDefinitions() throws SQLException { + return false; + } + + /** + * Can a schema name be used in a privilege definition statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { + return false; + } + + /** + * Can a schema name be used in a procedure call statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSchemasInProcedureCalls() throws SQLException { + return false; + } + + /** + * Can a schema name be used in a table definition statement? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSchemasInTableDefinitions() throws SQLException { + return false; + } + + /** + * Is SELECT for UPDATE supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSelectForUpdate() throws SQLException { + return this.conn.versionMeetsMinimum(4, 0, 0); + } + + /** + * @see DatabaseMetaData#supportsStatementPooling() + */ + public boolean supportsStatementPooling() throws SQLException { + return false; + } + + /** + * Are stored procedure calls using the stored procedure escape syntax + * supported? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsStoredProcedures() throws SQLException { + return this.conn.versionMeetsMinimum(5, 0, 0); + } + + /** + * Are subqueries in comparison expressions supported? A JDBC compliant + * driver always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSubqueriesInComparisons() throws SQLException { + return this.conn.versionMeetsMinimum(4, 1, 0); + } + + /** + * Are subqueries in exists expressions supported? A JDBC compliant driver + * always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSubqueriesInExists() throws SQLException { + return this.conn.versionMeetsMinimum(4, 1, 0); + } + + /** + * Are subqueries in "in" statements supported? A JDBC compliant driver + * always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSubqueriesInIns() throws SQLException { + return this.conn.versionMeetsMinimum(4, 1, 0); + } + + /** + * Are subqueries in quantified expressions supported? A JDBC compliant + * driver always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsSubqueriesInQuantifieds() throws SQLException { + return this.conn.versionMeetsMinimum(4, 1, 0); + } + + /** + * Are table correlation names supported? A JDBC compliant driver always + * returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsTableCorrelationNames() throws SQLException { + return true; + } + + /** + * Does the database support the given transaction isolation level? + * + * @param level + * the values are defined in java.sql.Connection + * @return true if so + * @throws SQLException + * if a database access error occurs + * @see Connection + */ + public boolean supportsTransactionIsolationLevel(int level) + throws SQLException { + if (this.conn.supportsIsolationLevel()) { + switch (level) { + case java.sql.Connection.TRANSACTION_READ_COMMITTED: + case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED: + case java.sql.Connection.TRANSACTION_REPEATABLE_READ: + case java.sql.Connection.TRANSACTION_SERIALIZABLE: + return true; + + default: + return false; + } + } + + return false; + } + + /** + * Are transactions supported? If not, commit is a noop and the isolation + * level is TRANSACTION_NONE. + * + * @return true if transactions are supported + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsTransactions() throws SQLException { + return this.conn.supportsTransactions(); + } + + /** + * Is SQL UNION supported? A JDBC compliant driver always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsUnion() throws SQLException { + return this.conn.versionMeetsMinimum(4, 0, 0); + } + + /** + * Is SQL UNION ALL supported? A JDBC compliant driver always returns true. + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean supportsUnionAll() throws SQLException { + return this.conn.versionMeetsMinimum(4, 0, 0); + } + + /** + * JDBC 2.0 Determine whether or not a visible row update can be detected by + * calling ResultSet.rowUpdated(). + * + * @param type + * set type, i.e. ResultSet.TYPE_XXX + * @return true if changes are detected by the resultset type + * @exception SQLException + * if a database-access error occurs. + */ + public boolean updatesAreDetected(int type) throws SQLException { + return false; + } + + /** + * Does the database use a file for each table? + * + * @return true if the database uses a local file for each table + * @throws SQLException + * DOCUMENT ME! + */ + public boolean usesLocalFilePerTable() throws SQLException { + return false; + } + + /** + * Does the database store tables in a local file? + * + * @return true if so + * @throws SQLException + * DOCUMENT ME! + */ + public boolean usesLocalFiles() throws SQLException { + return false; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/DatabaseMetaDataUsingInfoSchema.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/DatabaseMetaDataUsingInfoSchema.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/DatabaseMetaDataUsingInfoSchema.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,1214 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ +package com.mysql.jdbc; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; + +/** + * DatabaseMetaData implementation that uses INFORMATION_SCHEMA available in + * MySQL-5.0 and newer. + * + * The majority of the queries in this code were built for Connector/OO.org by + * Georg Richter (georg_at_mysql.com). + */ +public class DatabaseMetaDataUsingInfoSchema extends DatabaseMetaData { + + public DatabaseMetaDataUsingInfoSchema(Connection connToSet, + String databaseToSet) { + super(connToSet, databaseToSet); + } + + private ResultSet executeMetadataQuery(PreparedStatement pStmt) + throws SQLException { + ResultSet rs = pStmt.executeQuery(); + ((com.mysql.jdbc.ResultSet) rs).setOwningStatement(null); + + return rs; + } + + /** + * Get a description of the access rights for a table's columns. + *

+ * Only privileges matching the column name criteria are returned. They are + * ordered by COLUMN_NAME and PRIVILEGE. + *

+ *

+ * Each privilige description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. COLUMN_NAME String => column name
  8. + *
  9. GRANTOR => grantor of access (may be null)
  10. + *
  11. GRANTEE String => grantee of access
  12. + *
  13. PRIVILEGE String => name of access (SELECT, INSERT, UPDATE, + * REFRENCES, ...)
  14. + *
  15. IS_GRANTABLE String => "YES" if grantee is permitted to + * grant to others; "NO" if not; null if unknown
  16. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name; "" retrieves those without a schema + * @param table + * a table name + * @param columnNamePattern + * a column name pattern + * @return ResultSet each row is a column privilege description + * @throws SQLException + * if a database access error occurs + * @see #getSearchStringEscape + */ + public java.sql.ResultSet getColumnPrivileges(String catalog, + String schema, String table, String columnNamePattern) + throws SQLException { + if (columnNamePattern == null) { + if (this.conn.getNullNamePatternMatchesAll()) { + columnNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Column name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + catalog = this.database; + } + } + + String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME," + +"COLUMN_NAME, NULL AS GRANTOR, GRANTEE, PRIVILEGE_TYPE AS PRIVILEGE, IS_GRANTABLE FROM " + + "INFORMATION_SCHEMA.COLUMN_PRIVILEGES WHERE " + + "TABLE_SCHEMA LIKE ? AND " + + "TABLE_NAME =? AND COLUMN_NAME LIKE ? ORDER BY " + + "COLUMN_NAME, PRIVILEGE_TYPE"; + + PreparedStatement pStmt = null; + + try { + pStmt = prepareMetaDataSafeStatement(sql); + + if (catalog != null) { + pStmt.setString(1, catalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, table); + pStmt.setString(3, columnNamePattern); + + ResultSet rs = executeMetadataQuery(pStmt); + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "TABLE_CAT", Types.CHAR, 64), + new Field("", "TABLE_SCHEM", Types.CHAR, 1), + new Field("", "TABLE_NAME", Types.CHAR, 64), + new Field("", "COLUMN_NAME", Types.CHAR, 64), + new Field("", "GRANTOR", Types.CHAR, 77), + new Field("", "GRANTEE", Types.CHAR, 77), + new Field("", "PRIVILEGE", Types.CHAR, 64), + new Field("", "IS_GRANTABLE", Types.CHAR, 3)}); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + /** + * Get a description of table columns available in a catalog. + *

+ * Only column descriptions matching the catalog, schema, table and column + * name criteria are returned. They are ordered by TABLE_SCHEM, TABLE_NAME + * and ORDINAL_POSITION. + *

+ *

+ * Each column description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. COLUMN_NAME String => column name
  8. + *
  9. DATA_TYPE short => SQL type from java.sql.Types
  10. + *
  11. TYPE_NAME String => Data source dependent type name
  12. + *
  13. COLUMN_SIZE int => column size. For char or date types this + * is the maximum number of characters, for numeric or decimal types this is + * precision.
  14. + *
  15. BUFFER_LENGTH is not used.
  16. + *
  17. DECIMAL_DIGITS int => the number of fractional digits
  18. + *
  19. NUM_PREC_RADIX int => Radix (typically either 10 or 2)
  20. + *
  21. NULLABLE int => is NULL allowed? + *
      + *
    • columnNoNulls - might not allow NULL values
    • + *
    • columnNullable - definitely allows NULL values
    • + *
    • columnNullableUnknown - nullability unknown
    • + *
    + *
  22. + *
  23. REMARKS String => comment describing column (may be null) + *
  24. + *
  25. COLUMN_DEF String => default value (may be null)
  26. + *
  27. SQL_DATA_TYPE int => unused
  28. + *
  29. SQL_DATETIME_SUB int => unused
  30. + *
  31. CHAR_OCTET_LENGTH int => for char types the maximum number + * of bytes in the column
  32. + *
  33. ORDINAL_POSITION int => index of column in table (starting + * at 1)
  34. + *
  35. IS_NULLABLE String => "NO" means column definitely does not + * allow NULL values; "YES" means the column might allow NULL values. An + * empty string means nobody knows.
  36. + *
+ *

+ */ + public ResultSet getColumns(String catalog, String schemaPattern, + String tableName, String columnNamePattern) throws SQLException { + if (columnNamePattern == null) { + if (this.conn.getNullNamePatternMatchesAll()) { + columnNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Column name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + catalog = this.database; + } + } + + StringBuffer sqlBuf = new StringBuffer("SELECT " + + "TABLE_SCHEMA AS TABLE_CAT, " + "NULL AS TABLE_SCHEM," + + "TABLE_NAME," + "COLUMN_NAME,"); + MysqlDefs.appendJdbcTypeMappingQuery(sqlBuf, "DATA_TYPE"); + + sqlBuf.append(" AS DATA_TYPE, "); + + if (conn.getCapitalizeTypeNames()) { + sqlBuf.append("UPPER(CASE WHEN LOCATE('unsigned', COLUMN_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END) AS TYPE_NAME,"); + } else { + sqlBuf.append("CASE WHEN LOCATE('unsigned', COLUMN_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END AS TYPE_NAME,"); + } + + sqlBuf + .append("CASE WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN NUMERIC_PRECISION ELSE CASE WHEN CHARACTER_MAXIMUM_LENGTH > " + + Integer.MAX_VALUE + " THEN " + Integer.MAX_VALUE + + " ELSE CHARACTER_MAXIMUM_LENGTH END END AS COLUMN_SIZE, " + + MysqlIO.getMaxBuf() + " AS BUFFER_LENGTH," + + "NUMERIC_SCALE AS DECIMAL_DIGITS," + + "10 AS NUM_PREC_RADIX," + + "CASE WHEN IS_NULLABLE='NO' THEN " + columnNoNulls + " ELSE CASE WHEN IS_NULLABLE='YES' THEN " + columnNullable + " ELSE " + columnNullableUnknown + " END END AS NULLABLE," + + "COLUMN_COMMENT AS REMARKS," + + "COLUMN_DEFAULT AS COLUMN_DEF," + + "0 AS SQL_DATA_TYPE," + + "0 AS SQL_DATETIME_SUB," + + "CASE WHEN CHARACTER_OCTET_LENGTH > " + Integer.MAX_VALUE + " THEN " + Integer.MAX_VALUE + " ELSE CHARACTER_OCTET_LENGTH END AS CHAR_OCTET_LENGTH," + + "ORDINAL_POSITION," + + "IS_NULLABLE," + + "NULL AS SCOPE_CATALOG," + + "NULL AS SCOPE_SCHEMA," + + "NULL AS SCOPE_TABLE," + + "NULL AS SOURCE_DATA_TYPE," + + "IF (EXTRA LIKE '%auto_increment%','YES','NO') AS IS_AUTOINCREMENT " + + "FROM INFORMATION_SCHEMA.COLUMNS WHERE " + + "TABLE_SCHEMA LIKE ? AND " + + "TABLE_NAME LIKE ? AND COLUMN_NAME LIKE ? " + + "ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION"); + + PreparedStatement pStmt = null; + + try { + pStmt = prepareMetaDataSafeStatement(sqlBuf.toString()); + + if (catalog != null) { + pStmt.setString(1, catalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, tableName); + pStmt.setString(3, columnNamePattern); + + ResultSet rs = executeMetadataQuery(pStmt); + + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "TABLE_CAT", Types.CHAR, 255), + new Field("", "TABLE_SCHEM", Types.CHAR, 0), + new Field("", "TABLE_NAME", Types.CHAR, 255), + new Field("", "COLUMN_NAME", Types.CHAR, 32), + new Field("", "DATA_TYPE", Types.SMALLINT, 5), + new Field("", "TYPE_NAME", Types.CHAR, 16), + new Field("", "COLUMN_SIZE", Types.INTEGER, Integer + .toString(Integer.MAX_VALUE).length()), + new Field("", "BUFFER_LENGTH", Types.INTEGER, 10), + new Field("", "DECIMAL_DIGITS", Types.INTEGER, 10), + new Field("", "NUM_PREC_RADIX", Types.INTEGER, 10), + new Field("", "NULLABLE", Types.INTEGER, 10), + new Field("", "REMARKS", Types.CHAR, 0), + new Field("", "COLUMN_DEF", Types.CHAR, 0), + new Field("", "SQL_DATA_TYPE", Types.INTEGER, 10), + new Field("", "SQL_DATETIME_SUB", Types.INTEGER, 10), + new Field("", "CHAR_OCTET_LENGTH", Types.INTEGER, Integer + .toString(Integer.MAX_VALUE).length()), + new Field("", "ORDINAL_POSITION", Types.INTEGER, 10), + new Field("", "IS_NULLABLE", Types.CHAR, 3), + new Field("", "SCOPE_CATALOG", Types.CHAR, 255), + new Field("", "SCOPE_SCHEMA", Types.CHAR, 255), + new Field("", "SCOPE_TABLE", Types.CHAR, 255), + new Field("", "SOURCE_DATA_TYPE", Types.SMALLINT, 10), + new Field("", "IS_AUTOINCREMENT", Types.CHAR, 3) }); + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + /** + * Get a description of the foreign key columns in the foreign key table + * that reference the primary key columns of the primary key table (describe + * how one table imports another's key.) This should normally return a + * single foreign key/primary key pair (most tables only import a foreign + * key from a table once.) They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, + * FKTABLE_NAME, and KEY_SEQ. + *

+ * Each foreign key column description has the following columns: + *

    + *
  1. PKTABLE_CAT String => primary key table catalog (may be + * null)
  2. + *
  3. PKTABLE_SCHEM String => primary key table schema (may be + * null)
  4. + *
  5. PKTABLE_NAME String => primary key table name
  6. + *
  7. PKCOLUMN_NAME String => primary key column name
  8. + *
  9. FKTABLE_CAT String => foreign key table catalog (may be + * null) being exported (may be null)
  10. + *
  11. FKTABLE_SCHEM String => foreign key table schema (may be + * null) being exported (may be null)
  12. + *
  13. FKTABLE_NAME String => foreign key table name being exported + *
  14. + *
  15. FKCOLUMN_NAME String => foreign key column name being + * exported
  16. + *
  17. KEY_SEQ short => sequence number within foreign key
  18. + *
  19. UPDATE_RULE short => What happens to foreign key when + * primary is updated: + *
      + *
    • importedKeyCascade - change imported key to agree with primary key + * update
    • + *
    • importedKeyRestrict - do not allow update of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been updated
    • + *
    + *
  20. + *
  21. DELETE_RULE short => What happens to the foreign key when + * primary is deleted. + *
      + *
    • importedKeyCascade - delete rows that import a deleted key
    • + *
    • importedKeyRestrict - do not allow delete of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been deleted
    • + *
    + *
  22. + *
  23. FK_NAME String => foreign key identifier (may be null)
  24. + *
  25. PK_NAME String => primary key identifier (may be null)
  26. + *
+ *

+ * + * @param primaryCatalog + * a catalog name; "" retrieves those without a catalog + * @param primarySchema + * a schema name pattern; "" retrieves those without a schema + * @param primaryTable + * a table name + * @param foreignCatalog + * a catalog name; "" retrieves those without a catalog + * @param foreignSchema + * a schema name pattern; "" retrieves those without a schema + * @param foreignTable + * a table name + * @return ResultSet each row is a foreign key column description + * @throws SQLException + * if a database access error occurs + */ + public java.sql.ResultSet getCrossReference(String primaryCatalog, + String primarySchema, String primaryTable, String foreignCatalog, + String foreignSchema, String foreignTable) throws SQLException { + if (primaryTable == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (primaryCatalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + primaryCatalog = this.database; + } + } + + if (foreignCatalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + foreignCatalog = this.database; + } + } + + Field[] fields = new Field[14]; + fields[0] = new Field("", "PKTABLE_CAT", Types.CHAR, 255); + fields[1] = new Field("", "PKTABLE_SCHEM", Types.CHAR, 0); + fields[2] = new Field("", "PKTABLE_NAME", Types.CHAR, 255); + fields[3] = new Field("", "PKCOLUMN_NAME", Types.CHAR, 32); + fields[4] = new Field("", "FKTABLE_CAT", Types.CHAR, 255); + fields[5] = new Field("", "FKTABLE_SCHEM", Types.CHAR, 0); + fields[6] = new Field("", "FKTABLE_NAME", Types.CHAR, 255); + fields[7] = new Field("", "FKCOLUMN_NAME", Types.CHAR, 32); + fields[8] = new Field("", "KEY_SEQ", Types.SMALLINT, 2); + fields[9] = new Field("", "UPDATE_RULE", Types.SMALLINT, 2); + fields[10] = new Field("", "DELETE_RULE", Types.SMALLINT, 2); + fields[11] = new Field("", "FK_NAME", Types.CHAR, 0); + fields[12] = new Field("", "PK_NAME", Types.CHAR, 0); + fields[13] = new Field("", "DEFERRABILITY", Types.INTEGER, 2); + + String sql = "SELECT " + + "A.REFERENCED_TABLE_SCHEMA AS PKTABLE_CAT," + + "NULL AS PKTABLE_SCHEM," + + "A.REFERENCED_TABLE_NAME AS PKTABLE_NAME," + + "A.REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME," + + "A.TABLE_SCHEMA AS FKTABLE_CAT," + + "NULL AS FKTABLE_SCHEM," + + "A.TABLE_NAME AS FKTABLE_NAME, " + + "A.COLUMN_NAME AS FKCOLUMN_NAME, " + + "A.ORDINAL_POSITION AS KEY_SEQ," + + importedKeyRestrict + + " AS UPDATE_RULE," + + importedKeyRestrict + + " AS DELETE_RULE," + + "A.CONSTRAINT_NAME AS FK_NAME," + + "NULL AS PK_NAME," + + importedKeyNotDeferrable + + " AS DEFERRABILITY " + + "FROM " + + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE A," + + "INFORMATION_SCHEMA.TABLE_CONSTRAINTS B " + + "WHERE " + + "A.TABLE_SCHEMA=B.TABLE_SCHEMA AND A.TABLE_NAME=B.TABLE_NAME " + + "AND " + + "A.CONSTRAINT_NAME=B.CONSTRAINT_NAME AND B.CONSTRAINT_TYPE IS NOT NULL " + + "AND A.REFERENCED_TABLE_SCHEMA LIKE ? AND A.REFERENCED_TABLE_NAME=? " + + "AND A.TABLE_SCHEMA LIKE ? AND A.TABLE_NAME=? " + "ORDER BY " + + "A.TABLE_SCHEMA, A.TABLE_NAME, A.ORDINAL_POSITION"; + + PreparedStatement pStmt = null; + + try { + pStmt = prepareMetaDataSafeStatement(sql); + if (primaryCatalog != null) { + pStmt.setString(1, primaryCatalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, primaryTable); + + if (foreignCatalog != null) { + pStmt.setString(3, foreignCatalog); + } else { + pStmt.setString(3, "%"); + } + + pStmt.setString(4, foreignTable); + + ResultSet rs = executeMetadataQuery(pStmt); + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "PKTABLE_CAT", Types.CHAR, 255), + new Field("", "PKTABLE_SCHEM", Types.CHAR, 0), + new Field("", "PKTABLE_NAME", Types.CHAR, 255), + new Field("", "PKCOLUMN_NAME", Types.CHAR, 32), + new Field("", "FKTABLE_CAT", Types.CHAR, 255), + new Field("", "FKTABLE_SCHEM", Types.CHAR, 0), + new Field("", "FKTABLE_NAME", Types.CHAR, 255), + new Field("", "FKCOLUMN_NAME", Types.CHAR, 32), + new Field("", "KEY_SEQ", Types.SMALLINT, 2), + new Field("", "UPDATE_RULE", Types.SMALLINT, 2), + new Field("", "DELETE_RULE", Types.SMALLINT, 2), + new Field("", "FK_NAME", Types.CHAR, 0), + new Field("", "PK_NAME", Types.CHAR, 0), + new Field("", "DEFERRABILITY", Types.INTEGER, 2) }); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + /** + * Get a description of a foreign key columns that reference a table's + * primary key columns (the foreign keys exported by a table). They are + * ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and KEY_SEQ. + *

+ * Each foreign key column description has the following columns: + *

    + *
  1. PKTABLE_CAT String => primary key table catalog (may be + * null)
  2. + *
  3. PKTABLE_SCHEM String => primary key table schema (may be + * null)
  4. + *
  5. PKTABLE_NAME String => primary key table name
  6. + *
  7. PKCOLUMN_NAME String => primary key column name
  8. + *
  9. FKTABLE_CAT String => foreign key table catalog (may be + * null) being exported (may be null)
  10. + *
  11. FKTABLE_SCHEM String => foreign key table schema (may be + * null) being exported (may be null)
  12. + *
  13. FKTABLE_NAME String => foreign key table name being exported + *
  14. + *
  15. FKCOLUMN_NAME String => foreign key column name being + * exported
  16. + *
  17. KEY_SEQ short => sequence number within foreign key
  18. + *
  19. UPDATE_RULE short => What happens to foreign key when + * primary is updated: + *
      + *
    • importedKeyCascade - change imported key to agree with primary key + * update
    • + *
    • importedKeyRestrict - do not allow update of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been updated
    • + *
    + *
  20. + *
  21. DELETE_RULE short => What happens to the foreign key when + * primary is deleted. + *
      + *
    • importedKeyCascade - delete rows that import a deleted key
    • + *
    • importedKeyRestrict - do not allow delete of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been deleted
    • + *
    + *
  22. + *
  23. FK_NAME String => foreign key identifier (may be null)
  24. + *
  25. PK_NAME String => primary key identifier (may be null)
  26. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @return ResultSet each row is a foreign key column description + * @throws SQLException + * if a database access error occurs + * @see #getImportedKeys + */ + public java.sql.ResultSet getExportedKeys(String catalog, String schema, + String table) throws SQLException { + // TODO: Can't determine actions using INFORMATION_SCHEMA yet... + + if (table == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + catalog = this.database; + } + } + + String sql = "SELECT " + + "A.REFERENCED_TABLE_SCHEMA AS PKTABLE_CAT," + + "NULL AS PKTABLE_SCHEM," + + "A.REFERENCED_TABLE_NAME AS PKTABLE_NAME, " + + "A.REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME, " + + "A.TABLE_SCHEMA AS FKTABLE_CAT," + + "NULL AS FKTABLE_SCHEM," + + "A.TABLE_NAME AS FKTABLE_NAME," + + "A.COLUMN_NAME AS FKCOLUMN_NAME, " + + "A.ORDINAL_POSITION AS KEY_SEQ," + + importedKeyRestrict + + " AS UPDATE_RULE," + + importedKeyRestrict + + " AS DELETE_RULE," + + "A.CONSTRAINT_NAME AS FK_NAME," + + "NULL AS PK_NAME," + + importedKeyNotDeferrable + + " AS DEFERRABILITY " + + "FROM " + + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE A," + + "INFORMATION_SCHEMA.TABLE_CONSTRAINTS B " + + "WHERE " + + "A.TABLE_SCHEMA=B.TABLE_SCHEMA AND A.TABLE_NAME=B.TABLE_NAME " + + "AND " + + "A.CONSTRAINT_NAME=B.CONSTRAINT_NAME AND B.CONSTRAINT_TYPE IS NOT NULL " + + "AND A.REFERENCED_TABLE_SCHEMA LIKE ? AND A.REFERENCED_TABLE_NAME=? " + + "ORDER BY A.TABLE_SCHEMA, A.TABLE_NAME, A.ORDINAL_POSITION"; + + PreparedStatement pStmt = null; + + try { + pStmt = prepareMetaDataSafeStatement(sql); + + if (catalog != null) { + pStmt.setString(1, catalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, table); + + ResultSet rs = executeMetadataQuery(pStmt); + + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "PKTABLE_CAT", Types.CHAR, 255), + new Field("", "PKTABLE_SCHEM", Types.CHAR, 0), + new Field("", "PKTABLE_NAME", Types.CHAR, 255), + new Field("", "PKCOLUMN_NAME", Types.CHAR, 32), + new Field("", "FKTABLE_CAT", Types.CHAR, 255), + new Field("", "FKTABLE_SCHEM", Types.CHAR, 0), + new Field("", "FKTABLE_NAME", Types.CHAR, 255), + new Field("", "FKCOLUMN_NAME", Types.CHAR, 32), + new Field("", "KEY_SEQ", Types.SMALLINT, 2), + new Field("", "UPDATE_RULE", Types.SMALLINT, 2), + new Field("", "DELETE_RULE", Types.SMALLINT, 2), + new Field("", "FK_NAME", Types.CHAR, 255), + new Field("", "PK_NAME", Types.CHAR, 0), + new Field("", "DEFERRABILITY", Types.INTEGER, 2) }); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + + } + + /* + * + * getTablePrivileges + * + * if (getMysqlVersion() > 49999) { if (!strcasecmp("localhost", + * m_pSettings->pConnection->host)) { sprintf(user, "A.GRANTEE = + * \"'%s'@'localhost'\" OR A.GRANTEE LIKE \"'%'@'localhost'\"", + * m_pSettings->pConnection->user, m_pSettings->pConnection->user); } else { + * sprintf(user, "\"'%s'@'%s'\" LIKE A.GRANTEE", + * m_pSettings->pConnection->user, m_pSettings->pConnection->host); } + * + * sprintf(query, "SELECT DISTINCT A.TABLE_CATALOG, B.TABLE_SCHEMA, + * B.TABLE_NAME, CURRENT_USER(), " \ "A.PRIVILEGE_TYPE FROM + * INFORMATION_SCHEMA.USER_PRIVILEGES A, INFORMATION_SCHEMA.TABLES B " \ + * "WHERE B.TABLE_SCHEMA LIKE '%s' AND B.TABLE_NAME LIKE '%s' AND (%s) " \ + * "UNION " \ "SELECT DISTINCT A.TABLE_CATALOG, B.TABLE_SCHEMA, + * B.TABLE_NAME, CURRENT_USER(), A.PRIVILEGE_TYPE " \ "FROM + * INFORMATION_SCHEMA.SCHEMA_PRIVILEGES A, INFORMATION_SCHEMA.TABLES B WHERE " \ + * "B.TABLE_SCHEMA LIKE '%s' AND B.TABLE_NAME LIKE '%s' AND (%s) " \ "UNION "\ + * "SELECT DISTINCT A.TABLE_CATALOG, A.TABLE_SCHEMA, A.TABLE_NAME, + * CURRENT_USER, A.PRIVILEGE_TYPE FROM " \ + * "INFORMATION_SCHEMA.TABLE_PRIVILEGES A WHERE A.TABLE_SCHEMA LIKE '%s' AND + * A.TABLE_NAME LIKE '%s' " \ "AND (%s)", schemaName, tableName, user, + * schemaName, tableName, user, schemaName, tableName, user ); + */ + + /** + * Get a description of the primary key columns that are referenced by a + * table's foreign key columns (the primary keys imported by a table). They + * are ordered by PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ. + *

+ * Each primary key column description has the following columns: + *

    + *
  1. PKTABLE_CAT String => primary key table catalog being + * imported (may be null)
  2. + *
  3. PKTABLE_SCHEM String => primary key table schema being + * imported (may be null)
  4. + *
  5. PKTABLE_NAME String => primary key table name being imported + *
  6. + *
  7. PKCOLUMN_NAME String => primary key column name being + * imported
  8. + *
  9. FKTABLE_CAT String => foreign key table catalog (may be + * null)
  10. + *
  11. FKTABLE_SCHEM String => foreign key table schema (may be + * null)
  12. + *
  13. FKTABLE_NAME String => foreign key table name
  14. + *
  15. FKCOLUMN_NAME String => foreign key column name
  16. + *
  17. KEY_SEQ short => sequence number within foreign key
  18. + *
  19. UPDATE_RULE short => What happens to foreign key when + * primary is updated: + *
      + *
    • importedKeyCascade - change imported key to agree with primary key + * update
    • + *
    • importedKeyRestrict - do not allow update of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been updated
    • + *
    + *
  20. + *
  21. DELETE_RULE short => What happens to the foreign key when + * primary is deleted. + *
      + *
    • importedKeyCascade - delete rows that import a deleted key
    • + *
    • importedKeyRestrict - do not allow delete of primary key if it has + * been imported
    • + *
    • importedKeySetNull - change imported key to NULL if its primary key + * has been deleted
    • + *
    + *
  22. + *
  23. FK_NAME String => foreign key name (may be null)
  24. + *
  25. PK_NAME String => primary key name (may be null)
  26. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @return ResultSet each row is a primary key column description + * @throws SQLException + * if a database access error occurs + * @see #getExportedKeys + */ + public java.sql.ResultSet getImportedKeys(String catalog, String schema, + String table) throws SQLException { + if (table == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + catalog = this.database; + } + } + + String sql = "SELECT " + + "A.REFERENCED_TABLE_SCHEMA AS PKTABLE_CAT," + + "NULL AS PKTABLE_SCHEM," + + "A.REFERENCED_TABLE_NAME AS PKTABLE_NAME," + + "A.REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME," + + "A.TABLE_SCHEMA AS FKTABLE_CAT," + + "NULL AS FKTABLE_SCHEM," + + "A.TABLE_NAME AS FKTABLE_NAME, " + + "A.COLUMN_NAME AS FKCOLUMN_NAME, " + + "A.ORDINAL_POSITION AS KEY_SEQ," + + importedKeyRestrict + + " AS UPDATE_RULE," + + importedKeyRestrict + + " AS DELETE_RULE," + + "A.CONSTRAINT_NAME AS FK_NAME," + + "NULL AS PK_NAME, " + + importedKeyNotDeferrable + + " AS DEFERRABILITY " + + "FROM " + + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE A, " + + "INFORMATION_SCHEMA.TABLE_CONSTRAINTS B WHERE A.TABLE_SCHEMA LIKE ? " + + "AND A.CONSTRAINT_NAME=B.CONSTRAINT_NAME AND A.TABLE_NAME=? " + + "AND " + + "B.TABLE_NAME=? AND A.REFERENCED_TABLE_SCHEMA IS NOT NULL " + + " ORDER BY " + + "A.REFERENCED_TABLE_SCHEMA, A.REFERENCED_TABLE_NAME, " + + "A.ORDINAL_POSITION"; + + PreparedStatement pStmt = null; + + try { + pStmt = prepareMetaDataSafeStatement(sql); + + if (catalog != null) { + pStmt.setString(1, catalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, table); + pStmt.setString(3, table); + + ResultSet rs = executeMetadataQuery(pStmt); + + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "PKTABLE_CAT", Types.CHAR, 255), + new Field("", "PKTABLE_SCHEM", Types.CHAR, 0), + new Field("", "PKTABLE_NAME", Types.CHAR, 255), + new Field("", "PKCOLUMN_NAME", Types.CHAR, 32), + new Field("", "FKTABLE_CAT", Types.CHAR, 255), + new Field("", "FKTABLE_SCHEM", Types.CHAR, 0), + new Field("", "FKTABLE_NAME", Types.CHAR, 255), + new Field("", "FKCOLUMN_NAME", Types.CHAR, 32), + new Field("", "KEY_SEQ", Types.SMALLINT, 2), + new Field("", "UPDATE_RULE", Types.SMALLINT, 2), + new Field("", "DELETE_RULE", Types.SMALLINT, 2), + new Field("", "FK_NAME", Types.CHAR, 255), + new Field("", "PK_NAME", Types.CHAR, 0), + new Field("", "DEFERRABILITY", Types.INTEGER, 2) }); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + /** + * Get a description of a table's indices and statistics. They are ordered + * by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION. + *

+ * Each index column description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. NON_UNIQUE boolean => Can index values be non-unique? false + * when TYPE is tableIndexStatistic
  8. + *
  9. INDEX_QUALIFIER String => index catalog (may be null); null + * when TYPE is tableIndexStatistic
  10. + *
  11. INDEX_NAME String => index name; null when TYPE is + * tableIndexStatistic
  12. + *
  13. TYPE short => index type: + *
      + *
    • tableIndexStatistic - this identifies table statistics that are + * returned in conjuction with a table's index descriptions
    • + *
    • tableIndexClustered - this is a clustered index
    • + *
    • tableIndexHashed - this is a hashed index
    • + *
    • tableIndexOther - this is some other style of index
    • + *
    + *
  14. + *
  15. ORDINAL_POSITION short => column sequence number within + * index; zero when TYPE is tableIndexStatistic
  16. + *
  17. COLUMN_NAME String => column name; null when TYPE is + * tableIndexStatistic
  18. + *
  19. ASC_OR_DESC String => column sort sequence, "A" => + * ascending, "D" => descending, may be null if sort sequence is not + * supported; null when TYPE is tableIndexStatistic
  20. + *
  21. CARDINALITY int => When TYPE is tableIndexStatisic then this + * is the number of rows in the table; otherwise it is the number of unique + * values in the index.
  22. + *
  23. PAGES int => When TYPE is tableIndexStatisic then this is + * the number of pages used for the table, otherwise it is the number of + * pages used for the current index.
  24. + *
  25. FILTER_CONDITION String => Filter condition, if any. (may be + * null)
  26. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @param unique + * when true, return only indices for unique values; when false, + * return indices regardless of whether unique or not + * @param approximate + * when true, result is allowed to reflect approximate or out of + * data values; when false, results are requested to be accurate + * @return ResultSet each row is an index column description + * @throws SQLException + * DOCUMENT ME! + */ + public ResultSet getIndexInfo(String catalog, String schema, String table, + boolean unique, boolean approximate) throws SQLException { + StringBuffer sqlBuf = new StringBuffer("SELECT " + + "TABLE_SCHEMA AS TABLE_CAT, " + "NULL AS TABLE_SCHEM," + + "TABLE_NAME," + "NON_UNIQUE," + + "TABLE_SCHEMA AS INDEX_QUALIFIER," + "INDEX_NAME," + + tableIndexOther + " AS TYPE," + + "SEQ_IN_INDEX AS ORDINAL_POSITION," + "COLUMN_NAME," + + "COLLATION AS ASC_OR_DESC," + "CARDINALITY," + + "NULL AS PAGES," + "NULL AS FILTER_CONDITION " + + "FROM INFORMATION_SCHEMA.STATISTICS WHERE " + + "TABLE_SCHEMA LIKE ? AND " + "TABLE_NAME LIKE ?"); + + if (unique) { + sqlBuf.append(" AND NON_UNIQUE=0 "); + } + + sqlBuf.append("ORDER BY NON_UNIQUE, INDEX_NAME, SEQ_IN_INDEX"); + + PreparedStatement pStmt = null; + + try { + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + catalog = this.database; + } + } + + pStmt = prepareMetaDataSafeStatement(sqlBuf.toString()); + + if (catalog != null) { + pStmt.setString(1, catalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, table); + + ResultSet rs = executeMetadataQuery(pStmt); + + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "TABLE_CAT", Types.CHAR, 255), + new Field("", "TABLE_SCHEM", Types.CHAR, 0), + new Field("", "TABLE_NAME", Types.CHAR, 255), + new Field("", "NON_UNIQUE", Types.CHAR, 4), + new Field("", "INDEX_QUALIFIER", Types.CHAR, 1), + new Field("", "INDEX_NAME", Types.CHAR, 32), + new Field("", "TYPE", Types.CHAR, 32), + new Field("", "ORDINAL_POSITION", Types.SMALLINT, 5), + new Field("", "COLUMN_NAME", Types.CHAR, 32), + new Field("", "ASC_OR_DESC", Types.CHAR, 1), + new Field("", "CARDINALITY", Types.INTEGER, 10), + new Field("", "PAGES", Types.INTEGER, 10), + new Field("", "FILTER_CONDITION", Types.CHAR, 32) }); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + /** + * Get a description of a table's primary key columns. They are ordered by + * COLUMN_NAME. + *

+ * Each column description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. COLUMN_NAME String => column name
  8. + *
  9. KEY_SEQ short => sequence number within primary key
  10. + *
  11. PK_NAME String => primary key name (may be null)
  12. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schema + * a schema name pattern; "" retrieves those without a schema + * @param table + * a table name + * @return ResultSet each row is a primary key column description + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getPrimaryKeys(String catalog, String schema, + String table) throws SQLException { + + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + catalog = this.database; + } + } + + if (table == null) { + throw SQLError.createSQLException("Table not specified.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME, " + + "COLUMN_NAME, SEQ_IN_INDEX AS KEY_SEQ, 'PRIMARY' AS PK_NAME FROM INFORMATION_SCHEMA.STATISTICS " + + "WHERE TABLE_SCHEMA LIKE ? AND TABLE_NAME LIKE ? AND " + + "INDEX_NAME='PRIMARY' ORDER BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX"; + + PreparedStatement pStmt = null; + + try { + pStmt = prepareMetaDataSafeStatement(sql); + + if (catalog != null) { + pStmt.setString(1, catalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, table); + + ResultSet rs = executeMetadataQuery(pStmt); + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "TABLE_CAT", Types.CHAR, 255), + new Field("", "TABLE_SCHEM", Types.CHAR, 0), + new Field("", "TABLE_NAME", Types.CHAR, 255), + new Field("", "COLUMN_NAME", Types.CHAR, 32), + new Field("", "KEY_SEQ", Types.SMALLINT, 5), + new Field("", "PK_NAME", Types.CHAR, 32) }); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + /** + * Get a description of stored procedures available in a catalog. + *

+ * Only procedure descriptions matching the schema and procedure name + * criteria are returned. They are ordered by PROCEDURE_SCHEM, and + * PROCEDURE_NAME. + *

+ *

+ * Each procedure description has the the following columns: + *

    + *
  1. PROCEDURE_CAT String => procedure catalog (may be null) + *
  2. + *
  3. PROCEDURE_SCHEM String => procedure schema (may be null) + *
  4. + *
  5. PROCEDURE_NAME String => procedure name
  6. + *
  7. reserved for future use
  8. + *
  9. reserved for future use
  10. + *
  11. reserved for future use
  12. + *
  13. REMARKS String => explanatory comment on the procedure
  14. + *
  15. PROCEDURE_TYPE short => kind of procedure: + *
      + *
    • procedureResultUnknown - May return a result
    • + *
    • procedureNoResult - Does not return a result
    • + *
    • procedureReturnsResult - Returns a result
    • + *
    + *
  16. + *
+ *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param procedureNamePattern + * a procedure name pattern + * @return ResultSet each row is a procedure description + * @throws SQLException + * if a database access error occurs + * @see #getSearchStringEscape + */ + public ResultSet getProcedures(String catalog, String schemaPattern, + String procedureNamePattern) throws SQLException { + + if ((procedureNamePattern == null) + || (procedureNamePattern.length() == 0)) { + if (this.conn.getNullNamePatternMatchesAll()) { + procedureNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Procedure name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + String db = null; + + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + db = this.database; + } + } + + String sql = "SELECT ROUTINE_SCHEMA AS PROCEDURE_CAT, " + + "NULL AS PROCEDURE_SCHEM, " + + "ROUTINE_NAME AS PROCEDURE_NAME, " + "NULL AS RESERVED_1, " + + "NULL AS RESERVED_2, " + "NULL AS RESERVED_3, " + + "ROUTINE_COMMENT AS REMARKS, " + + "CASE WHEN ROUTINE_TYPE = 'PROCEDURE' THEN " + + procedureNoResult + " WHEN ROUTINE_TYPE='FUNCTION' THEN " + + procedureReturnsResult + " ELSE " + procedureResultUnknown + + " END AS PROCEDURE_TYPE " + + "FROM INFORMATION_SCHEMA.ROUTINES WHERE " + + "ROUTINE_SCHEMA LIKE ? AND ROUTINE_NAME LIKE ? " + + "ORDER BY ROUTINE_SCHEMA, ROUTINE_NAME"; + + PreparedStatement pStmt = null; + + try { + pStmt = prepareMetaDataSafeStatement(sql); + + if (db != null) { + pStmt.setString(1, db); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, procedureNamePattern); + + ResultSet rs = executeMetadataQuery(pStmt); + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "PROCEDURE_CAT", Types.CHAR, 0), + new Field("", "PROCEDURE_SCHEM", Types.CHAR, 0), + new Field("", "PROCEDURE_NAME", Types.CHAR, 0), + new Field("", "reserved1", Types.CHAR, 0), + new Field("", "reserved2", Types.CHAR, 0), + new Field("", "reserved3", Types.CHAR, 0), + new Field("", "REMARKS", Types.CHAR, 0), + new Field("", "PROCEDURE_TYPE", Types.SMALLINT, 0) }); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + /** + * Get a description of tables available in a catalog. + *

+ * Only table descriptions matching the catalog, schema, table name and type + * criteria are returned. They are ordered by TABLE_TYPE, TABLE_SCHEM and + * TABLE_NAME. + *

+ *

+ * Each table description has the following columns: + *

    + *
  1. TABLE_CAT String => table catalog (may be null)
  2. + *
  3. TABLE_SCHEM String => table schema (may be null)
  4. + *
  5. TABLE_NAME String => table name
  6. + *
  7. TABLE_TYPE String => table type. Typical types are "TABLE", + * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", + * "SYNONYM".
  8. + *
  9. REMARKS String => explanatory comment on the table
  10. + *
+ *

+ *

+ * Note: Some databases may not return information for all tables. + *

+ * + * @param catalog + * a catalog name; "" retrieves those without a catalog + * @param schemaPattern + * a schema name pattern; "" retrieves those without a schema + * @param tableNamePattern + * a table name pattern + * @param types + * a list of table types to include; null returns all types + * @return ResultSet each row is a table description + * @throws SQLException + * DOCUMENT ME! + * @see #getSearchStringEscape + */ + public ResultSet getTables(String catalog, String schemaPattern, + String tableNamePattern, String[] types) throws SQLException { + if (catalog == null) { + if (this.conn.getNullCatalogMeansCurrent()) { + catalog = this.database; + } + } + + if (tableNamePattern == null) { + if (this.conn.getNullNamePatternMatchesAll()) { + tableNamePattern = "%"; + } else { + throw SQLError.createSQLException( + "Table name pattern can not be NULL or empty.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + PreparedStatement pStmt = null; + + String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, " + + "NULL AS TABLE_SCHEM, TABLE_NAME, " + + "CASE WHEN TABLE_TYPE='BASE TABLE' THEN 'TABLE' WHEN TABLE_TYPE='TEMPORARY' THEN 'LOCAL_TEMPORARY' ELSE TABLE_TYPE END AS TABLE_TYPE, " + + "TABLE_COMMENT AS REMARKS " + + "FROM INFORMATION_SCHEMA.TABLES WHERE " + + "TABLE_SCHEMA LIKE ? AND TABLE_NAME LIKE ? AND TABLE_TYPE IN (?,?,?) " + + "ORDER BY TABLE_TYPE, TABLE_SCHEMA, TABLE_NAME"; + try { + pStmt = prepareMetaDataSafeStatement(sql); + + if (catalog != null) { + pStmt.setString(1, catalog); + } else { + pStmt.setString(1, "%"); + } + + pStmt.setString(2, tableNamePattern); + + // This overloading of IN (...) allows us to cache this + // prepared statement + if (types == null || types.length == 0) { + pStmt.setString(3, "BASE TABLE"); + pStmt.setString(4, "VIEW"); + pStmt.setString(5, "TEMPORARY"); + } else { + pStmt.setNull(3, Types.VARCHAR); + pStmt.setNull(4, Types.VARCHAR); + pStmt.setNull(5, Types.VARCHAR); + + for (int i = 0; i < types.length; i++) { + if ("TABLE".equalsIgnoreCase(types[i])) { + pStmt.setString(3, "BASE TABLE"); + } + + if ("VIEW".equalsIgnoreCase(types[i])) { + pStmt.setString(4, "VIEW"); + } + + if ("LOCAL TEMPORARY".equalsIgnoreCase(types[i])) { + pStmt.setString(5, "TEMPORARY"); + } + } + } + + ResultSet rs = executeMetadataQuery(pStmt); + + ((com.mysql.jdbc.ResultSet) rs).redefineFieldsForDBMD(new Field[] { + new Field("", "TABLE_CAT", java.sql.Types.VARCHAR, + (catalog == null) ? 0 : catalog.length()), + new Field("", "TABLE_SCHEM", java.sql.Types.VARCHAR, 0), + new Field("", "TABLE_NAME", java.sql.Types.VARCHAR, 255), + new Field("", "TABLE_TYPE", java.sql.Types.VARCHAR, 5), + new Field("", "REMARKS", java.sql.Types.VARCHAR, 0) }); + + return rs; + } finally { + if (pStmt != null) { + pStmt.close(); + } + } + } + + private PreparedStatement prepareMetaDataSafeStatement(String sql) + throws SQLException { + // Can't use server-side here as we coerce a lot of types to match + // the spec. + PreparedStatement pStmt = this.conn.clientPrepareStatement(sql); + + if (pStmt.getMaxRows() != 0) { + pStmt.setMaxRows(0); + } + + pStmt.setHoldResultsOpenOverClose(true); + + return pStmt; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/DocsConnectionPropsHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/DocsConnectionPropsHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/DocsConnectionPropsHelper.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,20 @@ +/* + * Created on Jan 12, 2004 + * + * To change the template for this generated file go to + * Window - Preferences - Java - Code Generation - Code and Comments + */ +package com.mysql.jdbc; + +/** + * @author mmatthew + * + * To change the template for this generated type comment go to Window - + * Preferences - Java - Code Generation - Code and Comments + */ +public class DocsConnectionPropsHelper extends ConnectionProperties { + + public static void main(String[] args) throws Exception { + System.out.println(new DocsConnectionPropsHelper().exposeAsXml()); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Driver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Driver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Driver.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,80 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +/** + * The Java SQL framework allows for multiple database drivers. Each driver + * should supply a class that implements the Driver interface + * + *

+ * The DriverManager will try to load as many drivers as it can find and then + * for any given connection request, it will ask each driver in turn to try to + * connect to the target URL. + * + *

+ * It is strongly recommended that each Driver class should be small and + * standalone so that the Driver class can be loaded and queried without + * bringing in vast quantities of supporting code. + * + *

+ * When a Driver class is loaded, it should create an instance of itself and + * register it with the DriverManager. This means that a user can load and + * register a driver by doing Class.forName("foo.bah.Driver") + * + * @see org.gjt.mm.mysql.Connection + * @see java.sql.Driver + * @author Mark Matthews + * @version $Id: Driver.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + */ +public class Driver extends NonRegisteringDriver implements java.sql.Driver { + // ~ Static fields/initializers + // --------------------------------------------- + + // + // Register ourselves with the DriverManager + // + static { + try { + java.sql.DriverManager.registerDriver(new Driver()); + } catch (SQLException E) { + throw new RuntimeException("Can't register driver!"); + } + } + + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Construct a new driver and register it with DriverManager + * + * @throws SQLException + * if a database error occurs. + */ + public Driver() throws SQLException { + // Required for Class.forName().newInstance() + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeProcessor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeProcessor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeProcessor.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,676 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ + +/** + * EscapeProcessor performs all escape code processing as outlined in the JDBC + * spec by JavaSoft. + */ +package com.mysql.jdbc; + +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; + +import java.util.Calendar; +import java.util.Collections; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TimeZone; + +class EscapeProcessor { + private static Map JDBC_CONVERT_TO_MYSQL_TYPE_MAP; + + private static Map JDBC_NO_CONVERT_TO_MYSQL_EXPRESSION_MAP; + + static { + Map tempMap = new HashMap(); + + tempMap.put("BIGINT", "0 + ?"); + tempMap.put("BINARY", "BINARY"); + tempMap.put("BIT", "0 + ?"); + tempMap.put("CHAR", "CHAR"); + tempMap.put("DATE", "DATE"); + tempMap.put("DECIMAL", "0.0 + ?"); + tempMap.put("DOUBLE", "0.0 + ?"); + tempMap.put("FLOAT", "0.0 + ?"); + tempMap.put("INTEGER", "0 + ?"); + tempMap.put("LONGVARBINARY", "BINARY"); + tempMap.put("LONGVARCHAR", "CONCAT(?)"); + tempMap.put("REAL", "0.0 + ?"); + tempMap.put("SMALLINT", "CONCAT(?)"); + tempMap.put("TIME", "TIME"); + tempMap.put("TIMESTAMP", "DATETIME"); + tempMap.put("TINYINT", "CONCAT(?)"); + tempMap.put("VARBINARY", "BINARY"); + tempMap.put("VARCHAR", "CONCAT(?)"); + + JDBC_CONVERT_TO_MYSQL_TYPE_MAP = Collections.unmodifiableMap(tempMap); + + tempMap = new HashMap(JDBC_CONVERT_TO_MYSQL_TYPE_MAP); + + tempMap.put("BINARY", "CONCAT(?)"); + tempMap.put("CHAR", "CONCAT(?)"); + tempMap.remove("DATE"); + tempMap.put("LONGVARBINARY", "CONCAT(?)"); + tempMap.remove("TIME"); + tempMap.remove("TIMESTAMP"); + tempMap.put("VARBINARY", "CONCAT(?)"); + + JDBC_NO_CONVERT_TO_MYSQL_EXPRESSION_MAP = Collections + .unmodifiableMap(tempMap); + + } + + /** + * Escape process one string + * + * @param sql + * the SQL to escape process. + * + * @return the SQL after it has been escape processed. + * + * @throws java.sql.SQLException + * DOCUMENT ME! + * @throws SQLException + * DOCUMENT ME! + */ + public static final Object escapeSQL(String sql, + boolean serverSupportsConvertFn, + Connection conn) throws java.sql.SQLException { + boolean replaceEscapeSequence = false; + String escapeSequence = null; + + if (sql == null) { + return null; + } + + /* + * Short circuit this code if we don't have a matching pair of "{}". - + * Suggested by Ryan Gustafason + */ + int beginBrace = sql.indexOf('{'); + int nextEndBrace = (beginBrace == -1) ? (-1) : sql.indexOf('}', + beginBrace); + + if (nextEndBrace == -1) { + return sql; + } + + StringBuffer newSql = new StringBuffer(); + + EscapeTokenizer escapeTokenizer = new EscapeTokenizer(sql); + + byte usesVariables = Statement.USES_VARIABLES_FALSE; + boolean callingStoredFunction = false; + + while (escapeTokenizer.hasMoreTokens()) { + String token = escapeTokenizer.nextToken(); + + if (token.length() != 0) { + if (token.charAt(0) == '{') { // It's an escape code + + if (!token.endsWith("}")) { + throw SQLError.createSQLException("Not a valid escape sequence: " + + token); + } + + if (token.length() > 2) { + int nestedBrace = token.indexOf('{', 2); + + if (nestedBrace != -1) { + StringBuffer buf = new StringBuffer(token + .substring(0, 1)); + + Object remainingResults = escapeSQL(token + .substring(1, token.length() - 1), + serverSupportsConvertFn, conn); + + String remaining = null; + + if (remainingResults instanceof String) { + remaining = (String) remainingResults; + } else { + remaining = ((EscapeProcessorResult) remainingResults).escapedSql; + + if (usesVariables != Statement.USES_VARIABLES_TRUE) { + usesVariables = ((EscapeProcessorResult) remainingResults).usesVariables; + } + } + + buf.append(remaining); + + buf.append('}'); + + token = buf.toString(); + } + } + + // nested escape code + // Compare to tokens with _no_ whitespace + String collapsedToken = removeWhitespace(token); + + /* + * Process the escape code + */ + if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{escape")) { + try { + StringTokenizer st = new StringTokenizer(token, + " '"); + st.nextToken(); // eat the "escape" token + escapeSequence = st.nextToken(); + + if (escapeSequence.length() < 3) { + newSql.append(token); // it's just part of the query, push possible syntax errors onto server's shoulders + } else { + + + escapeSequence = escapeSequence.substring(1, + escapeSequence.length() - 1); + replaceEscapeSequence = true; + } + } catch (java.util.NoSuchElementException e) { + newSql.append(token); // it's just part of the query, push possible syntax errors onto server's shoulders + } + } else if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{fn")) { + int startPos = token.toLowerCase().indexOf("fn ") + 3; + int endPos = token.length() - 1; // no } + + String fnToken = token.substring(startPos, endPos); + + // We need to handle 'convert' by ourselves + + if (StringUtils.startsWithIgnoreCaseAndWs(fnToken, + "convert")) { + newSql.append(processConvertToken(fnToken, + serverSupportsConvertFn)); + } else { + // just pass functions right to the DB + newSql.append(fnToken); + } + } else if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{d")) { + int startPos = token.indexOf('\'') + 1; + int endPos = token.lastIndexOf('\''); // no } + + if ((startPos == -1) || (endPos == -1)) { + newSql.append(token); // it's just part of the query, push possible syntax errors onto server's shoulders + } else { + + String argument = token.substring(startPos, endPos); + + try { + StringTokenizer st = new StringTokenizer(argument, + " -"); + String year4 = st.nextToken(); + String month2 = st.nextToken(); + String day2 = st.nextToken(); + String dateString = "'" + year4 + "-" + month2 + + "-" + day2 + "'"; + newSql.append(dateString); + } catch (java.util.NoSuchElementException e) { + throw SQLError.createSQLException( + "Syntax error for DATE escape sequence '" + + argument + "'", "42000"); + } + } + } else if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{ts")) { + int startPos = token.indexOf('\'') + 1; + int endPos = token.lastIndexOf('\''); // no } + + if ((startPos == -1) || (endPos == -1)) { + newSql.append(token); // it's just part of the query, push possible syntax errors onto server's shoulders + } else { + + String argument = token.substring(startPos, endPos); + + try { + StringTokenizer st = new StringTokenizer(argument, + " .-:"); + String year4 = st.nextToken(); + String month2 = st.nextToken(); + String day2 = st.nextToken(); + String hour = st.nextToken(); + String minute = st.nextToken(); + String second = st.nextToken(); + + /* + * For now, we get the fractional seconds part, but + * we don't use it, as MySQL doesn't support it in + * it's TIMESTAMP data type + * + * String fractionalSecond = ""; + * + * if (st.hasMoreTokens()) { fractionalSecond = + * st.nextToken(); } + */ + /* + * Use the full format because number format will + * not work for "between" clauses. + * + * Ref. Mysql Docs + * + * You can specify DATETIME, DATE and TIMESTAMP + * values using any of a common set of formats: + * + * As a string in either 'YYYY-MM-DD HH:MM:SS' or + * 'YY-MM-DD HH:MM:SS' format. + * + * Thanks to Craig Longman for pointing out this bug + */ + if (!conn.getUseTimezone() && !conn.getUseJDBCCompliantTimezoneShift()) { + newSql.append("'").append(year4).append("-") + .append(month2).append("-").append(day2) + .append(" ").append(hour).append(":") + .append(minute).append(":").append(second) + .append("'"); + } else { + Calendar sessionCalendar; + + if (conn != null) { + sessionCalendar = conn.getCalendarInstanceForSessionOrNew(); + } else { + sessionCalendar = new GregorianCalendar(); + sessionCalendar.setTimeZone(TimeZone.getTimeZone("GMT")); + } + + try { + int year4Int = Integer.parseInt(year4); + int month2Int = Integer.parseInt(month2); + int day2Int = Integer.parseInt(day2); + int hourInt = Integer.parseInt(hour); + int minuteInt = Integer.parseInt(minute); + int secondInt = Integer.parseInt(second); + + synchronized (sessionCalendar) { + boolean useGmtMillis = conn.getUseGmtMillisForDatetimes(); + + Timestamp toBeAdjusted = TimeUtil.fastTimestampCreate(useGmtMillis, + useGmtMillis ? Calendar.getInstance(TimeZone.getTimeZone("GMT")): null, + sessionCalendar, + year4Int, + month2Int, + day2Int, + hourInt, + minuteInt, + secondInt, + 0); + + Timestamp inServerTimezone = TimeUtil.changeTimezone( + conn, + sessionCalendar, + null, + toBeAdjusted, + sessionCalendar.getTimeZone(), + conn.getServerTimezoneTZ(), + false); + + + newSql.append("'"); + + String timezoneLiteral = inServerTimezone.toString(); + + int indexOfDot = timezoneLiteral.indexOf("."); + + if (indexOfDot != -1) { + timezoneLiteral = timezoneLiteral.substring(0, indexOfDot); + } + + newSql.append(timezoneLiteral); + } + + newSql.append("'"); + + + } catch (NumberFormatException nfe) { + throw SQLError.createSQLException("Syntax error in TIMESTAMP escape sequence '" + + token + "'.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } catch (java.util.NoSuchElementException e) { + throw SQLError.createSQLException( + "Syntax error for TIMESTAMP escape sequence '" + + argument + "'", "42000"); + } + } + } else if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{t")) { + int startPos = token.indexOf('\'') + 1; + int endPos = token.lastIndexOf('\''); // no } + + if ((startPos == -1) || (endPos == -1)) { + newSql.append(token); // it's just part of the query, push possible syntax errors onto server's shoulders + } else { + + String argument = token.substring(startPos, endPos); + + try { + StringTokenizer st = new StringTokenizer(argument, + " :"); + String hour = st.nextToken(); + String minute = st.nextToken(); + String second = st.nextToken(); + + if (!conn.getUseTimezone()) { + String timeString = "'" + hour + ":" + minute + ":" + + second + "'"; + newSql.append(timeString); + } else { + Calendar sessionCalendar = null; + + if (conn != null) { + sessionCalendar = conn.getCalendarInstanceForSessionOrNew(); + } else { + sessionCalendar = new GregorianCalendar(); + } + + try { + int hourInt = Integer.parseInt(hour); + int minuteInt = Integer.parseInt(minute); + int secondInt = Integer.parseInt(second); + + synchronized (sessionCalendar) { + Time toBeAdjusted = TimeUtil.fastTimeCreate( + sessionCalendar, + hourInt, + minuteInt, + secondInt); + + Time inServerTimezone = TimeUtil.changeTimezone( + conn, + sessionCalendar, + null, + toBeAdjusted, + sessionCalendar.getTimeZone(), + conn.getServerTimezoneTZ(), + false); + + newSql.append("'"); + newSql.append(inServerTimezone.toString()); + newSql.append("'"); + } + + } catch (NumberFormatException nfe) { + throw SQLError.createSQLException("Syntax error in TIMESTAMP escape sequence '" + + token + "'.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } catch (java.util.NoSuchElementException e) { + throw SQLError.createSQLException( + "Syntax error for escape sequence '" + + argument + "'", "42000"); + } + } + } else if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{call") + || StringUtils.startsWithIgnoreCase(collapsedToken, + "{?=call")) { + + int startPos = StringUtils.indexOfIgnoreCase(token, + "CALL") + 5; + int endPos = token.length() - 1; + + if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{?=call")) { + callingStoredFunction = true; + newSql.append("SELECT "); + newSql.append(token.substring(startPos, endPos)); + } else { + callingStoredFunction = false; + newSql.append("CALL "); + newSql.append(token.substring(startPos, endPos)); + } + + for (int i = endPos - 1; i >= startPos; i--) { + char c = token.charAt(i); + + if (Character.isWhitespace(c)) { + continue; + } + + if (c != ')') { + newSql.append("()"); // handle no-parenthesis no-arg call not supported + // by MySQL parser + } + + break; + } + } else if (StringUtils.startsWithIgnoreCase(collapsedToken, + "{oj")) { + // MySQL already handles this escape sequence + // because of ODBC. Cool. + newSql.append(token); + } + } else { + newSql.append(token); // it's just part of the query + } + } + } + + String escapedSql = newSql.toString(); + + // + // FIXME: Let MySQL do this, however requires + // lightweight parsing of statement + // + if (replaceEscapeSequence) { + String currentSql = escapedSql; + + while (currentSql.indexOf(escapeSequence) != -1) { + int escapePos = currentSql.indexOf(escapeSequence); + String lhs = currentSql.substring(0, escapePos); + String rhs = currentSql.substring(escapePos + 1, currentSql + .length()); + currentSql = lhs + "\\" + rhs; + } + + escapedSql = currentSql; + } + + EscapeProcessorResult epr = new EscapeProcessorResult(); + epr.escapedSql = escapedSql; + epr.callingStoredFunction = callingStoredFunction; + + if (usesVariables != Statement.USES_VARIABLES_TRUE) { + if (escapeTokenizer.sawVariableUse()) { + epr.usesVariables = Statement.USES_VARIABLES_TRUE; + } else { + epr.usesVariables = Statement.USES_VARIABLES_FALSE; + } + } + + return epr; + } + + /** + * Re-writes {fn convert (expr, type)} as cast(expr AS type) + * + * @param functionToken + * @return + * @throws SQLException + */ + private static String processConvertToken(String functionToken, + boolean serverSupportsConvertFn) throws SQLException { + // The JDBC spec requires these types: + // + // BIGINT + // BINARY + // BIT + // CHAR + // DATE + // DECIMAL + // DOUBLE + // FLOAT + // INTEGER + // LONGVARBINARY + // LONGVARCHAR + // REAL + // SMALLINT + // TIME + // TIMESTAMP + // TINYINT + // VARBINARY + // VARCHAR + + // MySQL supports these types: + // + // BINARY + // CHAR + // DATE + // DATETIME + // SIGNED (integer) + // UNSIGNED (integer) + // TIME + + int firstIndexOfParen = functionToken.indexOf("("); + + if (firstIndexOfParen == -1) { + throw SQLError.createSQLException( + "Syntax error while processing {fn convert (... , ...)} token, missing opening parenthesis in token '" + + functionToken + "'.", + SQLError.SQL_STATE_SYNTAX_ERROR); + } + + int tokenLength = functionToken.length(); + + int indexOfComma = functionToken.lastIndexOf(","); + + if (indexOfComma == -1) { + throw SQLError.createSQLException( + "Syntax error while processing {fn convert (... , ...)} token, missing comma in token '" + + functionToken + "'.", + SQLError.SQL_STATE_SYNTAX_ERROR); + } + + int indexOfCloseParen = functionToken.indexOf(')', indexOfComma); + + if (indexOfCloseParen == -1) { + throw SQLError.createSQLException( + "Syntax error while processing {fn convert (... , ...)} token, missing closing parenthesis in token '" + + functionToken + "'.", + SQLError.SQL_STATE_SYNTAX_ERROR); + + } + + String expression = functionToken.substring(firstIndexOfParen + 1, + indexOfComma); + String type = functionToken.substring(indexOfComma + 1, + indexOfCloseParen); + + String newType = null; + + String trimmedType = type.trim(); + + if (StringUtils.startsWithIgnoreCase(trimmedType, "SQL_")) { + trimmedType = trimmedType.substring(4, trimmedType.length()); + } + + if (serverSupportsConvertFn) { + newType = (String) JDBC_CONVERT_TO_MYSQL_TYPE_MAP.get(trimmedType + .toUpperCase(Locale.ENGLISH)); + } else { + newType = (String) JDBC_NO_CONVERT_TO_MYSQL_EXPRESSION_MAP + .get(trimmedType.toUpperCase(Locale.ENGLISH)); + + // We need a 'special' check here to give a better error message. If + // we're in this + // block, the version of MySQL we're connected to doesn't support + // CAST/CONVERT, + // so we can't re-write some data type conversions + // (date,time,timestamp, datetime) + + if (newType == null) { + throw SQLError.createSQLException( + "Can't find conversion re-write for type '" + + type + + "' that is applicable for this server version while processing escape tokens.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + if (newType == null) { + throw SQLError.createSQLException("Unsupported conversion type '" + + type.trim() + "' found while processing escape token.", + SQLError.SQL_STATE_GENERAL_ERROR); + } + + int replaceIndex = newType.indexOf("?"); + + if (replaceIndex != -1) { + StringBuffer convertRewrite = new StringBuffer(newType.substring(0, + replaceIndex)); + convertRewrite.append(expression); + convertRewrite.append(newType.substring(replaceIndex + 1, newType + .length())); + + return convertRewrite.toString(); + } else { + + StringBuffer castRewrite = new StringBuffer("CAST("); + castRewrite.append(expression); + castRewrite.append(" AS "); + castRewrite.append(newType); + castRewrite.append(")"); + + return castRewrite.toString(); + } + } + + /** + * Removes all whitespace from the given String. We use this to make escape + * token comparison white-space ignorant. + * + * @param toCollapse + * the string to remove the whitespace from + * + * @return a string with _no_ whitespace. + */ + private static String removeWhitespace(String toCollapse) { + if (toCollapse == null) { + return null; + } + + int length = toCollapse.length(); + + StringBuffer collapsed = new StringBuffer(length); + + for (int i = 0; i < length; i++) { + char c = toCollapse.charAt(i); + + if (!Character.isWhitespace(c)) { + collapsed.append(c); + } + } + + return collapsed.toString(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeProcessorResult.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeProcessorResult.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeProcessorResult.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,43 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Wraps output from EscapeProcessor, to help prevent multiple passes over the + * query string, to detect characters such as '@' (defining/using a variable), + * which are used further up the call stack to handle failover. + * + * @author Mark Matthews + * + * @version $Id: EscapeProcessorResult.java,v 1.1.2.1 2005/05/13 18:58:38 + * mmatthews Exp $ + */ +class EscapeProcessorResult { + boolean callingStoredFunction = false; + + String escapedSql; + + byte usesVariables = Statement.USES_VARIABLES_FALSE; +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeTokenizer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeTokenizer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/EscapeTokenizer.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,194 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * EscapeTokenizer breaks up an SQL statement into SQL and escape code parts. + * + * @author Mark Matthews + */ +public class EscapeTokenizer { + // ~ Instance fields + // -------------------------------------------------------- + + private int bracesLevel = 0; + + private boolean emittingEscapeCode = false; + + private boolean inComment = false; + + private boolean inQuotes = false; + + private char lastChar = 0; + + private char lastLastChar = 0; + + private int pos = 0; + + private char quoteChar = 0; + + private boolean sawVariableUse = false; + + private String source = null; + + private int sourceLength = 0; + + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Creates a new EscapeTokenizer object. + * + * @param s + * the string to tokenize + */ + public EscapeTokenizer(String s) { + this.source = s; + this.sourceLength = s.length(); + this.pos = 0; + } + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Does this tokenizer have more tokens available? + * + * @return if this tokenizer has more tokens available + */ + public synchronized boolean hasMoreTokens() { + return (this.pos < this.sourceLength); + } + + /** + * Returns the next token + * + * @return the next token. + */ + public synchronized String nextToken() { + StringBuffer tokenBuf = new StringBuffer(); + + if (this.emittingEscapeCode) { + tokenBuf.append("{"); //$NON-NLS-1$ + this.emittingEscapeCode = false; + } + + for (; this.pos < this.sourceLength; this.pos++) { + char c = this.source.charAt(this.pos); + + // Detect variable usage + + if (!this.inQuotes && c == '@') { + this.sawVariableUse = true; + } + + if (c == '\'' || c == '"') { + if (this.inQuotes && c == quoteChar) { + if (this.pos + 1 < this.sourceLength) { + if (this.source.charAt(this.pos + 1) == quoteChar) { + // Doubled-up quote escape + tokenBuf.append(quoteChar); + tokenBuf.append(quoteChar); + this.pos++; + continue; + } + } + } + if (this.lastChar != '\\') { + if (this.inQuotes) { + if (this.quoteChar == c) { + this.inQuotes = false; + } + } else { + this.inQuotes = true; + this.quoteChar = c; + } + } else if (this.lastLastChar == '\\') { + if (this.inQuotes) { + if (this.quoteChar == c) { + this.inQuotes = false; + } + } else { + this.inQuotes = true; + this.quoteChar = c; + } + } + + tokenBuf.append(c); + } else if (c == '-') { + if ((this.lastChar == '-') + && ((this.lastLastChar != '\\') & !this.inQuotes)) { + this.inComment = true; + } + + tokenBuf.append(c); + } else if ((c == '\n') || (c == '\r')) { + this.inComment = false; + + tokenBuf.append(c); + } else if (c == '{') { + if (this.inQuotes || this.inComment) { + tokenBuf.append(c); + } else { + this.bracesLevel++; + + if (this.bracesLevel == 1) { + this.pos++; + this.emittingEscapeCode = true; + + return tokenBuf.toString(); + } + + tokenBuf.append(c); + } + } else if (c == '}') { + tokenBuf.append(c); + + if (!this.inQuotes && !this.inComment) { + this.lastChar = c; + + this.bracesLevel--; + + if (this.bracesLevel == 0) { + this.pos++; + + return tokenBuf.toString(); + } + } + } else { + tokenBuf.append(c); + } + + this.lastLastChar = this.lastChar; + this.lastChar = c; + } + + return tokenBuf.toString(); + } + + boolean sawVariableUse() { + return this.sawVariableUse; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ExportControlled.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ExportControlled.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ExportControlled.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,94 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; + +/** + * Holds functionality that falls under export-control regulations. + * + * @author Mark Matthews + * + * @version $Id: ExportControlled.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews + * Exp $ + */ +public class ExportControlled { + protected static boolean enabled() { + // we may wish to un-static-ify this class + // this static method call may be removed entirely by the compiler + return true; + } + + /** + * Converts the socket being used in the given MysqlIO to an SSLSocket by + * performing the SSL/TLS handshake. + * + * @param mysqlIO + * the MysqlIO instance containing the socket to convert to an + * SSLSocket. + * + * @throws CommunicationsException + * if the handshake fails, or if this distribution of + * Connector/J doesn't contain the SSL crytpo hooks needed to + * perform the handshake. + */ + protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) + throws CommunicationsException { + javax.net.ssl.SSLSocketFactory sslFact = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory + .getDefault(); + + try { + mysqlIO.mysqlConnection = sslFact.createSocket( + mysqlIO.mysqlConnection, mysqlIO.host, mysqlIO.port, true); + + // need to force TLSv1, or else JSSE tries to do a SSLv2 handshake + // which MySQL doesn't understand + ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection) + .setEnabledProtocols(new String[] { "TLSv1" }); //$NON-NLS-1$ + ((javax.net.ssl.SSLSocket) mysqlIO.mysqlConnection) + .startHandshake(); + + if (mysqlIO.connection.getUseUnbufferedInput()) { + mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream(); + } else { + mysqlIO.mysqlInput = new BufferedInputStream( + mysqlIO.mysqlConnection.getInputStream(), 16384); + } + + mysqlIO.mysqlOutput = new BufferedOutputStream( + mysqlIO.mysqlConnection.getOutputStream(), 16384); + + mysqlIO.mysqlOutput.flush(); + } catch (IOException ioEx) { + throw new CommunicationsException(mysqlIO.connection, + mysqlIO.lastPacketSentTimeMs, ioEx); + } + } + + private ExportControlled() { /* prevent instantiation */ + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Field.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Field.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Field.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,895 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.UnsupportedEncodingException; +import java.sql.SQLException; +import java.sql.Types; + +/** + * Field is a class used to describe fields in a ResultSet + * + * @author Mark Matthews + * @version $Id: Field.java,v 1.1 2012/08/17 14:57:10 marcin Exp $ + */ +public class Field { + + private static final int AUTO_INCREMENT_FLAG = 512; + + private static final int NO_CHARSET_INFO = -1; + + private byte[] buffer; + + private int charsetIndex = 0; + + private String charsetName = null; + + private int colDecimals; + + private short colFlag; + + private String collationName = null; + + private Connection connection = null; + + private String databaseName = null; + + private int databaseNameLength = -1; + + // database name info + private int databaseNameStart = -1; + + private int defaultValueLength = -1; + + // default value info - from COM_LIST_FIELDS execution + private int defaultValueStart = -1; + + private String fullName = null; + + private String fullOriginalName = null; + + private boolean isImplicitTempTable = false; + + private long length; // Internal length of the field; + + private int mysqlType = -1; // the MySQL type + + private String name; // The Field name + + private int nameLength; + + private int nameStart; + + private String originalColumnName = null; + + private int originalColumnNameLength = -1; + + // column name info (before aliasing) + private int originalColumnNameStart = -1; + + private String originalTableName = null; + + private int originalTableNameLength = -1; + + // table name info (before aliasing) + private int originalTableNameStart = -1; + + private int precisionAdjustFactor = 0; + + private int sqlType = -1; // the java.sql.Type + + private String tableName; // The Name of the Table + + private int tableNameLength; + + private int tableNameStart; + + private boolean useOldNameMetadata = false; + + private boolean isSingleBit; + + private int maxBytesPerChar; + + /** + * Constructor used when communicating with 4.1 and newer servers + */ + Field(Connection conn, byte[] buffer, int databaseNameStart, + int databaseNameLength, int tableNameStart, int tableNameLength, + int originalTableNameStart, int originalTableNameLength, + int nameStart, int nameLength, int originalColumnNameStart, + int originalColumnNameLength, long length, int mysqlType, + short colFlag, int colDecimals, int defaultValueStart, + int defaultValueLength, int charsetIndex) throws SQLException { + this.connection = conn; + this.buffer = buffer; + this.nameStart = nameStart; + this.nameLength = nameLength; + this.tableNameStart = tableNameStart; + this.tableNameLength = tableNameLength; + this.length = length; + this.colFlag = colFlag; + this.colDecimals = colDecimals; + this.mysqlType = mysqlType; + + // 4.1 field info... + this.databaseNameStart = databaseNameStart; + this.databaseNameLength = databaseNameLength; + + this.originalTableNameStart = originalTableNameStart; + this.originalTableNameLength = originalTableNameLength; + + this.originalColumnNameStart = originalColumnNameStart; + this.originalColumnNameLength = originalColumnNameLength; + + this.defaultValueStart = defaultValueStart; + this.defaultValueLength = defaultValueLength; + + // If we're not running 4.1 or newer, use the connection's + // charset + this.charsetIndex = charsetIndex; + + + // Map MySqlTypes to java.sql Types + this.sqlType = MysqlDefs.mysqlToJavaType(this.mysqlType); + + checkForImplicitTemporaryTable(); + // Re-map to 'real' blob type, if we're a BLOB + + if (this.mysqlType == MysqlDefs.FIELD_TYPE_BLOB) { + boolean isFromFunction = this.originalTableNameLength == 0; + + if (this.connection != null && this.connection.getBlobsAreStrings() || + (this.connection.getFunctionsNeverReturnBlobs() && isFromFunction)) { + this.sqlType = Types.VARCHAR; + this.mysqlType = MysqlDefs.FIELD_TYPE_VARCHAR; + } else if (this.charsetIndex == 63 || + !this.connection.versionMeetsMinimum(4, 1, 0)) { + setBlobTypeBasedOnLength(); + this.sqlType = MysqlDefs.mysqlToJavaType(this.mysqlType); + } else { + // *TEXT masquerading as blob + this.mysqlType = MysqlDefs.FIELD_TYPE_VAR_STRING; + this.sqlType = Types.LONGVARCHAR; + } + } + + if (this.sqlType == Types.TINYINT && this.length == 1 + && this.connection.getTinyInt1isBit()) { + // Adjust for pseudo-boolean + if (conn.getTinyInt1isBit()) { + if (conn.getTransformedBitIsBoolean()) { + this.sqlType = Types.BOOLEAN; + } else { + this.sqlType = Types.BIT; + } + } + + } + + if (!isNativeNumericType() && !isNativeDateTimeType()) { + this.charsetName = this.connection + .getCharsetNameForIndex(this.charsetIndex); + + + // Handle VARBINARY/BINARY (server doesn't have a different type + // for this + + boolean isBinary = isBinary(); + + if (this.connection.versionMeetsMinimum(4, 1, 0) && + this.mysqlType == MysqlDefs.FIELD_TYPE_VAR_STRING && + isBinary && + this.charsetIndex == 63) { + if (this.isOpaqueBinary()) { + this.sqlType = Types.VARBINARY; + } + } + + if (this.connection.versionMeetsMinimum(4, 1, 0) && + this.mysqlType == MysqlDefs.FIELD_TYPE_STRING && + isBinary && this.charsetIndex == 63) { + // + // Okay, this is a hack, but there's currently no way + // to easily distinguish something like DATE_FORMAT( ..) + // from the "BINARY" column type, other than looking + // at the original column name. + // + + if (isOpaqueBinary() && !this.connection.getBlobsAreStrings()) { + this.sqlType = Types.BINARY; + } + } + + + + if (this.mysqlType == MysqlDefs.FIELD_TYPE_BIT) { + this.isSingleBit = (this.length == 0); + + if (this.connection != null && (this.connection.versionMeetsMinimum(5, 0, 21) || + this.connection.versionMeetsMinimum(5, 1, 10)) && this.length == 1) { + this.isSingleBit = true; + } + + if (this.isSingleBit) { + this.sqlType = Types.BIT; + } else { + this.sqlType = Types.VARBINARY; + this.colFlag |= 128; // we need to pretend this is a full + this.colFlag |= 16; // binary blob + isBinary = true; + } + } + + // + // Handle TEXT type (special case), Fix proposed by Peter McKeown + // + if ((this.sqlType == java.sql.Types.LONGVARBINARY) && !isBinary) { + this.sqlType = java.sql.Types.LONGVARCHAR; + } else if ((this.sqlType == java.sql.Types.VARBINARY) && !isBinary) { + this.sqlType = java.sql.Types.VARCHAR; + } + } else { + this.charsetName = "US-ASCII"; + } + + // + // Handle odd values for 'M' for floating point/decimal numbers + // + if (!isUnsigned()) { + switch (this.mysqlType) { + case MysqlDefs.FIELD_TYPE_DECIMAL: + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + this.precisionAdjustFactor = -1; + + break; + case MysqlDefs.FIELD_TYPE_DOUBLE: + case MysqlDefs.FIELD_TYPE_FLOAT: + this.precisionAdjustFactor = 1; + + break; + } + } else { + switch (this.mysqlType) { + case MysqlDefs.FIELD_TYPE_DOUBLE: + case MysqlDefs.FIELD_TYPE_FLOAT: + this.precisionAdjustFactor = 1; + + break; + } + } + } + + /** + * Constructor used when communicating with pre 4.1 servers + */ + Field(Connection conn, byte[] buffer, int nameStart, int nameLength, + int tableNameStart, int tableNameLength, int length, int mysqlType, + short colFlag, int colDecimals) throws SQLException { + this(conn, buffer, -1, -1, tableNameStart, tableNameLength, -1, -1, + nameStart, nameLength, -1, -1, length, mysqlType, colFlag, + colDecimals, -1, -1, NO_CHARSET_INFO); + } + + /** + * Constructor used by DatabaseMetaData methods. + */ + Field(String tableName, String columnName, int jdbcType, int length) { + this.tableName = tableName; + this.name = columnName; + this.length = length; + this.sqlType = jdbcType; + this.colFlag = 0; + this.colDecimals = 0; + } + + private void checkForImplicitTemporaryTable() { + this.isImplicitTempTable = this.tableNameLength > 5 + && this.buffer[tableNameStart] == (byte) '#' + && this.buffer[tableNameStart + 1] == (byte) 's' + && this.buffer[tableNameStart + 2] == (byte) 'q' + && this.buffer[tableNameStart + 3] == (byte) 'l' + && this.buffer[tableNameStart + 4] == (byte) '_'; + } + + /** + * Returns the character set (if known) for this field. + * + * @return the character set + */ + public String getCharacterSet() throws SQLException { + return this.charsetName; + } + + public synchronized String getCollation() throws SQLException { + if (this.collationName == null) { + if (this.connection != null) { + if (this.connection.versionMeetsMinimum(4, 1, 0)) { + if (this.connection.getUseDynamicCharsetInfo()) { + java.sql.DatabaseMetaData dbmd = this.connection + .getMetaData(); + + String quotedIdStr = dbmd.getIdentifierQuoteString(); + + if (" ".equals(quotedIdStr)) { //$NON-NLS-1$ + quotedIdStr = ""; //$NON-NLS-1$ + } + + String csCatalogName = getDatabaseName(); + String csTableName = getOriginalTableName(); + String csColumnName = getOriginalName(); + + if (csCatalogName != null && csCatalogName.length() != 0 + && csTableName != null && csTableName.length() != 0 + && csColumnName != null + && csColumnName.length() != 0) { + StringBuffer queryBuf = new StringBuffer(csCatalogName + .length() + + csTableName.length() + 28); + queryBuf.append("SHOW FULL COLUMNS FROM "); //$NON-NLS-1$ + queryBuf.append(quotedIdStr); + queryBuf.append(csCatalogName); + queryBuf.append(quotedIdStr); + queryBuf.append("."); //$NON-NLS-1$ + queryBuf.append(quotedIdStr); + queryBuf.append(csTableName); + queryBuf.append(quotedIdStr); + + java.sql.Statement collationStmt = null; + java.sql.ResultSet collationRs = null; + + try { + collationStmt = this.connection.createStatement(); + + collationRs = collationStmt.executeQuery(queryBuf + .toString()); + + while (collationRs.next()) { + if (csColumnName.equals(collationRs + .getString("Field"))) { //$NON-NLS-1$ + this.collationName = collationRs + .getString("Collation"); //$NON-NLS-1$ + + break; + } + } + } finally { + if (collationRs != null) { + collationRs.close(); + collationRs = null; + } + + if (collationStmt != null) { + collationStmt.close(); + collationStmt = null; + } + } + } + } else { + this.collationName = CharsetMapping.INDEX_TO_COLLATION[charsetIndex]; + } + } + } + } + + return this.collationName; + } + + public String getColumnLabel() throws SQLException { + return getName(); // column name if not aliased, alias if used + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getDatabaseName() throws SQLException { + if ((this.databaseName == null) && (this.databaseNameStart != -1) + && (this.databaseNameLength != -1)) { + this.databaseName = getStringFromBytes(this.databaseNameStart, + this.databaseNameLength); + } + + return this.databaseName; + } + + int getDecimals() { + return this.colDecimals; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getFullName() throws SQLException { + if (this.fullName == null) { + StringBuffer fullNameBuf = new StringBuffer(getTableName().length() + + 1 + getName().length()); + fullNameBuf.append(this.tableName); + + // much faster to append a char than a String + fullNameBuf.append('.'); + fullNameBuf.append(this.name); + this.fullName = fullNameBuf.toString(); + fullNameBuf = null; + } + + return this.fullName; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getFullOriginalName() throws SQLException { + getOriginalName(); + + if (this.originalColumnName == null) { + return null; // we don't have this information + } + + if (this.fullName == null) { + StringBuffer fullOriginalNameBuf = new StringBuffer( + getOriginalTableName().length() + 1 + + getOriginalName().length()); + fullOriginalNameBuf.append(this.originalTableName); + + // much faster to append a char than a String + fullOriginalNameBuf.append('.'); + fullOriginalNameBuf.append(this.originalColumnName); + this.fullOriginalName = fullOriginalNameBuf.toString(); + fullOriginalNameBuf = null; + } + + return this.fullOriginalName; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public long getLength() { + return this.length; + } + + public synchronized int getMaxBytesPerCharacter() throws SQLException { + if (this.maxBytesPerChar == 0) { + this.maxBytesPerChar = this.connection.getMaxBytesPerChar(getCharacterSet()); + } + + return this.maxBytesPerChar; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getMysqlType() { + return this.mysqlType; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getName() throws SQLException { + if (this.name == null) { + this.name = getStringFromBytes(this.nameStart, this.nameLength); + } + + return this.name; + } + + public String getNameNoAliases() throws SQLException { + if (this.useOldNameMetadata) { + return getName(); + } + + if (this.connection != null && + this.connection.versionMeetsMinimum(4, 1, 0)) { + return getOriginalName(); + } + + return getName(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getOriginalName() throws SQLException { + if ((this.originalColumnName == null) + && (this.originalColumnNameStart != -1) + && (this.originalColumnNameLength != -1)) { + this.originalColumnName = getStringFromBytes( + this.originalColumnNameStart, this.originalColumnNameLength); + } + + return this.originalColumnName; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getOriginalTableName() throws SQLException { + if ((this.originalTableName == null) + && (this.originalTableNameStart != -1) + && (this.originalTableNameLength != -1)) { + this.originalTableName = getStringFromBytes( + this.originalTableNameStart, this.originalTableNameLength); + } + + return this.originalTableName; + } + + /** + * Returns amount of correction that should be applied to the precision + * value. + * + * Different versions of MySQL report different precision values. + * + * @return the amount to adjust precision value by. + */ + public int getPrecisionAdjustFactor() { + return this.precisionAdjustFactor; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getSQLType() { + return this.sqlType; + } + + /** + * Create a string with the correct charset encoding from the byte-buffer + * that contains the data for this field + */ + private String getStringFromBytes(int stringStart, int stringLength) + throws SQLException { + if ((stringStart == -1) || (stringLength == -1)) { + return null; + } + + String stringVal = null; + + if (this.connection != null) { + if (this.connection.getUseUnicode()) { + String encoding = this.connection.getCharacterSetMetadata(); + + if (encoding == null) { + encoding = connection.getEncoding(); + } + + if (encoding != null) { + SingleByteCharsetConverter converter = null; + + if (this.connection != null) { + converter = this.connection + .getCharsetConverter(encoding); + } + + if (converter != null) { // we have a converter + stringVal = converter.toString(this.buffer, + stringStart, stringLength); + } else { + // we have no converter, use JVM converter + byte[] stringBytes = new byte[stringLength]; + + int endIndex = stringStart + stringLength; + int pos = 0; + + for (int i = stringStart; i < endIndex; i++) { + stringBytes[pos++] = this.buffer[i]; + } + + try { + stringVal = new String(stringBytes, encoding); + } catch (UnsupportedEncodingException ue) { + throw new RuntimeException(Messages + .getString("Field.12") + encoding //$NON-NLS-1$ + + Messages.getString("Field.13")); //$NON-NLS-1$ + } + } + } else { + // we have no encoding, use JVM standard charset + stringVal = StringUtils.toAsciiString(this.buffer, + stringStart, stringLength); + } + } else { + // we are not using unicode, so use JVM standard charset + stringVal = StringUtils.toAsciiString(this.buffer, stringStart, + stringLength); + } + } else { + // we don't have a connection, so punt + stringVal = StringUtils.toAsciiString(this.buffer, stringStart, + stringLength); + } + + return stringVal; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getTable() throws SQLException { + return getTableName(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getTableName() throws SQLException { + if (this.tableName == null) { + this.tableName = getStringFromBytes(this.tableNameStart, + this.tableNameLength); + } + + return this.tableName; + } + + public String getTableNameNoAliases() throws SQLException { + if (this.connection.versionMeetsMinimum(4, 1, 0)) { + return getOriginalTableName(); + } + + return getTableName(); // pre-4.1, no aliases returned + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isAutoIncrement() { + return ((this.colFlag & AUTO_INCREMENT_FLAG) > 0); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isBinary() { + return ((this.colFlag & 128) > 0); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isBlob() { + return ((this.colFlag & 16) > 0); + } + + /** + * Is this field owned by a server-created temporary table? + * + * @return + */ + private boolean isImplicitTemporaryTable() { + return this.isImplicitTempTable; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isMultipleKey() { + return ((this.colFlag & 8) > 0); + } + + boolean isNotNull() { + return ((this.colFlag & 1) > 0); + } + + boolean isOpaqueBinary() throws SQLException { + + // + // Detect CHAR(n) CHARACTER SET BINARY which is a synonym for + // fixed-length binary types + // + + if (this.charsetIndex == 63 && isBinary() + && (this.getMysqlType() == MysqlDefs.FIELD_TYPE_STRING || + this.getMysqlType() == MysqlDefs.FIELD_TYPE_VAR_STRING)) { + + if (this.originalTableNameLength == 0 && ( + this.connection != null && !this.connection.versionMeetsMinimum(5, 0, 25))) { + return false; // Probably from function + } + + // Okay, queries resolved by temp tables also have this 'signature', + // check for that + + return !isImplicitTemporaryTable(); + } + + return (this.connection.versionMeetsMinimum(4, 1, 0) && "binary" + .equalsIgnoreCase(getCharacterSet())); + + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isPrimaryKey() { + return ((this.colFlag & 2) > 0); + } + + /** + * Is this field _definitely_ not writable? + * + * @return true if this field can not be written to in an INSERT/UPDATE + * statement. + */ + boolean isReadOnly() throws SQLException { + if (this.connection.versionMeetsMinimum(4, 1, 0)) { + String orgColumnName = getOriginalName(); + String orgTableName = getOriginalTableName(); + + return !(orgColumnName != null && orgColumnName.length() > 0 + && orgTableName != null && orgTableName.length() > 0); + } + + return false; // we can't tell definitively in this case. + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isUniqueKey() { + return ((this.colFlag & 4) > 0); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isUnsigned() { + return ((this.colFlag & 32) > 0); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isZeroFill() { + return ((this.colFlag & 64) > 0); + } + + // + // MySQL only has one protocol-level BLOB type that it exposes + // which is FIELD_TYPE_BLOB, although we can divine what the + // actual type is by the length reported ... + // + private void setBlobTypeBasedOnLength() { + if (this.length == MysqlDefs.LENGTH_TINYBLOB) { + this.mysqlType = MysqlDefs.FIELD_TYPE_TINY_BLOB; + } else if (this.length == MysqlDefs.LENGTH_BLOB) { + this.mysqlType = MysqlDefs.FIELD_TYPE_BLOB; + } else if (this.length == MysqlDefs.LENGTH_MEDIUMBLOB) { + this.mysqlType = MysqlDefs.FIELD_TYPE_MEDIUM_BLOB; + } else if (this.length == MysqlDefs.LENGTH_LONGBLOB) { + this.mysqlType = MysqlDefs.FIELD_TYPE_LONG_BLOB; + } + } + + private boolean isNativeNumericType() { + return ((this.mysqlType >= MysqlDefs.FIELD_TYPE_TINY && + this.mysqlType <= MysqlDefs.FIELD_TYPE_DOUBLE) || + this.mysqlType == MysqlDefs.FIELD_TYPE_LONGLONG || + this.mysqlType == MysqlDefs.FIELD_TYPE_YEAR); + } + + private boolean isNativeDateTimeType() { + return (this.mysqlType == MysqlDefs.FIELD_TYPE_DATE || + this.mysqlType == MysqlDefs.FIELD_TYPE_NEWDATE || + this.mysqlType == MysqlDefs.FIELD_TYPE_DATETIME || + this.mysqlType == MysqlDefs.FIELD_TYPE_TIME || + this.mysqlType == MysqlDefs.FIELD_TYPE_TIMESTAMP); + } + + /** + * DOCUMENT ME! + * + * @param conn + * DOCUMENT ME! + */ + public void setConnection(Connection conn) { + this.connection = conn; + + this.charsetName = this.connection.getEncoding(); + } + + void setMysqlType(int type) { + this.mysqlType = type; + this.sqlType = MysqlDefs.mysqlToJavaType(this.mysqlType); + } + + protected void setUseOldNameMetadata(boolean useOldNameMetadata) { + this.useOldNameMetadata = useOldNameMetadata; + } + + public String toString() { + try { + StringBuffer asString = new StringBuffer(128); + asString.append(super.toString()); + + asString.append("\n catalog: "); + asString.append(this.getDatabaseName()); + asString.append("\n table name: "); + asString.append(this.getTableName()); + asString.append("\n original table name: "); + asString.append(this.getOriginalTableName()); + asString.append("\n column name: "); + asString.append(this.getName()); + asString.append("\n original column name: "); + asString.append(this.getOriginalName()); + asString.append("\n MySQL data type: "); + asString.append(getMysqlType()); + asString.append("("); + asString.append(MysqlDefs.typeToName(getMysqlType())); + asString.append(")"); + + if (this.buffer != null) { + asString.append("\n\nData as received from server:\n\n"); + asString.append(StringUtils.dumpAsHex(this.buffer, + this.buffer.length)); + } + + return asString.toString(); + } catch (Throwable t) { + return super.toString(); + } + } + + protected boolean isSingleBit() { + return this.isSingleBit; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/LicenseConfiguration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/LicenseConfiguration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/LicenseConfiguration.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,59 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +import java.util.Map; + +/** + * Used in commercially-licensed clients that require connections to + * commercially-licensed servers as part of the licensing terms. + * + * @author Mark Matthews + * @version $Id: LicenseConfiguration.java,v 1.1.2.1 2005/05/13 18:58:38 + * mmatthews Exp $ + */ +class LicenseConfiguration { + + /** + * Used in commercially-licensed clients that require connections to + * commercially-licensed servers as part of the licensing terms. + * + * @param serverVariables + * a Map of the output of 'show variables' from the server we're + * connecting to. + * + * @throws SQLException + * if commercial license is required, but not found + */ + static void checkLicenseType(Map serverVariables) throws SQLException { + // This is a GPL build, so we don't check anything... + } + + private LicenseConfiguration() { + // this is a static utility class + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/LoadBalancingConnectionProxy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/LoadBalancingConnectionProxy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/LoadBalancingConnectionProxy.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,532 @@ +/* + Copyright (C) 2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + +package com.mysql.jdbc; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * An implementation of java.sql.Connection that load balances requests across a + * series of MySQL JDBC connections, where the balancing takes place at + * transaction commit. + * + * Therefore, for this to work (at all), you must use transactions, even if only + * reading data. + * + * This implementation will invalidate connections that it detects have had + * communication errors when processing a request. A new connection to the + * problematic host will be attempted the next time it is selected by the load + * balancing algorithm. + * + * This implementation is thread-safe, but it's questionable whether sharing a + * connection instance amongst threads is a good idea, given that transactions + * are scoped to connections in JDBC. + * + * @version $Id: LoadBalancingConnectionProxy.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + * + */ +public class LoadBalancingConnectionProxy implements InvocationHandler, PingTarget { + + private static Method getLocalTimeMethod; + + static { + try { + getLocalTimeMethod = System.class.getMethod("nanoTime", + new Class[0]); + } catch (SecurityException e) { + // ignore + } catch (NoSuchMethodException e) { + // ignore + } + } + + interface BalanceStrategy { + abstract Connection pickConnection() throws SQLException; + } + + class BestResponseTimeBalanceStrategy implements BalanceStrategy { + + public Connection pickConnection() throws SQLException { + long minResponseTime = Long.MAX_VALUE; + + int bestHostIndex = 0; + + long[] localResponseTimes = new long[responseTimes.length]; + + synchronized (responseTimes) { + System.arraycopy(responseTimes, 0, localResponseTimes, 0, responseTimes.length); + } + + SQLException ex = null; + + for (int attempts = 0; attempts < 1200 /* 5 minutes */; attempts++) { + for (int i = 0; i < localResponseTimes.length; i++) { + long candidateResponseTime = localResponseTimes[i]; + + if (candidateResponseTime < minResponseTime) { + if (candidateResponseTime == 0) { + bestHostIndex = i; + + break; + } + + bestHostIndex = i; + minResponseTime = candidateResponseTime; + } + } + + if (bestHostIndex == localResponseTimes.length - 1) { + // try again, assuming that the previous list was mostly + // correct as far as distribution of response times went + + synchronized (responseTimes) { + System.arraycopy(responseTimes, 0, localResponseTimes, 0, responseTimes.length); + } + + continue; + } + String bestHost = (String) hostList.get(bestHostIndex); + + Connection conn = (Connection) liveConnections.get(bestHost); + + if (conn == null) { + try { + conn = createConnectionForHost(bestHost); + } catch (SQLException sqlEx) { + ex = sqlEx; + + if (sqlEx instanceof CommunicationsException || "08S01".equals(sqlEx.getSQLState())) { + localResponseTimes[bestHostIndex] = Long.MAX_VALUE; + + try { + Thread.sleep(250); + } catch (InterruptedException e) { + } + + continue; + } else { + throw sqlEx; + } + } + } + + return conn; + } + + if (ex != null) { + throw ex; + } + + return null; // we won't get here, compiler can't tell + } + } + + // Lifted from C/J 5.1's JDBC-2.0 connection pool classes, let's merge this + // if/when this gets into 5.1 + protected class ConnectionErrorFiringInvocationHandler implements + InvocationHandler { + Object invokeOn = null; + + public ConnectionErrorFiringInvocationHandler(Object toInvokeOn) { + invokeOn = toInvokeOn; + } + + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + Object result = null; + + try { + result = method.invoke(invokeOn, args); + + if (result != null) { + result = proxyIfInterfaceIsJdbc(result, result.getClass()); + } + } catch (InvocationTargetException e) { + dealWithInvocationException(e); + } + + return result; + } + } + + class RandomBalanceStrategy implements BalanceStrategy { + + public Connection pickConnection() throws SQLException { + int random = (int) (Math.random() * hostList.size()); + + if (random == hostList.size()) { + random--; + } + + String hostPortSpec = (String) hostList.get(random); + + SQLException ex = null; + + for (int attempts = 0; attempts < 1200 /* 5 minutes */; attempts++) { + Connection conn = (Connection) liveConnections.get(hostPortSpec); + + if (conn == null) { + try { + conn = createConnectionForHost(hostPortSpec); + } catch (SQLException sqlEx) { + ex = sqlEx; + + if (sqlEx instanceof CommunicationsException || "08S01".equals(sqlEx.getSQLState())) { + + try { + Thread.sleep(250); + } catch (InterruptedException e) { + } + + continue; + } else { + throw sqlEx; + } + } + } + + return conn; + } + + if (ex != null) { + throw ex; + } + + return null; // we won't get here, compiler can't tell + } + + } + + private Connection currentConn; + + private List hostList; + + private Map liveConnections; + + private Map connectionsToHostsMap; + + private long[] responseTimes; + + private Map hostsToListIndexMap; + + boolean inTransaction = false; + + long transactionStartTime = 0; + + Properties localProps; + + boolean isClosed = false; + + BalanceStrategy balancer; + + /** + * Creates a proxy for java.sql.Connection that routes requests between the + * given list of host:port and uses the given properties when creating + * connections. + * + * @param hosts + * @param props + * @throws SQLException + */ + LoadBalancingConnectionProxy(List hosts, Properties props) + throws SQLException { + this.hostList = hosts; + + int numHosts = this.hostList.size(); + + this.liveConnections = new HashMap(numHosts); + this.connectionsToHostsMap = new HashMap(numHosts); + this.responseTimes = new long[numHosts]; + this.hostsToListIndexMap = new HashMap(numHosts); + + for (int i = 0; i < numHosts; i++) { + this.hostsToListIndexMap.put(this.hostList.get(i), new Integer(i)); + } + + this.localProps = (Properties) props.clone(); + this.localProps.remove(NonRegisteringDriver.HOST_PROPERTY_KEY); + this.localProps.remove(NonRegisteringDriver.PORT_PROPERTY_KEY); + this.localProps.setProperty("useLocalSessionState", "true"); + + String strategy = this.localProps.getProperty("loadBalanceStrategy", + "random"); + + if ("random".equals(strategy)) { + this.balancer = new RandomBalanceStrategy(); + } else if ("bestResponseTime".equals(strategy)) { + this.balancer = new BestResponseTimeBalanceStrategy(); + } else { + throw SQLError.createSQLException(Messages.getString( + "InvalidLoadBalanceStrategy", new Object[] { strategy }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + pickNewConnection(); + } + + /** + * Creates a new physical connection for the given host:port and updates + * required internal mappings and statistics for that connection. + * + * @param hostPortSpec + * @return + * @throws SQLException + */ + private synchronized Connection createConnectionForHost(String hostPortSpec) + throws SQLException { + Properties connProps = (Properties) this.localProps.clone(); + + String[] hostPortPair = NonRegisteringDriver + .parseHostPortPair(hostPortSpec); + + if (hostPortPair[1] == null) { + hostPortPair[1] = "3306"; + } + + connProps.setProperty(NonRegisteringDriver.HOST_PROPERTY_KEY, + hostPortSpec); + connProps.setProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, + hostPortPair[1]); + + Connection conn = new Connection(hostPortSpec, Integer + .parseInt(hostPortPair[1]), connProps, connProps + .getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY), + "jdbc:mysql://" + hostPortPair[0] + ":" + hostPortPair[1] + "/"); + + this.liveConnections.put(hostPortSpec, conn); + this.connectionsToHostsMap.put(conn, hostPortSpec); + + return conn; + } + + /** + * @param e + * @throws SQLException + * @throws Throwable + * @throws InvocationTargetException + */ + void dealWithInvocationException(InvocationTargetException e) + throws SQLException, Throwable, InvocationTargetException { + Throwable t = e.getTargetException(); + + if (t != null) { + if (t instanceof SQLException) { + String sqlState = ((SQLException) t).getSQLState(); + + if (sqlState != null) { + if (sqlState.startsWith("08")) { + // connection error, close up shop on current + // connection + invalidateCurrentConnection(); + } + } + } + + throw t; + } + + throw e; + } + + /** + * Closes current connection and removes it from required mappings. + * + * @throws SQLException + */ + synchronized void invalidateCurrentConnection() throws SQLException { + try { + if (!this.currentConn.isClosed()) { + this.currentConn.close(); + } + + } finally { + this.liveConnections.remove(this.connectionsToHostsMap + .get(this.currentConn)); + this.connectionsToHostsMap.remove(this.currentConn); + } + } + + /** + * Proxies method invocation on the java.sql.Connection interface, trapping + * "close", "isClosed" and "commit/rollback" (to switch connections for load + * balancing). + */ + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + + String methodName = method.getName(); + + if ("close".equals(methodName)) { + synchronized (this.liveConnections) { + // close all underlying connections + Iterator allConnections = this.liveConnections.values() + .iterator(); + + while (allConnections.hasNext()) { + ((Connection) allConnections.next()).close(); + } + + this.liveConnections.clear(); + this.connectionsToHostsMap.clear(); + } + + return null; + } + + if ("isClosed".equals(methodName)) { + return Boolean.valueOf(this.isClosed); + } + + if (this.isClosed) { + throw SQLError.createSQLException( + "No operations allowed after connection closed.", + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); + } + + if (!inTransaction) { + this.inTransaction = true; + this.transactionStartTime = getLocalTimeBestResolution(); + } + + Object result = null; + + try { + result = method.invoke(this.currentConn, args); + + if (result != null) { + if (result instanceof com.mysql.jdbc.Statement) { + ((com.mysql.jdbc.Statement)result).setPingTarget(this); + } + + result = proxyIfInterfaceIsJdbc(result, result.getClass()); + } + } catch (InvocationTargetException e) { + dealWithInvocationException(e); + } finally { + if ("commit".equals(methodName) || "rollback".equals(methodName)) { + this.inTransaction = false; + + // Update stats + int hostIndex = ((Integer) this.hostsToListIndexMap + .get(this.connectionsToHostsMap.get(this.currentConn))) + .intValue(); + + synchronized (this.responseTimes) { + this.responseTimes[hostIndex] = getLocalTimeBestResolution() + - this.transactionStartTime; + } + + pickNewConnection(); + } + } + + return result; + } + + /** + * Picks the "best" connection to use for the next transaction based on the + * BalanceStrategy in use. + * + * @throws SQLException + */ + private synchronized void pickNewConnection() throws SQLException { + if (this.currentConn == null) { + this.currentConn = this.balancer.pickConnection(); + + return; + } + + Connection newConn = this.balancer.pickConnection(); + + newConn.setTransactionIsolation(this.currentConn + .getTransactionIsolation()); + newConn.setAutoCommit(this.currentConn.getAutoCommit()); + this.currentConn = newConn; + } + + /** + * Recursively checks for interfaces on the given object to determine if it + * implements a java.sql interface, and if so, proxies the instance so that + * we can catch and fire SQL errors. + * + * @param toProxy + * @param clazz + * @return + */ + Object proxyIfInterfaceIsJdbc(Object toProxy, Class clazz) { + Class[] interfaces = clazz.getInterfaces(); + + for (int i = 0; i < interfaces.length; i++) { + String packageName = interfaces[i].getPackage().getName(); + + if ("java.sql".equals(packageName) + || "javax.sql".equals(packageName)) { + return Proxy.newProxyInstance(toProxy.getClass() + .getClassLoader(), interfaces, + new ConnectionErrorFiringInvocationHandler(toProxy)); + } + + return proxyIfInterfaceIsJdbc(toProxy, interfaces[i]); + } + + return toProxy; + } + + /** + * Returns best-resolution representation of local time, using nanoTime() if + * availble, otherwise defaulting to currentTimeMillis(). + */ + private static long getLocalTimeBestResolution() { + if (getLocalTimeMethod != null) { + try { + return ((Long) getLocalTimeMethod.invoke(null, null)) + .longValue(); + } catch (IllegalArgumentException e) { + // ignore - we fall through to currentTimeMillis() + } catch (IllegalAccessException e) { + // ignore - we fall through to currentTimeMillis() + } catch (InvocationTargetException e) { + // ignore - we fall through to currentTimeMillis() + } + } + + return System.currentTimeMillis(); + } + + public synchronized void doPing() throws SQLException { + Iterator allConns = this.liveConnections.values().iterator(); + + while (allConns.hasNext()) { + ((Connection)allConns.next()).ping(); + } + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/LocalizedErrorMessages.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/LocalizedErrorMessages.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/LocalizedErrorMessages.properties 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,424 @@ +# +# Fixed +# + +ResultSet.Retrieved__1=Retrieved +ResultSet.Bad_format_for_BigDecimal=Bad format for BigDecimal ''{0}'' in column {1}. +ResultSet.Bad_format_for_BigInteger=Bad format for BigInteger ''{0}'' in column {1}. +ResultSet.Column_Index_out_of_range_low=Column Index out of range, {0} < 1. +ResultSet.Column_Index_out_of_range_high=Column Index out of range, {0} > {1}. +ResultSet.Value_is_out_of_range=Value ''{0}'' is out of range [{1}, {2}]. +ResultSet.Positioned_Update_not_supported=Positioned Update not supported. +ResultSet.Bad_format_for_Date=Bad format for DATE ''{0}'' in column {1}. +ResultSet.Bad_format_for_Column=Bad format for {0} ''{1}'' in column {2} ({3}). +ResultSet.Bad_format_for_number=Bad format for number ''{0}'' in column {1}. +ResultSet.Illegal_operation_on_empty_result_set=Illegal operation on empty result set. + +Statement.0=Connection is closed. +Statement.2=Unsupported character encoding ''{0}'' +Statement.5=Illegal value for setFetchDirection(). +Statement.7=Illegal value for setFetchSize(). +Statement.11=Illegal value for setMaxFieldSize(). +Statement.13=Can not set max field size > max allowed packet of {0} bytes. +Statement.15=setMaxRows() out of range. +Statement.19=Illegal flag for getMoreResults(int). +Statement.21=Illegal value for setQueryTimeout(). +Statement.27=Connection is read-only. +Statement.28=Queries leading to data modification are not allowed. +Statement.34=Connection is read-only. +Statement.35=Queries leading to data modification are not allowed. +Statement.40=Can not issue INSERT/UPDATE/DELETE with executeQuery(). +Statement.42=Connection is read-only. +Statement.43=Queries leading to data modification are not allowed. +Statement.46=Can not issue SELECT via executeUpdate(). +Statement.49=No operations allowed after statement closed. +Statement.57=Can not issue data manipulation statements with executeQuery(). +Statement.59=Can not issue NULL query. +Statement.61=Can not issue empty query. +Statement.63=Statement not closed explicitly. You should call close() on created +Statement.64=Statement instances from your code to be more efficient. + +UpdatableResultSet.1=Can not call deleteRow() when on insert row. +UpdatableResultSet.2=Can not call deleteRow() on empty result set. +UpdatableResultSet.3=Before start of result set. Can not call deleteRow(). +UpdatableResultSet.4=After end of result set. Can not call deleteRow(). +UpdatableResultSet.7=Not on insert row. +UpdatableResultSet.8=Can not call refreshRow() when on insert row. +UpdatableResultSet.9=Can not call refreshRow() on empty result set. +UpdatableResultSet.10=Before start of result set. Can not call refreshRow(). +UpdatableResultSet.11=After end of result set. Can not call refreshRow(). +UpdatableResultSet.12=refreshRow() called on row that has been deleted or had primary key changed. +UpdatableResultSet.34=Updatable result set created, but never updated. You should only create updatable result sets when you want to update/insert/delete values using the updateRow(), deleteRow() and insertRow() methods. +UpdatableResultSet.39=Unsupported character encoding ''{0}''. +UpdatableResultSet.43=Can not create updatable result sets when there is no currently selected database and MySQL server version < 4.1. + +# +# Possible re-names +# + +ResultSet.Query_generated_no_fields_for_ResultSet_57=Query generated no fields for ResultSet +ResultSet.Illegal_value_for_fetch_direction_64=Illegal value for fetch direction +ResultSet.Value_must_be_between_0_and_getMaxRows()_66=Value must be between 0 and getMaxRows() +ResultSet.Query_generated_no_fields_for_ResultSet_99=Query generated no fields for ResultSet +ResultSet.Cannot_absolute_position_to_row_0_110=Cannot absolute position to row 0 +ResultSet.Operation_not_allowed_after_ResultSet_closed_144=Operation not allowed after ResultSet closed +ResultSet.Before_start_of_result_set_146=Before start of result set +ResultSet.After_end_of_result_set_148=After end of result set +ResultSet.Query_generated_no_fields_for_ResultSet_133=Query generated no fields for ResultSet +ResultSet.ResultSet_is_from_UPDATE._No_Data_115=ResultSet is from UPDATE. No Data. +ResultSet.N/A_159=N/A + +# +# To fix +# + +ResultSet.Invalid_value_for_getFloat()_-____68=Invalid value for getFloat() - \' +ResultSet.Invalid_value_for_getInt()_-____74=Invalid value for getInt() - \' +ResultSet.Invalid_value_for_getLong()_-____79=Invalid value for getLong() - \' +ResultSet.Invalid_value_for_getFloat()_-____200=Invalid value for getFloat() - \' +ResultSet.___in_column__201=\' in column +ResultSet.Invalid_value_for_getInt()_-____206=Invalid value for getInt() - \' +ResultSet.___in_column__207=\' in column +ResultSet.Invalid_value_for_getLong()_-____211=Invalid value for getLong() - \' +ResultSet.___in_column__212=\' in column +ResultSet.Invalid_value_for_getShort()_-____217=Invalid value for getShort() - \' +ResultSet.___in_column__218=\' in column + +ResultSet.Class_not_found___91=Class not found: +ResultSet._while_reading_serialized_object_92=\ while reading serialized object + +ResultSet.Invalid_value_for_getShort()_-____96=Invalid value for getShort() - \' +ResultSet.Unsupported_character_encoding____101=Unsupported character encoding \' + +ResultSet.Malformed_URL____104=Malformed URL \' +ResultSet.Malformed_URL____107=Malformed URL \' +ResultSet.Malformed_URL____141=Malformed URL \' + +ResultSet.Column____112=Column \' +ResultSet.___not_found._113=\' not found. + +ResultSet.Unsupported_character_encoding____135=Unsupported character encoding \' +ResultSet.Unsupported_character_encoding____138=Unsupported character encoding \' + +# +# Usage advisor messages for ResultSets +# + +ResultSet.ResultSet_implicitly_closed_by_driver=ResultSet implicitly closed by driver.\n\nYou should close ResultSets explicitly from your code to free up resources in a more efficient manner. +ResultSet.Possible_incomplete_traversal_of_result_set=Possible incomplete traversal of result set. Cursor was left on row {0} of {1} rows when it was closed.\n\nYou should consider re-formulating your query to return only the rows you are interested in using. +ResultSet.The_following_columns_were_never_referenced=The following columns were part of the SELECT statement for this result set, but were never referenced: +ResultSet.Too_Large_Result_Set=Result set size of {0} rows is larger than \"resultSetSizeThreshold\" of {1} rows. Application may be requesting more data than it is using. Consider reformulating the query. +ResultSet.CostlyConversion=ResultSet type conversion via parsing detected when calling {0} for column {1} (column named '{2}') in table '{3}'{4}\n\nJava class of column type is '{5}', MySQL field type is '{6}'.\n\nTypes that could be converted directly without parsing are:\n{7} +ResultSet.CostlyConversionCreatedFromQuery= created from query:\n\n + +ResultSet.Value____173=Value \' +ResultSetMetaData.46=Column index out of range. +ResultSet.___is_out_of_range_[-127,127]_174=\' is out of range [-127,127] +ResultSet.Bad_format_for_Date____180=Bad format for Date \' + +ResultSet.Timestamp_too_small_to_convert_to_Time_value_in_column__223=Timestamp too small to convert to Time value in column +ResultSet.Precision_lost_converting_TIMESTAMP_to_Time_with_getTime()_on_column__227=Precision lost converting TIMESTAMP to Time with getTime() on column +ResultSet.Precision_lost_converting_DATETIME_to_Time_with_getTime()_on_column__230=Precision lost converting DATETIME to Time with getTime() on column +ResultSet.Bad_format_for_Time____233=Bad format for Time \' +ResultSet.___in_column__234=\' in column +ResultSet.Bad_format_for_Timestamp____244=Bad format for Timestamp \' +ResultSet.___in_column__245=\' in column +ResultSet.Cannot_convert_value____249=Cannot convert value \' +ResultSet.___from_column__250=\' from column +ResultSet._)_to_TIMESTAMP._252=\ ) to TIMESTAMP. +ResultSet.Timestamp_too_small_to_convert_to_Time_value_in_column__257=Timestamp too small to convert to Time value in column +ResultSet.Precision_lost_converting_TIMESTAMP_to_Time_with_getTime()_on_column__261=Precision lost converting TIMESTAMP to Time with getTime() on column +ResultSet.Precision_lost_converting_DATETIME_to_Time_with_getTime()_on_column__264=Precision lost converting DATETIME to Time with getTime() on column +ResultSet.Bad_format_for_Time____267=Bad format for Time \' +ResultSet.___in_column__268=\' in column +ResultSet.Bad_format_for_Timestamp____278=Bad format for Timestamp \' +ResultSet.___in_column__279=\' in column +ResultSet.Cannot_convert_value____283=Cannot convert value \' +ResultSet.___from_column__284=\' from column +ResultSet._)_to_TIMESTAMP._286=\ ) to TIMESTAMP. + +CallableStatement.2=Parameter name can not be NULL or zero-length. +CallableStatement.3=No parameter named ' +CallableStatement.4=' +CallableStatement.5=Parameter named ' +CallableStatement.6=' is not an OUT parameter +CallableStatement.7=No output parameters registered. +CallableStatement.8=No output parameters returned by procedure. +CallableStatement.9=Parameter number +CallableStatement.10=\ is not an OUT parameter +CallableStatement.11=Parameter index of +CallableStatement.12=\ is out of range (1, +CallableStatement.13=) +CallableStatement.14=Can not use streaming result sets with callable statements that have output parameters +CallableStatement.1=Unable to retrieve metadata for procedure. +CallableStatement.0=Parameter name can not be +CallableStatement.15=null. +CallableStatement.16=empty. +CallableStatement.21=Parameter +CallableStatement.22=\ is not registered as an output parameter + +CommunicationsException.2=\ is longer than the server configured value of +CommunicationsException.3='wait_timeout' +CommunicationsException.4='interactive_timeout' +CommunicationsException.5=may or may not be greater than the server-side timeout +CommunicationsException.6=(the driver was unable to determine the value of either the +CommunicationsException.7='wait_timeout' or 'interactive_timeout' configuration values from +CommunicationsException.8=the server. +CommunicationsException.9=The last communications with the server was +CommunicationsException.10=\ seconds ago, which +CommunicationsException.11=. You should consider either expiring and/or testing connection validity +CommunicationsException.12=before use in your application, increasing the server configured values for client timeouts, +CommunicationsException.13=or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. +CommunicationsException.14=The driver was unable to create a connection due to +CommunicationsException.15=an inability to establish the client portion of a socket.\n\n +CommunicationsException.16=This is usually caused by a limit on the number of sockets imposed by +CommunicationsException.17=the operating system. This limit is usually configurable. \n\n +CommunicationsException.18=For Unix-based platforms, see the manual page for the 'ulimit' command. Kernel or system reconfiguration may also be required. +CommunicationsException.19=\n\nFor Windows-based platforms, see Microsoft Knowledge Base Article 196271 (Q196271). +CommunicationsException.19a=The configuration parameter \"localSocketAddress\" has been set to a network interface not available for use by the JVM. +CommunicationsException.20=Communications link failure +CommunicationsException.21=\ due to underlying exception: +CommunicationsException.ClientWasStreaming=Application was streaming results when the connection failed. Consider raising value of 'net_write_timeout' on the server. +NonRegisteringDriver.3=Hostname of MySQL Server +NonRegisteringDriver.7=Port number of MySQL Server +NonRegisteringDriver.13=Username to authenticate as +NonRegisteringDriver.16=Password to use for authentication +NonRegisteringDriver.17=Cannot load connection class because of underlying exception: ' +NonRegisteringDriver.18='. +NonRegisteringDriver.37=Must specify port after ':' in connection string +SQLError.35=Disconnect error +SQLError.36=Data truncated +SQLError.37=Privilege not revoked +SQLError.38=Invalid connection string attribute +SQLError.39=Error in row +SQLError.40=No rows updated or deleted +SQLError.41=More than one row updated or deleted +SQLError.42=Wrong number of parameters +SQLError.43=Unable to connect to data source +SQLError.44=Connection in use +SQLError.45=Connection not open +SQLError.46=Data source rejected establishment of connection +SQLError.47=Connection failure during transaction +SQLError.48=Communication link failure +SQLError.49=Insert value list does not match column list +SQLError.50=Numeric value out of range +SQLError.51=Datetime field overflow +SQLError.52=Division by zero +SQLError.53=Deadlock found when trying to get lock; Try restarting transaction +SQLError.54=Invalid authorization specification +SQLError.55=Syntax error or access violation +SQLError.56=Base table or view not found +SQLError.57=Base table or view already exists +SQLError.58=Base table not found +SQLError.59=Index already exists +SQLError.60=Index not found +SQLError.61=Column already exists +SQLError.62=Column not found +SQLError.63=No default for column +SQLError.64=General error +SQLError.65=Memory allocation failure +SQLError.66=Invalid column number +SQLError.67=Invalid argument value +SQLError.68=Driver not capable +SQLError.69=Timeout expired +ChannelBuffer.0=Unsupported character encoding ' +ChannelBuffer.1=' +Field.12=Unsupported character encoding ' +Field.13=' +Blob.0=indexToWriteAt must be >= 1 +Blob.1=IO Error while writing bytes to blob +Blob.2=Position 'pos' can not be < 1 +StringUtils.0=Unsupported character encoding ' +StringUtils.1='. +StringUtils.5=Unsupported character encoding ' +StringUtils.6='. +StringUtils.10=Unsupported character encoding ' +StringUtils.11='. +RowDataDynamic.2=WARN: Possible incomplete traversal of result set. Streaming result set had +RowDataDynamic.3=\ rows left to read when it was closed. +RowDataDynamic.4=\n\nYou should consider re-formulating your query to +RowDataDynamic.5=return only the rows you are interested in using. +RowDataDynamic.6=\n\nResultSet was created at: +RowDataDynamic.7=\n\nNested Stack Trace:\n +RowDataDynamic.8=Error retrieving record: Unexpected Exception: +RowDataDynamic.9=\ message given: +RowDataDynamic.10=Operation not supported for streaming result sets +Clob.0=indexToWriteAt must be >= 1 +Clob.1=indexToWriteAt must be >= 1 +Clob.2=Starting position can not be < 1 +Clob.3=String to set can not be NULL +Clob.4=Starting position can not be < 1 +Clob.5=String to set can not be NULL +Clob.6=CLOB start position can not be < 1 +Clob.7=CLOB start position + length can not be > length of CLOB +Clob.8=Illegal starting position for search, ' +Clob.9=' +Clob.10=Starting position for search is past end of CLOB +Clob.11=Cannot truncate CLOB of length +Clob.12=\ to length of +Clob.13=. +PacketTooBigException.0=Packet for query is too large ( +PacketTooBigException.1=\ > +PacketTooBigException.2=). +PacketTooBigException.3=You can change this value on the server by setting the +PacketTooBigException.4=max_allowed_packet' variable. +Util.1=\n\n** BEGIN NESTED EXCEPTION ** \n\n +Util.2=\nMESSAGE: +Util.3=\n\nSTACKTRACE:\n\n +Util.4=\n\n** END NESTED EXCEPTION **\n\n +MiniAdmin.0=Conection can not be null. +MiniAdmin.1=MiniAdmin can only be used with MySQL connections +NamedPipeSocketFactory.2=Can not specify NULL or empty value for property ' +NamedPipeSocketFactory.3='. +NamedPipeSocketFactory.4=Named pipe path can not be null or empty +MysqlIO.1=Unexpected end of input stream +MysqlIO.2=Reading packet of length +MysqlIO.3=\nPacket header:\n +MysqlIO.4=readPacket() payload:\n +MysqlIO.8=Slow query explain results for ' +MysqlIO.9=' :\n\n +MysqlIO.10=\ message from server: " +MysqlIO.15=SSL Connection required, but not supported by server. +MysqlIO.17=Attempt to close streaming result set +MysqlIO.18=\ when no streaming result set was registered. This is an internal error. +MysqlIO.19=Attempt to close streaming result set +MysqlIO.20=\ that was not registered. +MysqlIO.21=\ Only one streaming result set may be open and in use per-connection. Ensure that you have called .close() on +MysqlIO.22=\ any active result sets before attempting more queries. +MysqlIO.23=Can not use streaming results with multiple result statements +MysqlIO.25=\ ... (truncated) +MysqlIO.SlowQuery=Slow query (exceeded {0} {1}, duration: {2} {1}): +Nanoseconds=ns +Milliseconds=ms +MysqlIO.28=Not issuing EXPLAIN for query of size > +MysqlIO.29=\ bytes. +MysqlIO.33=The following query was executed with a bad index, use 'EXPLAIN' for more details: +MysqlIO.35=The following query was executed using no index, use 'EXPLAIN' for more details: +MysqlIO.36=\n\nLarge packet dump truncated at +MysqlIO.37=\ bytes. +MysqlIO.39=Streaming result set +MysqlIO.40=\ is still active. +MysqlIO.41=\ No statements may be issued when any streaming result sets are open and in use on a given connection. +MysqlIO.42=\ Ensure that you have called .close() on any active streaming result sets before attempting more queries. +MysqlIO.43=Unexpected end of input stream +MysqlIO.44=Reading reusable packet of length +MysqlIO.45=\nPacket header:\n +MysqlIO.46=reuseAndReadPacket() payload:\n +MysqlIO.47=Unexpected end of input stream +MysqlIO.48=Unexpected end of input stream +MysqlIO.49=Packets received out of order +MysqlIO.50=Short read from server, expected +MysqlIO.51=\ bytes, received only +MysqlIO.53=Packets received out of order +MysqlIO.54=Short read from server, expected +MysqlIO.55=\ bytes, received only +MysqlIO.57=send() compressed packet:\n +MysqlIO.58=\n\nOriginal packet (uncompressed):\n +MysqlIO.59=send() packet payload:\n +MysqlIO.60=Unable to open file +MysqlIO.63=for 'LOAD DATA LOCAL INFILE' command. +MysqlIO.64=Due to underlying IOException: +MysqlIO.65=Unable to close local file during LOAD DATA LOCAL INFILE command +MysqlIO.68=\ message from server: " +MysqlIO.70=Unknown column +MysqlIO.72=\ message from server: " +MysqlIO.75=No name specified for socket factory +MysqlIO.76=Could not create socket factory ' +MysqlIO.77=' due to underlying exception: +MysqlIO.79=Unexpected end of input stream +MysqlIO.80=Unexpected end of input stream +MysqlIO.81=Unexpected end of input stream +MysqlIO.82=Unexpected end of input stream +MysqlIO.83=Packets received out of order +MysqlIO.84=Packets received out of order +MysqlIO.85=Unexpected end of input stream +MysqlIO.86=Unexpected end of input stream +MysqlIO.87=Unexpected end of input stream +MysqlIO.88=Packets received out of order +MysqlIO.89=Packets received out of order +MysqlIO.91=Failed to create message digest 'SHA-1' for authentication. +MysqlIO.92=\ You must use a JDK that supports JCE to be able to use secure connection authentication +MysqlIO.93=Failed to create message digest 'SHA-1' for authentication. +MysqlIO.94=\ You must use a JDK that supports JCE to be able to use secure connection authentication +MysqlIO.95=Failed to create message digest 'SHA-1' for authentication. +MysqlIO.96=\ You must use a JDK that supports JCE to be able to use secure connection authentication +MysqlIO.97=Unknown type ' +MysqlIO.98=\ in column +MysqlIO.99=\ of +MysqlIO.100=\ in binary-encoded result set. +MysqlIO.102=, underlying cause: +MysqlIO.EOF=Can not read response from server. Expected to read {0} bytes, read {1} bytes before connection was unexpectedly lost. +MysqlIO.NoInnoDBStatusFound=No InnoDB status output returned by server. +MysqlIO.InnoDBStatusFailed=Couldn't retrieve InnoDB status due to underlying exception: +MysqlIO.LoadDataLocalNotAllowed=Server asked for stream in response to LOAD DATA LOCAL INFILE but functionality is disabled at client by 'allowLoadLocalInfile' being set to 'false'. +NotImplemented.0=Feature not implemented +PreparedStatement.0=SQL String can not be NULL +PreparedStatement.1=SQL String can not be NULL +PreparedStatement.2=Parameter index out of range ( +PreparedStatement.3=\ > +PreparedStatement.4=) +PreparedStatement.16=Unknown Types value +PreparedStatement.17=Cannot convert +PreparedStatement.18=\ to SQL type requested due to +PreparedStatement.19=\ - +PreparedStatement.20=Connection is read-only. +PreparedStatement.21=Queries leading to data modification are not allowed +PreparedStatement.25=Connection is read-only. +PreparedStatement.26=Queries leading to data modification are not allowed +PreparedStatement.32=Unsupported character encoding ' +PreparedStatement.33=' +PreparedStatement.34=Connection is read-only. +PreparedStatement.35=Queries leading to data modification are not allowed +PreparedStatement.37=Can not issue executeUpdate() for SELECTs +PreparedStatement.40=No value specified for parameter +PreparedStatement.43=PreparedStatement created, but used 1 or fewer times. It is more efficient to prepare statements once, and re-use them many times +PreparedStatement.48=PreparedStatement has been closed. No further operations allowed. +PreparedStatement.49=Parameter index out of range ( +PreparedStatement.50=\ < 1 ). +PreparedStatement.51=Parameter index out of range ( +PreparedStatement.52=\ > number of parameters, which is +PreparedStatement.53=). +PreparedStatement.54=Invalid argument value: +PreparedStatement.55=Error reading from InputStream +PreparedStatement.56=Error reading from InputStream +PreparedStatement.61=SQL String can not be NULL +ServerPreparedStatement.2=Connection is read-only. +ServerPreparedStatement.3=Queries leading to data modification are not allowed +ServerPreparedStatement.6=\ unable to materialize as string due to underlying SQLException: +ServerPreparedStatement.7=Not supported for server-side prepared statements. +ServerPreparedStatement.8=No parameters defined during prepareCall() +ServerPreparedStatement.9=Parameter index out of bounds. +ServerPreparedStatement.10=\ is not between valid values of 1 and +ServerPreparedStatement.11=Driver can not re-execute prepared statement when a parameter has been changed +ServerPreparedStatement.12=from a streaming type to an intrinsic data type without calling clearParameters() first. +ServerPreparedStatement.13=Statement parameter +ServerPreparedStatement.14=\ not set. +ServerPreparedStatement.15=Slow query (exceeded +ServerPreparedStatement.15a=\ ms., duration:\ +ServerPreparedStatement.16=\ ms): +ServerPreparedStatement.18=Unknown LONG DATA type ' +ServerPreparedStatement.22=Unsupported character encoding ' +ServerPreparedStatement.24=Error while reading binary stream: +ServerPreparedStatement.25=Error while reading binary stream: +ByteArrayBuffer.0=ByteArrayBuffer has no NIO buffers +ByteArrayBuffer.1=Unsupported character encoding ' +AssertionFailedException.0=ASSERT FAILS: Exception +AssertionFailedException.1=\ that should not be thrown, was thrown + +NotUpdatable.0=Result Set not updatable. +NotUpdatable.1=This result set must come from a statement +NotUpdatable.2=that was created with a result set type of ResultSet.CONCUR_UPDATABLE, +NotUpdatable.3=the query must select only one table, can not use functions and must +NotUpdatable.4=select all primary keys from that table. See the JDBC 2.1 API Specification, +NotUpdatable.5=section 5.6 for more details. +NotUpdatableReason.0=Result Set not updatable (references more than one table). +NotUpdatableReason.1=Result Set not updatable (references more than one database). +NotUpdatableReason.2=Result Set not updatable (references no tables). +NotUpdatableReason.3=Result Set not updatable (references computed values or doesn't reference any columns or tables). +NotUpdatableReason.4=Result Set not updatable (references no primary keys). +NotUpdatableReason.5=Result Set not updatable (referenced table has no primary keys). +NotUpdatableReason.6=Result Set not updatable (references unknown primary key {0}). +NotUpdatableReason.7=Result Set not updatable (does not reference all primary keys). + +InvalidLoadBalanceStrategy=Invalid load balancing strategy '{0}'. +Connection.Connection.BadValueInServerVariables=Invalid value '{1}' for server variable named '{0}', falling back to sane default of '{2}'. Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Messages.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Messages.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Messages.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,112 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.text.MessageFormat; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +/** + * Support for localized messages. + * + * @author Mark Matthews + * @version $Id: Messages.java,v 1.1 2012/08/17 14:57:10 marcin Exp $ + */ +public class Messages { + + private static final String BUNDLE_NAME = "com.mysql.jdbc.LocalizedErrorMessages"; //$NON-NLS-1$ + + private static final ResourceBundle RESOURCE_BUNDLE; + + static { + ResourceBundle temp = null; + + // + // Overly-pedantic here, some appserver and JVM combos don't deal + // well with the no-args version, others don't deal well with + // the three-arg version, so we need to try both :( + // + + try { + temp = ResourceBundle.getBundle(BUNDLE_NAME, Locale.getDefault(), + Messages.class.getClassLoader()); + } catch (Throwable t) { + try { + temp = ResourceBundle.getBundle(BUNDLE_NAME); + } catch (Throwable t2) { + throw new RuntimeException( + "Can't load resource bundle due to underlying exception " + + t.toString()); + } + } finally { + RESOURCE_BUNDLE = temp; + } + } + + /** + * Returns the localized message for the given message key + * + * @param key + * the message key + * @return The localized message for the key + */ + public static String getString(String key) { + if (RESOURCE_BUNDLE == null) { + throw new RuntimeException( + "Localized messages from resource bundle '" + BUNDLE_NAME + + "' not loaded during initialization of driver."); + } + + try { + if (key == null) { + throw new IllegalArgumentException( + "Message key can not be null"); + } + + String message = RESOURCE_BUNDLE.getString(key); + + if (message == null) { + message = "Missing error message for key '" + key + "'"; + } + + return message; + } catch (MissingResourceException e) { + return '!' + key + '!'; + } + } + + public static String getString(String key, Object[] args) { + return MessageFormat.format(getString(key), args); + } + + /** + * Dis-allow construction ... + */ + private Messages() { + + // XXX Auto-generated constructor stub + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/MiniAdmin.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/MiniAdmin.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/MiniAdmin.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,110 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +import java.util.Properties; + +/** + * Utility functions for admin functionality from Java. + * + * @author Mark Matthews + */ +public class MiniAdmin { + // ~ Instance fields + // -------------------------------------------------------- + + private Connection conn; + + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Create a new MiniAdmin using the given connection + * + * @param conn + * the existing connection to use. + * + * @throws SQLException + * if an error occurs + */ + public MiniAdmin(java.sql.Connection conn) throws SQLException { + if (conn == null) { + throw SQLError.createSQLException( + Messages.getString("MiniAdmin.0"), SQLError.SQL_STATE_GENERAL_ERROR); //$NON-NLS-1$ + } + + if (!(conn instanceof Connection)) { + throw SQLError.createSQLException(Messages.getString("MiniAdmin.1"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + + this.conn = (Connection) conn; + } + + /** + * Create a new MiniAdmin, connecting using the given JDBC URL. + * + * @param jdbcUrl + * the JDBC URL to use + * + * @throws SQLException + * if an error occurs + */ + public MiniAdmin(String jdbcUrl) throws SQLException { + this(jdbcUrl, new Properties()); + } + + /** + * Create a new MiniAdmin, connecting using the given JDBC URL and + * properties + * + * @param jdbcUrl + * the JDBC URL to use + * @param props + * the properties to use when connecting + * + * @throws SQLException + * if an error occurs + */ + public MiniAdmin(String jdbcUrl, Properties props) throws SQLException { + this.conn = (Connection) (new Driver().connect(jdbcUrl, props)); + } + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Shuts down the MySQL server at the other end of the connection that this + * MiniAdmin was created from/for. + * + * @throws SQLException + * if an error occurs + */ + public void shutdown() throws SQLException { + this.conn.shutdownServer(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlDataTruncation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlDataTruncation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlDataTruncation.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,74 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.DataTruncation; + +/** + * MySQL wrapper for DataTruncation until the server can support sending all + * needed information. + * + * @author Mark Matthews + * + * @version $Id: MysqlDataTruncation.java,v 1.1.2.1 2005/05/13 18:58:38 + * mmatthews Exp $ + */ +public class MysqlDataTruncation extends DataTruncation { + + private String message; + + /** + * Creates a new MysqlDataTruncation exception/warning. + * + * @param message + * the message from the server + * @param index + * of column or parameter + * @param parameter + * was a parameter? + * @param read + * was truncated on read? + * @param dataSize + * size requested + * @param transferSize + * size actually used + */ + public MysqlDataTruncation(String message, int index, boolean parameter, + boolean read, int dataSize, int transferSize) { + super(index, parameter, read, dataSize, transferSize); + + this.message = message; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Throwable#getMessage() + */ + public String getMessage() { + // TODO Auto-generated method stub + return super.getMessage() + ": " + this.message; //$NON-NLS-1$ + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlDefs.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlDefs.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlDefs.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,592 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.Types; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * MysqlDefs contains many values that are needed for communication with the + * MySQL server. + * + * @author Mark Matthews + * @version $Id: MysqlDefs.java,v 1.1 2012/08/17 14:57:08 marcin Exp $ + */ +final class MysqlDefs { + // ~ Static fields/initializers + // --------------------------------------------- + + static final int COM_BINLOG_DUMP = 18; + + static final int COM_CHANGE_USER = 17; + + static final int COM_CLOSE_STATEMENT = 25; + + static final int COM_CONNECT_OUT = 20; + + static final int COM_END = 29; + + static final int COM_EXECUTE = 23; + + static final int COM_FETCH = 28; + + static final int COM_LONG_DATA = 24; + + static final int COM_PREPARE = 22; + + static final int COM_REGISTER_SLAVE = 21; + + static final int COM_RESET_STMT = 26; + + static final int COM_SET_OPTION = 27; + + static final int COM_TABLE_DUMP = 19; + + static final int CONNECT = 11; + + static final int CREATE_DB = 5; + + static final int DEBUG = 13; + + static final int DELAYED_INSERT = 16; + + static final int DROP_DB = 6; + + static final int FIELD_LIST = 4; + + static final int FIELD_TYPE_BIT = 16; + + static final int FIELD_TYPE_BLOB = 252; + + static final int FIELD_TYPE_DATE = 10; + + static final int FIELD_TYPE_DATETIME = 12; + + // Data Types + static final int FIELD_TYPE_DECIMAL = 0; + + static final int FIELD_TYPE_DOUBLE = 5; + + static final int FIELD_TYPE_ENUM = 247; + + static final int FIELD_TYPE_FLOAT = 4; + + static final int FIELD_TYPE_GEOMETRY = 255; + + static final int FIELD_TYPE_INT24 = 9; + + static final int FIELD_TYPE_LONG = 3; + + static final int FIELD_TYPE_LONG_BLOB = 251; + + static final int FIELD_TYPE_LONGLONG = 8; + + static final int FIELD_TYPE_MEDIUM_BLOB = 250; + + static final int FIELD_TYPE_NEW_DECIMAL = 246; + + static final int FIELD_TYPE_NEWDATE = 14; + + static final int FIELD_TYPE_NULL = 6; + + static final int FIELD_TYPE_SET = 248; + + static final int FIELD_TYPE_SHORT = 2; + + static final int FIELD_TYPE_STRING = 254; + + static final int FIELD_TYPE_TIME = 11; + + static final int FIELD_TYPE_TIMESTAMP = 7; + + static final int FIELD_TYPE_TINY = 1; + + // Older data types + static final int FIELD_TYPE_TINY_BLOB = 249; + + static final int FIELD_TYPE_VAR_STRING = 253; + + static final int FIELD_TYPE_VARCHAR = 15; + + // Newer data types + static final int FIELD_TYPE_YEAR = 13; + + static final int INIT_DB = 2; + + static final long LENGTH_BLOB = 65535; + + static final long LENGTH_LONGBLOB = 4294967295L; + + static final long LENGTH_MEDIUMBLOB = 16777215; + + static final long LENGTH_TINYBLOB = 255; + + // Limitations + static final int MAX_ROWS = 50000000; // From the MySQL FAQ + + /** + * Used to indicate that the server sent no field-level character set + * information, so the driver should use the connection-level character + * encoding instead. + */ + public static final int NO_CHARSET_INFO = -1; + + static final byte OPEN_CURSOR_FLAG = 1; + + static final int PING = 14; + + static final int PROCESS_INFO = 10; + + static final int PROCESS_KILL = 12; + + static final int QUERY = 3; + + static final int QUIT = 1; + + // ~ Methods + // ---------------------------------------------------------------- + + static final int RELOAD = 7; + + static final int SHUTDOWN = 8; + + // + // Constants defined from mysql + // + // DB Operations + static final int SLEEP = 0; + + static final int STATISTICS = 9; + + static final int TIME = 15; + + /** + * Maps the given MySQL type to the correct JDBC type. + */ + static int mysqlToJavaType(int mysqlType) { + int jdbcType; + + switch (mysqlType) { + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + case MysqlDefs.FIELD_TYPE_DECIMAL: + jdbcType = Types.DECIMAL; + + break; + + case MysqlDefs.FIELD_TYPE_TINY: + jdbcType = Types.TINYINT; + + break; + + case MysqlDefs.FIELD_TYPE_SHORT: + jdbcType = Types.SMALLINT; + + break; + + case MysqlDefs.FIELD_TYPE_LONG: + jdbcType = Types.INTEGER; + + break; + + case MysqlDefs.FIELD_TYPE_FLOAT: + jdbcType = Types.REAL; + + break; + + case MysqlDefs.FIELD_TYPE_DOUBLE: + jdbcType = Types.DOUBLE; + + break; + + case MysqlDefs.FIELD_TYPE_NULL: + jdbcType = Types.NULL; + + break; + + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + jdbcType = Types.TIMESTAMP; + + break; + + case MysqlDefs.FIELD_TYPE_LONGLONG: + jdbcType = Types.BIGINT; + + break; + + case MysqlDefs.FIELD_TYPE_INT24: + jdbcType = Types.INTEGER; + + break; + + case MysqlDefs.FIELD_TYPE_DATE: + jdbcType = Types.DATE; + + break; + + case MysqlDefs.FIELD_TYPE_TIME: + jdbcType = Types.TIME; + + break; + + case MysqlDefs.FIELD_TYPE_DATETIME: + jdbcType = Types.TIMESTAMP; + + break; + + case MysqlDefs.FIELD_TYPE_YEAR: + jdbcType = Types.DATE; + + break; + + case MysqlDefs.FIELD_TYPE_NEWDATE: + jdbcType = Types.DATE; + + break; + + case MysqlDefs.FIELD_TYPE_ENUM: + jdbcType = Types.CHAR; + + break; + + case MysqlDefs.FIELD_TYPE_SET: + jdbcType = Types.CHAR; + + break; + + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + jdbcType = Types.VARBINARY; + + break; + + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + jdbcType = Types.LONGVARBINARY; + + break; + + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + jdbcType = Types.LONGVARBINARY; + + break; + + case MysqlDefs.FIELD_TYPE_BLOB: + jdbcType = Types.LONGVARBINARY; + + break; + + case MysqlDefs.FIELD_TYPE_VAR_STRING: + case MysqlDefs.FIELD_TYPE_VARCHAR: + jdbcType = Types.VARCHAR; + + break; + + case MysqlDefs.FIELD_TYPE_STRING: + jdbcType = Types.CHAR; + + break; + case MysqlDefs.FIELD_TYPE_GEOMETRY: + jdbcType = Types.BINARY; + + break; + case MysqlDefs.FIELD_TYPE_BIT: + jdbcType = Types.BIT; + + break; + default: + jdbcType = Types.VARCHAR; + } + + return jdbcType; + } + + /** + * Maps the given MySQL type to the correct JDBC type. + */ + static int mysqlToJavaType(String mysqlType) { + if (mysqlType.equalsIgnoreCase("BIT")) { + return mysqlToJavaType(FIELD_TYPE_BIT); + } else if (mysqlType.equalsIgnoreCase("TINYINT")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_TINY); + } else if (mysqlType.equalsIgnoreCase("SMALLINT")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_SHORT); + } else if (mysqlType.equalsIgnoreCase("MEDIUMINT")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_INT24); + } else if (mysqlType.equalsIgnoreCase("INT") || mysqlType.equalsIgnoreCase("INTEGER")) { //$NON-NLS-1$ //$NON-NLS-2$ + return mysqlToJavaType(FIELD_TYPE_LONG); + } else if (mysqlType.equalsIgnoreCase("BIGINT")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_LONGLONG); + } else if (mysqlType.equalsIgnoreCase("INT24")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_INT24); + } else if (mysqlType.equalsIgnoreCase("REAL")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_DOUBLE); + } else if (mysqlType.equalsIgnoreCase("FLOAT")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_FLOAT); + } else if (mysqlType.equalsIgnoreCase("DECIMAL")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_DECIMAL); + } else if (mysqlType.equalsIgnoreCase("NUMERIC")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_DECIMAL); + } else if (mysqlType.equalsIgnoreCase("DOUBLE")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_DOUBLE); + } else if (mysqlType.equalsIgnoreCase("CHAR")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_STRING); + } else if (mysqlType.equalsIgnoreCase("VARCHAR")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_VAR_STRING); + } else if (mysqlType.equalsIgnoreCase("DATE")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_DATE); + } else if (mysqlType.equalsIgnoreCase("TIME")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_TIME); + } else if (mysqlType.equalsIgnoreCase("YEAR")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_YEAR); + } else if (mysqlType.equalsIgnoreCase("TIMESTAMP")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_TIMESTAMP); + } else if (mysqlType.equalsIgnoreCase("DATETIME")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_DATETIME); + } else if (mysqlType.equalsIgnoreCase("TINYBLOB")) { //$NON-NLS-1$ + return java.sql.Types.BINARY; + } else if (mysqlType.equalsIgnoreCase("BLOB")) { //$NON-NLS-1$ + return java.sql.Types.LONGVARBINARY; + } else if (mysqlType.equalsIgnoreCase("MEDIUMBLOB")) { //$NON-NLS-1$ + return java.sql.Types.LONGVARBINARY; + } else if (mysqlType.equalsIgnoreCase("LONGBLOB")) { //$NON-NLS-1$ + return java.sql.Types.LONGVARBINARY; + } else if (mysqlType.equalsIgnoreCase("TINYTEXT")) { //$NON-NLS-1$ + return java.sql.Types.VARCHAR; + } else if (mysqlType.equalsIgnoreCase("TEXT")) { //$NON-NLS-1$ + return java.sql.Types.LONGVARCHAR; + } else if (mysqlType.equalsIgnoreCase("MEDIUMTEXT")) { //$NON-NLS-1$ + return java.sql.Types.LONGVARCHAR; + } else if (mysqlType.equalsIgnoreCase("LONGTEXT")) { //$NON-NLS-1$ + return java.sql.Types.LONGVARCHAR; + } else if (mysqlType.equalsIgnoreCase("ENUM")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_ENUM); + } else if (mysqlType.equalsIgnoreCase("SET")) { //$NON-NLS-1$ + return mysqlToJavaType(FIELD_TYPE_SET); + } else if (mysqlType.equalsIgnoreCase("GEOMETRY")) { + return mysqlToJavaType(FIELD_TYPE_GEOMETRY); + } else if (mysqlType.equalsIgnoreCase("BINARY")) { + return Types.BINARY; // no concrete type on the wire + } else if (mysqlType.equalsIgnoreCase("VARBINARY")) { + return Types.VARBINARY; // no concrete type on the wire + } else if (mysqlType.equalsIgnoreCase("BIT")) { + return mysqlToJavaType(FIELD_TYPE_BIT); + } + + // Punt + return java.sql.Types.OTHER; + } + + /** + * @param mysqlType + * @return + */ + public static String typeToName(int mysqlType) { + switch (mysqlType) { + case MysqlDefs.FIELD_TYPE_DECIMAL: + return "FIELD_TYPE_DECIMAL"; + + case MysqlDefs.FIELD_TYPE_TINY: + return "FIELD_TYPE_TINY"; + + case MysqlDefs.FIELD_TYPE_SHORT: + return "FIELD_TYPE_SHORT"; + + case MysqlDefs.FIELD_TYPE_LONG: + return "FIELD_TYPE_LONG"; + + case MysqlDefs.FIELD_TYPE_FLOAT: + return "FIELD_TYPE_FLOAT"; + + case MysqlDefs.FIELD_TYPE_DOUBLE: + return "FIELD_TYPE_DOUBLE"; + + case MysqlDefs.FIELD_TYPE_NULL: + return "FIELD_TYPE_NULL"; + + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + return "FIELD_TYPE_TIMESTAMP"; + + case MysqlDefs.FIELD_TYPE_LONGLONG: + return "FIELD_TYPE_LONGLONG"; + + case MysqlDefs.FIELD_TYPE_INT24: + return "FIELD_TYPE_INT24"; + + case MysqlDefs.FIELD_TYPE_DATE: + return "FIELD_TYPE_DATE"; + + case MysqlDefs.FIELD_TYPE_TIME: + return "FIELD_TYPE_TIME"; + + case MysqlDefs.FIELD_TYPE_DATETIME: + return "FIELD_TYPE_DATETIME"; + + case MysqlDefs.FIELD_TYPE_YEAR: + return "FIELD_TYPE_YEAR"; + + case MysqlDefs.FIELD_TYPE_NEWDATE: + return "FIELD_TYPE_NEWDATE"; + + case MysqlDefs.FIELD_TYPE_ENUM: + return "FIELD_TYPE_ENUM"; + + case MysqlDefs.FIELD_TYPE_SET: + return "FIELD_TYPE_SET"; + + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + return "FIELD_TYPE_TINY_BLOB"; + + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + return "FIELD_TYPE_MEDIUM_BLOB"; + + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + return "FIELD_TYPE_LONG_BLOB"; + + case MysqlDefs.FIELD_TYPE_BLOB: + return "FIELD_TYPE_BLOB"; + + case MysqlDefs.FIELD_TYPE_VAR_STRING: + return "FIELD_TYPE_VAR_STRING"; + + case MysqlDefs.FIELD_TYPE_STRING: + return "FIELD_TYPE_STRING"; + + case MysqlDefs.FIELD_TYPE_VARCHAR: + return "FIELD_TYPE_VARCHAR"; + + case MysqlDefs.FIELD_TYPE_GEOMETRY: + return "FIELD_TYPE_GEOMETRY"; + + default: + return " Unknown MySQL Type # " + mysqlType; + } + } + + private static Map mysqlToJdbcTypesMap = new HashMap(); + + static { + mysqlToJdbcTypesMap.put("BIT", new Integer( + mysqlToJavaType(FIELD_TYPE_BIT))); + + mysqlToJdbcTypesMap.put("TINYINT", new Integer( + mysqlToJavaType(FIELD_TYPE_TINY))); + mysqlToJdbcTypesMap.put("SMALLINT", new Integer( + mysqlToJavaType(FIELD_TYPE_SHORT))); + mysqlToJdbcTypesMap.put("MEDIUMINT", new Integer( + mysqlToJavaType(FIELD_TYPE_INT24))); + mysqlToJdbcTypesMap.put("INT", new Integer( + mysqlToJavaType(FIELD_TYPE_LONG))); + mysqlToJdbcTypesMap.put("INTEGER", new Integer( + mysqlToJavaType(FIELD_TYPE_LONG))); + mysqlToJdbcTypesMap.put("BIGINT", new Integer( + mysqlToJavaType(FIELD_TYPE_LONGLONG))); + mysqlToJdbcTypesMap.put("INT24", new Integer( + mysqlToJavaType(FIELD_TYPE_INT24))); + mysqlToJdbcTypesMap.put("REAL", new Integer( + mysqlToJavaType(FIELD_TYPE_DOUBLE))); + mysqlToJdbcTypesMap.put("FLOAT", new Integer( + mysqlToJavaType(FIELD_TYPE_FLOAT))); + mysqlToJdbcTypesMap.put("DECIMAL", new Integer( + mysqlToJavaType(FIELD_TYPE_DECIMAL))); + mysqlToJdbcTypesMap.put("NUMERIC", new Integer( + mysqlToJavaType(FIELD_TYPE_DECIMAL))); + mysqlToJdbcTypesMap.put("DOUBLE", new Integer( + mysqlToJavaType(FIELD_TYPE_DOUBLE))); + mysqlToJdbcTypesMap.put("CHAR", new Integer( + mysqlToJavaType(FIELD_TYPE_STRING))); + mysqlToJdbcTypesMap.put("VARCHAR", new Integer( + mysqlToJavaType(FIELD_TYPE_VAR_STRING))); + mysqlToJdbcTypesMap.put("DATE", new Integer( + mysqlToJavaType(FIELD_TYPE_DATE))); + mysqlToJdbcTypesMap.put("TIME", new Integer( + mysqlToJavaType(FIELD_TYPE_TIME))); + mysqlToJdbcTypesMap.put("YEAR", new Integer( + mysqlToJavaType(FIELD_TYPE_YEAR))); + mysqlToJdbcTypesMap.put("TIMESTAMP", new Integer( + mysqlToJavaType(FIELD_TYPE_TIMESTAMP))); + mysqlToJdbcTypesMap.put("DATETIME", new Integer( + mysqlToJavaType(FIELD_TYPE_DATETIME))); + mysqlToJdbcTypesMap.put("TINYBLOB", new Integer(java.sql.Types.BINARY)); + mysqlToJdbcTypesMap.put("BLOB", new Integer( + java.sql.Types.LONGVARBINARY)); + mysqlToJdbcTypesMap.put("MEDIUMBLOB", new Integer( + java.sql.Types.LONGVARBINARY)); + mysqlToJdbcTypesMap.put("LONGBLOB", new Integer( + java.sql.Types.LONGVARBINARY)); + mysqlToJdbcTypesMap + .put("TINYTEXT", new Integer(java.sql.Types.VARCHAR)); + mysqlToJdbcTypesMap + .put("TEXT", new Integer(java.sql.Types.LONGVARCHAR)); + mysqlToJdbcTypesMap.put("MEDIUMTEXT", new Integer( + java.sql.Types.LONGVARCHAR)); + mysqlToJdbcTypesMap.put("LONGTEXT", new Integer( + java.sql.Types.LONGVARCHAR)); + mysqlToJdbcTypesMap.put("ENUM", new Integer( + mysqlToJavaType(FIELD_TYPE_ENUM))); + mysqlToJdbcTypesMap.put("SET", new Integer( + mysqlToJavaType(FIELD_TYPE_SET))); + mysqlToJdbcTypesMap.put("GEOMETRY", new Integer( + mysqlToJavaType(FIELD_TYPE_GEOMETRY))); + } + + static final void appendJdbcTypeMappingQuery(StringBuffer buf, String mysqlTypeColumnName) { + + buf.append("CASE "); + Map typesMap = new HashMap(); + typesMap.putAll(mysqlToJdbcTypesMap); + typesMap.put("BINARY", new Integer(Types.BINARY)); + typesMap.put("VARBINARY", new Integer(Types.VARBINARY)); + + Iterator mysqlTypes = typesMap.keySet().iterator(); + + while (mysqlTypes.hasNext()) { + String mysqlTypeName = (String)mysqlTypes.next(); + buf.append(" WHEN "); + buf.append(mysqlTypeColumnName); + buf.append("='"); + buf.append(mysqlTypeName); + buf.append("' THEN "); + buf.append(typesMap.get(mysqlTypeName)); + + if (mysqlTypeName.equalsIgnoreCase("DOUBLE") || + mysqlTypeName.equalsIgnoreCase("FLOAT") || + mysqlTypeName.equalsIgnoreCase("DECIMAL") || + mysqlTypeName.equalsIgnoreCase("NUMERIC")) { + buf.append(" WHEN "); + buf.append(mysqlTypeColumnName); + buf.append("='"); + buf.append(mysqlTypeName); + buf.append(" unsigned' THEN "); + buf.append(typesMap.get(mysqlTypeName)); + } + } + + buf.append(" ELSE "); + buf.append(Types.OTHER); + buf.append(" END "); + + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlErrorNumbers.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlErrorNumbers.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlErrorNumbers.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,641 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Constants representing MySQL error numbers returned by the server in error + * messages. + * + * @author Mark Matthews + * + * @version $Id: MysqlErrorNumbers.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews + * Exp $ + */ +public final class MysqlErrorNumbers { + + public final static int ER_ABORTING_CONNECTION = 1152; + + public final static int ER_ACCESS_DENIED_ERROR = 1045; + + public final static int ER_ALTER_INFO = 1088; + + public final static int ER_AUTO_CONVERT = 1246; + + public final static int ER_BAD_DB_ERROR = 1049; + + public final static int ER_BAD_FIELD_ERROR = 1054; + + public final static int ER_BAD_FT_COLUMN = 1283; + + public final static int ER_BAD_HOST_ERROR = 1042; + + public final static int ER_BAD_NULL_ERROR = 1048; + + public final static int ER_BAD_SLAVE = 1200; + + public final static int ER_BAD_SLAVE_UNTIL_COND = 1277; + + public final static int ER_BAD_TABLE_ERROR = 1051; + + public final static int ER_BLOB_CANT_HAVE_DEFAULT = 1101; + + public final static int ER_BLOB_KEY_WITHOUT_LENGTH = 1170; + + public final static int ER_BLOB_USED_AS_KEY = 1073; + + public final static int ER_BLOBS_AND_NO_TERMINATED = 1084; + + public final static int ER_CANNOT_ADD_FOREIGN = 1215; + + public final static int ER_CANT_AGGREGATE_2COLLATIONS = 1267; + + public final static int ER_CANT_AGGREGATE_3COLLATIONS = 1270; + + public final static int ER_CANT_AGGREGATE_NCOLLATIONS = 1271; + + public final static int ER_CANT_CREATE_DB = 1006; + + public final static int ER_CANT_CREATE_FILE = 1004; + + public final static int ER_CANT_CREATE_TABLE = 1005; + + public final static int ER_CANT_CREATE_THREAD = 1135; + + public final static int ER_CANT_DELETE_FILE = 1011; + + public final static int ER_CANT_DO_THIS_DURING_AN_TRANSACTION = 1179; + + public final static int ER_CANT_DROP_FIELD_OR_KEY = 1091; + + public final static int ER_CANT_FIND_DL_ENTRY = 1127; + + public final static int ER_CANT_FIND_SYSTEM_REC = 1012; + + public final static int ER_CANT_FIND_UDF = 1122; + + public final static int ER_CANT_GET_STAT = 1013; + + public final static int ER_CANT_GET_WD = 1014; + + public final static int ER_CANT_INITIALIZE_UDF = 1123; + + public final static int ER_CANT_LOCK = 1015; + + public final static int ER_CANT_OPEN_FILE = 1016; + + public final static int ER_CANT_OPEN_LIBRARY = 1126; + + public final static int ER_CANT_READ_DIR = 1018; + + public final static int ER_CANT_REMOVE_ALL_FIELDS = 1090; + + public final static int ER_CANT_REOPEN_TABLE = 1137; + + public final static int ER_CANT_SET_WD = 1019; + + public final static int ER_CANT_UPDATE_WITH_READLOCK = 1223; + + public final static int ER_CANT_USE_OPTION_HERE = 1234; + + public final static int ER_CHECK_NO_SUCH_TABLE = 1177; + + public final static int ER_CHECK_NOT_IMPLEMENTED = 1178; + + public final static int ER_CHECKREAD = 1020; + + public final static int ER_COLLATION_CHARSET_MISMATCH = 1253; + + public final static int ER_COLUMNACCESS_DENIED_ERROR = 1143; + + public final static int ER_CON_COUNT_ERROR = 1040; + + public final static int ER_CONNECT_TO_MASTER = 1218; + + public final static int ER_CORRUPT_HELP_DB = 1244; + + public final static int ER_CRASHED_ON_REPAIR = 1195; + + public final static int ER_CRASHED_ON_USAGE = 1194; + + public final static int ER_CREATE_DB_WITH_READ_LOCK = 1209; + + public final static int ER_CUT_VALUE_GROUP_CONCAT = 1260; + + public final static int ER_CYCLIC_REFERENCE = 1245; + + public final static int ER_DB_CREATE_EXISTS = 1007; + + public final static int ER_DB_DROP_DELETE = 1009; + + public final static int ER_DB_DROP_EXISTS = 1008; + + public final static int ER_DB_DROP_RMDIR = 1010; + + public final static int ER_DBACCESS_DENIED_ERROR = 1044; + + public final static int ER_DELAYED_CANT_CHANGE_LOCK = 1150; + + public final static int ER_DELAYED_INSERT_TABLE_LOCKED = 1165; + + public final static int ER_DERIVED_MUST_HAVE_ALIAS = 1248; + + public final static int ER_DISK_FULL = 1021; + + public final static int ER_DROP_DB_WITH_READ_LOCK = 1208; + + public final static int ER_DROP_USER = 1268; + + public final static int ER_DUMP_NOT_IMPLEMENTED = 1185; + + public final static int ER_DUP_ARGUMENT = 1225; + + public final static int ER_DUP_ENTRY = 1062; + + public final static int ER_DUP_FIELDNAME = 1060; + + public final static int ER_DUP_KEY = 1022; + + public final static int ER_DUP_KEYNAME = 1061; + + public final static int ER_DUP_UNIQUE = 1169; + + public final static int ER_DUPLICATED_VALUE_IN_TYPE = 1291; + + public final static int ER_EMPTY_QUERY = 1065; + + public final static int ER_ERROR_DURING_CHECKPOINT = 1183; + + public final static int ER_ERROR_DURING_COMMIT = 1180; + + public final static int ER_ERROR_DURING_FLUSH_LOGS = 1182; + + public final static int ER_ERROR_DURING_ROLLBACK = 1181; + + public final static int ER_ERROR_MESSAGES = 298; + + public final static int ER_ERROR_ON_CLOSE = 1023; + + public final static int ER_ERROR_ON_READ = 1024; + + public final static int ER_ERROR_ON_RENAME = 1025; + + public final static int ER_ERROR_ON_WRITE = 1026; + + public final static int ER_ERROR_WHEN_EXECUTING_COMMAND = 1220; + + public final static int ER_FEATURE_DISABLED = 1289; + + public final static int ER_FIELD_SPECIFIED_TWICE = 1110; + + public final static int ER_FILE_EXISTS_ERROR = 1086; + + public final static int ER_FILE_NOT_FOUND = 1017; + + public final static int ER_FILE_USED = 1027; + + public final static int ER_FILSORT_ABORT = 1028; + + public final static int ER_FLUSH_MASTER_BINLOG_CLOSED = 1186; + + public final static int ER_FORCING_CLOSE = 1080; + + public final static int ER_FORM_NOT_FOUND = 1029; + + public final static int ER_FT_MATCHING_KEY_NOT_FOUND = 1191; + + public final static int ER_FUNCTION_NOT_DEFINED = 1128; + + public final static int ER_GET_ERRMSG = 1296; + + public final static int ER_GET_ERRNO = 1030; + + public final static int ER_GET_TEMPORARY_ERRMSG = 1297; + + public final static int ER_GLOBAL_VARIABLE = 1229; + + public final static int ER_GOT_SIGNAL = 1078; + + public final static int ER_GRANT_WRONG_HOST_OR_USER = 1145; + + public final static int ER_HANDSHAKE_ERROR = 1043; + + public final static int ER_HASHCHK = 1000; + + public final static int ER_HOST_IS_BLOCKED = 1129; + + public final static int ER_HOST_NOT_PRIVILEGED = 1130; + + public final static int ER_ILLEGAL_GRANT_FOR_TABLE = 1144; + + public final static int ER_ILLEGAL_HA = 1031; + + public final static int ER_ILLEGAL_REFERENCE = 1247; + + public final static int ER_INCORRECT_GLOBAL_LOCAL_VAR = 1238; + + public final static int ER_INDEX_REBUILD = 1187; + + public final static int ER_INSERT_INFO = 1092; + + public final static int ER_INVALID_DEFAULT = 1067; + + public final static int ER_INVALID_GROUP_FUNC_USE = 1111; + + public final static int ER_INVALID_ON_UPDATE = 1294; + + public final static int ER_INVALID_USE_OF_NULL = 1138; + + public final static int ER_IPSOCK_ERROR = 1081; + + public final static int ER_KEY_COLUMN_DOES_NOT_EXITS = 1072; + + public final static int ER_KEY_DOES_NOT_EXITS = 1176; + + public final static int ER_KEY_NOT_FOUND = 1032; + + public final static int ER_KEY_REF_DO_NOT_MATCH_TABLE_REF = 1240; + + public final static int ER_KILL_DENIED_ERROR = 1095; + + public final static int ER_LOAD_INFO = 1087; + + public final static int ER_LOCAL_VARIABLE = 1228; + + public final static int ER_LOCK_DEADLOCK = 1213; + + public final static int ER_LOCK_OR_ACTIVE_TRANSACTION = 1192; + + public final static int ER_LOCK_TABLE_FULL = 1206; + + public final static int ER_LOCK_WAIT_TIMEOUT = 1205; + + public final static int ER_MASTER = 1188; + + public final static int ER_MASTER_FATAL_ERROR_READING_BINLOG = 1236; + + public final static int ER_MASTER_INFO = 1201; + + public final static int ER_MASTER_NET_READ = 1189; + + public final static int ER_MASTER_NET_WRITE = 1190; + + public final static int ER_MISSING_SKIP_SLAVE = 1278; + + public final static int ER_MIX_OF_GROUP_FUNC_AND_FIELDS = 1140; + + public final static int ER_MIXING_NOT_ALLOWED = 1224; + + public final static int ER_MULTIPLE_PRI_KEY = 1068; + + public final static int ER_NET_ERROR_ON_WRITE = 1160; + + public final static int ER_NET_FCNTL_ERROR = 1155; + + public final static int ER_NET_PACKET_TOO_LARGE = 1153; + + public final static int ER_NET_PACKETS_OUT_OF_ORDER = 1156; + + public final static int ER_NET_READ_ERROR = 1158; + + public final static int ER_NET_READ_ERROR_FROM_PIPE = 1154; + + public final static int ER_NET_READ_INTERRUPTED = 1159; + + public final static int ER_NET_UNCOMPRESS_ERROR = 1157; + + public final static int ER_NET_WRITE_INTERRUPTED = 1161; + + public final static int ER_NEW_ABORTING_CONNECTION = 1184; + + public final static int ER_NISAMCHK = 1001; + + public final static int ER_NO = 1002; + + public final static int ER_NO_DB_ERROR = 1046; + + public final static int ER_NO_DEFAULT = 1230; + + public final static int ER_NO_PERMISSION_TO_CREATE_USER = 1211; + + public final static int ER_NO_RAID_COMPILED = 1174; + + public final static int ER_NO_REFERENCED_ROW = 1216; + + public final static int ER_NO_SUCH_INDEX = 1082; + + public final static int ER_NO_SUCH_TABLE = 1146; + + public final static int ER_NO_SUCH_THREAD = 1094; + + public final static int ER_NO_TABLES_USED = 1096; + + public final static int ER_NO_UNIQUE_LOGFILE = 1098; + + public final static int ER_NON_UNIQ_ERROR = 1052; + + public final static int ER_NON_UPDATABLE_TABLE = 1288; + + public final static int ER_NONEXISTING_GRANT = 1141; + + public final static int ER_NONEXISTING_TABLE_GRANT = 1147; + + public final static int ER_NONUNIQ_TABLE = 1066; + + public final static int ER_NORMAL_SHUTDOWN = 1077; + + public final static int ER_NOT_ALLOWED_COMMAND = 1148; + + public final static int ER_NOT_FORM_FILE = 1033; + + public final static int ER_NOT_KEYFILE = 1034; + + public final static int ER_NOT_SUPPORTED_AUTH_MODE = 1251; + + public final static int ER_NOT_SUPPORTED_YET = 1235; + + public final static int ER_NULL_COLUMN_IN_INDEX = 1121; + + public final static int ER_OLD_KEYFILE = 1035; + + public final static int ER_OPEN_AS_READONLY = 1036; + + public final static int ER_OPERAND_COLUMNS = 1241; + + public final static int ER_OPTION_PREVENTS_STATEMENT = 1290; + + public final static int ER_OUT_OF_RESOURCES = 1041; + + public final static int ER_OUT_OF_SORTMEMORY = 1038; + + public final static int ER_OUTOFMEMORY = 1037; + + public final static int ER_PARSE_ERROR = 1064; + + public final static int ER_PASSWORD_ANONYMOUS_USER = 1131; + + public final static int ER_PASSWORD_NO_MATCH = 1133; + + public final static int ER_PASSWORD_NOT_ALLOWED = 1132; + + public final static int ER_PRIMARY_CANT_HAVE_NULL = 1171; + + public final static int ER_QUERY_ON_MASTER = 1219; + + public final static int ER_READ_ONLY_TRANSACTION = 1207; + + public final static int ER_READY = 1076; + + public final static int ER_RECORD_FILE_FULL = 1114; + + public final static int ER_REGEXP_ERROR = 1139; + + public final static int ER_REQUIRES_PRIMARY_KEY = 1173; + + public final static int ER_REVOKE_GRANTS = 1269; + + public final static int ER_ROW_IS_REFERENCED = 1217; + + public final static int ER_SELECT_REDUCED = 1249; + + public final static int ER_SERVER_IS_IN_SECURE_AUTH_MODE = 1275; + + public final static int ER_SERVER_SHUTDOWN = 1053; + + public final static int ER_SET_CONSTANTS_ONLY = 1204; + + public final static int ER_SHUTDOWN_COMPLETE = 1079; + + public final static int ER_SLAVE_IGNORED_SSL_PARAMS = 1274; + + public final static int ER_SLAVE_IGNORED_TABLE = 1237; + + public final static int ER_SLAVE_MUST_STOP = 1198; + + public final static int ER_SLAVE_NOT_RUNNING = 1199; + + public final static int ER_SLAVE_THREAD = 1202; + + public final static int ER_SLAVE_WAS_NOT_RUNNING = 1255; + + public final static int ER_SLAVE_WAS_RUNNING = 1254; + + public final static int ER_SPATIAL_CANT_HAVE_NULL = 1252; + + public final static int ER_SPECIFIC_ACCESS_DENIED_ERROR = 1227; + + public final static int ER_STACK_OVERRUN = 1119; + + public final static int ER_SUBQUERY_NO_1_ROW = 1242; + + public final static int ER_SYNTAX_ERROR = 1149; + + public final static int ER_TABLE_CANT_HANDLE_AUTO_INCREMENT = 1164; + + public final static int ER_TABLE_CANT_HANDLE_BLOB = 1163; + + public final static int ER_TABLE_CANT_HANDLE_FT = 1214; + + public final static int ER_TABLE_EXISTS_ERROR = 1050; + + public final static int ER_TABLE_MUST_HAVE_COLUMNS = 1113; + + public final static int ER_TABLE_NOT_LOCKED = 1100; + + public final static int ER_TABLE_NOT_LOCKED_FOR_WRITE = 1099; + + public final static int ER_TABLEACCESS_DENIED_ERROR = 1142; + + public final static int ER_TABLENAME_NOT_ALLOWED_HERE = 1250; + + public final static int ER_TEXTFILE_NOT_READABLE = 1085; + + public final static int ER_TOO_BIG_FIELDLENGTH = 1074; + + public final static int ER_TOO_BIG_FOR_UNCOMPRESS = 1256; + + public final static int ER_TOO_BIG_ROWSIZE = 1118; + + public final static int ER_TOO_BIG_SELECT = 1104; + + public final static int ER_TOO_BIG_SET = 1097; + + public final static int ER_TOO_LONG_IDENT = 1059; + + public final static int ER_TOO_LONG_KEY = 1071; + + public final static int ER_TOO_LONG_STRING = 1162; + + public final static int ER_TOO_MANY_DELAYED_THREADS = 1151; + + public final static int ER_TOO_MANY_FIELDS = 1117; + + public final static int ER_TOO_MANY_KEY_PARTS = 1070; + + public final static int ER_TOO_MANY_KEYS = 1069; + + public final static int ER_TOO_MANY_ROWS = 1172; + + public final static int ER_TOO_MANY_TABLES = 1116; + + public final static int ER_TOO_MANY_USER_CONNECTIONS = 1203; + + public final static int ER_TOO_MUCH_AUTO_TIMESTAMP_COLS = 1293; + + public final static int ER_TRANS_CACHE_FULL = 1197; + + public final static int ER_TRUNCATED_WRONG_VALUE = 1292; + + public final static int ER_UDF_EXISTS = 1125; + + public final static int ER_UDF_NO_PATHS = 1124; + + public final static int ER_UNEXPECTED_EOF = 1039; + + public final static int ER_UNION_TABLES_IN_DIFFERENT_DIR = 1212; + + public final static int ER_UNKNOWN_CHARACTER_SET = 1115; + + public final static int ER_UNKNOWN_COLLATION = 1273; + + public final static int ER_UNKNOWN_COM_ERROR = 1047; + + public final static int ER_UNKNOWN_ERROR = 1105; + + public final static int ER_UNKNOWN_KEY_CACHE = 1284; + + public final static int ER_UNKNOWN_PROCEDURE = 1106; + + public final static int ER_UNKNOWN_STMT_HANDLER = 1243; + + public final static int ER_UNKNOWN_STORAGE_ENGINE = 1286; + + public final static int ER_UNKNOWN_SYSTEM_VARIABLE = 1193; + + public final static int ER_UNKNOWN_TABLE = 1109; + + public final static int ER_UNSUPPORTED_EXTENSION = 1112; + + public final static int ER_UNSUPPORTED_PS = 1295; + + public final static int ER_UNTIL_COND_IGNORED = 1279; + + public final static int ER_UPDATE_INFO = 1134; + + public final static int ER_UPDATE_TABLE_USED = 1093; + + public final static int ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE = 1175; + + public final static int ER_USER_LIMIT_REACHED = 1226; + + public final static int ER_VAR_CANT_BE_READ = 1233; + + public final static int ER_VARIABLE_IS_NOT_STRUCT = 1272; + + public final static int ER_WARN_DATA_OUT_OF_RANGE = 1264; + + public final static int ER_WARN_DATA_TRUNCATED = 1265; + + public final static int ER_WARN_DEPRECATED_SYNTAX = 1287; + + public final static int ER_WARN_FIELD_RESOLVED = 1276; + + public final static int ER_WARN_HOSTNAME_WONT_WORK = 1285; + + public final static int ER_WARN_NULL_TO_NOTNULL = 1263; + + public final static int ER_WARN_QC_RESIZE = 1282; + + public final static int ER_WARN_TOO_FEW_RECORDS = 1261; + + public final static int ER_WARN_TOO_MANY_RECORDS = 1262; + + public final static int ER_WARN_USING_OTHER_HANDLER = 1266; + + public final static int ER_WARNING_NOT_COMPLETE_ROLLBACK = 1196; + + public final static int ER_WRONG_ARGUMENTS = 1210; + + public final static int ER_WRONG_AUTO_KEY = 1075; + + public final static int ER_WRONG_COLUMN_NAME = 1166; + + public final static int ER_WRONG_DB_NAME = 1102; + + public final static int ER_WRONG_FIELD_SPEC = 1063; + + public final static int ER_WRONG_FIELD_TERMINATORS = 1083; + + public final static int ER_WRONG_FIELD_WITH_GROUP = 1055; + + public final static int ER_WRONG_FK_DEF = 1239; + + public final static int ER_WRONG_GROUP_FIELD = 1056; + + public final static int ER_WRONG_KEY_COLUMN = 1167; + + public final static int ER_WRONG_MRG_TABLE = 1168; + + public final static int ER_WRONG_NAME_FOR_CATALOG = 1281; + + public final static int ER_WRONG_NAME_FOR_INDEX = 1280; + + public final static int ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT = 1222; + + public final static int ER_WRONG_OUTER_JOIN = 1120; + + public final static int ER_WRONG_PARAMCOUNT_TO_PROCEDURE = 1107; + + public final static int ER_WRONG_PARAMETERS_TO_PROCEDURE = 1108; + + public final static int ER_WRONG_SUB_KEY = 1089; + + public final static int ER_WRONG_SUM_SELECT = 1057; + + public final static int ER_WRONG_TABLE_NAME = 1103; + + public final static int ER_WRONG_TYPE_FOR_VAR = 1232; + + public final static int ER_WRONG_USAGE = 1221; + + public final static int ER_WRONG_VALUE_COUNT = 1058; + + public final static int ER_WRONG_VALUE_COUNT_ON_ROW = 1136; + + public final static int ER_WRONG_VALUE_FOR_VAR = 1231; + + public final static int ER_XA_RMERR = 1401; + + public final static int ER_YES = 1003; + + public final static int ER_ZLIB_Z_BUF_ERROR = 1258; + + public final static int ER_ZLIB_Z_DATA_ERROR = 1259; + + public final static int ER_ZLIB_Z_MEM_ERROR = 1257; + + private MysqlErrorNumbers() { + // prevent instantiation + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlIO.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlIO.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlIO.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,4066 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.lang.ref.SoftReference; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.nio.ByteBuffer; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; +import java.util.zip.Deflater; + +import com.mysql.jdbc.profiler.ProfileEventSink; +import com.mysql.jdbc.profiler.ProfilerEvent; +import com.mysql.jdbc.util.ReadAheadInputStream; +import com.mysql.jdbc.util.ResultSetUtil; + + +/** + * This class is used by Connection for communicating with the MySQL server. + * + * @author Mark Matthews + * @version $Id: MysqlIO.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + * + * @see java.sql.Connection + */ +class MysqlIO { + protected static final int NULL_LENGTH = ~0; + protected static final int COMP_HEADER_LENGTH = 3; + protected static final int MIN_COMPRESS_LEN = 50; + protected static final int HEADER_LENGTH = 4; + protected static final int AUTH_411_OVERHEAD = 33; + private static int maxBufferSize = 65535; + private static final int CLIENT_COMPRESS = 32; /* Can use compression + protcol */ + protected static final int CLIENT_CONNECT_WITH_DB = 8; + private static final int CLIENT_FOUND_ROWS = 2; + private static final int CLIENT_LOCAL_FILES = 128; /* Can use LOAD DATA + LOCAL */ + + /* Found instead of + affected rows */ + private static final int CLIENT_LONG_FLAG = 4; /* Get all column flags */ + private static final int CLIENT_LONG_PASSWORD = 1; /* new more secure + passwords */ + private static final int CLIENT_PROTOCOL_41 = 512; // for > 4.1.1 + private static final int CLIENT_INTERACTIVE = 1024; + protected static final int CLIENT_SSL = 2048; + private static final int CLIENT_TRANSACTIONS = 8192; // Client knows about transactions + protected static final int CLIENT_RESERVED = 16384; // for 4.1.0 only + protected static final int CLIENT_SECURE_CONNECTION = 32768; + private static final int CLIENT_MULTI_QUERIES = 65536; // Enable/disable multiquery support + private static final int CLIENT_MULTI_RESULTS = 131072; // Enable/disable multi-results + private static final int SERVER_STATUS_IN_TRANS = 1; + private static final int SERVER_STATUS_AUTOCOMMIT = 2; // Server in auto_commit mode + private static final int SERVER_MORE_RESULTS_EXISTS = 8; // Multi query - next query exists + private static final int SERVER_QUERY_NO_GOOD_INDEX_USED = 16; + private static final int SERVER_QUERY_NO_INDEX_USED = 32; + private static final int SERVER_STATUS_CURSOR_EXISTS = 64; + private static final String FALSE_SCRAMBLE = "xxxxxxxx"; //$NON-NLS-1$ + protected static final int MAX_QUERY_SIZE_TO_LOG = 1024; // truncate logging of queries at 1K + protected static final int MAX_QUERY_SIZE_TO_EXPLAIN = 1024 * 1024; // don't explain queries above 1MB + protected static final int INITIAL_PACKET_SIZE = 1024; + /** + * We store the platform 'encoding' here, only used to avoid munging + * filenames for LOAD DATA LOCAL INFILE... + */ + private static String jvmPlatformCharset = null; + + /** + * Are we using packed or unpacked binary result set rows? + */ + private boolean binaryResultsAreUnpacked = true; + + /** + * We need to have a 'marker' for all-zero datetimes so that ResultSet + * can decide what to do based on connection setting + */ + protected final static String ZERO_DATE_VALUE_MARKER = "0000-00-00"; + protected final static String ZERO_DATETIME_VALUE_MARKER = "0000-00-00 00:00:00"; + + static { + OutputStreamWriter outWriter = null; + + // + // Use the I/O system to get the encoding (if possible), to avoid + // security restrictions on System.getProperty("file.encoding") in + // applets (why is that restricted?) + // + try { + outWriter = new OutputStreamWriter(new ByteArrayOutputStream()); + jvmPlatformCharset = outWriter.getEncoding(); + } finally { + try { + if (outWriter != null) { + outWriter.close(); + } + } catch (IOException ioEx) { + // ignore + } + } + } + + /** Max number of bytes to dump when tracing the protocol */ + private final static int MAX_PACKET_DUMP_LENGTH = 1024; + private boolean packetSequenceReset = false; + protected int serverCharsetIndex; + + // + // Use this when reading in rows to avoid thousands of new() + // calls, because the byte arrays just get copied out of the + // packet anyway + // + private Buffer reusablePacket = null; + private Buffer sendPacket = null; + private Buffer sharedSendPacket = null; + + /** Data to the server */ + protected BufferedOutputStream mysqlOutput = null; + protected com.mysql.jdbc.Connection connection; + private Deflater deflater = null; + protected InputStream mysqlInput = null; + private LinkedList packetDebugRingBuffer = null; + private RowData streamingData = null; + + /** The connection to the server */ + protected Socket mysqlConnection = null; + private SocketFactory socketFactory = null; + + // + // Packet used for 'LOAD DATA LOCAL INFILE' + // + // We use a SoftReference, so that we don't penalize intermittent + // use of this feature + // + private SoftReference loadFileBufRef; + + // + // Used to send large packets to the server versions 4+ + // We use a SoftReference, so that we don't penalize intermittent + // use of this feature + // + private SoftReference splitBufRef; + protected String host = null; + protected String seed; + private String serverVersion = null; + private String socketFactoryClassName = null; + private byte[] packetHeaderBuf = new byte[4]; + private boolean colDecimalNeedsBump = false; // do we need to increment the colDecimal flag? + private boolean hadWarnings = false; + private boolean has41NewNewProt = false; + + /** Does the server support long column info? */ + private boolean hasLongColumnInfo = false; + private boolean isInteractiveClient = false; + private boolean logSlowQueries = false; + + /** + * Does the character set of this connection match the character set of the + * platform + */ + private boolean platformDbCharsetMatches = true; // changed once we've connected. + private boolean profileSql = false; + private boolean queryBadIndexUsed = false; + private boolean queryNoIndexUsed = false; + + /** Should we use 4.1 protocol extensions? */ + private boolean use41Extensions = false; + private boolean useCompression = false; + private boolean useNewLargePackets = false; + private boolean useNewUpdateCounts = false; // should we use the new larger update counts? + private byte packetSequence = 0; + private byte readPacketSequence = -1; + private boolean checkPacketSequence = false; + byte protocolVersion = 0; + private int maxAllowedPacket = 1024 * 1024; + protected int maxThreeBytes = 255 * 255 * 255; + protected int port = 3306; + protected int serverCapabilities; + private int serverMajorVersion = 0; + private int serverMinorVersion = 0; + private int serverStatus = 0; + private int serverSubMinorVersion = 0; + private int warningCount = 0; + protected long clientParam = 0; + protected long lastPacketSentTimeMs = 0; + private boolean traceProtocol = false; + private boolean enablePacketDebug = false; + private Calendar sessionCalendar; + private boolean useConnectWithDb; + private boolean needToGrabQueryFromPacket; + private boolean autoGenerateTestcaseScript; + private long threadId; + private boolean useNanosForElapsedTime; + private long slowQueryThreshold; + private String queryTimingUnits; + + /** + * Constructor: Connect to the MySQL server and setup a stream connection. + * + * @param host the hostname to connect to + * @param port the port number that the server is listening on + * @param props the Properties from DriverManager.getConnection() + * @param socketFactoryClassName the socket factory to use + * @param conn the Connection that is creating us + * @param socketTimeout the timeout to set for the socket (0 means no + * timeout) + * + * @throws IOException if an IOException occurs during connect. + * @throws SQLException if a database access error occurs. + */ + public MysqlIO(String host, int port, Properties props, + String socketFactoryClassName, com.mysql.jdbc.Connection conn, + int socketTimeout) throws IOException, SQLException { + this.connection = conn; + + if (this.connection.getEnablePacketDebug()) { + this.packetDebugRingBuffer = new LinkedList(); + } + + this.logSlowQueries = this.connection.getLogSlowQueries(); + + this.reusablePacket = new Buffer(INITIAL_PACKET_SIZE); + this.sendPacket = new Buffer(INITIAL_PACKET_SIZE); + + this.port = port; + this.host = host; + + this.socketFactoryClassName = socketFactoryClassName; + this.socketFactory = createSocketFactory(); + + this.mysqlConnection = this.socketFactory.connect(this.host, this.port, + props); + + if (socketTimeout != 0) { + try { + this.mysqlConnection.setSoTimeout(socketTimeout); + } catch (Exception ex) { + /* Ignore if the platform does not support it */ + ; + } + } + + this.mysqlConnection = this.socketFactory.beforeHandshake(); + + if (this.connection.getUseReadAheadInput()) { + this.mysqlInput = new ReadAheadInputStream(this.mysqlConnection + .getInputStream(), 16384, this.connection + .getTraceProtocol(), this.connection.getLog()); + } else if (this.connection.useUnbufferedInput()) { + this.mysqlInput = this.mysqlConnection.getInputStream(); + } else { + this.mysqlInput = new BufferedInputStream(this.mysqlConnection + .getInputStream(), 16384); + } + + this.mysqlOutput = new BufferedOutputStream(this.mysqlConnection + .getOutputStream(), 16384); + + this.isInteractiveClient = this.connection.getInteractiveClient(); + this.profileSql = this.connection.getProfileSql(); + this.sessionCalendar = Calendar.getInstance(); + this.autoGenerateTestcaseScript = this.connection + .getAutoGenerateTestcaseScript(); + + this.needToGrabQueryFromPacket = (this.profileSql + || this.logSlowQueries || this.autoGenerateTestcaseScript); + + if (this.connection.getUseNanosForElapsedTime() + && Util.nanoTimeAvailable()) { + this.useNanosForElapsedTime = true; + + this.queryTimingUnits = Messages.getString("Nanoseconds"); + } else { + this.queryTimingUnits = Messages.getString("Milliseconds"); + } + + if (this.connection.getLogSlowQueries()) { + calculateSlowQueryThreshold(); + } + } + + /** + * Does the server send back extra column info? + * + * @return true if so + */ + public boolean hasLongColumnInfo() { + return this.hasLongColumnInfo; + } + + protected boolean isDataAvailable() throws SQLException { + try { + return this.mysqlInput.available() > 0; + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } + } + + /** + * DOCUMENT ME! + * + * @return Returns the lastPacketSentTimeMs. + */ + protected long getLastPacketSentTimeMs() { + return this.lastPacketSentTimeMs; + } + + /** + * Build a result set. Delegates to buildResultSetWithRows() to build a + * JDBC-version-specific ResultSet, given rows as byte data, and field + * information. + * + * @param callingStatement DOCUMENT ME! + * @param columnCount the number of columns in the result set + * @param maxRows the maximum number of rows to read (-1 means all rows) + * @param resultSetType (TYPE_FORWARD_ONLY, TYPE_SCROLL_????) + * @param resultSetConcurrency the type of result set (CONCUR_UPDATABLE or + * READ_ONLY) + * @param streamResults should the result set be read all at once, or + * streamed? + * @param catalog the database name in use when the result set was created + * @param isBinaryEncoded is this result set in native encoding? + * @param unpackFieldInfo should we read MYSQL_FIELD info (if available)? + * + * @return a result set + * + * @throws SQLException if a database access error occurs + */ + protected ResultSet getResultSet(Statement callingStatement, + long columnCount, int maxRows, int resultSetType, + int resultSetConcurrency, boolean streamResults, String catalog, + boolean isBinaryEncoded, boolean unpackFieldInfo, Field[] metadataFromCache) + throws SQLException { + Buffer packet; // The packet from the server + Field[] fields = null; + + // Read in the column information + + if (unpackFieldInfo) { + fields = new Field[(int) columnCount]; + + for (int i = 0; i < columnCount; i++) { + Buffer fieldPacket = null; + + fieldPacket = readPacket(); + fields[i] = unpackField(fieldPacket, false); + } + } else { + for (int i = 0; i < columnCount; i++) { + skipPacket(); + } + + //this.reusablePacket.clear(); + } + + packet = reuseAndReadPacket(this.reusablePacket); + + readServerStatusForResultSets(packet); + + // + // Handle cursor-based fetch first + // + + if (this.connection.versionMeetsMinimum(5, 0, 2) + && this.connection.getUseCursorFetch() + && isBinaryEncoded + && callingStatement != null + && callingStatement.getFetchSize() != 0 + && callingStatement.getResultSetType() == ResultSet.TYPE_FORWARD_ONLY) { + ServerPreparedStatement prepStmt = (com.mysql.jdbc.ServerPreparedStatement) callingStatement; + + Field[] fieldMetadata = ((com.mysql.jdbc.ResultSetMetaData) prepStmt.getMetaData()).fields; + + boolean usingCursor = true; + + // + // Server versions 5.0.5 or newer will only open + // a cursor and set this flag if they can, otherwise + // they punt and go back to mysql_store_results() behavior + // + + if (this.connection.versionMeetsMinimum(5, 0, 5)) { + usingCursor = (this.serverStatus & + SERVER_STATUS_CURSOR_EXISTS) != 0; + } + + if (usingCursor) { + RowData rows = new CursorRowProvider( + this, + prepStmt, + fields); + + ResultSet rs = buildResultSetWithRows( + callingStatement, + catalog, + fields, + rows, resultSetType, resultSetConcurrency, isBinaryEncoded); + + if (usingCursor) { + rs.setFetchSize(callingStatement.getFetchSize()); + } + + return rs; + } + } + + RowData rowData = null; + + if (!streamResults) { + rowData = readSingleRowSet(columnCount, maxRows, + resultSetConcurrency, isBinaryEncoded, unpackFieldInfo ? fields : metadataFromCache); + } else { + rowData = new RowDataDynamic(this, (int) columnCount, unpackFieldInfo ? fields : metadataFromCache, + isBinaryEncoded); + this.streamingData = rowData; + } + + ResultSet rs = buildResultSetWithRows(callingStatement, catalog, fields, + rowData, resultSetType, resultSetConcurrency, isBinaryEncoded); + + + + return rs; + } + + /** + * Forcibly closes the underlying socket to MySQL. + */ + protected final void forceClose() { + try { + if (this.mysqlInput != null) { + this.mysqlInput.close(); + } + } catch (IOException ioEx) { + // we can't do anything constructive about this + // Let the JVM clean it up later + this.mysqlInput = null; + } + + try { + if (this.mysqlOutput != null) { + this.mysqlOutput.close(); + } + } catch (IOException ioEx) { + // we can't do anything constructive about this + // Let the JVM clean it up later + this.mysqlOutput = null; + } + + try { + if (this.mysqlConnection != null) { + this.mysqlConnection.close(); + } + } catch (IOException ioEx) { + // we can't do anything constructive about this + // Let the JVM clean it up later + this.mysqlConnection = null; + } + } + + /** + * Reads and discards a single MySQL packet from the input stream. + * + * @throws SQLException if the network fails while skipping the + * packet. + */ + protected final void skipPacket() throws SQLException { + try { + + int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, + 0, 4); + + if (lengthRead < 4) { + forceClose(); + throw new IOException(Messages.getString("MysqlIO.1")); //$NON-NLS-1$ + } + + int packetLength = (this.packetHeaderBuf[0] & 0xff) + + ((this.packetHeaderBuf[1] & 0xff) << 8) + + ((this.packetHeaderBuf[2] & 0xff) << 16); + + if (this.traceProtocol) { + StringBuffer traceMessageBuf = new StringBuffer(); + + traceMessageBuf.append(Messages.getString("MysqlIO.2")); //$NON-NLS-1$ + traceMessageBuf.append(packetLength); + traceMessageBuf.append(Messages.getString("MysqlIO.3")); //$NON-NLS-1$ + traceMessageBuf.append(StringUtils.dumpAsHex( + this.packetHeaderBuf, 4)); + + this.connection.getLog().logTrace(traceMessageBuf.toString()); + } + + byte multiPacketSeq = this.packetHeaderBuf[3]; + + if (!this.packetSequenceReset) { + if (this.enablePacketDebug && this.checkPacketSequence) { + checkPacketSequencing(multiPacketSeq); + } + } else { + this.packetSequenceReset = false; + } + + this.readPacketSequence = multiPacketSeq; + + skipFully(this.mysqlInput, packetLength); + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } catch (OutOfMemoryError oom) { + try { + this.connection.realClose(false, false, true, oom); + } finally { + throw oom; + } + } + } + + /** + * Read one packet from the MySQL server + * + * @return the packet from the server. + * + * @throws SQLException + * DOCUMENT ME! + * @throws CommunicationsException + * DOCUMENT ME! + */ + protected final Buffer readPacket() throws SQLException { + try { + + int lengthRead = readFully(this.mysqlInput, + this.packetHeaderBuf, 0, 4); + + if (lengthRead < 4) { + forceClose(); + throw new IOException(Messages.getString("MysqlIO.1")); //$NON-NLS-1$ + } + + int packetLength = (this.packetHeaderBuf[0] & 0xff) + + ((this.packetHeaderBuf[1] & 0xff) << 8) + + ((this.packetHeaderBuf[2] & 0xff) << 16); + + if (this.traceProtocol) { + StringBuffer traceMessageBuf = new StringBuffer(); + + traceMessageBuf.append(Messages.getString("MysqlIO.2")); //$NON-NLS-1$ + traceMessageBuf.append(packetLength); + traceMessageBuf.append(Messages.getString("MysqlIO.3")); //$NON-NLS-1$ + traceMessageBuf.append(StringUtils.dumpAsHex( + this.packetHeaderBuf, 4)); + + this.connection.getLog().logTrace(traceMessageBuf.toString()); + } + + byte multiPacketSeq = this.packetHeaderBuf[3]; + + if (!this.packetSequenceReset) { + if (this.enablePacketDebug && this.checkPacketSequence) { + checkPacketSequencing(multiPacketSeq); + } + } else { + this.packetSequenceReset = false; + } + + this.readPacketSequence = multiPacketSeq; + + // Read data + byte[] buffer = new byte[packetLength + 1]; + int numBytesRead = readFully(this.mysqlInput, buffer, 0, + packetLength); + + if (numBytesRead != packetLength) { + throw new IOException("Short read, expected " + + packetLength + " bytes, only read " + numBytesRead); + } + + buffer[packetLength] = 0; + + Buffer packet = new Buffer(buffer); + packet.setBufLength(packetLength + 1); + + if (this.traceProtocol) { + StringBuffer traceMessageBuf = new StringBuffer(); + + traceMessageBuf.append(Messages.getString("MysqlIO.4")); //$NON-NLS-1$ + traceMessageBuf.append(getPacketDumpToLog(packet, + packetLength)); + + this.connection.getLog().logTrace(traceMessageBuf.toString()); + } + + if (this.enablePacketDebug) { + enqueuePacketForDebugging(false, false, 0, + this.packetHeaderBuf, packet); + } + + return packet; + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } catch (OutOfMemoryError oom) { + try { + this.connection.realClose(false, false, true, oom); + } finally { + throw oom; + } + } + } + + /** + * Unpacks the Field information from the given packet. Understands pre 4.1 + * and post 4.1 server version field packet structures. + * + * @param packet the packet containing the field information + * @param extractDefaultValues should default values be extracted? + * + * @return the unpacked field + * + * @throws SQLException DOCUMENT ME! + */ + protected final Field unpackField(Buffer packet, + boolean extractDefaultValues) throws SQLException { + if (this.use41Extensions) { + // we only store the position of the string and + // materialize only if needed... + if (this.has41NewNewProt) { + // Not used yet, 5.0? + int catalogNameStart = packet.getPosition() + 1; + int catalogNameLength = packet.fastSkipLenString(); + catalogNameStart = adjustStartForFieldLength(catalogNameStart, catalogNameLength); + } + + int databaseNameStart = packet.getPosition() + 1; + int databaseNameLength = packet.fastSkipLenString(); + databaseNameStart = adjustStartForFieldLength(databaseNameStart, databaseNameLength); + + int tableNameStart = packet.getPosition() + 1; + int tableNameLength = packet.fastSkipLenString(); + tableNameStart = adjustStartForFieldLength(tableNameStart, tableNameLength); + + // orgTableName is never used so skip + int originalTableNameStart = packet.getPosition() + 1; + int originalTableNameLength = packet.fastSkipLenString(); + originalTableNameStart = adjustStartForFieldLength(originalTableNameStart, originalTableNameLength); + + // we only store the position again... + int nameStart = packet.getPosition() + 1; + int nameLength = packet.fastSkipLenString(); + + nameStart = adjustStartForFieldLength(nameStart, nameLength); + + // orgColName is not required so skip... + int originalColumnNameStart = packet.getPosition() + 1; + int originalColumnNameLength = packet.fastSkipLenString(); + originalColumnNameStart = adjustStartForFieldLength(originalColumnNameStart, originalColumnNameLength); + + packet.readByte(); + + short charSetNumber = (short) packet.readInt(); + + long colLength = 0; + + if (this.has41NewNewProt) { + colLength = packet.readLong(); + } else { + colLength = packet.readLongInt(); + } + + int colType = packet.readByte() & 0xff; + + short colFlag = 0; + + if (this.hasLongColumnInfo) { + colFlag = (short) packet.readInt(); + } else { + colFlag = (short) (packet.readByte() & 0xff); + } + + int colDecimals = packet.readByte() & 0xff; + + int defaultValueStart = -1; + int defaultValueLength = -1; + + if (extractDefaultValues) { + defaultValueStart = packet.getPosition() + 1; + defaultValueLength = packet.fastSkipLenString(); + } + + Field field = new Field(this.connection, packet.getByteBuffer(), + databaseNameStart, databaseNameLength, tableNameStart, + tableNameLength, originalTableNameStart, + originalTableNameLength, nameStart, nameLength, + originalColumnNameStart, originalColumnNameLength, + colLength, colType, colFlag, colDecimals, + defaultValueStart, defaultValueLength, charSetNumber); + + return field; + } + + int tableNameStart = packet.getPosition() + 1; + int tableNameLength = packet.fastSkipLenString(); + tableNameStart = adjustStartForFieldLength(tableNameStart, tableNameLength); + + int nameStart = packet.getPosition() + 1; + int nameLength = packet.fastSkipLenString(); + nameStart = adjustStartForFieldLength(nameStart, nameLength); + + int colLength = packet.readnBytes(); + int colType = packet.readnBytes(); + packet.readByte(); // We know it's currently 2 + + short colFlag = 0; + + if (this.hasLongColumnInfo) { + colFlag = (short) (packet.readInt()); + } else { + colFlag = (short) (packet.readByte() & 0xff); + } + + int colDecimals = (packet.readByte() & 0xff); + + if (this.colDecimalNeedsBump) { + colDecimals++; + } + + Field field = new Field(this.connection, packet.getByteBuffer(), + nameStart, nameLength, tableNameStart, tableNameLength, + colLength, colType, colFlag, colDecimals); + + return field; + } + + private int adjustStartForFieldLength(int nameStart, int nameLength) { + if (nameLength < 251) { + return nameStart; + } + + if (nameLength >= 251 && nameLength < 65536) { + return nameStart + 2; + } + + if (nameLength >= 65536 && nameLength < 16777216) { + return nameStart + 3; + } + + return nameStart + 8; + } + + protected boolean isSetNeededForAutoCommitMode(boolean autoCommitFlag) { + if (this.use41Extensions && this.connection.getElideSetAutoCommits()) { + boolean autoCommitModeOnServer = ((this.serverStatus & + SERVER_STATUS_AUTOCOMMIT) != 0); + + if (!autoCommitFlag && versionMeetsMinimum(5, 0, 0)) { + // Just to be safe, check if a transaction is in progress on the server.... + // if so, then we must be in autoCommit == false + // therefore return the opposite of transaction status + boolean inTransactionOnServer = ((this.serverStatus & + SERVER_STATUS_IN_TRANS) != 0); + + return !inTransactionOnServer; + } + + return autoCommitModeOnServer != autoCommitFlag; + } + + return true; + } + + protected boolean inTransactionOnServer() { + return (this.serverStatus & SERVER_STATUS_IN_TRANS) != 0; + } + + /** + * Re-authenticates as the given user and password + * + * @param userName DOCUMENT ME! + * @param password DOCUMENT ME! + * @param database DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ + protected void changeUser(String userName, String password, String database) + throws SQLException { + this.packetSequence = -1; + + int passwordLength = 16; + int userLength = (userName != null) ? userName.length() : 0; + int databaseLength = (database != null) ? database.length() : 0; + + int packLength = ((userLength + passwordLength + databaseLength) * 2) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD; + + if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) { + Buffer changeUserPacket = new Buffer(packLength + 1); + changeUserPacket.writeByte((byte) MysqlDefs.COM_CHANGE_USER); + + if (versionMeetsMinimum(4, 1, 1)) { + secureAuth411(changeUserPacket, packLength, userName, password, + database, false); + } else { + secureAuth(changeUserPacket, packLength, userName, password, + database, false); + } + } else { + // Passwords can be 16 chars long + Buffer packet = new Buffer(packLength); + packet.writeByte((byte) MysqlDefs.COM_CHANGE_USER); + + // User/Password data + packet.writeString(userName); + + if (this.protocolVersion > 9) { + packet.writeString(Util.newCrypt(password, this.seed)); + } else { + packet.writeString(Util.oldCrypt(password, this.seed)); + } + + boolean localUseConnectWithDb = this.useConnectWithDb && + (database != null && database.length() > 0); + + if (localUseConnectWithDb) { + packet.writeString(database); + } + + send(packet, packet.getPosition()); + checkErrorPacket(); + + if (!localUseConnectWithDb) { + changeDatabaseTo(database); + } + } + } + + /** + * Checks for errors in the reply packet, and if none, returns the reply + * packet, ready for reading + * + * @return a packet ready for reading. + * + * @throws SQLException is the packet is an error packet + */ + protected Buffer checkErrorPacket() throws SQLException { + return checkErrorPacket(-1); + } + + /** + * Determines if the database charset is the same as the platform charset + */ + protected void checkForCharsetMismatch() { + if (this.connection.getUseUnicode() && + (this.connection.getEncoding() != null)) { + String encodingToCheck = jvmPlatformCharset; + + if (encodingToCheck == null) { + encodingToCheck = System.getProperty("file.encoding"); //$NON-NLS-1$ + } + + if (encodingToCheck == null) { + this.platformDbCharsetMatches = false; + } else { + this.platformDbCharsetMatches = encodingToCheck.equals(this.connection.getEncoding()); + } + } + } + + protected void clearInputStream() throws SQLException { + + try { + int len = this.mysqlInput.available(); + + while (len > 0) { + this.mysqlInput.skip(len); + len = this.mysqlInput.available(); + } + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } + } + + protected void resetReadPacketSequence() { + this.readPacketSequence = 0; + } + + protected void dumpPacketRingBuffer() throws SQLException { + if ((this.packetDebugRingBuffer != null) && + this.connection.getEnablePacketDebug()) { + StringBuffer dumpBuffer = new StringBuffer(); + + dumpBuffer.append("Last " + this.packetDebugRingBuffer.size() + + " packets received from server, from oldest->newest:\n"); + dumpBuffer.append("\n"); + + for (Iterator ringBufIter = this.packetDebugRingBuffer.iterator(); + ringBufIter.hasNext();) { + dumpBuffer.append((StringBuffer) ringBufIter.next()); + dumpBuffer.append("\n"); + } + + this.connection.getLog().logTrace(dumpBuffer.toString()); + } + } + + /** + * Runs an 'EXPLAIN' on the given query and dumps the results to the log + * + * @param querySQL DOCUMENT ME! + * @param truncatedQuery DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ + protected void explainSlowQuery(byte[] querySQL, String truncatedQuery) + throws SQLException { + if (StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, "SELECT")) { //$NON-NLS-1$ + + PreparedStatement stmt = null; + java.sql.ResultSet rs = null; + + try { + stmt = this.connection.clientPrepareStatement("EXPLAIN ?"); //$NON-NLS-1$ + stmt.setBytesNoEscapeNoQuotes(1, querySQL); + rs = stmt.executeQuery(); + + StringBuffer explainResults = new StringBuffer(Messages.getString( + "MysqlIO.8") + truncatedQuery //$NON-NLS-1$ + +Messages.getString("MysqlIO.9")); //$NON-NLS-1$ + + ResultSetUtil.appendResultSetSlashGStyle(explainResults, rs); + + this.connection.getLog().logWarn(explainResults.toString()); + } catch (SQLException sqlEx) { + } finally { + if (rs != null) { + rs.close(); + } + + if (stmt != null) { + stmt.close(); + } + } + } else { + } + } + + static int getMaxBuf() { + return maxBufferSize; + } + + /** + * Get the major version of the MySQL server we are talking to. + * + * @return DOCUMENT ME! + */ + final int getServerMajorVersion() { + return this.serverMajorVersion; + } + + /** + * Get the minor version of the MySQL server we are talking to. + * + * @return DOCUMENT ME! + */ + final int getServerMinorVersion() { + return this.serverMinorVersion; + } + + /** + * Get the sub-minor version of the MySQL server we are talking to. + * + * @return DOCUMENT ME! + */ + final int getServerSubMinorVersion() { + return this.serverSubMinorVersion; + } + + /** + * Get the version string of the server we are talking to + * + * @return DOCUMENT ME! + */ + String getServerVersion() { + return this.serverVersion; + } + + /** + * Initialize communications with the MySQL server. Handles logging on, and + * handling initial connection errors. + * + * @param user DOCUMENT ME! + * @param password DOCUMENT ME! + * @param database DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + * @throws CommunicationsException DOCUMENT ME! + */ + void doHandshake(String user, String password, String database) + throws SQLException { + // Read the first packet + this.checkPacketSequence = false; + this.readPacketSequence = 0; + + Buffer buf = readPacket(); + + // Get the protocol version + this.protocolVersion = buf.readByte(); + + if (this.protocolVersion == -1) { + try { + this.mysqlConnection.close(); + } catch (Exception e) { + ; // ignore + } + + int errno = 2000; + + errno = buf.readInt(); + + String serverErrorMessage = buf.readString(); + + StringBuffer errorBuf = new StringBuffer(Messages.getString( + "MysqlIO.10")); //$NON-NLS-1$ + errorBuf.append(serverErrorMessage); + errorBuf.append("\""); //$NON-NLS-1$ + + String xOpen = SQLError.mysqlToSqlState(errno, + this.connection.getUseSqlStateCodes()); + + throw SQLError.createSQLException(SQLError.get(xOpen) + ", " //$NON-NLS-1$ + +errorBuf.toString(), xOpen, errno); + } + + this.serverVersion = buf.readString(); + + // Parse the server version into major/minor/subminor + int point = this.serverVersion.indexOf("."); //$NON-NLS-1$ + + if (point != -1) { + try { + int n = Integer.parseInt(this.serverVersion.substring(0, point)); + this.serverMajorVersion = n; + } catch (NumberFormatException NFE1) { + ; + } + + String remaining = this.serverVersion.substring(point + 1, + this.serverVersion.length()); + point = remaining.indexOf("."); //$NON-NLS-1$ + + if (point != -1) { + try { + int n = Integer.parseInt(remaining.substring(0, point)); + this.serverMinorVersion = n; + } catch (NumberFormatException nfe) { + ; + } + + remaining = remaining.substring(point + 1, remaining.length()); + + int pos = 0; + + while (pos < remaining.length()) { + if ((remaining.charAt(pos) < '0') || + (remaining.charAt(pos) > '9')) { + break; + } + + pos++; + } + + try { + int n = Integer.parseInt(remaining.substring(0, pos)); + this.serverSubMinorVersion = n; + } catch (NumberFormatException nfe) { + ; + } + } + } + + if (versionMeetsMinimum(4, 0, 8)) { + this.maxThreeBytes = (256 * 256 * 256) - 1; + this.useNewLargePackets = true; + } else { + this.maxThreeBytes = 255 * 255 * 255; + this.useNewLargePackets = false; + } + + this.colDecimalNeedsBump = versionMeetsMinimum(3, 23, 0); + this.colDecimalNeedsBump = !versionMeetsMinimum(3, 23, 15); // guess? Not noted in changelog + this.useNewUpdateCounts = versionMeetsMinimum(3, 22, 5); + + threadId = buf.readLong(); + this.seed = buf.readString(); + + this.serverCapabilities = 0; + + if (buf.getPosition() < buf.getBufLength()) { + this.serverCapabilities = buf.readInt(); + } + + if (versionMeetsMinimum(4, 1, 1)) { + int position = buf.getPosition(); + + /* New protocol with 16 bytes to describe server characteristics */ + this.serverCharsetIndex = buf.readByte() & 0xff; + this.serverStatus = buf.readInt(); + buf.setPosition(position + 16); + + String seedPart2 = buf.readString(); + StringBuffer newSeed = new StringBuffer(20); + newSeed.append(this.seed); + newSeed.append(seedPart2); + this.seed = newSeed.toString(); + } + + if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && + this.connection.getUseCompression()) { + this.clientParam |= CLIENT_COMPRESS; + } + + this.useConnectWithDb = (database != null) && + (database.length() > 0) && + !this.connection.getCreateDatabaseIfNotExist(); + + if (this.useConnectWithDb) { + this.clientParam |= CLIENT_CONNECT_WITH_DB; + } + + if (((this.serverCapabilities & CLIENT_SSL) == 0) && + this.connection.getUseSSL()) { + if (this.connection.getRequireSSL()) { + this.connection.close(); + forceClose(); + throw SQLError.createSQLException(Messages.getString("MysqlIO.15"), //$NON-NLS-1$ + SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE); + } + + this.connection.setUseSSL(false); + } + + if ((this.serverCapabilities & CLIENT_LONG_FLAG) != 0) { + // We understand other column flags, as well + this.clientParam |= CLIENT_LONG_FLAG; + this.hasLongColumnInfo = true; + } + + // return FOUND rows + this.clientParam |= CLIENT_FOUND_ROWS; + + if (this.connection.getAllowLoadLocalInfile()) { + this.clientParam |= CLIENT_LOCAL_FILES; + } + + if (this.isInteractiveClient) { + this.clientParam |= CLIENT_INTERACTIVE; + } + + // Authenticate + if (this.protocolVersion > 9) { + this.clientParam |= CLIENT_LONG_PASSWORD; // for long passwords + } else { + this.clientParam &= ~CLIENT_LONG_PASSWORD; + } + + // + // 4.1 has some differences in the protocol + // + if (versionMeetsMinimum(4, 1, 0)) { + if (versionMeetsMinimum(4, 1, 1)) { + this.clientParam |= CLIENT_PROTOCOL_41; + this.has41NewNewProt = true; + + // Need this to get server status values + this.clientParam |= CLIENT_TRANSACTIONS; + + // We always allow multiple result sets + this.clientParam |= CLIENT_MULTI_RESULTS; + + // We allow the user to configure whether + // or not they want to support multiple queries + // (by default, this is disabled). + if (this.connection.getAllowMultiQueries()) { + this.clientParam |= CLIENT_MULTI_QUERIES; + } + } else { + this.clientParam |= CLIENT_RESERVED; + this.has41NewNewProt = false; + } + + this.use41Extensions = true; + } + + int passwordLength = 16; + int userLength = (user != null) ? user.length() : 0; + int databaseLength = (database != null) ? database.length() : 0; + + int packLength = ((userLength + passwordLength + databaseLength) * 2) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD; + + Buffer packet = null; + + if (!this.connection.getUseSSL()) { + if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) { + this.clientParam |= CLIENT_SECURE_CONNECTION; + + if (versionMeetsMinimum(4, 1, 1)) { + secureAuth411(null, packLength, user, password, database, + true); + } else { + secureAuth(null, packLength, user, password, database, true); + } + } else { + // Passwords can be 16 chars long + packet = new Buffer(packLength); + + if ((this.clientParam & CLIENT_RESERVED) != 0) { + if (versionMeetsMinimum(4, 1, 1)) { + packet.writeLong(this.clientParam); + packet.writeLong(this.maxThreeBytes); + + // charset, JDBC will connect as 'latin1', + // and use 'SET NAMES' to change to the desired + // charset after the connection is established. + packet.writeByte((byte) 8); + + // Set of bytes reserved for future use. + packet.writeBytesNoNull(new byte[23]); + } else { + packet.writeLong(this.clientParam); + packet.writeLong(this.maxThreeBytes); + } + } else { + packet.writeInt((int) this.clientParam); + packet.writeLongInt(this.maxThreeBytes); + } + + // User/Password data + packet.writeString(user, "Cp1252", this.connection); + + if (this.protocolVersion > 9) { + packet.writeString(Util.newCrypt(password, this.seed), "Cp1252", this.connection); + } else { + packet.writeString(Util.oldCrypt(password, this.seed), "Cp1252", this.connection); + } + + if (this.useConnectWithDb) { + packet.writeString(database, "Cp1252", this.connection); + } + + send(packet, packet.getPosition()); + } + } else { + negotiateSSLConnection(user, password, database, packLength); + } + + // Check for errors, not for 4.1.1 or newer, + // as the new auth protocol doesn't work that way + // (see secureAuth411() for more details...) + if (!versionMeetsMinimum(4, 1, 1)) { + checkErrorPacket(); + } + + // + // Can't enable compression until after handshake + // + if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && + this.connection.getUseCompression()) { + // The following matches with ZLIB's + // compress() + this.deflater = new Deflater(); + this.useCompression = true; + this.mysqlInput = new CompressedInputStream(this.connection, + this.mysqlInput); + } + + if (!this.useConnectWithDb) { + changeDatabaseTo(database); + } + } + + private void changeDatabaseTo(String database) throws SQLException, CommunicationsException { + if (database == null || database.length() == 0) { + return; + } + + try { + sendCommand(MysqlDefs.INIT_DB, database, null, false, null); + } catch (Exception ex) { + if (this.connection.getCreateDatabaseIfNotExist()) { + sendCommand(MysqlDefs.QUERY, "CREATE DATABASE IF NOT EXISTS " + + database, + null, false, null); + sendCommand(MysqlDefs.INIT_DB, database, null, false, null); + } else { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ex); + } + } + } + + /** + * Retrieve one row from the MySQL server. Note: this method is not + * thread-safe, but it is only called from methods that are guarded by + * synchronizing on this object. + * + * @param fields DOCUMENT ME! + * @param columnCount DOCUMENT ME! + * @param isBinaryEncoded DOCUMENT ME! + * @param resultSetConcurrency DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ + final Object[] nextRow(Field[] fields, int columnCount, + boolean isBinaryEncoded, int resultSetConcurrency) + throws SQLException { + // Get the next incoming packet, re-using the packet because + // all the data we need gets copied out of it. + Buffer rowPacket = checkErrorPacket(); + + if (!isBinaryEncoded) { + // + // Didn't read an error, so re-position to beginning + // of packet in order to read result set data + // + rowPacket.setPosition(rowPacket.getPosition() - 1); + + if (!rowPacket.isLastDataPacket()) { + byte[][] rowData = new byte[columnCount][]; + + int offset = 0; + + for (int i = 0; i < columnCount; i++) { + rowData[i] = rowPacket.readLenByteArray(offset); + } + + return rowData; + } + + readServerStatusForResultSets(rowPacket); + + return null; + } + + // + // Handle binary-encoded data for server-side + // PreparedStatements... + // + if (!rowPacket.isLastDataPacket()) { + return unpackBinaryResultSetRow(fields, rowPacket, + resultSetConcurrency); + } + + rowPacket.setPosition(rowPacket.getPosition() - 1); + readServerStatusForResultSets(rowPacket); + + return null; + } + + /** + * Log-off of the MySQL server and close the socket. + * + * @throws SQLException DOCUMENT ME! + */ + final void quit() throws SQLException { + Buffer packet = new Buffer(6); + this.packetSequence = -1; + packet.writeByte((byte) MysqlDefs.QUIT); + send(packet, packet.getPosition()); + forceClose(); + } + + /** + * Returns the packet used for sending data (used by PreparedStatement) + * Guarded by external synchronization on a mutex. + * + * @return A packet to send data with + */ + Buffer getSharedSendPacket() { + if (this.sharedSendPacket == null) { + this.sharedSendPacket = new Buffer(INITIAL_PACKET_SIZE); + } + + return this.sharedSendPacket; + } + + void closeStreamer(RowData streamer) throws SQLException { + if (this.streamingData == null) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.17") //$NON-NLS-1$ + +streamer + Messages.getString("MysqlIO.18")); //$NON-NLS-1$ + } + + if (streamer != this.streamingData) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.19") //$NON-NLS-1$ + +streamer + Messages.getString("MysqlIO.20") //$NON-NLS-1$ + +Messages.getString("MysqlIO.21") //$NON-NLS-1$ + +Messages.getString("MysqlIO.22")); //$NON-NLS-1$ + } + + this.streamingData = null; + } + + ResultSet readAllResults(Statement callingStatement, int maxRows, + int resultSetType, int resultSetConcurrency, boolean streamResults, + String catalog, Buffer resultPacket, boolean isBinaryEncoded, + long preSentColumnCount, boolean unpackFieldInfo, Field[] metadataFromCache) + throws SQLException { + resultPacket.setPosition(resultPacket.getPosition() - 1); + + ResultSet topLevelResultSet = readResultsForQueryOrUpdate(callingStatement, + maxRows, resultSetType, resultSetConcurrency, streamResults, + catalog, resultPacket, isBinaryEncoded, preSentColumnCount, + unpackFieldInfo, metadataFromCache); + + ResultSet currentResultSet = topLevelResultSet; + + boolean checkForMoreResults = ((this.clientParam & + CLIENT_MULTI_RESULTS) != 0); + + boolean serverHasMoreResults = (this.serverStatus & + SERVER_MORE_RESULTS_EXISTS) != 0; + + // + // TODO: We need to support streaming of multiple result sets + // + if (serverHasMoreResults && streamResults) { + clearInputStream(); + + throw SQLError.createSQLException(Messages.getString("MysqlIO.23"), //$NON-NLS-1$ + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } + + boolean moreRowSetsExist = checkForMoreResults & serverHasMoreResults; + + while (moreRowSetsExist) { + Buffer fieldPacket = checkErrorPacket(); + fieldPacket.setPosition(0); + + ResultSet newResultSet = readResultsForQueryOrUpdate(callingStatement, + maxRows, resultSetType, resultSetConcurrency, + streamResults, catalog, fieldPacket, isBinaryEncoded, + preSentColumnCount, unpackFieldInfo, metadataFromCache); + + currentResultSet.setNextResultSet(newResultSet); + + currentResultSet = newResultSet; + + moreRowSetsExist = (this.serverStatus & SERVER_MORE_RESULTS_EXISTS) != 0; + } + + if (!streamResults) { + clearInputStream(); + } + + reclaimLargeReusablePacket(); + + return topLevelResultSet; + } + + /** + * Sets the buffer size to max-buf + */ + void resetMaxBuf() { + this.maxAllowedPacket = this.connection.getMaxAllowedPacket(); + } + + /** + * Send a command to the MySQL server If data is to be sent with command, + * it should be put in extraData. + * + * Raw packets can be sent by setting queryPacket to something other + * than null. + * + * @param command the MySQL protocol 'command' from MysqlDefs + * @param extraData any 'string' data for the command + * @param queryPacket a packet pre-loaded with data for the protocol (i.e. + * from a client-side prepared statement). + * @param skipCheck do not call checkErrorPacket() if true + * @param extraDataCharEncoding the character encoding of the extraData + * parameter. + * + * @return the response packet from the server + * + * @throws SQLException if an I/O error or SQL error occurs + */ + + final Buffer sendCommand(int command, String extraData, Buffer queryPacket, + boolean skipCheck, String extraDataCharEncoding) + throws SQLException { + // + // We cache these locally, per-command, as the checks + // for them are in very 'hot' sections of the I/O code + // and we save 10-15% in overall performance by doing this... + // + this.enablePacketDebug = this.connection.getEnablePacketDebug(); + this.traceProtocol = this.connection.getTraceProtocol(); + this.readPacketSequence = 0; + + try { + + checkForOutstandingStreamingData(); + + // Clear serverStatus...this value is guarded by an + // external mutex, as you can only ever be processing + // one command at a time + this.serverStatus = 0; + this.hadWarnings = false; + this.warningCount = 0; + + this.queryNoIndexUsed = false; + this.queryBadIndexUsed = false; + + // + // Compressed input stream needs cleared at beginning + // of each command execution... + // + if (this.useCompression) { + int bytesLeft = this.mysqlInput.available(); + + if (bytesLeft > 0) { + this.mysqlInput.skip(bytesLeft); + } + } + + try { + clearInputStream(); + + // + // PreparedStatements construct their own packets, + // for efficiency's sake. + // + // If this is a generic query, we need to re-use + // the sending packet. + // + if (queryPacket == null) { + int packLength = HEADER_LENGTH + COMP_HEADER_LENGTH + 1 + + ((extraData != null) ? extraData.length() : 0) + 2; + + if (this.sendPacket == null) { + this.sendPacket = new Buffer(packLength); + } + + this.packetSequence = -1; + this.readPacketSequence = 0; + this.checkPacketSequence = true; + this.sendPacket.clear(); + + this.sendPacket.writeByte((byte) command); + + if ((command == MysqlDefs.INIT_DB) || + (command == MysqlDefs.CREATE_DB) || + (command == MysqlDefs.DROP_DB) || + (command == MysqlDefs.QUERY) || + (command == MysqlDefs.COM_PREPARE)) { + if (extraDataCharEncoding == null) { + this.sendPacket.writeStringNoNull(extraData); + } else { + this.sendPacket.writeStringNoNull(extraData, + extraDataCharEncoding, + this.connection.getServerCharacterEncoding(), + this.connection.parserKnowsUnicode(), this.connection); + } + } else if (command == MysqlDefs.PROCESS_KILL) { + long id = new Long(extraData).longValue(); + this.sendPacket.writeLong(id); + } + + send(this.sendPacket, this.sendPacket.getPosition()); + } else { + this.packetSequence = -1; + send(queryPacket, queryPacket.getPosition()); // packet passed by PreparedStatement + } + } catch (SQLException sqlEx) { + // don't wrap SQLExceptions + throw sqlEx; + } catch (Exception ex) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ex); + } + + Buffer returnPacket = null; + + if (!skipCheck) { + if ((command == MysqlDefs.COM_EXECUTE) || + (command == MysqlDefs.COM_RESET_STMT)) { + this.readPacketSequence = 0; + this.packetSequenceReset = true; + } + + returnPacket = checkErrorPacket(command); + } + + return returnPacket; + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } + } + + /** + * Send a query stored in a packet directly to the server. + * + * @param callingStatement DOCUMENT ME! + * @param resultSetConcurrency DOCUMENT ME! + * @param characterEncoding DOCUMENT ME! + * @param queryPacket DOCUMENT ME! + * @param maxRows DOCUMENT ME! + * @param conn DOCUMENT ME! + * @param resultSetType DOCUMENT ME! + * @param resultSetConcurrency DOCUMENT ME! + * @param streamResults DOCUMENT ME! + * @param catalog DOCUMENT ME! + * @param unpackFieldInfo should we read MYSQL_FIELD info (if available)? + * + * @return DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ + final ResultSet sqlQueryDirect(Statement callingStatement, String query, + String characterEncoding, Buffer queryPacket, int maxRows, + Connection conn, int resultSetType, int resultSetConcurrency, + boolean streamResults, String catalog, boolean unpackFieldInfo) + throws Exception { + long queryStartTime = 0; + long queryEndTime = 0; + + if (query != null) { + + + // We don't know exactly how many bytes we're going to get + // from the query. Since we're dealing with Unicode, the + // max is 2, so pad it (2 * query) + space for headers + int packLength = HEADER_LENGTH + 1 + (query.length() * 2) + 2; + + if (this.sendPacket == null) { + this.sendPacket = new Buffer(packLength); + } else { + this.sendPacket.clear(); + } + + this.sendPacket.writeByte((byte) MysqlDefs.QUERY); + + if (characterEncoding != null) { + if (this.platformDbCharsetMatches) { + this.sendPacket.writeStringNoNull(query, characterEncoding, + this.connection.getServerCharacterEncoding(), + this.connection.parserKnowsUnicode(), + this.connection); + } else { + if (StringUtils.startsWithIgnoreCaseAndWs(query, "LOAD DATA")) { //$NON-NLS-1$ + this.sendPacket.writeBytesNoNull(query.getBytes()); + } else { + this.sendPacket.writeStringNoNull(query, + characterEncoding, + this.connection.getServerCharacterEncoding(), + this.connection.parserKnowsUnicode(), + this.connection); + } + } + } else { + this.sendPacket.writeStringNoNull(query); + } + + queryPacket = this.sendPacket; + } + + byte[] queryBuf = null; + int oldPacketPosition = 0; + + + + if (needToGrabQueryFromPacket) { + queryBuf = queryPacket.getByteBuffer(); + + // save the packet position + oldPacketPosition = queryPacket.getPosition(); + + queryStartTime = getCurrentTimeNanosOrMillis(); + } + + // Send query command and sql query string + Buffer resultPacket = sendCommand(MysqlDefs.QUERY, null, queryPacket, + false, null); + + long fetchBeginTime = 0; + long fetchEndTime = 0; + + String profileQueryToLog = null; + + boolean queryWasSlow = false; + + if (this.profileSql || this.logSlowQueries) { + queryEndTime = getCurrentTimeNanosOrMillis(); + + boolean shouldExtractQuery = false; + + if (this.profileSql) { + shouldExtractQuery = true; + } else if (this.logSlowQueries) { + + if ((queryEndTime - queryStartTime) > this.slowQueryThreshold) { + shouldExtractQuery = true; + queryWasSlow = true; + } + } + + if (shouldExtractQuery) { + // Extract the actual query from the network packet + boolean truncated = false; + + int extractPosition = oldPacketPosition; + + if (oldPacketPosition > this.connection.getMaxQuerySizeToLog()) { + extractPosition = this.connection.getMaxQuerySizeToLog() + 5; + truncated = true; + } + + profileQueryToLog = new String(queryBuf, 5, + (extractPosition - 5)); + + if (truncated) { + profileQueryToLog += Messages.getString("MysqlIO.25"); //$NON-NLS-1$ + } + } + + fetchBeginTime = queryEndTime; + } + + if (this.autoGenerateTestcaseScript) { + String testcaseQuery = null; + + if (query != null) { + testcaseQuery = query; + } else { + testcaseQuery = new String(queryBuf, 5, + (oldPacketPosition - 5)); + } + + StringBuffer debugBuf = new StringBuffer(testcaseQuery.length() + 32); + this.connection.generateConnectionCommentBlock(debugBuf); + debugBuf.append(testcaseQuery); + debugBuf.append(';'); + this.connection.dumpTestcaseQuery(debugBuf.toString()); + } + + ResultSet rs = readAllResults(callingStatement, maxRows, resultSetType, + resultSetConcurrency, streamResults, catalog, resultPacket, + false, -1L, unpackFieldInfo, null /* we don't need metadata for cached MD in this case */); + + if (queryWasSlow) { + StringBuffer mesgBuf = new StringBuffer(48 + + profileQueryToLog.length()); + + mesgBuf.append(Messages.getString("MysqlIO.SlowQuery", + new Object[] {new Long(this.slowQueryThreshold), + queryTimingUnits, + new Long(queryEndTime - queryStartTime)})); + mesgBuf.append(profileQueryToLog); + + ProfileEventSink eventSink = ProfileEventSink.getInstance(this.connection); + + eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, + "", catalog, this.connection.getId(), //$NON-NLS-1$ + (callingStatement != null) ? callingStatement.getId() : 999, + rs.resultId, System.currentTimeMillis(), + (int) (queryEndTime - queryStartTime), queryTimingUnits, null, + new Throwable(), mesgBuf.toString())); + + if (this.connection.getExplainSlowQueries()) { + if (oldPacketPosition < MAX_QUERY_SIZE_TO_EXPLAIN) { + explainSlowQuery(queryPacket.getBytes(5, + (oldPacketPosition - 5)), profileQueryToLog); + } else { + this.connection.getLog().logWarn(Messages.getString( + "MysqlIO.28") //$NON-NLS-1$ + +MAX_QUERY_SIZE_TO_EXPLAIN + + Messages.getString("MysqlIO.29")); //$NON-NLS-1$ + } + } + } + + if (this.profileSql) { + fetchEndTime = getCurrentTimeNanosOrMillis(); + + ProfileEventSink eventSink = ProfileEventSink.getInstance(this.connection); + + eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_QUERY, + "", catalog, this.connection.getId(), //$NON-NLS-1$ + (callingStatement != null) ? callingStatement.getId() : 999, + rs.resultId, System.currentTimeMillis(), + (queryEndTime - queryStartTime), this.queryTimingUnits, + null, + new Throwable(), profileQueryToLog)); + + eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_FETCH, + "", catalog, this.connection.getId(), //$NON-NLS-1$ + (callingStatement != null) ? callingStatement.getId() : 999, + rs.resultId, System.currentTimeMillis(), + (fetchEndTime - fetchBeginTime), this.queryTimingUnits, + null, + new Throwable(), null)); + + if (this.queryBadIndexUsed) { + eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, //$NON-NLS-1$ + this.connection.getId(), + (callingStatement != null) ? callingStatement.getId() + : 999, rs.resultId, + System.currentTimeMillis(), + (queryEndTime - queryStartTime), this.queryTimingUnits, + null, + new Throwable(), + Messages.getString("MysqlIO.33") //$NON-NLS-1$ + +profileQueryToLog)); + } + + if (this.queryNoIndexUsed) { + eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, //$NON-NLS-1$ + this.connection.getId(), + (callingStatement != null) ? callingStatement.getId() + : 999, rs.resultId, + System.currentTimeMillis(), + (queryEndTime - queryStartTime), this.queryTimingUnits, + null, + new Throwable(), + Messages.getString("MysqlIO.35") //$NON-NLS-1$ + +profileQueryToLog)); + } + } + + if (this.hadWarnings) { + scanForAndThrowDataTruncation(); + } + + return rs; + } + + private void calculateSlowQueryThreshold() { + this.slowQueryThreshold = this.connection.getSlowQueryThresholdMillis(); + + if (this.connection.getUseNanosForElapsedTime()) { + long nanosThreshold = this.connection.getSlowQueryThresholdNanos(); + + if (nanosThreshold != 0) { + this.slowQueryThreshold = nanosThreshold; + } else { + this.slowQueryThreshold *= 1000000; // 1 million millis in a nano + } + } + } + + protected long getCurrentTimeNanosOrMillis() { + if (this.useNanosForElapsedTime) { + return Util.getCurrentTimeNanosOrMillis(); + } + + return System.currentTimeMillis(); + } + + /** + * Returns the host this IO is connected to + * + * @return DOCUMENT ME! + */ + String getHost() { + return this.host; + } + + /** + * Is the version of the MySQL server we are connected to the given + * version? + * + * @param major the major version + * @param minor the minor version + * @param subminor the subminor version + * + * @return true if the version of the MySQL server we are connected is the + * given version + */ + boolean isVersion(int major, int minor, int subminor) { + return ((major == getServerMajorVersion()) && + (minor == getServerMinorVersion()) && + (subminor == getServerSubMinorVersion())); + } + + /** + * Does the version of the MySQL server we are connected to meet the given + * minimums? + * + * @param major DOCUMENT ME! + * @param minor DOCUMENT ME! + * @param subminor DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + boolean versionMeetsMinimum(int major, int minor, int subminor) { + if (getServerMajorVersion() >= major) { + if (getServerMajorVersion() == major) { + if (getServerMinorVersion() >= minor) { + if (getServerMinorVersion() == minor) { + return (getServerSubMinorVersion() >= subminor); + } + + // newer than major.minor + return true; + } + + // older than major.minor + return false; + } + + // newer than major + return true; + } + + return false; + } + + /** + * Returns the hex dump of the given packet, truncated to + * MAX_PACKET_DUMP_LENGTH if packetLength exceeds that value. + * + * @param packetToDump the packet to dump in hex + * @param packetLength the number of bytes to dump + * + * @return the hex dump of the given packet + */ + private final static String getPacketDumpToLog(Buffer packetToDump, + int packetLength) { + if (packetLength < MAX_PACKET_DUMP_LENGTH) { + return packetToDump.dump(packetLength); + } + + StringBuffer packetDumpBuf = new StringBuffer(MAX_PACKET_DUMP_LENGTH * 4); + packetDumpBuf.append(packetToDump.dump(MAX_PACKET_DUMP_LENGTH)); + packetDumpBuf.append(Messages.getString("MysqlIO.36")); //$NON-NLS-1$ + packetDumpBuf.append(MAX_PACKET_DUMP_LENGTH); + packetDumpBuf.append(Messages.getString("MysqlIO.37")); //$NON-NLS-1$ + + return packetDumpBuf.toString(); + } + + private final int readFully(InputStream in, byte[] b, int off, int len) + throws IOException { + if (len < 0) { + throw new IndexOutOfBoundsException(); + } + + int n = 0; + + while (n < len) { + int count = in.read(b, off + n, len - n); + + if (count < 0) { + throw new EOFException(Messages.getString("MysqlIO.EOF", + new Object[] {new Integer(len), new Integer(n)})); + } + + n += count; + } + + return n; + } + + private final long skipFully(InputStream in, long len) throws IOException { + if (len < 0) { + throw new IOException("Negative skip length not allowed"); + } + + long n = 0; + + while (n < len) { + long count = in.skip(len - n); + + if (count < 0) { + throw new EOFException(Messages.getString("MysqlIO.EOF", + new Object[] {new Long(len), new Long(n)})); + } + + n += count; + } + + return n; + } + + /** + * Reads one result set off of the wire, if the result is actually an + * update count, creates an update-count only result set. + * + * @param callingStatement DOCUMENT ME! + * @param maxRows the maximum rows to return in the result set. + * @param resultSetType scrollability + * @param resultSetConcurrency updatability + * @param streamResults should the driver leave the results on the wire, + * and read them only when needed? + * @param catalog the catalog in use + * @param resultPacket the first packet of information in the result set + * @param isBinaryEncoded is this result set from a prepared statement? + * @param preSentColumnCount do we already know the number of columns? + * @param unpackFieldInfo should we unpack the field information? + * + * @return a result set that either represents the rows, or an update count + * + * @throws SQLException if an error occurs while reading the rows + */ + private final ResultSet readResultsForQueryOrUpdate( + Statement callingStatement, int maxRows, int resultSetType, + int resultSetConcurrency, boolean streamResults, String catalog, + Buffer resultPacket, boolean isBinaryEncoded, long preSentColumnCount, + boolean unpackFieldInfo, Field[] metadataFromCache) throws SQLException { + long columnCount = resultPacket.readFieldLength(); + + if (columnCount == 0) { + return buildResultSetWithUpdates(callingStatement, resultPacket); + } else if (columnCount == Buffer.NULL_LENGTH) { + String charEncoding = null; + + if (this.connection.getUseUnicode()) { + charEncoding = this.connection.getEncoding(); + } + + String fileName = null; + + if (this.platformDbCharsetMatches) { + fileName = ((charEncoding != null) + ? resultPacket.readString(charEncoding) + : resultPacket.readString()); + } else { + fileName = resultPacket.readString(); + } + + return sendFileToServer(callingStatement, fileName); + } else { + com.mysql.jdbc.ResultSet results = getResultSet(callingStatement, + columnCount, maxRows, resultSetType, resultSetConcurrency, + streamResults, catalog, isBinaryEncoded, unpackFieldInfo, + metadataFromCache); + + return results; + } + } + + private int alignPacketSize(int a, int l) { + return ((((a) + (l)) - 1) & ~((l) - 1)); + } + + private com.mysql.jdbc.ResultSet buildResultSetWithRows( + Statement callingStatement, String catalog, + com.mysql.jdbc.Field[] fields, RowData rows, int resultSetType, + int resultSetConcurrency, boolean isBinaryEncoded) + throws SQLException { + ResultSet rs = null; + + switch (resultSetConcurrency) { + case java.sql.ResultSet.CONCUR_READ_ONLY: + rs = new com.mysql.jdbc.ResultSet(catalog, fields, rows, + this.connection, callingStatement); + + if (isBinaryEncoded) { + rs.setBinaryEncoded(); + } + + break; + + case java.sql.ResultSet.CONCUR_UPDATABLE: + rs = new com.mysql.jdbc.UpdatableResultSet(catalog, fields, rows, + this.connection, callingStatement); + + break; + + default: + return new com.mysql.jdbc.ResultSet(catalog, fields, rows, + this.connection, callingStatement); + } + + rs.setResultSetType(resultSetType); + rs.setResultSetConcurrency(resultSetConcurrency); + + return rs; + } + + private com.mysql.jdbc.ResultSet buildResultSetWithUpdates( + Statement callingStatement, Buffer resultPacket) + throws SQLException { + long updateCount = -1; + long updateID = -1; + String info = null; + + try { + if (this.useNewUpdateCounts) { + updateCount = resultPacket.newReadLength(); + updateID = resultPacket.newReadLength(); + } else { + updateCount = resultPacket.readLength(); + updateID = resultPacket.readLength(); + } + + if (this.use41Extensions) { + this.serverStatus = resultPacket.readInt(); + + this.warningCount = resultPacket.readInt(); + + if (this.warningCount > 0) { + this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand() + } + + resultPacket.readByte(); // advance pointer + + if (this.profileSql) { + this.queryNoIndexUsed = (this.serverStatus & + SERVER_QUERY_NO_GOOD_INDEX_USED) != 0; + this.queryBadIndexUsed = (this.serverStatus & + SERVER_QUERY_NO_INDEX_USED) != 0; + } + } + + if (this.connection.isReadInfoMsgEnabled()) { + info = resultPacket.readString(); + } + } catch (Exception ex) { + throw SQLError.createSQLException(SQLError.get( + SQLError.SQL_STATE_GENERAL_ERROR) + ": " //$NON-NLS-1$ + +ex.getClass().getName(), SQLError.SQL_STATE_GENERAL_ERROR, -1); + } + + ResultSet updateRs = new com.mysql.jdbc.ResultSet(updateCount, + updateID, this.connection, callingStatement); + + if (info != null) { + updateRs.setServerInfo(info); + } + + return updateRs; + } + + private void checkForOutstandingStreamingData() throws SQLException { + if (this.streamingData != null) { + if (!this.connection.getClobberStreamingResults()) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.39") //$NON-NLS-1$ + +this.streamingData + + Messages.getString("MysqlIO.40") //$NON-NLS-1$ + +Messages.getString("MysqlIO.41") //$NON-NLS-1$ + +Messages.getString("MysqlIO.42")); //$NON-NLS-1$ + } + + // Close the result set + this.streamingData.getOwner().realClose(false); + + // clear any pending data.... + clearInputStream(); + } + } + + private Buffer compressPacket(Buffer packet, int offset, int packetLen, + int headerLength) throws SQLException { + packet.writeLongInt(packetLen - headerLength); + packet.writeByte((byte) 0); // wrapped packet has 0 packet seq. + + int lengthToWrite = 0; + int compressedLength = 0; + byte[] bytesToCompress = packet.getByteBuffer(); + byte[] compressedBytes = null; + int offsetWrite = 0; + + if (packetLen < MIN_COMPRESS_LEN) { + lengthToWrite = packetLen; + compressedBytes = packet.getByteBuffer(); + compressedLength = 0; + offsetWrite = offset; + } else { + compressedBytes = new byte[bytesToCompress.length * 2]; + + this.deflater.reset(); + this.deflater.setInput(bytesToCompress, offset, packetLen); + this.deflater.finish(); + + int compLen = this.deflater.deflate(compressedBytes); + + if (compLen > packetLen) { + lengthToWrite = packetLen; + compressedBytes = packet.getByteBuffer(); + compressedLength = 0; + offsetWrite = offset; + } else { + lengthToWrite = compLen; + headerLength += COMP_HEADER_LENGTH; + compressedLength = packetLen; + } + } + + Buffer compressedPacket = new Buffer(packetLen + headerLength); + + compressedPacket.setPosition(0); + compressedPacket.writeLongInt(lengthToWrite); + compressedPacket.writeByte(this.packetSequence); + compressedPacket.writeLongInt(compressedLength); + compressedPacket.writeBytesNoNull(compressedBytes, offsetWrite, + lengthToWrite); + + return compressedPacket; + } + + private final void readServerStatusForResultSets(Buffer rowPacket) + throws SQLException { + if (this.use41Extensions) { + rowPacket.readByte(); // skips the 'last packet' flag + + this.warningCount = rowPacket.readInt(); + + if (this.warningCount > 0) { + this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand() + } + + this.serverStatus = rowPacket.readInt(); + + if (this.profileSql) { + this.queryNoIndexUsed = (this.serverStatus & + SERVER_QUERY_NO_GOOD_INDEX_USED) != 0; + this.queryBadIndexUsed = (this.serverStatus & + SERVER_QUERY_NO_INDEX_USED) != 0; + } + } + } + + private SocketFactory createSocketFactory() throws SQLException { + try { + if (this.socketFactoryClassName == null) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.75"), //$NON-NLS-1$ + SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE); + } + + return (SocketFactory) (Class.forName(this.socketFactoryClassName) + .newInstance()); + } catch (Exception ex) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.76") //$NON-NLS-1$ + +this.socketFactoryClassName + + Messages.getString("MysqlIO.77") + ex.toString() //$NON-NLS-1$ + +(this.connection.getParanoid() ? "" //$NON-NLS-1$ + : Util.stackTraceToString(ex)), + SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE); + } + } + + private void enqueuePacketForDebugging(boolean isPacketBeingSent, + boolean isPacketReused, int sendLength, byte[] header, Buffer packet) + throws SQLException { + if ((this.packetDebugRingBuffer.size() + 1) > this.connection.getPacketDebugBufferSize()) { + this.packetDebugRingBuffer.removeFirst(); + } + + StringBuffer packetDump = null; + + if (!isPacketBeingSent) { + int bytesToDump = Math.min(MAX_PACKET_DUMP_LENGTH, + packet.getBufLength()); + + Buffer packetToDump = new Buffer(4 + bytesToDump); + + packetToDump.setPosition(0); + packetToDump.writeBytesNoNull(header); + packetToDump.writeBytesNoNull(packet.getBytes(0, bytesToDump)); + + String packetPayload = packetToDump.dump(bytesToDump); + + packetDump = new StringBuffer(96 + packetPayload.length()); + + packetDump.append("Server "); + + if (isPacketReused) { + packetDump.append("(re-used)"); + } else { + packetDump.append("(new)"); + } + + packetDump.append(" "); + packetDump.append(packet.toSuperString()); + packetDump.append(" --------------------> Client\n"); + packetDump.append("\nPacket payload:\n\n"); + packetDump.append(packetPayload); + + if (bytesToDump == MAX_PACKET_DUMP_LENGTH) { + packetDump.append("\nNote: Packet of " + packet.getBufLength() + + " bytes truncated to " + MAX_PACKET_DUMP_LENGTH + + " bytes.\n"); + } + } else { + int bytesToDump = Math.min(MAX_PACKET_DUMP_LENGTH, sendLength); + + String packetPayload = packet.dump(bytesToDump); + + packetDump = new StringBuffer(64 + 4 + packetPayload.length()); + + packetDump.append("Client "); + packetDump.append(packet.toSuperString()); + packetDump.append("--------------------> Server\n"); + packetDump.append("\nPacket payload:\n\n"); + packetDump.append(packetPayload); + + if (bytesToDump == MAX_PACKET_DUMP_LENGTH) { + packetDump.append("\nNote: Packet of " + sendLength + + " bytes truncated to " + MAX_PACKET_DUMP_LENGTH + + " bytes.\n"); + } + } + + this.packetDebugRingBuffer.addLast(packetDump); + } + + private RowData readSingleRowSet(long columnCount, int maxRows, + int resultSetConcurrency, boolean isBinaryEncoded, Field[] fields) + throws SQLException { + RowData rowData; + ArrayList rows = new ArrayList(); + + // Now read the data + Object rowBytes = nextRow(fields, (int) columnCount, isBinaryEncoded, + resultSetConcurrency); + + int rowCount = 0; + + if (rowBytes != null) { + rows.add(rowBytes); + rowCount = 1; + } + + while (rowBytes != null) { + rowBytes = nextRow(fields, (int) columnCount, isBinaryEncoded, + resultSetConcurrency); + + if (rowBytes != null) { + if ((maxRows == -1) || (rowCount < maxRows)) { + rows.add(rowBytes); + rowCount++; + } + } + } + + rowData = new RowDataStatic(rows); + + return rowData; + } + + /** + * Don't hold on to overly-large packets + */ + private void reclaimLargeReusablePacket() { + if ((this.reusablePacket != null) && + (this.reusablePacket.getCapacity() > 1048576)) { + this.reusablePacket = new Buffer(INITIAL_PACKET_SIZE); + } + } + + /** + * Re-use a packet to read from the MySQL server + * + * @param reuse DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + * @throws SQLException DOCUMENT ME! + */ + private final Buffer reuseAndReadPacket(Buffer reuse) + throws SQLException { + + try { + reuse.setWasMultiPacket(false); + + int lengthRead = readFully(this.mysqlInput, + this.packetHeaderBuf, 0, 4); + + if (lengthRead < 4) { + forceClose(); + throw new IOException(Messages.getString("MysqlIO.43")); //$NON-NLS-1$ + } + + int packetLength = (this.packetHeaderBuf[0] & 0xff) + + ((this.packetHeaderBuf[1] & 0xff) << 8) + + ((this.packetHeaderBuf[2] & 0xff) << 16); + + if (this.traceProtocol) { + StringBuffer traceMessageBuf = new StringBuffer(); + + traceMessageBuf.append(Messages.getString("MysqlIO.44")); //$NON-NLS-1$ + traceMessageBuf.append(packetLength); + traceMessageBuf.append(Messages.getString("MysqlIO.45")); //$NON-NLS-1$ + traceMessageBuf.append(StringUtils.dumpAsHex( + this.packetHeaderBuf, 4)); + + this.connection.getLog().logTrace(traceMessageBuf.toString()); + } + + byte multiPacketSeq = this.packetHeaderBuf[3]; + + if (!this.packetSequenceReset) { + if (this.enablePacketDebug && this.checkPacketSequence) { + checkPacketSequencing(multiPacketSeq); + } + } else { + this.packetSequenceReset = false; + } + + this.readPacketSequence = multiPacketSeq; + + // Set the Buffer to it's original state + reuse.setPosition(0); + + // Do we need to re-alloc the byte buffer? + // + // Note: We actually check the length of the buffer, + // rather than getBufLength(), because getBufLength() is not + // necesarily the actual length of the byte array + // used as the buffer + if (reuse.getByteBuffer().length <= packetLength) { + reuse.setByteBuffer(new byte[packetLength + 1]); + } + + // Set the new length + reuse.setBufLength(packetLength); + + // Read the data from the server + int numBytesRead = readFully(this.mysqlInput, + reuse.getByteBuffer(), 0, packetLength); + + if (numBytesRead != packetLength) { + throw new IOException("Short read, expected " + + packetLength + " bytes, only read " + numBytesRead); + } + + if (this.traceProtocol) { + StringBuffer traceMessageBuf = new StringBuffer(); + + traceMessageBuf.append(Messages.getString("MysqlIO.46")); //$NON-NLS-1$ + traceMessageBuf.append(getPacketDumpToLog(reuse, + packetLength)); + + this.connection.getLog().logTrace(traceMessageBuf.toString()); + } + + if (this.enablePacketDebug) { + enqueuePacketForDebugging(false, true, 0, + this.packetHeaderBuf, reuse); + } + + boolean isMultiPacket = false; + + if (packetLength == this.maxThreeBytes) { + reuse.setPosition(this.maxThreeBytes); + + int packetEndPoint = packetLength; + + // it's multi-packet + isMultiPacket = true; + + lengthRead = readFully(this.mysqlInput, + this.packetHeaderBuf, 0, 4); + + if (lengthRead < 4) { + forceClose(); + throw new IOException(Messages.getString("MysqlIO.47")); //$NON-NLS-1$ + } + + packetLength = (this.packetHeaderBuf[0] & 0xff) + + ((this.packetHeaderBuf[1] & 0xff) << 8) + + ((this.packetHeaderBuf[2] & 0xff) << 16); + + Buffer multiPacket = new Buffer(packetLength); + boolean firstMultiPkt = true; + + while (true) { + if (!firstMultiPkt) { + lengthRead = readFully(this.mysqlInput, + this.packetHeaderBuf, 0, 4); + + if (lengthRead < 4) { + forceClose(); + throw new IOException(Messages.getString( + "MysqlIO.48")); //$NON-NLS-1$ + } + + packetLength = (this.packetHeaderBuf[0] & 0xff) + + ((this.packetHeaderBuf[1] & 0xff) << 8) + + ((this.packetHeaderBuf[2] & 0xff) << 16); + } else { + firstMultiPkt = false; + } + + if (!this.useNewLargePackets && (packetLength == 1)) { + clearInputStream(); + + break; + } else if (packetLength < this.maxThreeBytes) { + byte newPacketSeq = this.packetHeaderBuf[3]; + + if (newPacketSeq != (multiPacketSeq + 1)) { + throw new IOException(Messages.getString( + "MysqlIO.49")); //$NON-NLS-1$ + } + + multiPacketSeq = newPacketSeq; + + // Set the Buffer to it's original state + multiPacket.setPosition(0); + + // Set the new length + multiPacket.setBufLength(packetLength); + + // Read the data from the server + byte[] byteBuf = multiPacket.getByteBuffer(); + int lengthToWrite = packetLength; + + int bytesRead = readFully(this.mysqlInput, byteBuf, + 0, packetLength); + + if (bytesRead != lengthToWrite) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, + SQLError.createSQLException(Messages.getString( + "MysqlIO.50") //$NON-NLS-1$ + +lengthToWrite + + Messages.getString("MysqlIO.51") + + bytesRead //$NON-NLS-1$ + +".")); //$NON-NLS-1$ + } + + reuse.writeBytesNoNull(byteBuf, 0, lengthToWrite); + + packetEndPoint += lengthToWrite; + + break; // end of multipacket sequence + } + + byte newPacketSeq = this.packetHeaderBuf[3]; + + if (newPacketSeq != (multiPacketSeq + 1)) { + throw new IOException(Messages.getString( + "MysqlIO.53")); //$NON-NLS-1$ + } + + multiPacketSeq = newPacketSeq; + + // Set the Buffer to it's original state + multiPacket.setPosition(0); + + // Set the new length + multiPacket.setBufLength(packetLength); + + // Read the data from the server + byte[] byteBuf = multiPacket.getByteBuffer(); + int lengthToWrite = packetLength; + + int bytesRead = readFully(this.mysqlInput, byteBuf, 0, + packetLength); + + if (bytesRead != lengthToWrite) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, + SQLError.createSQLException(Messages.getString( + "MysqlIO.54") //$NON-NLS-1$ + +lengthToWrite + + Messages.getString("MysqlIO.55") //$NON-NLS-1$ + +bytesRead + ".")); //$NON-NLS-1$ + } + + reuse.writeBytesNoNull(byteBuf, 0, lengthToWrite); + + packetEndPoint += lengthToWrite; + } + + reuse.setPosition(0); + reuse.setWasMultiPacket(true); + } + + if (!isMultiPacket) { + reuse.getByteBuffer()[packetLength] = 0; // Null-termination + } + + return reuse; + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } catch (OutOfMemoryError oom) { + try { + // _Try_ this + clearInputStream(); + } finally { + try { + this.connection.realClose(false, false, true, oom); + } finally { + throw oom; + } + } + } + + } + + /** + * @param multiPacketSeq + * @throws CommunicationsException + */ + private void checkPacketSequencing(byte multiPacketSeq) + throws CommunicationsException { + if ((multiPacketSeq == -128) && (this.readPacketSequence != 127)) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, + new IOException("Packets out of order, expected packet # -128, but received packet # " + + multiPacketSeq)); + } + + if ((this.readPacketSequence == -1) && (multiPacketSeq != 0)) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, + new IOException("Packets out of order, expected packet # -1, but received packet # " + + multiPacketSeq)); + } + + if ((multiPacketSeq != -128) && (this.readPacketSequence != -1) && + (multiPacketSeq != (this.readPacketSequence + 1))) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, + new IOException("Packets out of order, expected packet # " + + (this.readPacketSequence + 1) + ", but received packet # " + + multiPacketSeq)); + } + } + + void enableMultiQueries() throws SQLException { + Buffer buf = getSharedSendPacket(); + + buf.clear(); + buf.writeByte((byte)MysqlDefs.COM_SET_OPTION); + buf.writeInt(0); + sendCommand(MysqlDefs.COM_SET_OPTION, null, buf, false, null); + } + + void disableMultiQueries() throws SQLException { + Buffer buf = getSharedSendPacket(); + + buf.clear(); + buf.writeByte((byte)MysqlDefs.COM_SET_OPTION); + buf.writeInt(1); + sendCommand(MysqlDefs.COM_SET_OPTION, null, buf, false, null); + } + + private final void send(Buffer packet, int packetLen) + throws SQLException { + try { + if (packetLen > this.maxAllowedPacket) { + throw new PacketTooBigException(packetLen, this.maxAllowedPacket); + } + + if (this.connection.getMaintainTimeStats()) { + this.lastPacketSentTimeMs = System.currentTimeMillis(); + } + + if ((this.serverMajorVersion >= 4) && + (packetLen >= this.maxThreeBytes)) { + sendSplitPackets(packet); + } else { + this.packetSequence++; + + Buffer packetToSend = packet; + + packetToSend.setPosition(0); + + if (this.useCompression) { + int originalPacketLen = packetLen; + + packetToSend = compressPacket(packet, 0, packetLen, + HEADER_LENGTH); + packetLen = packetToSend.getPosition(); + + if (this.traceProtocol) { + StringBuffer traceMessageBuf = new StringBuffer(); + + traceMessageBuf.append(Messages.getString("MysqlIO.57")); //$NON-NLS-1$ + traceMessageBuf.append(getPacketDumpToLog( + packetToSend, packetLen)); + traceMessageBuf.append(Messages.getString("MysqlIO.58")); //$NON-NLS-1$ + traceMessageBuf.append(getPacketDumpToLog(packet, + originalPacketLen)); + + this.connection.getLog().logTrace(traceMessageBuf.toString()); + } + } else { + packetToSend.writeLongInt(packetLen - HEADER_LENGTH); + packetToSend.writeByte(this.packetSequence); + + if (this.traceProtocol) { + StringBuffer traceMessageBuf = new StringBuffer(); + + traceMessageBuf.append(Messages.getString("MysqlIO.59")); //$NON-NLS-1$ + traceMessageBuf.append(packetToSend.dump(packetLen)); + + this.connection.getLog().logTrace(traceMessageBuf.toString()); + } + } + + + this.mysqlOutput.write(packetToSend.getByteBuffer(), 0, + packetLen); + this.mysqlOutput.flush(); + } + + if (this.enablePacketDebug) { + enqueuePacketForDebugging(true, false, packetLen + 5, + this.packetHeaderBuf, packet); + } + + // + // Don't hold on to large packets + // + if (packet == this.sharedSendPacket) { + reclaimLargeSharedSendPacket(); + } + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } + } + + /** + * Reads and sends a file to the server for LOAD DATA LOCAL INFILE + * + * @param callingStatement DOCUMENT ME! + * @param fileName the file name to send. + * + * @return DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ + private final ResultSet sendFileToServer(Statement callingStatement, + String fileName) throws SQLException { + + Buffer filePacket = (this.loadFileBufRef == null) ? null + : (Buffer) (this.loadFileBufRef.get()); + + int bigPacketLength = Math.min(this.connection.getMaxAllowedPacket() - + (HEADER_LENGTH * 3), + alignPacketSize(this.connection.getMaxAllowedPacket() - 16, 4096) - + (HEADER_LENGTH * 3)); + + int oneMeg = 1024 * 1024; + + int smallerPacketSizeAligned = Math.min(oneMeg - (HEADER_LENGTH * 3), + alignPacketSize(oneMeg - 16, 4096) - (HEADER_LENGTH * 3)); + + int packetLength = Math.min(smallerPacketSizeAligned, bigPacketLength); + + if (filePacket == null) { + try { + filePacket = new Buffer((packetLength + HEADER_LENGTH)); + this.loadFileBufRef = new SoftReference(filePacket); + } catch (OutOfMemoryError oom) { + throw SQLError.createSQLException("Could not allocate packet of " + packetLength + + " bytes required for LOAD DATA LOCAL INFILE operation." + + " Try increasing max heap allocation for JVM or decreasing server variable " + + "'max_allowed_packet'", SQLError.SQL_STATE_MEMORY_ALLOCATION_FAILURE); + + } + } + + filePacket.clear(); + send(filePacket, 0); + + byte[] fileBuf = new byte[packetLength]; + + BufferedInputStream fileIn = null; + + try { + if (!this.connection.getAllowLoadLocalInfile()) { + throw SQLError.createSQLException( + Messages.getString("MysqlIO.LoadDataLocalNotAllowed"), + SQLError.SQL_STATE_GENERAL_ERROR); + } + + if (!this.connection.getAllowUrlInLocalInfile()) { + fileIn = new BufferedInputStream(new FileInputStream(fileName)); + } else { + // First look for ':' + if (fileName.indexOf(":") != -1) { + try { + URL urlFromFileName = new URL(fileName); + fileIn = new BufferedInputStream(urlFromFileName.openStream()); + } catch (MalformedURLException badUrlEx) { + // we fall back to trying this as a file input stream + fileIn = new BufferedInputStream(new FileInputStream( + fileName)); + } + } else { + fileIn = new BufferedInputStream(new FileInputStream( + fileName)); + } + } + + int bytesRead = 0; + + while ((bytesRead = fileIn.read(fileBuf)) != -1) { + filePacket.clear(); + filePacket.writeBytesNoNull(fileBuf, 0, bytesRead); + send(filePacket, filePacket.getPosition()); + } + } catch (IOException ioEx) { + StringBuffer messageBuf = new StringBuffer(Messages.getString( + "MysqlIO.60")); //$NON-NLS-1$ + + if (!this.connection.getParanoid()) { + messageBuf.append("'"); //$NON-NLS-1$ + + if (fileName != null) { + messageBuf.append(fileName); + } + + messageBuf.append("'"); //$NON-NLS-1$ + } + + messageBuf.append(Messages.getString("MysqlIO.63")); //$NON-NLS-1$ + + if (!this.connection.getParanoid()) { + messageBuf.append(Messages.getString("MysqlIO.64")); //$NON-NLS-1$ + messageBuf.append(Util.stackTraceToString(ioEx)); + } + + throw SQLError.createSQLException(messageBuf.toString(), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } finally { + if (fileIn != null) { + try { + fileIn.close(); + } catch (Exception ex) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.65"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + + fileIn = null; + } else { + // file open failed, but server needs one packet + filePacket.clear(); + send(filePacket, filePacket.getPosition()); + checkErrorPacket(); // to clear response off of queue + } + } + + // send empty packet to mark EOF + filePacket.clear(); + send(filePacket, filePacket.getPosition()); + + Buffer resultPacket = checkErrorPacket(); + + return buildResultSetWithUpdates(callingStatement, resultPacket); + } + + /** + * Checks for errors in the reply packet, and if none, returns the reply + * packet, ready for reading + * + * @param command the command being issued (if used) + * + * @return DOCUMENT ME! + * + * @throws SQLException if an error packet was received + * @throws CommunicationsException DOCUMENT ME! + */ + private Buffer checkErrorPacket(int command) throws SQLException { + int statusCode = 0; + Buffer resultPacket = null; + this.serverStatus = 0; + + try { + // Check return value, if we get a java.io.EOFException, + // the server has gone away. We'll pass it on up the + // exception chain and let someone higher up decide + // what to do (barf, reconnect, etc). + resultPacket = reuseAndReadPacket(this.reusablePacket); + statusCode = resultPacket.readByte(); + } catch (SQLException sqlEx) { + // Don't wrap SQL Exceptions + throw sqlEx; + } catch (Exception fallThru) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, fallThru); + } + + // Error handling + if (statusCode == (byte) 0xff) { + String serverErrorMessage; + int errno = 2000; + + if (this.protocolVersion > 9) { + errno = resultPacket.readInt(); + + String xOpen = null; + + serverErrorMessage = + resultPacket.readString(this.connection.getErrorMessageEncoding()); + + if (serverErrorMessage.startsWith("#")) { //$NON-NLS-1$ + + // we have an SQLState + if (serverErrorMessage.length() > 6) { + xOpen = serverErrorMessage.substring(1, 6); + serverErrorMessage = serverErrorMessage.substring(6); + + if (xOpen.equals("HY000")) { //$NON-NLS-1$ + xOpen = SQLError.mysqlToSqlState(errno, + this.connection.getUseSqlStateCodes()); + } + } else { + xOpen = SQLError.mysqlToSqlState(errno, + this.connection.getUseSqlStateCodes()); + } + } else { + xOpen = SQLError.mysqlToSqlState(errno, + this.connection.getUseSqlStateCodes()); + } + + clearInputStream(); + + StringBuffer errorBuf = new StringBuffer(); + + String xOpenErrorMessage = SQLError.get(xOpen); + + if (!this.connection.getUseOnlyServerErrorMessages()) { + if (xOpenErrorMessage != null) { + errorBuf.append(xOpenErrorMessage); + errorBuf.append(Messages.getString("MysqlIO.68")); //$NON-NLS-1$ + } + } + + errorBuf.append(serverErrorMessage); + + if (!this.connection.getUseOnlyServerErrorMessages()) { + if (xOpenErrorMessage != null) { + errorBuf.append("\""); //$NON-NLS-1$ + } + } + + appendInnodbStatusInformation(xOpen, errorBuf); + + if (xOpen != null && xOpen.startsWith("22")) { + throw new MysqlDataTruncation(errorBuf.toString(), 0, true, false, 0, 0); + } else { + throw SQLError.createSQLException(errorBuf.toString(), xOpen, errno); + } + } + + serverErrorMessage = resultPacket.readString( + this.connection.getErrorMessageEncoding()); + clearInputStream(); + + if (serverErrorMessage.indexOf(Messages.getString("MysqlIO.70")) != -1) { //$NON-NLS-1$ + throw SQLError.createSQLException(SQLError.get( + SQLError.SQL_STATE_COLUMN_NOT_FOUND) + + ", " //$NON-NLS-1$ + +serverErrorMessage, SQLError.SQL_STATE_COLUMN_NOT_FOUND, + -1); + } + + StringBuffer errorBuf = new StringBuffer(Messages.getString( + "MysqlIO.72")); //$NON-NLS-1$ + errorBuf.append(serverErrorMessage); + errorBuf.append("\""); //$NON-NLS-1$ + + throw SQLError.createSQLException(SQLError.get( + SQLError.SQL_STATE_GENERAL_ERROR) + ", " //$NON-NLS-1$ + +errorBuf.toString(), SQLError.SQL_STATE_GENERAL_ERROR, -1); + } + + return resultPacket; + } + + private void appendInnodbStatusInformation(String xOpen, + StringBuffer errorBuf) throws SQLException { + if (this.connection.getIncludeInnodbStatusInDeadlockExceptions() + && xOpen != null + && (xOpen.startsWith("40") || xOpen.startsWith("41")) + && this.streamingData == null) { + ResultSet rs = null; + + try { + rs = sqlQueryDirect(null, "SHOW ENGINE INNODB STATUS", + this.connection.getEncoding(), null, -1, + this.connection, ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, false, this.connection + .getCatalog(), true); + if (rs.next()) { + errorBuf.append("\n\n"); + errorBuf.append(rs.getString(1)); + } else { + errorBuf.append(Messages + .getString("MysqlIO.NoInnoDBStatusFound")); + } + } catch (Exception ex) { + errorBuf.append(Messages + .getString("MysqlIO.InnoDBStatusFailed")); + errorBuf.append("\n\n"); + errorBuf.append(Util.stackTraceToString(ex)); + } finally { + if (rs != null) { + rs.close(); + } + } + } + } + + /** + * Sends a large packet to the server as a series of smaller packets + * + * @param packet + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + * @throws CommunicationsException + * DOCUMENT ME! + */ + private final void sendSplitPackets(Buffer packet) + throws SQLException { + try { + // + // Big packets are handled by splitting them in packets of MAX_THREE_BYTES + // length. The last packet is always a packet that is < MAX_THREE_BYTES. + // (The last packet may even have a length of 0) + // + // + // NB: Guarded by execSQL. If the driver changes architecture, this + // will need to be synchronized in some other way + // + Buffer headerPacket = (this.splitBufRef == null) ? null + : (Buffer) (this.splitBufRef.get()); + + // + // Store this packet in a soft reference...It can be re-used if not GC'd (so clients + // that use it frequently won't have to re-alloc the 16M buffer), but we don't + // penalize infrequent users of large packets by keeping 16M allocated all of the time + // + if (headerPacket == null) { + headerPacket = new Buffer((this.maxThreeBytes + + HEADER_LENGTH)); + this.splitBufRef = new SoftReference(headerPacket); + } + + int len = packet.getPosition(); + int splitSize = this.maxThreeBytes; + int originalPacketPos = HEADER_LENGTH; + byte[] origPacketBytes = packet.getByteBuffer(); + byte[] headerPacketBytes = headerPacket.getByteBuffer(); + + while (len >= this.maxThreeBytes) { + this.packetSequence++; + + headerPacket.setPosition(0); + headerPacket.writeLongInt(splitSize); + + headerPacket.writeByte(this.packetSequence); + System.arraycopy(origPacketBytes, originalPacketPos, + headerPacketBytes, 4, splitSize); + + int packetLen = splitSize + HEADER_LENGTH; + + // + // Swap a compressed packet in, if we're using + // compression... + // + if (!this.useCompression) { + this.mysqlOutput.write(headerPacketBytes, 0, + splitSize + HEADER_LENGTH); + this.mysqlOutput.flush(); + } else { + Buffer packetToSend; + + headerPacket.setPosition(0); + packetToSend = compressPacket(headerPacket, HEADER_LENGTH, + splitSize, HEADER_LENGTH); + packetLen = packetToSend.getPosition(); + + this.mysqlOutput.write(packetToSend.getByteBuffer(), 0, + packetLen); + this.mysqlOutput.flush(); + } + + originalPacketPos += splitSize; + len -= splitSize; + } + + // + // Write last packet + // + headerPacket.clear(); + headerPacket.setPosition(0); + headerPacket.writeLongInt(len - HEADER_LENGTH); + this.packetSequence++; + headerPacket.writeByte(this.packetSequence); + + if (len != 0) { + System.arraycopy(origPacketBytes, originalPacketPos, + headerPacketBytes, 4, len - HEADER_LENGTH); + } + + int packetLen = len - HEADER_LENGTH; + + // + // Swap a compressed packet in, if we're using + // compression... + // + if (!this.useCompression) { + this.mysqlOutput.write(headerPacket.getByteBuffer(), 0, len); + this.mysqlOutput.flush(); + } else { + Buffer packetToSend; + + headerPacket.setPosition(0); + packetToSend = compressPacket(headerPacket, HEADER_LENGTH, + packetLen, HEADER_LENGTH); + packetLen = packetToSend.getPosition(); + + this.mysqlOutput.write(packetToSend.getByteBuffer(), 0, + packetLen); + this.mysqlOutput.flush(); + } + } catch (IOException ioEx) { + throw new CommunicationsException(this.connection, + this.lastPacketSentTimeMs, ioEx); + } + } + + private void reclaimLargeSharedSendPacket() { + if ((this.sharedSendPacket != null) && + (this.sharedSendPacket.getCapacity() > 1048576)) { + this.sharedSendPacket = new Buffer(INITIAL_PACKET_SIZE); + } + } + + boolean hadWarnings() { + return this.hadWarnings; + } + + void scanForAndThrowDataTruncation() throws SQLException { + if ((this.streamingData == null) && versionMeetsMinimum(4, 1, 0) && + this.connection.getJdbcCompliantTruncation() && this.warningCount > 0) { + SQLError.convertShowWarningsToSQLWarnings(this.connection, + this.warningCount, true); + } + } + + /** + * Secure authentication for 4.1 and newer servers. + * + * @param packet DOCUMENT ME! + * @param packLength + * @param user + * @param password + * @param database DOCUMENT ME! + * @param writeClientParams + * + * @throws SQLException + */ + private void secureAuth(Buffer packet, int packLength, String user, + String password, String database, boolean writeClientParams) + throws SQLException { + // Passwords can be 16 chars long + if (packet == null) { + packet = new Buffer(packLength); + } + + if (writeClientParams) { + if (this.use41Extensions) { + if (versionMeetsMinimum(4, 1, 1)) { + packet.writeLong(this.clientParam); + packet.writeLong(this.maxThreeBytes); + + // charset, JDBC will connect as 'latin1', + // and use 'SET NAMES' to change to the desired + // charset after the connection is established. + packet.writeByte((byte) 8); + + // Set of bytes reserved for future use. + packet.writeBytesNoNull(new byte[23]); + } else { + packet.writeLong(this.clientParam); + packet.writeLong(this.maxThreeBytes); + } + } else { + packet.writeInt((int) this.clientParam); + packet.writeLongInt(this.maxThreeBytes); + } + } + + // User/Password data + packet.writeString(user, "Cp1252", this.connection); + + if (password.length() != 0) { + /* Prepare false scramble */ + packet.writeString(FALSE_SCRAMBLE, "Cp1252", this.connection); + } else { + /* For empty password*/ + packet.writeString("", "Cp1252", this.connection); //$NON-NLS-1$ + } + + if (this.useConnectWithDb) { + packet.writeString(database, "Cp1252", this.connection); + } + + send(packet, packet.getPosition()); + + // + // Don't continue stages if password is empty + // + if (password.length() > 0) { + Buffer b = readPacket(); + + b.setPosition(0); + + byte[] replyAsBytes = b.getByteBuffer(); + + if ((replyAsBytes.length == 25) && (replyAsBytes[0] != 0)) { + // Old passwords will have '*' at the first byte of hash */ + if (replyAsBytes[0] != '*') { + try { + /* Build full password hash as it is required to decode scramble */ + byte[] buff = Security.passwordHashStage1(password); + + /* Store copy as we'll need it later */ + byte[] passwordHash = new byte[buff.length]; + System.arraycopy(buff, 0, passwordHash, 0, buff.length); + + /* Finally hash complete password using hash we got from server */ + passwordHash = Security.passwordHashStage2(passwordHash, + replyAsBytes); + + byte[] packetDataAfterSalt = new byte[replyAsBytes.length - + 5]; + + System.arraycopy(replyAsBytes, 4, packetDataAfterSalt, + 0, replyAsBytes.length - 5); + + byte[] mysqlScrambleBuff = new byte[20]; + + /* Decypt and store scramble 4 = hash for stage2 */ + Security.passwordCrypt(packetDataAfterSalt, + mysqlScrambleBuff, passwordHash, 20); + + /* Encode scramble with password. Recycle buffer */ + Security.passwordCrypt(mysqlScrambleBuff, buff, buff, 20); + + Buffer packet2 = new Buffer(25); + packet2.writeBytesNoNull(buff); + + this.packetSequence++; + + send(packet2, 24); + } catch (NoSuchAlgorithmException nse) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.91") //$NON-NLS-1$ + +Messages.getString("MysqlIO.92"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } else { + try { + /* Create password to decode scramble */ + byte[] passwordHash = Security.createKeyFromOldPassword(password); + + /* Decypt and store scramble 4 = hash for stage2 */ + byte[] netReadPos4 = new byte[replyAsBytes.length - 5]; + + System.arraycopy(replyAsBytes, 4, netReadPos4, 0, + replyAsBytes.length - 5); + + byte[] mysqlScrambleBuff = new byte[20]; + + /* Decypt and store scramble 4 = hash for stage2 */ + Security.passwordCrypt(netReadPos4, mysqlScrambleBuff, + passwordHash, 20); + + /* Finally scramble decoded scramble with password */ + String scrambledPassword = Util.scramble(new String( + mysqlScrambleBuff), password); + + Buffer packet2 = new Buffer(packLength); + packet2.writeString(scrambledPassword, "Cp1252", this.connection); + this.packetSequence++; + + send(packet2, 24); + } catch (NoSuchAlgorithmException nse) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.93") //$NON-NLS-1$ + +Messages.getString("MysqlIO.94"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + } + } + } + + /** + * Secure authentication for 4.1.1 and newer servers. + * + * @param packet DOCUMENT ME! + * @param packLength + * @param user + * @param password + * @param database DOCUMENT ME! + * @param writeClientParams + * + * @throws SQLException + */ + void secureAuth411(Buffer packet, int packLength, String user, + String password, String database, boolean writeClientParams) + throws SQLException { + // SERVER: public_seed=create_random_string() + // send(public_seed) + // + // CLIENT: recv(public_seed) + // hash_stage1=sha1("password") + // hash_stage2=sha1(hash_stage1) + // reply=xor(hash_stage1, sha1(public_seed,hash_stage2) + // + // // this three steps are done in scramble() + // + // send(reply) + // + // + // SERVER: recv(reply) + // hash_stage1=xor(reply, sha1(public_seed,hash_stage2)) + // candidate_hash2=sha1(hash_stage1) + // check(candidate_hash2==hash_stage2) + // Passwords can be 16 chars long + if (packet == null) { + packet = new Buffer(packLength); + } + + if (writeClientParams) { + if (this.use41Extensions) { + if (versionMeetsMinimum(4, 1, 1)) { + packet.writeLong(this.clientParam); + packet.writeLong(this.maxThreeBytes); + + // charset, JDBC will connect as 'latin1', + // and use 'SET NAMES' to change to the desired + // charset after the connection is established. + packet.writeByte((byte) 8); + + // Set of bytes reserved for future use. + packet.writeBytesNoNull(new byte[23]); + } else { + packet.writeLong(this.clientParam); + packet.writeLong(this.maxThreeBytes); + } + } else { + packet.writeInt((int) this.clientParam); + packet.writeLongInt(this.maxThreeBytes); + } + } + + // User/Password data + packet.writeString(user); + + if (password.length() != 0) { + packet.writeByte((byte) 0x14); + + try { + packet.writeBytesNoNull(Security.scramble411(password, this.seed)); + } catch (NoSuchAlgorithmException nse) { + throw SQLError.createSQLException(Messages.getString("MysqlIO.95") //$NON-NLS-1$ + +Messages.getString("MysqlIO.96"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } else { + /* For empty password*/ + packet.writeByte((byte) 0); + } + + if (this.useConnectWithDb) { + packet.writeString(database); + } + + send(packet, packet.getPosition()); + + byte savePacketSequence = this.packetSequence++; + + Buffer reply = checkErrorPacket(); + + if (reply.isLastDataPacket()) { + /* + By sending this very specific reply server asks us to send scrambled + password in old format. The reply contains scramble_323. + */ + this.packetSequence = ++savePacketSequence; + packet.clear(); + + String seed323 = this.seed.substring(0, 8); + packet.writeString(Util.newCrypt(password, seed323)); + send(packet, packet.getPosition()); + + /* Read what server thinks about out new auth message report */ + checkErrorPacket(); + } + } + + /** + * Un-packs binary-encoded result set data for one row + * + * @param fields + * @param binaryData + * @param resultSetConcurrency DOCUMENT ME! + * + * @return byte[][] + * + * @throws SQLException DOCUMENT ME! + */ + private final Object[] unpackBinaryResultSetRow(Field[] fields, + Buffer binaryData, int resultSetConcurrency) throws SQLException { + int numFields = fields.length; + + Object[] unpackedRowData = new Object[numFields]; + + // + // Unpack the null bitmask, first + // + + /* Reserve place for null-marker bytes */ + int nullCount = (numFields + 9) / 8; + + byte[] nullBitMask = new byte[nullCount]; + + for (int i = 0; i < nullCount; i++) { + nullBitMask[i] = binaryData.readByte(); + } + + int nullMaskPos = 0; + int bit = 4; // first two bits are reserved for future use + + // + // TODO: Benchmark if moving check for updatable result + // sets out of loop is worthwhile? + // + + for (int i = 0; i < numFields; i++) { + if ((nullBitMask[nullMaskPos] & bit) != 0) { + unpackedRowData[i] = null; + } else { + if (resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) { + extractNativeEncodedColumn(binaryData, fields, i, + unpackedRowData); + } else { + unpackNativeEncodedColumn(binaryData, fields, i, + unpackedRowData); + } + } + + if (((bit <<= 1) & 255) == 0) { + bit = 1; /* To next byte */ + + nullMaskPos++; + } + } + + return unpackedRowData; + } + + + private final void extractNativeEncodedColumn(Buffer binaryData, + Field[] fields, int columnIndex, Object[] unpackedRowData) throws SQLException { + Field curField = fields[columnIndex]; + + switch (curField.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_NULL: + break; // for dummy binds + + case MysqlDefs.FIELD_TYPE_TINY: + + unpackedRowData[columnIndex] = new byte[] {binaryData.readByte()}; + break; + + case MysqlDefs.FIELD_TYPE_SHORT: + case MysqlDefs.FIELD_TYPE_YEAR: + + unpackedRowData[columnIndex] = binaryData.getBytes(2); + break; + case MysqlDefs.FIELD_TYPE_LONG: + case MysqlDefs.FIELD_TYPE_INT24: + + unpackedRowData[columnIndex] = binaryData.getBytes(4); + break; + case MysqlDefs.FIELD_TYPE_LONGLONG: + + unpackedRowData[columnIndex] = binaryData.getBytes(8); + break; + case MysqlDefs.FIELD_TYPE_FLOAT: + + unpackedRowData[columnIndex] = binaryData.getBytes(4); + break; + case MysqlDefs.FIELD_TYPE_DOUBLE: + + unpackedRowData[columnIndex] = binaryData.getBytes(8); + break; + case MysqlDefs.FIELD_TYPE_TIME: + + int length = (int) binaryData.readFieldLength(); + + unpackedRowData[columnIndex] = binaryData.getBytes(length); + + break; + case MysqlDefs.FIELD_TYPE_DATE: + + length = (int) binaryData.readFieldLength(); + + unpackedRowData[columnIndex] = binaryData.getBytes(length); + + break; + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + length = (int) binaryData.readFieldLength(); + + unpackedRowData[columnIndex] = binaryData.getBytes(length); + break; + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + case MysqlDefs.FIELD_TYPE_BLOB: + case MysqlDefs.FIELD_TYPE_VAR_STRING: + case MysqlDefs.FIELD_TYPE_VARCHAR: + case MysqlDefs.FIELD_TYPE_STRING: + case MysqlDefs.FIELD_TYPE_DECIMAL: + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + case MysqlDefs.FIELD_TYPE_GEOMETRY: + unpackedRowData[columnIndex] = binaryData.readLenByteArray(0); + + break; + case MysqlDefs.FIELD_TYPE_BIT: + unpackedRowData[columnIndex] = binaryData.readLenByteArray(0); + + break; + default: + throw SQLError.createSQLException(Messages.getString("MysqlIO.97") //$NON-NLS-1$ + +curField.getMysqlType() + + Messages.getString("MysqlIO.98") + columnIndex + + Messages.getString("MysqlIO.99") //$NON-NLS-1$ //$NON-NLS-2$ + + fields.length + Messages.getString("MysqlIO.100"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + private final void unpackNativeEncodedColumn(Buffer binaryData, + Field[] fields, int columnIndex, Object[] unpackedRowData) + throws SQLException { + Field curField = fields[columnIndex]; + + switch (curField.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_NULL: + break; // for dummy binds + + case MysqlDefs.FIELD_TYPE_TINY: + + byte tinyVal = binaryData.readByte(); + + if (!curField.isUnsigned()) { + unpackedRowData[columnIndex] = String.valueOf(tinyVal) + .getBytes(); + } else { + short unsignedTinyVal = (short) (tinyVal & 0xff); + + unpackedRowData[columnIndex] = String.valueOf(unsignedTinyVal) + .getBytes(); + } + + break; + + case MysqlDefs.FIELD_TYPE_SHORT: + case MysqlDefs.FIELD_TYPE_YEAR: + + short shortVal = (short) binaryData.readInt(); + + if (!curField.isUnsigned()) { + unpackedRowData[columnIndex] = String.valueOf(shortVal) + .getBytes(); + } else { + int unsignedShortVal = shortVal & 0xffff; + + unpackedRowData[columnIndex] = String.valueOf(unsignedShortVal) + .getBytes(); + } + + break; + + case MysqlDefs.FIELD_TYPE_LONG: + case MysqlDefs.FIELD_TYPE_INT24: + + int intVal = (int) binaryData.readLong(); + + if (!curField.isUnsigned()) { + unpackedRowData[columnIndex] = String.valueOf(intVal) + .getBytes(); + } else { + long longVal = intVal & 0xffffffffL; + + unpackedRowData[columnIndex] = String.valueOf(longVal) + .getBytes(); + } + + break; + + case MysqlDefs.FIELD_TYPE_LONGLONG: + + long longVal = binaryData.readLongLong(); + + if (!curField.isUnsigned()) { + unpackedRowData[columnIndex] = String.valueOf(longVal) + .getBytes(); + } else { + BigInteger asBigInteger = ResultSet.convertLongToUlong(longVal); + + unpackedRowData[columnIndex] = asBigInteger.toString() + .getBytes(); + } + + break; + + case MysqlDefs.FIELD_TYPE_FLOAT: + + float floatVal = Float.intBitsToFloat(binaryData.readIntAsLong()); + + unpackedRowData[columnIndex] = String.valueOf(floatVal).getBytes(); + + break; + + case MysqlDefs.FIELD_TYPE_DOUBLE: + + double doubleVal = Double.longBitsToDouble(binaryData.readLongLong()); + + unpackedRowData[columnIndex] = String.valueOf(doubleVal).getBytes(); + + break; + + case MysqlDefs.FIELD_TYPE_TIME: + + int length = (int) binaryData.readFieldLength(); + + int hour = 0; + int minute = 0; + int seconds = 0; + + if (length != 0) { + binaryData.readByte(); // skip tm->neg + binaryData.readLong(); // skip daysPart + hour = binaryData.readByte(); + minute = binaryData.readByte(); + seconds = binaryData.readByte(); + + if (length > 8) { + binaryData.readLong(); // ignore 'secondsPart' + } + } + + + byte[] timeAsBytes = new byte[8]; + + timeAsBytes[0] = (byte) Character.forDigit(hour / 10, 10); + timeAsBytes[1] = (byte) Character.forDigit(hour % 10, 10); + + timeAsBytes[2] = (byte) ':'; + + timeAsBytes[3] = (byte) Character.forDigit(minute / 10, + 10); + timeAsBytes[4] = (byte) Character.forDigit(minute % 10, + 10); + + timeAsBytes[5] = (byte) ':'; + + timeAsBytes[6] = (byte) Character.forDigit(seconds / 10, + 10); + timeAsBytes[7] = (byte) Character.forDigit(seconds % 10, + 10); + + unpackedRowData[columnIndex] = timeAsBytes; + + + break; + + case MysqlDefs.FIELD_TYPE_DATE: + length = (int) binaryData.readFieldLength(); + + int year = 0; + int month = 0; + int day = 0; + + hour = 0; + minute = 0; + seconds = 0; + + if (length != 0) { + year = binaryData.readInt(); + month = binaryData.readByte(); + day = binaryData.readByte(); + } + + if ((year == 0) && (month == 0) && (day == 0)) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals( + this.connection.getZeroDateTimeBehavior())) { + unpackedRowData[columnIndex] = null; + + break; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals( + this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '0000-00-00' can not be represented as java.sql.Date", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + year = 1; + month = 1; + day = 1; + } + + + byte[] dateAsBytes = new byte[10]; + + dateAsBytes[0] = (byte) Character.forDigit(year / 1000, + 10); + + int after1000 = year % 1000; + + dateAsBytes[1] = (byte) Character.forDigit(after1000 / 100, + 10); + + int after100 = after1000 % 100; + + dateAsBytes[2] = (byte) Character.forDigit(after100 / 10, + 10); + dateAsBytes[3] = (byte) Character.forDigit(after100 % 10, + 10); + + dateAsBytes[4] = (byte) '-'; + + dateAsBytes[5] = (byte) Character.forDigit(month / 10, + 10); + dateAsBytes[6] = (byte) Character.forDigit(month % 10, + 10); + + dateAsBytes[7] = (byte) '-'; + + dateAsBytes[8] = (byte) Character.forDigit(day / 10, 10); + dateAsBytes[9] = (byte) Character.forDigit(day % 10, 10); + + unpackedRowData[columnIndex] = dateAsBytes; + + + break; + + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + length = (int) binaryData.readFieldLength(); + + year = 0; + month = 0; + day = 0; + + hour = 0; + minute = 0; + seconds = 0; + + int nanos = 0; + + if (length != 0) { + year = binaryData.readInt(); + month = binaryData.readByte(); + day = binaryData.readByte(); + + if (length > 4) { + hour = binaryData.readByte(); + minute = binaryData.readByte(); + seconds = binaryData.readByte(); + } + + //if (length > 7) { + // nanos = (int)binaryData.readLong(); + //} + } + + if ((year == 0) && (month == 0) && (day == 0)) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals( + this.connection.getZeroDateTimeBehavior())) { + unpackedRowData[columnIndex] = null; + + break; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals( + this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '0000-00-00' can not be represented as java.sql.Timestamp", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + year = 1; + month = 1; + day = 1; + } + + + int stringLength = 19; + + byte[] nanosAsBytes = Integer.toString(nanos).getBytes(); + + stringLength += (1 + nanosAsBytes.length); // '.' + # of digits + + byte[] datetimeAsBytes = new byte[stringLength]; + + datetimeAsBytes[0] = (byte) Character.forDigit(year / 1000, + 10); + + after1000 = year % 1000; + + datetimeAsBytes[1] = (byte) Character.forDigit(after1000 / 100, + 10); + + after100 = after1000 % 100; + + datetimeAsBytes[2] = (byte) Character.forDigit(after100 / 10, + 10); + datetimeAsBytes[3] = (byte) Character.forDigit(after100 % 10, + 10); + + datetimeAsBytes[4] = (byte) '-'; + + datetimeAsBytes[5] = (byte) Character.forDigit(month / 10, + 10); + datetimeAsBytes[6] = (byte) Character.forDigit(month % 10, + 10); + + datetimeAsBytes[7] = (byte) '-'; + + datetimeAsBytes[8] = (byte) Character.forDigit(day / 10, + 10); + datetimeAsBytes[9] = (byte) Character.forDigit(day % 10, + 10); + + datetimeAsBytes[10] = (byte) ' '; + + datetimeAsBytes[11] = (byte) Character.forDigit(hour / 10, + 10); + datetimeAsBytes[12] = (byte) Character.forDigit(hour % 10, + 10); + + datetimeAsBytes[13] = (byte) ':'; + + datetimeAsBytes[14] = (byte) Character.forDigit(minute / 10, + 10); + datetimeAsBytes[15] = (byte) Character.forDigit(minute % 10, + 10); + + datetimeAsBytes[16] = (byte) ':'; + + datetimeAsBytes[17] = (byte) Character.forDigit(seconds / 10, + 10); + datetimeAsBytes[18] = (byte) Character.forDigit(seconds % 10, + 10); + + datetimeAsBytes[19] = (byte) '.'; + + int nanosOffset = 20; + + for (int j = 0; j < nanosAsBytes.length; j++) { + datetimeAsBytes[nanosOffset + j] = nanosAsBytes[j]; + } + + unpackedRowData[columnIndex] = datetimeAsBytes; + + + break; + + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + case MysqlDefs.FIELD_TYPE_BLOB: + case MysqlDefs.FIELD_TYPE_VAR_STRING: + case MysqlDefs.FIELD_TYPE_STRING: + case MysqlDefs.FIELD_TYPE_VARCHAR: + case MysqlDefs.FIELD_TYPE_DECIMAL: + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + case MysqlDefs.FIELD_TYPE_BIT: + unpackedRowData[columnIndex] = binaryData.readLenByteArray(0); + + break; + + default: + throw SQLError.createSQLException(Messages.getString("MysqlIO.97") //$NON-NLS-1$ + +curField.getMysqlType() + + Messages.getString("MysqlIO.98") + columnIndex + + Messages.getString("MysqlIO.99") //$NON-NLS-1$ //$NON-NLS-2$ + + fields.length + Messages.getString("MysqlIO.100"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + /** + * Optimization to only use one calendar per-session, or calculate it + * for each call, depending on user configuration + */ + private Calendar getCalendarInstanceForSessionOrNew() { + if (this.connection.getDynamicCalendars()) { + return Calendar.getInstance(); + } else { + return this.sessionCalendar; + } + } + + /** + * Negotiates the SSL communications channel used when connecting + * to a MySQL server that understands SSL. + * + * @param user + * @param password + * @param database + * @param packLength + * @throws SQLException + * @throws CommunicationsException + */ + private void negotiateSSLConnection(String user, String password, + String database, int packLength) + throws SQLException, CommunicationsException { + if (!ExportControlled.enabled()) { + throw new ConnectionFeatureNotAvailableException(this.connection, + this.lastPacketSentTimeMs, null); + } + + boolean doSecureAuth = false; + + if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) { + this.clientParam |= CLIENT_SECURE_CONNECTION; + doSecureAuth = true; + } + + this.clientParam |= CLIENT_SSL; + + Buffer packet = new Buffer(packLength); + + if (this.use41Extensions) { + packet.writeLong(this.clientParam); + } else { + packet.writeInt((int) this.clientParam); + } + + send(packet, packet.getPosition()); + + ExportControlled.transformSocketToSSLSocket(this); + + packet.clear(); + + if (doSecureAuth) { + if (versionMeetsMinimum(4, 1, 1)) { + secureAuth411(null, packLength, user, password, database, true); + } else { + secureAuth411(null, packLength, user, password, database, true); + } + } else { + if (this.use41Extensions) { + packet.writeLong(this.clientParam); + packet.writeLong(this.maxThreeBytes); + } else { + packet.writeInt((int) this.clientParam); + packet.writeLongInt(this.maxThreeBytes); + } + + // User/Password data + packet.writeString(user); + + if (this.protocolVersion > 9) { + packet.writeString(Util.newCrypt(password, this.seed)); + } else { + packet.writeString(Util.oldCrypt(password, this.seed)); + } + + if (((this.serverCapabilities & CLIENT_CONNECT_WITH_DB) != 0) && + (database != null) && (database.length() > 0)) { + packet.writeString(database); + } + + send(packet, packet.getPosition()); + } + } + + protected int getServerStatus() { + return this.serverStatus; + } + + protected List fetchRowsViaCursor(List fetchedRows, long statementId, + Field[] columnTypes, int fetchSize) throws SQLException { + + if (fetchedRows == null) { + fetchedRows = new ArrayList(fetchSize); + } else { + fetchedRows.clear(); + } + + this.sharedSendPacket.clear(); + + this.sharedSendPacket.writeByte((byte) MysqlDefs.COM_FETCH); + this.sharedSendPacket.writeLong(statementId); + this.sharedSendPacket.writeLong(fetchSize); + + sendCommand(MysqlDefs.COM_FETCH, null, this.sharedSendPacket, true, + null); + + Object[] row = null; + + while ((row = nextRow(columnTypes, columnTypes.length, true, + ResultSet.CONCUR_READ_ONLY)) != null) { + fetchedRows.add(row); + } + + return fetchedRows; + } + + protected long getThreadId() { + return this.threadId; + } + + protected boolean useNanosForElapsedTime() { + return this.useNanosForElapsedTime; + } + + protected long getSlowQueryThreshold() { + return this.slowQueryThreshold; + } + + protected String getQueryTimingUnits() { + return this.queryTimingUnits; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlParameterMetadata.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlParameterMetadata.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlParameterMetadata.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,162 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc; + +import java.sql.ParameterMetaData; +import java.sql.SQLException; +import java.sql.Types; + +public class MysqlParameterMetadata implements ParameterMetaData { + boolean returnSimpleMetadata = false; + ResultSetMetaData metadata = null; + int parameterCount = 0; + + + MysqlParameterMetadata(Field[] fieldInfo, int parameterCount) { + this.metadata = new ResultSetMetaData(fieldInfo, false); + + this.parameterCount = parameterCount; + } + + /** + * Used for "fake" basic metadata for client-side prepared statements + * when we don't know the parameter types. + * + * @param parameterCount + */ + MysqlParameterMetadata(int count) { + this.parameterCount = count; + this.returnSimpleMetadata = true; + } + + public int getParameterCount() throws SQLException { + return this.parameterCount; + } + + public int isNullable(int arg0) throws SQLException { + checkAvailable(); + + return this.metadata.isNullable(arg0); + } + + private void checkAvailable() throws SQLException { + if (this.metadata == null || this.metadata.fields == null) { + throw SQLError.createSQLException( + "Parameter metadata not available for the given statement", + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } + } + + public boolean isSigned(int arg0) throws SQLException { + if (this.returnSimpleMetadata) { + checkBounds(arg0); + + return false; + } + + checkAvailable(); + + return (this.metadata.isSigned(arg0)); + } + + public int getPrecision(int arg0) throws SQLException { + if (this.returnSimpleMetadata) { + checkBounds(arg0); + + return 0; + } + + checkAvailable(); + + return (this.metadata.getPrecision(arg0)); + } + + public int getScale(int arg0) throws SQLException { + if (this.returnSimpleMetadata) { + checkBounds(arg0); + + return 0; + } + + checkAvailable(); + + return (this.metadata.getScale(arg0)); + } + + public int getParameterType(int arg0) throws SQLException { + if (this.returnSimpleMetadata) { + checkBounds(arg0); + + return Types.VARCHAR; + } + + checkAvailable(); + + return (this.metadata.getColumnType(arg0)); + } + + public String getParameterTypeName(int arg0) throws SQLException { + if (this.returnSimpleMetadata) { + checkBounds(arg0); + + return "VARCHAR"; + } + + checkAvailable(); + + return (this.metadata.getColumnTypeName(arg0)); + } + + public String getParameterClassName(int arg0) throws SQLException { + if (this.returnSimpleMetadata) { + checkBounds(arg0); + + return "java.lang.String"; + } + + checkAvailable(); + + return (this.metadata.getColumnClassName(arg0)); + } + + public int getParameterMode(int arg0) throws SQLException { + return parameterModeIn; + } + + private void checkBounds(int paramNumber) throws SQLException { + if (paramNumber < 1) { + throw SQLError.createSQLException("Parameter index of '" + paramNumber + + "' is invalid.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (paramNumber > this.parameterCount) { + throw SQLError.createSQLException("Parameter index of '" + paramNumber + + "' is greater than number of parameters, which is '" + + this.parameterCount + "'.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlSavepoint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlSavepoint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/MysqlSavepoint.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,106 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.rmi.server.UID; +import java.sql.SQLException; +import java.sql.Savepoint; + +/** + * Represents SQL SAVEPOINTS in MySQL. + * + * @author Mark Matthews + * + * @version $Id: MysqlSavepoint.java,v 1.1 2012/08/17 14:57:08 marcin Exp $ + */ +public class MysqlSavepoint implements Savepoint { + private static String getUniqueId() { + // no need to re-invent the wheel here... + String uidStr = new UID().toString(); + + int uidLength = uidStr.length(); + + StringBuffer safeString = new StringBuffer(uidLength); + + for (int i = 0; i < uidLength; i++) { + char c = uidStr.charAt(i); + + if (Character.isLetter(c) || Character.isDigit(c)) { + safeString.append(c); + } else { + safeString.append('_'); + } + } + + return safeString.toString(); + } + + private String savepointName; + + /** + * Creates an unnamed savepoint. + * + * @param conn + * + * @throws SQLException + * if an error occurs + */ + MysqlSavepoint() throws SQLException { + this(getUniqueId()); + } + + /** + * Creates a named savepoint + * + * @param name + * the name of the savepoint. + * + * @throws SQLException + * if name == null or is empty. + */ + MysqlSavepoint(String name) throws SQLException { + if (name == null || name.length() == 0) { + throw SQLError.createSQLException("Savepoint name can not be NULL or empty", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + this.savepointName = name; + } + + /** + * @see java.sql.Savepoint#getSavepointId() + */ + public int getSavepointId() throws SQLException { + throw SQLError.createSQLException("Only named savepoints are supported.", + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } + + /** + * @see java.sql.Savepoint#getSavepointName() + */ + public String getSavepointName() throws SQLException { + return this.savepointName; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/NamedPipeSocketFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/NamedPipeSocketFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/NamedPipeSocketFactory.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,219 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; + +import java.net.Socket; +import java.net.SocketException; + +import java.util.Properties; + +/** + * A socket factory for named pipes (on Windows) + * + * @author Mark Matthews + */ +public class NamedPipeSocketFactory implements SocketFactory { + /** + * A socket that encapsulates named pipes on Windows + */ + class NamedPipeSocket extends Socket { + private boolean isClosed = false; + + private RandomAccessFile namedPipeFile; + + NamedPipeSocket(String filePath) throws IOException { + if ((filePath == null) || (filePath.length() == 0)) { + throw new IOException(Messages + .getString("NamedPipeSocketFactory.4")); //$NON-NLS-1$ + } + + this.namedPipeFile = new RandomAccessFile(filePath, "rw"); //$NON-NLS-1$ + } + + /** + * @see java.net.Socket#close() + */ + public synchronized void close() throws IOException { + this.namedPipeFile.close(); + this.isClosed = true; + } + + /** + * @see java.net.Socket#getInputStream() + */ + public InputStream getInputStream() throws IOException { + return new RandomAccessFileInputStream(this.namedPipeFile); + } + + /** + * @see java.net.Socket#getOutputStream() + */ + public OutputStream getOutputStream() throws IOException { + return new RandomAccessFileOutputStream(this.namedPipeFile); + } + + /** + * @see java.net.Socket#isClosed() + */ + public boolean isClosed() { + return this.isClosed; + } + } + + /** + * Enables OutputStream-type functionality for a RandomAccessFile + */ + class RandomAccessFileInputStream extends InputStream { + RandomAccessFile raFile; + + RandomAccessFileInputStream(RandomAccessFile file) { + this.raFile = file; + } + + /** + * @see java.io.InputStream#available() + */ + public int available() throws IOException { + return -1; + } + + /** + * @see java.io.InputStream#close() + */ + public void close() throws IOException { + this.raFile.close(); + } + + /** + * @see java.io.InputStream#read() + */ + public int read() throws IOException { + return this.raFile.read(); + } + + /** + * @see java.io.InputStream#read(byte[]) + */ + public int read(byte[] b) throws IOException { + return this.raFile.read(b); + } + + /** + * @see java.io.InputStream#read(byte[], int, int) + */ + public int read(byte[] b, int off, int len) throws IOException { + return this.raFile.read(b, off, len); + } + } + + /** + * Enables OutputStream-type functionality for a RandomAccessFile + */ + class RandomAccessFileOutputStream extends OutputStream { + RandomAccessFile raFile; + + RandomAccessFileOutputStream(RandomAccessFile file) { + this.raFile = file; + } + + /** + * @see java.io.OutputStream#close() + */ + public void close() throws IOException { + this.raFile.close(); + } + + /** + * @see java.io.OutputStream#write(byte[]) + */ + public void write(byte[] b) throws IOException { + this.raFile.write(b); + } + + /** + * @see java.io.OutputStream#write(byte[], int, int) + */ + public void write(byte[] b, int off, int len) throws IOException { + this.raFile.write(b, off, len); + } + + /** + * @see java.io.OutputStream#write(int) + */ + public void write(int b) throws IOException { + } + } + + private static final String NAMED_PIPE_PROP_NAME = "namedPipePath"; //$NON-NLS-1$ + + private Socket namedPipeSocket; + + /** + * Constructor for NamedPipeSocketFactory. + */ + public NamedPipeSocketFactory() { + super(); + } + + /** + * @see com.mysql.jdbc.SocketFactory#afterHandshake() + */ + public Socket afterHandshake() throws SocketException, IOException { + return this.namedPipeSocket; + } + + /** + * @see com.mysql.jdbc.SocketFactory#beforeHandshake() + */ + public Socket beforeHandshake() throws SocketException, IOException { + return this.namedPipeSocket; + } + + /** + * @see com.mysql.jdbc.SocketFactory#connect(String, Properties) + */ + public Socket connect(String host, int portNumber /* ignored */, + Properties props) throws SocketException, IOException { + String namedPipePath = props.getProperty(NAMED_PIPE_PROP_NAME); + + if (namedPipePath == null) { + namedPipePath = "\\\\.\\pipe\\MySQL"; //$NON-NLS-1$ + } else if (namedPipePath.length() == 0) { + throw new SocketException(Messages + .getString("NamedPipeSocketFactory.2") //$NON-NLS-1$ + + NAMED_PIPE_PROP_NAME + + Messages.getString("NamedPipeSocketFactory.3")); //$NON-NLS-1$ + } + + this.namedPipeSocket = new NamedPipeSocket(namedPipePath); + + return this.namedPipeSocket; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/NonRegisteringDriver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/NonRegisteringDriver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/NonRegisteringDriver.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,780 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.sql.Connection; +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.StringTokenizer; + +/** + * The Java SQL framework allows for multiple database drivers. Each driver + * should supply a class that implements the Driver interface + * + *

+ * The DriverManager will try to load as many drivers as it can find and then + * for any given connection request, it will ask each driver in turn to try to + * connect to the target URL. + *

+ * + *

+ * It is strongly recommended that each Driver class should be small and + * standalone so that the Driver class can be loaded and queried without + * bringing in vast quantities of supporting code. + *

+ * + *

+ * When a Driver class is loaded, it should create an instance of itself and + * register it with the DriverManager. This means that a user can load and + * register a driver by doing Class.forName("foo.bah.Driver") + *

+ * + * @author Mark Matthews + * @version $Id: NonRegisteringDriver.java,v 1.1.2.1 2005/05/13 18:58:38 + * mmatthews Exp $ + * + * @see org.gjt.mm.mysql.Connection + * @see java.sql.Driver + */ +public class NonRegisteringDriver implements java.sql.Driver { + private static final String REPLICATION_URL_PREFIX = "jdbc:mysql:replication://"; + + private static final String URL_PREFIX = "jdbc:mysql://"; + + private static final String MXJ_URL_PREFIX = "jdbc:mysql:mxj://"; + + private static final String LOADBALANCE_URL_PREFIX = "jdbc:mysql:loadbalance://"; + + /** + * Key used to retreive the database value from the properties instance + * passed to the driver. + */ + public static final String DBNAME_PROPERTY_KEY = "DBNAME"; + + /** Should the driver generate debugging output? */ + public static final boolean DEBUG = false; + + /** Index for hostname coming out of parseHostPortPair(). */ + public final static int HOST_NAME_INDEX = 0; + + /** + * Key used to retreive the hostname value from the properties instance + * passed to the driver. + */ + public static final String HOST_PROPERTY_KEY = "HOST"; + + /** + * Key used to retreive the password value from the properties instance + * passed to the driver. + */ + public static final String PASSWORD_PROPERTY_KEY = "password"; + + /** Index for port # coming out of parseHostPortPair(). */ + public final static int PORT_NUMBER_INDEX = 1; + + /** + * Key used to retreive the port number value from the properties instance + * passed to the driver. + */ + public static final String PORT_PROPERTY_KEY = "PORT"; + + public static final String PROPERTIES_TRANSFORM_KEY = "propertiesTransform"; + + /** Should the driver generate method-call traces? */ + public static final boolean TRACE = false; + + public static final String USE_CONFIG_PROPERTY_KEY = "useConfigs"; + + /** + * Key used to retreive the username value from the properties instance + * passed to the driver. + */ + public static final String USER_PROPERTY_KEY = "user"; + + /** + * Gets the drivers major version number + * + * @return the drivers major version number + */ + static int getMajorVersionInternal() { + return safeIntParse("@MYSQL_CJ_MAJOR_VERSION@"); //$NON-NLS-1$ + } + + /** + * Get the drivers minor version number + * + * @return the drivers minor version number + */ + static int getMinorVersionInternal() { + return safeIntParse("@MYSQL_CJ_MINOR_VERSION@"); //$NON-NLS-1$ + } + + /** + * Parses hostPortPair in the form of [host][:port] into an array, with the + * element of index HOST_NAME_INDEX being the host (or null if not + * specified), and the element of index PORT_NUMBER_INDEX being the port (or + * null if not specified). + * + * @param hostPortPair + * host and port in form of of [host][:port] + * + * @return array containing host and port as Strings + * + * @throws SQLException + * if a parse error occurs + */ + protected static String[] parseHostPortPair(String hostPortPair) + throws SQLException { + int portIndex = hostPortPair.indexOf(":"); //$NON-NLS-1$ + + String[] splitValues = new String[2]; + + String hostname = null; + + if (portIndex != -1) { + if ((portIndex + 1) < hostPortPair.length()) { + String portAsString = hostPortPair.substring(portIndex + 1); + hostname = hostPortPair.substring(0, portIndex); + + splitValues[HOST_NAME_INDEX] = hostname; + + splitValues[PORT_NUMBER_INDEX] = portAsString; + } else { + throw SQLError.createSQLException(Messages + .getString("NonRegisteringDriver.37"), //$NON-NLS-1$ + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + } else { + splitValues[HOST_NAME_INDEX] = hostPortPair; + splitValues[PORT_NUMBER_INDEX] = null; + } + + return splitValues; + } + + private static int safeIntParse(String intAsString) { + try { + return Integer.parseInt(intAsString); + } catch (NumberFormatException nfe) { + return 0; + } + } + + /** + * Construct a new driver and register it with DriverManager + * + * @throws SQLException + * if a database error occurs. + */ + public NonRegisteringDriver() throws SQLException { + // Required for Class.forName().newInstance() + } + + /** + * Typically, drivers will return true if they understand the subprotocol + * specified in the URL and false if they don't. This driver's protocols + * start with jdbc:mysql: + * + * @param url + * the URL of the driver + * + * @return true if this driver accepts the given URL + * + * @exception SQLException + * if a database-access error occurs + * + * @see java.sql.Driver#acceptsURL + */ + public boolean acceptsURL(String url) throws SQLException { + return (parseURL(url, null) != null); + } + + // + // return the database name property + // + + /** + * Try to make a database connection to the given URL. The driver should + * return "null" if it realizes it is the wrong kind of driver to connect to + * the given URL. This will be common, as when the JDBC driverManager is + * asked to connect to a given URL, it passes the URL to each loaded driver + * in turn. + * + *

+ * The driver should raise an SQLException if it is the right driver to + * connect to the given URL, but has trouble connecting to the database. + *

+ * + *

+ * The java.util.Properties argument can be used to pass arbitrary string + * tag/value pairs as connection arguments. + *

+ * + *

+ * My protocol takes the form: + * + *

+	 * 
+	 * jdbc:mysql://host:port/database
+	 * 
+	 * 
+ * + *

+ * + * @param url + * the URL of the database to connect to + * @param info + * a list of arbitrary tag/value pairs as connection arguments + * + * @return a connection to the URL or null if it isnt us + * + * @exception SQLException + * if a database access error occurs + * + * @see java.sql.Driver#connect + */ + public java.sql.Connection connect(String url, Properties info) + throws SQLException { + if (url != null) { + if (StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX)) { + return connectLoadBalanced(url, info); + } else if (StringUtils.startsWithIgnoreCase(url, + REPLICATION_URL_PREFIX)) { + return connectReplicationConnection(url, info); + } + } + + Properties props = null; + + if ((props = parseURL(url, info)) == null) { + return null; + } + + try { + Connection newConn = new com.mysql.jdbc.Connection(host(props), + port(props), props, database(props), url); + + return newConn; + } catch (SQLException sqlEx) { + // Don't wrap SQLExceptions, throw + // them un-changed. + throw sqlEx; + } catch (Exception ex) { + throw SQLError.createSQLException(Messages + .getString("NonRegisteringDriver.17") //$NON-NLS-1$ + + ex.toString() + + Messages.getString("NonRegisteringDriver.18"), //$NON-NLS-1$ + SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE); + } + } + + private java.sql.Connection connectLoadBalanced(String url, Properties info) + throws SQLException { + Properties parsedProps = parseURL(url, info); + + if (parsedProps == null) { + return null; + } + + String hostValues = parsedProps.getProperty(HOST_PROPERTY_KEY); + + List hostList = null; + + if (hostValues != null) { + hostList = StringUtils.split(hostValues, ",", true); + } + + if (hostList == null) { + hostList = new ArrayList(); + hostList.add("localhost:3306"); + } + + LoadBalancingConnectionProxy proxyBal = new LoadBalancingConnectionProxy( + hostList, parsedProps); + + return (java.sql.Connection) java.lang.reflect.Proxy.newProxyInstance(this + .getClass().getClassLoader(), + new Class[] { java.sql.Connection.class }, proxyBal); + } + + private java.sql.Connection connectReplicationConnection(String url, Properties info) + throws SQLException { + Properties parsedProps = parseURL(url, info); + + if (parsedProps == null) { + return null; + } + + Properties masterProps = (Properties) parsedProps.clone(); + Properties slavesProps = (Properties) parsedProps.clone(); + + // Marker used for further testing later on, also when + // debugging + slavesProps.setProperty("com.mysql.jdbc.ReplicationConnection.isSlave", + "true"); + + String hostValues = parsedProps.getProperty(HOST_PROPERTY_KEY); + + if (hostValues != null) { + StringTokenizer st = new StringTokenizer(hostValues, ","); + + StringBuffer masterHost = new StringBuffer(); + StringBuffer slaveHosts = new StringBuffer(); + + if (st.hasMoreTokens()) { + String[] hostPortPair = parseHostPortPair(st.nextToken()); + + if (hostPortPair[HOST_NAME_INDEX] != null) { + masterHost.append(hostPortPair[HOST_NAME_INDEX]); + } + + if (hostPortPair[PORT_NUMBER_INDEX] != null) { + masterHost.append(":"); + masterHost.append(hostPortPair[PORT_NUMBER_INDEX]); + } + } + + boolean firstSlaveHost = true; + + while (st.hasMoreTokens()) { + String[] hostPortPair = parseHostPortPair(st.nextToken()); + + if (!firstSlaveHost) { + slaveHosts.append(","); + } else { + firstSlaveHost = false; + } + + if (hostPortPair[HOST_NAME_INDEX] != null) { + slaveHosts.append(hostPortPair[HOST_NAME_INDEX]); + } + + if (hostPortPair[PORT_NUMBER_INDEX] != null) { + slaveHosts.append(":"); + slaveHosts.append(hostPortPair[PORT_NUMBER_INDEX]); + } + } + + if (slaveHosts.length() == 0) { + throw SQLError + .createSQLException( + "Must specify at least one slave host to connect to for master/slave replication load-balancing functionality", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + + masterProps.setProperty(HOST_PROPERTY_KEY, masterHost.toString()); + slavesProps.setProperty(HOST_PROPERTY_KEY, slaveHosts.toString()); + } + + return new ReplicationConnection(masterProps, slavesProps); + } + + /** + * Returns the database property from props + * + * @param props + * the Properties to look for the database property. + * + * @return the database name. + */ + public String database(Properties props) { + return props.getProperty(DBNAME_PROPERTY_KEY); //$NON-NLS-1$ + } + + /** + * Gets the drivers major version number + * + * @return the drivers major version number + */ + public int getMajorVersion() { + return getMajorVersionInternal(); + } + + // + // return the value of any property this driver knows about + // + + /** + * Get the drivers minor version number + * + * @return the drivers minor version number + */ + public int getMinorVersion() { + return getMinorVersionInternal(); + } + + /** + * The getPropertyInfo method is intended to allow a generic GUI tool to + * discover what properties it should prompt a human for in order to get + * enough information to connect to a database. + * + *

+ * Note that depending on the values the human has supplied so far, + * additional values may become necessary, so it may be necessary to iterate + * through several calls to getPropertyInfo + *

+ * + * @param url + * the Url of the database to connect to + * @param info + * a proposed list of tag/value pairs that will be sent on + * connect open. + * + * @return An array of DriverPropertyInfo objects describing possible + * properties. This array may be an empty array if no properties are + * required + * + * @exception SQLException + * if a database-access error occurs + * + * @see java.sql.Driver#getPropertyInfo + */ + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) + throws SQLException { + if (info == null) { + info = new Properties(); + } + + if ((url != null) && url.startsWith(URL_PREFIX)) { //$NON-NLS-1$ + info = parseURL(url, info); + } + + DriverPropertyInfo hostProp = new DriverPropertyInfo(HOST_PROPERTY_KEY, //$NON-NLS-1$ + info.getProperty(HOST_PROPERTY_KEY)); //$NON-NLS-1$ + hostProp.required = true; + hostProp.description = Messages.getString("NonRegisteringDriver.3"); //$NON-NLS-1$ + + DriverPropertyInfo portProp = new DriverPropertyInfo(PORT_PROPERTY_KEY, //$NON-NLS-1$ + info.getProperty(PORT_PROPERTY_KEY, "3306")); //$NON-NLS-1$ //$NON-NLS-2$ + portProp.required = false; + portProp.description = Messages.getString("NonRegisteringDriver.7"); //$NON-NLS-1$ + + DriverPropertyInfo dbProp = new DriverPropertyInfo(DBNAME_PROPERTY_KEY, //$NON-NLS-1$ + info.getProperty(DBNAME_PROPERTY_KEY)); //$NON-NLS-1$ + dbProp.required = false; + dbProp.description = "Database name"; //$NON-NLS-1$ + + DriverPropertyInfo userProp = new DriverPropertyInfo(USER_PROPERTY_KEY, //$NON-NLS-1$ + info.getProperty(USER_PROPERTY_KEY)); //$NON-NLS-1$ + userProp.required = true; + userProp.description = Messages.getString("NonRegisteringDriver.13"); //$NON-NLS-1$ + + DriverPropertyInfo passwordProp = new DriverPropertyInfo( + PASSWORD_PROPERTY_KEY, //$NON-NLS-1$ + info.getProperty(PASSWORD_PROPERTY_KEY)); //$NON-NLS-1$ + passwordProp.required = true; + passwordProp.description = Messages + .getString("NonRegisteringDriver.16"); //$NON-NLS-1$ + + DriverPropertyInfo[] dpi = ConnectionProperties + .exposeAsDriverPropertyInfo(info, 5); + + dpi[0] = hostProp; + dpi[1] = portProp; + dpi[2] = dbProp; + dpi[3] = userProp; + dpi[4] = passwordProp; + + return dpi; + } + + /** + * Returns the hostname property + * + * @param props + * the java.util.Properties instance to retrieve the hostname + * from. + * + * @return the hostname + */ + public String host(Properties props) { + return props.getProperty(HOST_PROPERTY_KEY, "localhost"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Report whether the driver is a genuine JDBC compliant driver. A driver + * may only report "true" here if it passes the JDBC compliance tests, + * otherwise it is required to return false. JDBC compliance requires full + * support for the JDBC API and full support for SQL 92 Entry Level. + * + *

+ * MySQL is not SQL92 compliant + *

+ * + * @return is this driver JDBC compliant? + */ + public boolean jdbcCompliant() { + return false; + } + + public Properties parseURL(String url, Properties defaults) + throws java.sql.SQLException { + Properties urlProps = (defaults != null) ? new Properties(defaults) + : new Properties(); + + if (url == null) { + return null; + } + + if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX) + && !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX) + && !StringUtils.startsWithIgnoreCase(url, + LOADBALANCE_URL_PREFIX) + && !StringUtils.startsWithIgnoreCase(url, + REPLICATION_URL_PREFIX)) { //$NON-NLS-1$ + + return null; + } + + int beginningOfSlashes = url.indexOf("//"); + + if (StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)) { + urlProps + .setProperty("socketFactory", + "com.mysql.management.driverlaunched.ServerLauncherSocketFactory"); + } + + /* + * Parse parameters after the ? in the URL and remove them from the + * original URL. + */ + int index = url.indexOf("?"); //$NON-NLS-1$ + + if (index != -1) { + String paramString = url.substring(index + 1, url.length()); + url = url.substring(0, index); + + StringTokenizer queryParams = new StringTokenizer(paramString, "&"); //$NON-NLS-1$ + + while (queryParams.hasMoreTokens()) { + String parameterValuePair = queryParams.nextToken(); + + int indexOfEquals = StringUtils.indexOfIgnoreCase(0, + parameterValuePair, "="); + + String parameter = null; + String value = null; + + if (indexOfEquals != -1) { + parameter = parameterValuePair.substring(0, indexOfEquals); + + if (indexOfEquals + 1 < parameterValuePair.length()) { + value = parameterValuePair.substring(indexOfEquals + 1); + } + } + + if ((value != null && value.length() > 0) + && (parameter != null && parameter.length() > 0)) { + try { + urlProps.put(parameter, URLDecoder.decode(value, + "UTF-8")); + } catch (UnsupportedEncodingException badEncoding) { + // punt + urlProps.put(parameter, URLDecoder.decode(value)); + } catch (NoSuchMethodError nsme) { + // punt again + urlProps.put(parameter, URLDecoder.decode(value)); + } + } + } + } + + url = url.substring(beginningOfSlashes + 2); + + String hostStuff = null; + + int slashIndex = url.indexOf("/"); //$NON-NLS-1$ + + if (slashIndex != -1) { + hostStuff = url.substring(0, slashIndex); + + if ((slashIndex + 1) < url.length()) { + urlProps.put(DBNAME_PROPERTY_KEY, //$NON-NLS-1$ + url.substring((slashIndex + 1), url.length())); + } + } else { + hostStuff = url; + } + + if ((hostStuff != null) && (hostStuff.length() > 0)) { + urlProps.put(HOST_PROPERTY_KEY, hostStuff); //$NON-NLS-1$ + } + + String propertiesTransformClassName = urlProps + .getProperty(PROPERTIES_TRANSFORM_KEY); + + if (propertiesTransformClassName != null) { + try { + ConnectionPropertiesTransform propTransformer = (ConnectionPropertiesTransform) Class + .forName(propertiesTransformClassName).newInstance(); + + urlProps = propTransformer.transformProperties(urlProps); + } catch (InstantiationException e) { + throw SQLError.createSQLException( + "Unable to create properties transform instance '" + + propertiesTransformClassName + + "' due to underlying exception: " + + e.toString(), + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } catch (IllegalAccessException e) { + throw SQLError.createSQLException( + "Unable to create properties transform instance '" + + propertiesTransformClassName + + "' due to underlying exception: " + + e.toString(), + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } catch (ClassNotFoundException e) { + throw SQLError.createSQLException( + "Unable to create properties transform instance '" + + propertiesTransformClassName + + "' due to underlying exception: " + + e.toString(), + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + } + + if (Util.isColdFusion() && + urlProps.getProperty("autoConfigureForColdFusion", "true").equalsIgnoreCase("true")) { + String configs = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY); + + StringBuffer newConfigs = new StringBuffer(); + + if (configs != null) { + newConfigs.append(configs); + newConfigs.append(","); + } + + newConfigs.append("coldFusion"); + + urlProps.setProperty(USE_CONFIG_PROPERTY_KEY, newConfigs.toString()); + } + + // If we use a config, it actually should get overridden by anything in + // the URL or passed-in properties + + String configNames = null; + + if (defaults != null) { + configNames = defaults.getProperty(USE_CONFIG_PROPERTY_KEY); + } + + if (configNames == null) { + configNames = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY); + } + + if (configNames != null) { + List splitNames = StringUtils.split(configNames, ",", true); + + Properties configProps = new Properties(); + + Iterator namesIter = splitNames.iterator(); + + while (namesIter.hasNext()) { + String configName = (String) namesIter.next(); + + try { + InputStream configAsStream = getClass() + .getResourceAsStream( + "configs/" + configName + ".properties"); + + if (configAsStream == null) { + throw SQLError + .createSQLException( + "Can't find configuration template named '" + + configName + "'", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + configProps.load(configAsStream); + } catch (IOException ioEx) { + throw SQLError.createSQLException( + "Unable to load configuration template '" + + configName + + "' due to underlying IOException: " + + ioEx, + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + } + + Iterator propsIter = urlProps.keySet().iterator(); + + while (propsIter.hasNext()) { + String key = propsIter.next().toString(); + String property = urlProps.getProperty(key); + configProps.setProperty(key, property); + } + + urlProps = configProps; + } + + // Properties passed in should override ones in URL + + if (defaults != null) { + Iterator propsIter = defaults.keySet().iterator(); + + while (propsIter.hasNext()) { + String key = propsIter.next().toString(); + String property = defaults.getProperty(key); + urlProps.setProperty(key, property); + } + } + + return urlProps; + } + + /** + * Returns the port number property + * + * @param props + * the properties to get the port number from + * + * @return the port number + */ + public int port(Properties props) { + return Integer.parseInt(props.getProperty(PORT_PROPERTY_KEY, "3306")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * Returns the given property from props + * + * @param name + * the property name + * @param props + * the property instance to look in + * + * @return the property value, or null if not found. + */ + public String property(String name, Properties props) { + return props.getProperty(name); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/NonRegisteringReplicationDriver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/NonRegisteringReplicationDriver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/NonRegisteringReplicationDriver.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,118 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + +package com.mysql.jdbc; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; +import java.util.StringTokenizer; + +/** + * Driver that opens two connections, one two a replication master, and another + * to one or more slaves, and decides to use master when the connection is not + * read-only, and use slave(s) when the connection is read-only. + * + * @version $Id: NonRegisteringReplicationDriver.java,v 1.1.2.1 2005/05/13 + * 18:58:37 mmatthews Exp $ + */ +public class NonRegisteringReplicationDriver extends NonRegisteringDriver { + public NonRegisteringReplicationDriver() throws SQLException { + super(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Driver#connect(java.lang.String, java.util.Properties) + */ + public Connection connect(String url, Properties info) throws SQLException { + Properties parsedProps = parseURL(url, info); + + if (parsedProps == null) { + return null; + } + + Properties masterProps = (Properties)parsedProps.clone(); + Properties slavesProps = (Properties)parsedProps.clone(); + + // Marker used for further testing later on, also when + // debugging + slavesProps.setProperty("com.mysql.jdbc.ReplicationConnection.isSlave", "true"); + + String hostValues = parsedProps.getProperty(HOST_PROPERTY_KEY); + + if (hostValues != null) { + StringTokenizer st = new StringTokenizer(hostValues, ","); + + StringBuffer masterHost = new StringBuffer(); + StringBuffer slaveHosts = new StringBuffer(); + + if (st.hasMoreTokens()) { + String[] hostPortPair = parseHostPortPair(st.nextToken()); + + if (hostPortPair[HOST_NAME_INDEX] != null) { + masterHost.append(hostPortPair[HOST_NAME_INDEX]); + } + + if (hostPortPair[PORT_NUMBER_INDEX] != null) { + masterHost.append(":"); + masterHost.append(hostPortPair[PORT_NUMBER_INDEX]); + } + } + + boolean firstSlaveHost = true; + + while (st.hasMoreTokens()) { + String[] hostPortPair = parseHostPortPair(st.nextToken()); + + if (!firstSlaveHost) { + slaveHosts.append(","); + } else { + firstSlaveHost = false; + } + + if (hostPortPair[HOST_NAME_INDEX] != null) { + slaveHosts.append(hostPortPair[HOST_NAME_INDEX]); + } + + if (hostPortPair[PORT_NUMBER_INDEX] != null) { + slaveHosts.append(":"); + slaveHosts.append(hostPortPair[PORT_NUMBER_INDEX]); + } + } + + if (slaveHosts.length() == 0) { + throw SQLError.createSQLException( + "Must specify at least one slave host to connect to for master/slave replication load-balancing functionality", + SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); + } + + masterProps.setProperty(HOST_PROPERTY_KEY, masterHost.toString()); + slavesProps.setProperty(HOST_PROPERTY_KEY, slaveHosts.toString()); + } + + return new ReplicationConnection(masterProps, slavesProps); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/NotImplemented.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/NotImplemented.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/NotImplemented.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,43 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Thrown from methods not required to be implemented. + * + * @author Mark Matthews + */ +public class NotImplemented extends java.sql.SQLException { + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Creates a new NotImplemented object. + */ + public NotImplemented() { + super( + Messages.getString("NotImplemented.0"), SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); //$NON-NLS-1$ + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/NotUpdatable.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/NotUpdatable.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/NotUpdatable.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,72 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +/** + * Thrown when a result sate is not updatable + * + * @author Mark Matthews + */ +public class NotUpdatable extends SQLException { + + private static final long serialVersionUID = 8084742846039782258L; + + /** + * The message to use when result set is not updatable. + * + * The same message is used in the warnings generated by Updatabale result + * set. + */ + public static final String NOT_UPDATEABLE_MESSAGE = Messages + .getString("NotUpdatable.0") //$NON-NLS-1$ + + Messages.getString("NotUpdatable.1") //$NON-NLS-1$ + + Messages.getString("NotUpdatable.2") //$NON-NLS-1$ + + Messages.getString("NotUpdatable.3") //$NON-NLS-1$ + + Messages.getString("NotUpdatable.4") //$NON-NLS-1$ + + Messages.getString("NotUpdatable.5"); //$NON-NLS-1$ + + /** + * Creates a new NotUpdatable exception. + */ + public NotUpdatable() { + this(NOT_UPDATEABLE_MESSAGE); + } + + /** + * Append the given reason to the not updatable message if the reason is not + * null. + */ + public NotUpdatable(String reason) { + super(reason + + Messages.getString("NotUpdatable.1") + + Messages.getString("NotUpdatable.2") + + Messages.getString("NotUpdatable.3") + + Messages.getString("NotUpdatable.4") + + Messages.getString("NotUpdatable.5"), + SQLError.SQL_STATE_GENERAL_ERROR); + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/OperationNotSupportedException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/OperationNotSupportedException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/OperationNotSupportedException.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,16 @@ +/* + * Created on Sep 23, 2004 + * + * TODO To change the template for this generated file go to + * Window - Preferences - Java - Code Style - Code Templates + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +class OperationNotSupportedException extends SQLException { + OperationNotSupportedException() { + super( + Messages.getString("RowDataDynamic.10"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/OutputStreamWatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/OutputStreamWatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/OutputStreamWatcher.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,42 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Objects that want to be notified of lifecycle events on a + * WatchableOutputStream should implement this interface, and register + * themselves with setWatcher() on the WatchableOutputStream instance. + * + * @author Mark Matthews + */ +interface OutputStreamWatcher { + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Called when the OutputStream being watched has .close() called + */ + void streamClosed(WatchableOutputStream out); +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/PacketTooBigException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/PacketTooBigException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/PacketTooBigException.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,54 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +/** + * Thrown when a packet that is too big for the server is created. + * + * @author Mark Matthews + */ +public class PacketTooBigException extends SQLException { + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Creates a new PacketTooBigException object. + * + * @param packetSize + * the size of the packet that was going to be sent + * @param maximumPacketSize + * the maximum size the server will accept + */ + public PacketTooBigException(long packetSize, long maximumPacketSize) { + super( + Messages.getString("PacketTooBigException.0") + packetSize + Messages.getString("PacketTooBigException.1") //$NON-NLS-1$ //$NON-NLS-2$ + + maximumPacketSize + + Messages.getString("PacketTooBigException.2") //$NON-NLS-1$ + + Messages.getString("PacketTooBigException.3") //$NON-NLS-1$ + + Messages.getString("PacketTooBigException.4"), SQLError.SQL_STATE_GENERAL_ERROR); //$NON-NLS-1$ + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/PingTarget.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/PingTarget.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/PingTarget.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,29 @@ +/* + Copyright (C) 2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +package com.mysql.jdbc; + +import java.sql.SQLException; + +public interface PingTarget { + public void doPing() throws SQLException; +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/PreparedStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/PreparedStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/PreparedStatement.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,4086 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectOutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URL; +import java.sql.Array; +import java.sql.Clob; +import java.sql.ParameterMetaData; +import java.sql.Ref; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Locale; +import java.util.TimeZone; + +import com.mysql.jdbc.Statement.CancelTask; +import com.mysql.jdbc.exceptions.MySQLTimeoutException; +import com.mysql.jdbc.profiler.ProfilerEvent; + +/** + * A SQL Statement is pre-compiled and stored in a PreparedStatement object. + * This object can then be used to efficiently execute this statement multiple + * times. + * + *

+ * Note: The setXXX methods for setting IN parameter values must specify + * types that are compatible with the defined SQL type of the input parameter. + * For instance, if the IN parameter has SQL type Integer, then setInt should be + * used. + *

+ * + *

+ * If arbitrary parameter type conversions are required, then the setObject + * method should be used with a target SQL type. + *

+ * + * @author Mark Matthews + * @version $Id: PreparedStatement.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews + * Exp $ + * + * @see java.sql.ResultSet + * @see java.sql.PreparedStatement + */ +public class PreparedStatement extends com.mysql.jdbc.Statement implements + java.sql.PreparedStatement { + class BatchParams { + boolean[] isNull = null; + + boolean[] isStream = null; + + InputStream[] parameterStreams = null; + + byte[][] parameterStrings = null; + + int[] streamLengths = null; + + BatchParams(byte[][] strings, InputStream[] streams, + boolean[] isStreamFlags, int[] lengths, boolean[] isNullFlags) { + // + // Make copies + // + this.parameterStrings = new byte[strings.length][]; + this.parameterStreams = new InputStream[streams.length]; + this.isStream = new boolean[isStreamFlags.length]; + this.streamLengths = new int[lengths.length]; + this.isNull = new boolean[isNullFlags.length]; + System.arraycopy(strings, 0, this.parameterStrings, 0, + strings.length); + System.arraycopy(streams, 0, this.parameterStreams, 0, + streams.length); + System.arraycopy(isStreamFlags, 0, this.isStream, 0, + isStreamFlags.length); + System.arraycopy(lengths, 0, this.streamLengths, 0, lengths.length); + System + .arraycopy(isNullFlags, 0, this.isNull, 0, + isNullFlags.length); + } + } + + class EndPoint { + int begin; + + int end; + + EndPoint(int b, int e) { + this.begin = b; + this.end = e; + } + } + + class ParseInfo { + char firstStmtChar = 0; + + boolean foundLimitClause = false; + + boolean foundLoadData = false; + + long lastUsed = 0; + + int statementLength = 0; + + int statementStartPos = 0; + + byte[][] staticSql = null; + + /** + * Represents the "parsed" state of a client-side + * prepared statement, with the statement broken up into + * it's static and dynamic (where parameters are bound) + * parts. + */ + public ParseInfo(String sql, Connection conn, + java.sql.DatabaseMetaData dbmd, String encoding, + SingleByteCharsetConverter converter) throws SQLException { + if (sql == null) { + throw SQLError.createSQLException(Messages + .getString("PreparedStatement.61"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + this.lastUsed = System.currentTimeMillis(); + + String quotedIdentifierString = dbmd.getIdentifierQuoteString(); + + char quotedIdentifierChar = 0; + + if ((quotedIdentifierString != null) + && !quotedIdentifierString.equals(" ") //$NON-NLS-1$ + && (quotedIdentifierString.length() > 0)) { + quotedIdentifierChar = quotedIdentifierString.charAt(0); + } + + this.statementLength = sql.length(); + + ArrayList endpointList = new ArrayList(); + boolean inQuotes = false; + char quoteChar = 0; + boolean inQuotedId = false; + int lastParmEnd = 0; + int i; + + int stopLookingForLimitClause = this.statementLength - 5; + + this.foundLimitClause = false; + + boolean noBackslashEscapes = connection.isNoBackslashEscapesSet(); + + // we're not trying to be real pedantic here, but we'd like to + // skip comments at the beginning of statements, as frameworks + // such as Hibernate use them to aid in debugging + + statementStartPos = findStartOfStatement(sql); + + for (i = statementStartPos; i < this.statementLength; ++i) { + char c = sql.charAt(i); + + if ((this.firstStmtChar == 0) && !Character.isWhitespace(c)) { + // Determine what kind of statement we're doing (_S_elect, + // _I_nsert, etc.) + this.firstStmtChar = Character.toUpperCase(c); + } + + if (!noBackslashEscapes && + c == '\\' && i < (this.statementLength - 1)) { + i++; + continue; // next character is escaped + } + + // are we in a quoted identifier? + // (only valid when the id is not inside a 'string') + if (!inQuotes && (quotedIdentifierChar != 0) + && (c == quotedIdentifierChar)) { + inQuotedId = !inQuotedId; + } else if (!inQuotedId) { + // only respect quotes when not in a quoted identifier + + if (inQuotes) { + if (((c == '\'') || (c == '"')) && c == quoteChar) { + if (i < (this.statementLength - 1) && sql.charAt(i + 1) == quoteChar) { + i++; + continue; // inline quote escape + } + + inQuotes = !inQuotes; + quoteChar = 0; + } else if (((c == '\'') || (c == '"')) && c == quoteChar) { + inQuotes = !inQuotes; + quoteChar = 0; + } + } else { + if (c == '#' + || (c == '-' && (i + 1) < this.statementLength && sql + .charAt(i + 1) == '-')) { + // run out to end of statement, or newline, + // whichever comes first + int endOfStmt = this.statementLength - 1; + + for (; i < endOfStmt; i++) { + c = sql.charAt(i); + + if (c == '\r' || c == '\n') { + break; + } + } + + continue; + } else if (c == '/' && (i + 1) < this.statementLength) { + // Comment? + char cNext = sql.charAt(i + 1); + + if (cNext == '*') { + i+= 2; + + for (int j = i; j < this.statementLength; j++) { + i++; + cNext = sql.charAt(j); + + if (cNext == '*' && (j + 1) < this.statementLength) { + if (sql.charAt(j + 1) == '/') { + i++; + + if (i < this.statementLength) { + c = sql.charAt(i); + } + + break; // comment done + } + } + } + } + } else if ((c == '\'') || (c == '"')) { + inQuotes = true; + quoteChar = c; + } + } + } + + if ((c == '?') && !inQuotes && !inQuotedId) { + endpointList.add(new int[] { lastParmEnd, i }); + lastParmEnd = i + 1; + } + + if (!inQuotes && (i < stopLookingForLimitClause)) { + if ((c == 'L') || (c == 'l')) { + char posI1 = sql.charAt(i + 1); + + if ((posI1 == 'I') || (posI1 == 'i')) { + char posM = sql.charAt(i + 2); + + if ((posM == 'M') || (posM == 'm')) { + char posI2 = sql.charAt(i + 3); + + if ((posI2 == 'I') || (posI2 == 'i')) { + char posT = sql.charAt(i + 4); + + if ((posT == 'T') || (posT == 't')) { + foundLimitClause = true; + } + } + } + } + } + } + } + + if (this.firstStmtChar == 'L') { + if (StringUtils.startsWithIgnoreCaseAndWs(sql, "LOAD DATA")) { //$NON-NLS-1$ + this.foundLoadData = true; + } else { + this.foundLoadData = false; + } + } else { + this.foundLoadData = false; + } + + endpointList.add(new int[] { lastParmEnd, this.statementLength }); + this.staticSql = new byte[endpointList.size()][]; + char[] asCharArray = sql.toCharArray(); + + for (i = 0; i < this.staticSql.length; i++) { + int[] ep = (int[]) endpointList.get(i); + int end = ep[1]; + int begin = ep[0]; + int len = end - begin; + + if (this.foundLoadData) { + String temp = new String(asCharArray, begin, len); + this.staticSql[i] = temp.getBytes(); + } else if (encoding == null) { + byte[] buf = new byte[len]; + + for (int j = 0; j < len; j++) { + buf[j] = (byte) sql.charAt(begin + j); + } + + this.staticSql[i] = buf; + } else { + if (converter != null) { + this.staticSql[i] = StringUtils.getBytes(sql, + converter, encoding, connection + .getServerCharacterEncoding(), begin, + len, connection.parserKnowsUnicode()); + } else { + String temp = new String(asCharArray, begin, len); + + this.staticSql[i] = StringUtils.getBytes(temp, + encoding, connection + .getServerCharacterEncoding(), + connection.parserKnowsUnicode(), conn); + } + } + } + } + } + + private final static byte[] HEX_DIGITS = new byte[] { (byte) '0', + (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', + (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', + (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' }; + + /** + * Reads length bytes from reader into buf. Blocks until enough input is + * available + * + * @param reader + * DOCUMENT ME! + * @param buf + * DOCUMENT ME! + * @param length + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException + * DOCUMENT ME! + */ + private static int readFully(Reader reader, char[] buf, int length) + throws IOException { + int numCharsRead = 0; + + while (numCharsRead < length) { + int count = reader.read(buf, numCharsRead, length - numCharsRead); + + if (count < 0) { + break; + } + + numCharsRead += count; + } + + return numCharsRead; + } + + /** + * Does the batch (if any) contain "plain" statements added by + * Statement.addBatch(String)? + * + * If so, we can't re-write it to use multi-value or multi-queries. + */ + protected boolean batchHasPlainStatements = false; + + private java.sql.DatabaseMetaData dbmd = null; + + /** + * What is the first character of the prepared statement (used to check for + * SELECT vs. INSERT/UPDATE/DELETE) + */ + protected char firstCharOfStmt = 0; + + /** Does the SQL for this statement contain a 'limit' clause? */ + protected boolean hasLimitClause = false; + + /** Is this query a LOAD DATA query? */ + protected boolean isLoadDataQuery = false; + + private boolean[] isNull = null; + + private boolean[] isStream = null; + + protected int numberOfExecutions = 0; + + /** The SQL that was passed in to 'prepare' */ + protected String originalSql = null; + + /** The number of parameters in this PreparedStatement */ + protected int parameterCount; + + protected MysqlParameterMetadata parameterMetaData; + + private InputStream[] parameterStreams = null; + + private byte[][] parameterValues = null; + + private ParseInfo parseInfo; + + private java.sql.ResultSetMetaData pstmtResultMetaData; + + private byte[][] staticSqlStrings = null; + + private byte[] streamConvertBuf = new byte[4096]; + + private int[] streamLengths = null; + + private SimpleDateFormat tsdf = null; + + /** + * Are we using a version of MySQL where we can use 'true' boolean values? + */ + protected boolean useTrueBoolean = false; + + private boolean usingAnsiMode; + + private String batchedValuesClause; + + /** Where does the statement text actually start? */ + + private int statementAfterCommentsPos; + + /** + * have we checked whether we can rewrite this statement as a multi-value + * insert? + */ + + private boolean hasCheckedForRewrite = false; + + /** Can we actually rewrite this statement as a multi-value insert? */ + + private boolean canRewrite = false; + + private boolean doPingInstead; + + /** + * Constructor used by server-side prepared statements + * + * @param conn + * the connection that created us + * @param catalog + * the catalog in use when we were created + * + * @throws SQLException + * if an error occurs + */ + protected PreparedStatement(Connection conn, String catalog) + throws SQLException { + super(conn, catalog); + } + + /** + * Constructor for the PreparedStatement class. + * + * @param conn + * the connection creating this statement + * @param sql + * the SQL for this statement + * @param catalog + * the catalog/database this statement should be issued against + * + * @throws SQLException + * if a database error occurs. + */ + public PreparedStatement(Connection conn, String sql, String catalog) + throws SQLException { + super(conn, catalog); + + if (sql == null) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.0"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + this.originalSql = sql; + + if (this.originalSql.startsWith(PING_MARKER)) { + this.doPingInstead = true; + } else { + this.doPingInstead = false; + } + + this.dbmd = this.connection.getMetaData(); + + this.useTrueBoolean = this.connection.versionMeetsMinimum(3, 21, 23); + + this.parseInfo = new ParseInfo(sql, this.connection, this.dbmd, + this.charEncoding, this.charConverter); + + initializeFromParseInfo(); + } + + /** + * Creates a new PreparedStatement object. + * + * @param conn + * the connection creating this statement + * @param sql + * the SQL for this statement + * @param catalog + * the catalog/database this statement should be issued against + * @param cachedParseInfo + * already created parseInfo. + * + * @throws SQLException + * DOCUMENT ME! + */ + public PreparedStatement(Connection conn, String sql, String catalog, + ParseInfo cachedParseInfo) throws SQLException { + super(conn, catalog); + + if (sql == null) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.1"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + this.originalSql = sql; + + this.dbmd = this.connection.getMetaData(); + + this.useTrueBoolean = this.connection.versionMeetsMinimum(3, 21, 23); + + this.parseInfo = cachedParseInfo; + + this.usingAnsiMode = !this.connection.useAnsiQuotedIdentifiers(); + + initializeFromParseInfo(); + } + + /** + * JDBC 2.0 Add a set of parameters to the batch. + * + * @exception SQLException + * if a database-access error occurs. + * + * @see Statement#addBatch + */ + public void addBatch() throws SQLException { + if (this.batchedArgs == null) { + this.batchedArgs = new ArrayList(); + } + + this.batchedArgs.add(new BatchParams(this.parameterValues, + this.parameterStreams, this.isStream, this.streamLengths, + this.isNull)); + } + + public synchronized void addBatch(String sql) throws SQLException { + this.batchHasPlainStatements = true; + + super.addBatch(sql); + } + + protected String asSql() throws SQLException { + return asSql(false); + } + + protected String asSql(boolean quoteStreamsAndUnknowns) throws SQLException { + if (this.isClosed) { + return "statement has been closed, no further internal information available"; + } + + StringBuffer buf = new StringBuffer(); + + try { + for (int i = 0; i < this.parameterCount; ++i) { + if (this.charEncoding != null) { + buf.append(new String(this.staticSqlStrings[i], + this.charEncoding)); + } else { + buf.append(new String(this.staticSqlStrings[i])); + } + + if ((this.parameterValues[i] == null) && !this.isStream[i]) { + if (quoteStreamsAndUnknowns) { + buf.append("'"); + } + + buf.append("** NOT SPECIFIED **"); //$NON-NLS-1$ + + if (quoteStreamsAndUnknowns) { + buf.append("'"); + } + } else if (this.isStream[i]) { + if (quoteStreamsAndUnknowns) { + buf.append("'"); + } + + buf.append("** STREAM DATA **"); //$NON-NLS-1$ + + if (quoteStreamsAndUnknowns) { + buf.append("'"); + } + } else { + if (this.charConverter != null) { + buf.append(this.charConverter + .toString(this.parameterValues[i])); + } else { + if (this.charEncoding != null) { + buf.append(new String(this.parameterValues[i], + this.charEncoding)); + } else { + buf.append(StringUtils + .toAsciiString(this.parameterValues[i])); + } + } + } + } + + if (this.charEncoding != null) { + buf.append(new String( + this.staticSqlStrings[this.parameterCount], + this.charEncoding)); + } else { + buf + .append(StringUtils + .toAsciiString(this.staticSqlStrings[this.parameterCount])); + } + } catch (UnsupportedEncodingException uue) { + throw new RuntimeException(Messages + .getString("PreparedStatement.32") //$NON-NLS-1$ + + this.charEncoding + + Messages.getString("PreparedStatement.33")); //$NON-NLS-1$ + } + + return buf.toString(); + } + + public synchronized void clearBatch() throws SQLException { + this.batchHasPlainStatements = false; + + super.clearBatch(); + } + + /** + * In general, parameter values remain in force for repeated used of a + * Statement. Setting a parameter value automatically clears its previous + * value. However, in some cases, it is useful to immediately release the + * resources used by the current parameter values; this can be done by + * calling clearParameters + * + * @exception SQLException + * if a database access error occurs + */ + public synchronized void clearParameters() throws SQLException { + checkClosed(); + + for (int i = 0; i < this.parameterValues.length; i++) { + this.parameterValues[i] = null; + this.parameterStreams[i] = null; + this.isStream[i] = false; + this.isNull[i] = false; + } + } + + /** + * Closes this prepared statement and releases all resources. + * + * @throws SQLException + * if database error occurs. + */ + public synchronized void close() throws SQLException { + realClose(true, true); + } + + private final void escapeblockFast(byte[] buf, Buffer packet, int size) + throws SQLException { + int lastwritten = 0; + + for (int i = 0; i < size; i++) { + byte b = buf[i]; + + if (b == '\0') { + // write stuff not yet written + if (i > lastwritten) { + packet.writeBytesNoNull(buf, lastwritten, i - lastwritten); + } + + // write escape + packet.writeByte((byte) '\\'); + packet.writeByte((byte) '0'); + lastwritten = i + 1; + } else { + if ((b == '\\') || (b == '\'') + || (!this.usingAnsiMode && b == '"')) { + // write stuff not yet written + if (i > lastwritten) { + packet.writeBytesNoNull(buf, lastwritten, i + - lastwritten); + } + + // write escape + packet.writeByte((byte) '\\'); + lastwritten = i; // not i+1 as b wasn't written. + } + } + } + + // write out remaining stuff from buffer + if (lastwritten < size) { + packet.writeBytesNoNull(buf, lastwritten, size - lastwritten); + } + } + + private final void escapeblockFast(byte[] buf, + ByteArrayOutputStream bytesOut, int size) { + int lastwritten = 0; + + for (int i = 0; i < size; i++) { + byte b = buf[i]; + + if (b == '\0') { + // write stuff not yet written + if (i > lastwritten) { + bytesOut.write(buf, lastwritten, i - lastwritten); + } + + // write escape + bytesOut.write('\\'); + bytesOut.write('0'); + lastwritten = i + 1; + } else { + if ((b == '\\') || (b == '\'') + || (!this.usingAnsiMode && b == '"')) { + // write stuff not yet written + if (i > lastwritten) { + bytesOut.write(buf, lastwritten, i - lastwritten); + } + + // write escape + bytesOut.write('\\'); + lastwritten = i; // not i+1 as b wasn't written. + } + } + } + + // write out remaining stuff from buffer + if (lastwritten < size) { + bytesOut.write(buf, lastwritten, size - lastwritten); + } + } + + /** + * Some prepared statements return multiple results; the execute method + * handles these complex statements as well as the simpler form of + * statements handled by executeQuery and executeUpdate + * + * @return true if the next result is a ResultSet; false if it is an update + * count or there are no more results + * + * @exception SQLException + * if a database access error occurs + */ + public boolean execute() throws SQLException { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + if (locallyScopedConn.isReadOnly() && (this.firstCharOfStmt != 'S')) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.20") //$NON-NLS-1$ + + Messages.getString("PreparedStatement.21"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + ResultSet rs = null; + + CachedResultSetMetaData cachedMetadata = null; + + synchronized (locallyScopedConn.getMutex()) { + clearWarnings(); + + this.batchedGeneratedKeys = null; + + Buffer sendPacket = fillSendPacket(); + + String oldCatalog = null; + + if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) { + oldCatalog = locallyScopedConn.getCatalog(); + locallyScopedConn.setCatalog(this.currentCatalog); + } + + // + // Check if we have cached metadata for this query... + // + if (locallyScopedConn.getCacheResultSetMetadata()) { + cachedMetadata = locallyScopedConn.getCachedMetaData(this.originalSql); + } + + Field[] metadataFromCache = null; + + if (cachedMetadata != null) { + metadataFromCache = cachedMetadata.fields; + } + + boolean oldInfoMsgState = false; + + if (this.retrieveGeneratedKeys) { + oldInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + } + + // If there isn't a limit clause in the SQL + // then limit the number of rows to return in + // an efficient manner. Only do this if + // setMaxRows() hasn't been used on any Statements + // generated from the current Connection (saves + // a query, and network traffic). + // + // Only apply max_rows to selects + // + if (locallyScopedConn.useMaxRows()) { + int rowLimit = -1; + + if (this.firstCharOfStmt == 'S') { + if (this.hasLimitClause) { + rowLimit = this.maxRows; + } else { + if (this.maxRows <= 0) { + locallyScopedConn.execSQL(this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, //$NON-NLS-1$ + null, java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.currentCatalog, true); + } else { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=" + this.maxRows, -1, //$NON-NLS-1$ + null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.currentCatalog, + true); + } + } + } else { + locallyScopedConn.execSQL(this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, null, //$NON-NLS-1$ + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.currentCatalog, true); + } + + // Finally, execute the query + rs = executeInternal(rowLimit, sendPacket, + createStreamingResultSet(), + (this.firstCharOfStmt == 'S'), true, metadataFromCache, false); + } else { + rs = executeInternal(-1, sendPacket, + createStreamingResultSet(), + (this.firstCharOfStmt == 'S'), true, metadataFromCache, false); + } + + if (cachedMetadata != null) { + locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, + cachedMetadata, this.results); + } else { + if (rs.reallyResult() && locallyScopedConn.getCacheResultSetMetadata()) { + locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, + null /* will be created */, rs); + } + } + + if (this.retrieveGeneratedKeys) { + locallyScopedConn.setReadInfoMsgEnabled(oldInfoMsgState); + rs.setFirstCharOfQuery(this.firstCharOfStmt); + } + + if (oldCatalog != null) { + locallyScopedConn.setCatalog(oldCatalog); + } + + this.lastInsertId = rs.getUpdateID(); + + if (rs != null) { + this.results = rs; + } + } + + return ((rs != null) && rs.reallyResult()); + } + + /** + * JDBC 2.0 Submit a batch of commands to the database for execution. This + * method is optional. + * + * @return an array of update counts containing one element for each command + * in the batch. The array is ordered according to the order in + * which commands were inserted into the batch + * + * @exception SQLException + * if a database-access error occurs, or the driver does not + * support batch statements + * @throws java.sql.BatchUpdateException + * DOCUMENT ME! + */ + public int[] executeBatch() throws SQLException { + checkClosed(); + + if (this.connection.isReadOnly()) { + throw new SQLException(Messages.getString("PreparedStatement.25") //$NON-NLS-1$ + + Messages.getString("PreparedStatement.26"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + synchronized (this.connection.getMutex()) { + if (this.batchedArgs == null || this.batchedArgs.size() == 0) { + return new int[0]; + } + + try { + clearWarnings(); + + if (!this.batchHasPlainStatements + && this.connection.getRewriteBatchedStatements()) { + + if (canRewriteAsMultivalueInsertStatement()) { + return executeBatchedInserts(); + } + } + + return executeBatchSerially(); + } catch (NullPointerException npe) { + // We do this, otherwise we need to totally overhaul how executeBatch() reuses + // existing execute() functionality, and pass around a locally-scoped connection, + // or catch the very rare race condition and handle it here. + + checkClosed(); // if we're really closed, this will throw a SQLException + + throw npe; // otherwise someone (me!) goofed error + } finally { + clearBatch(); + } + } + } + + public synchronized boolean canRewriteAsMultivalueInsertStatement() { + if (!this.hasCheckedForRewrite) { + // Needs to be INSERT, can't have INSERT ... SELECT or + // INSERT ... ON DUPLICATE KEY UPDATE + // + // We're not smart enough to re-write to + // + // INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) + // ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b); + // + // (yet) + + this.canRewrite = StringUtils.startsWithIgnoreCaseAndWs( + this.originalSql, "INSERT", this.statementAfterCommentsPos) + && StringUtils.indexOfIgnoreCaseRespectMarker(this.statementAfterCommentsPos, this.originalSql, "SELECT", "\"'`", "\"'`", false) == -1 + && StringUtils.indexOfIgnoreCaseRespectMarker(this.statementAfterCommentsPos, this.originalSql, "UPDATE", "\"'`", "\"'`", false) == -1; + + this.hasCheckedForRewrite = true; + } + + return this.canRewrite; + } + + /** + * Rewrites the already prepared statement into a multi-value insert + * statement of 'statementsPerBatch' values and executes the entire batch + * using this new statement. + * + * @return update counts in the same fashion as executeBatch() + * + * @throws SQLException + */ + protected int[] executeBatchedInserts() throws SQLException { + String valuesClause = extractValuesClause(); + + Connection locallyScopedConn = this.connection; + + if (valuesClause == null) { + return executeBatchSerially(); + } + + int numBatchedArgs = this.batchedArgs.size(); + + if (this.retrieveGeneratedKeys) { + this.batchedGeneratedKeys = new ArrayList(numBatchedArgs); + } + + int numValuesPerBatch = computeBatchSize(numBatchedArgs); + + if (numBatchedArgs < numValuesPerBatch) { + numValuesPerBatch = numBatchedArgs; + } + + java.sql.PreparedStatement batchedStatement = null; + + int batchedParamIndex = 1; + int updateCountRunningTotal = 0; + int numberToExecuteAsMultiValue = 0; + int batchCounter = 0; + + try { + if (this.retrieveGeneratedKeys) { + batchedStatement = locallyScopedConn.prepareStatement( + generateBatchedInsertSQL(valuesClause, numValuesPerBatch), + RETURN_GENERATED_KEYS); + } else { + batchedStatement = locallyScopedConn + .prepareStatement(generateBatchedInsertSQL(valuesClause, + numValuesPerBatch)); + } + + if (numBatchedArgs < numValuesPerBatch) { + numberToExecuteAsMultiValue = numBatchedArgs; + } else { + numberToExecuteAsMultiValue = numBatchedArgs / numValuesPerBatch; + } + + int numberArgsToExecute = numberToExecuteAsMultiValue * numValuesPerBatch; + + for (int i = 0; i < numberArgsToExecute; i++) { + if (i != 0 && i % numValuesPerBatch == 0) { + updateCountRunningTotal += batchedStatement.executeUpdate(); + + getBatchedGeneratedKeys(batchedStatement); + batchedStatement.clearParameters(); + batchedParamIndex = 1; + + } + + batchedParamIndex = setOneBatchedParameterSet(batchedStatement, + batchedParamIndex, this.batchedArgs + .get(batchCounter++)); + } + + updateCountRunningTotal += batchedStatement.executeUpdate(); + getBatchedGeneratedKeys(batchedStatement); + + numValuesPerBatch = numBatchedArgs - batchCounter; + } finally { + if (batchedStatement != null) { + batchedStatement.close(); + } + } + + try { + if (numValuesPerBatch > 0) { + + if (this.retrieveGeneratedKeys) { + batchedStatement = locallyScopedConn.prepareStatement( + generateBatchedInsertSQL(valuesClause, numValuesPerBatch), + RETURN_GENERATED_KEYS); + } else { + batchedStatement = locallyScopedConn.prepareStatement( + generateBatchedInsertSQL(valuesClause, numValuesPerBatch)); + } + + batchedParamIndex = 1; + + while (batchCounter < numBatchedArgs) { + batchedParamIndex = setOneBatchedParameterSet(batchedStatement, + batchedParamIndex, this.batchedArgs + .get(batchCounter++)); + } + + updateCountRunningTotal += batchedStatement.executeUpdate(); + getBatchedGeneratedKeys(batchedStatement); + } + + int[] updateCounts = new int[this.batchedArgs.size()]; + + for (int i = 0; i < this.batchedArgs.size(); i++) { + updateCounts[i] = 1; + } + + return updateCounts; + } finally { + if (batchedStatement != null) { + batchedStatement.close(); + } + } + } + + /** + * Computes the optimum number of batched parameter lists to send + * without overflowing max_allowed_packet. + * + * @param numBatchedArgs + * @return + */ + protected int computeBatchSize(int numBatchedArgs) { + long[] combinedValues = computeMaxParameterSetSizeAndBatchSize(numBatchedArgs); + + long maxSizeOfParameterSet = combinedValues[0]; + long sizeOfEntireBatch = combinedValues[1]; + + int maxAllowedPacket = this.connection.getMaxAllowedPacket(); + + if (sizeOfEntireBatch < maxAllowedPacket - this.originalSql.length()) { + return numBatchedArgs; + } + + return (int)Math.max(1, (maxAllowedPacket - this.originalSql.length()) / maxSizeOfParameterSet); + } + + /** + * Computes the maximum parameter set size, and entire batch size given + * the number of arguments in the batch. + */ + protected long[] computeMaxParameterSetSizeAndBatchSize(int numBatchedArgs) { + long sizeOfEntireBatch = 0; + long maxSizeOfParameterSet = 0; + + for (int i = 0; i < numBatchedArgs; i++) { + BatchParams paramArg = (BatchParams) this.batchedArgs + .get(i); + + boolean[] isNullBatch = paramArg.isNull; + boolean[] isStreamBatch = paramArg.isStream; + + long sizeOfParameterSet = 0; + + for (int j = 0; j < isNullBatch.length; j++) { + if (!isNullBatch[j]) { + + if (isStreamBatch[j]) { + int streamLength = paramArg.streamLengths[j]; + + if (streamLength != -1) { + sizeOfParameterSet += streamLength * 2; // for safety in escaping + } + } else { + sizeOfParameterSet += paramArg.parameterStrings[j].length; + } + } else { + sizeOfParameterSet += 4; // for NULL literal in SQL + } + } + + // + // Account for static part of values clause + // This is a little naiive, because the ?s will be replaced + // but it gives us some padding, and is less housekeeping + // to ignore them. We're looking for a "fuzzy" value here + // anyway + // + + sizeOfParameterSet += this.batchedValuesClause.length() + 1; + sizeOfEntireBatch += sizeOfParameterSet; + + if (sizeOfParameterSet > maxSizeOfParameterSet) { + maxSizeOfParameterSet = sizeOfParameterSet; + } + } + + return new long[] {maxSizeOfParameterSet, sizeOfEntireBatch}; + } + + /** + * Executes the current batch of statements by executing them one-by-one. + * + * @return a list of update counts + * @throws SQLException + * if an error occurs + */ + protected int[] executeBatchSerially() throws SQLException { + + Connection locallyScopedConn = this.connection; + + if (locallyScopedConn == null) { + checkClosed(); + } + + int[] updateCounts = null; + + if (this.batchedArgs != null) { + int nbrCommands = this.batchedArgs.size(); + updateCounts = new int[nbrCommands]; + + for (int i = 0; i < nbrCommands; i++) { + updateCounts[i] = -3; + } + + SQLException sqlEx = null; + + int commandIndex = 0; + + if (this.retrieveGeneratedKeys) { + this.batchedGeneratedKeys = new ArrayList(nbrCommands); + } + + for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) { + Object arg = this.batchedArgs.get(commandIndex); + + if (arg instanceof String) { + updateCounts[commandIndex] = executeUpdate((String) arg); + } else { + BatchParams paramArg = (BatchParams) arg; + + try { + updateCounts[commandIndex] = executeUpdate( + paramArg.parameterStrings, + paramArg.parameterStreams, paramArg.isStream, + paramArg.streamLengths, paramArg.isNull, true); + + if (this.retrieveGeneratedKeys) { + java.sql.ResultSet rs = null; + + try { + rs = getGeneratedKeysInternal(); + + while (rs.next()) { + this.batchedGeneratedKeys + .add(new byte[][] { rs.getBytes(1) }); + } + } finally { + if (rs != null) { + rs.close(); + } + } + } + } catch (SQLException ex) { + updateCounts[commandIndex] = EXECUTE_FAILED; + + if (this.continueBatchOnError) { + sqlEx = ex; + } else { + int[] newUpdateCounts = new int[commandIndex]; + System.arraycopy(updateCounts, 0, newUpdateCounts, + 0, commandIndex); + + throw new java.sql.BatchUpdateException(ex + .getMessage(), ex.getSQLState(), ex + .getErrorCode(), newUpdateCounts); + } + } + } + } + + if (sqlEx != null) { + throw new java.sql.BatchUpdateException(sqlEx.getMessage(), + sqlEx.getSQLState(), sqlEx.getErrorCode(), updateCounts); + } + } + + return (updateCounts != null) ? updateCounts : new int[0]; + } + + /** + * Actually execute the prepared statement. This is here so server-side + * PreparedStatements can re-use most of the code from this class. + * + * @param maxRowsToRetrieve + * the max number of rows to return + * @param sendPacket + * the packet to send + * @param createStreamingResultSet + * should a 'streaming' result set be created? + * @param queryIsSelectOnly + * is this query doing a SELECT? + * @param unpackFields + * DOCUMENT ME! + * + * @return the results as a ResultSet + * + * @throws SQLException + * if an error occurs. + */ + protected ResultSet executeInternal(int maxRowsToRetrieve, + Buffer sendPacket, boolean createStreamingResultSet, + boolean queryIsSelectOnly, boolean unpackFields, Field[] cachedFields, + boolean isBatch) + throws SQLException { + try { + + + synchronized (this.cancelTimeoutMutex) { + this.wasCancelled = false; + } + + Connection locallyScopedConnection= this.connection; + + this.numberOfExecutions++; + + if (this.doPingInstead) { + doPingInstead(); + + return this.results; + } + + ResultSet rs; + + CancelTask timeoutTask = null; + + try { + if (locallyScopedConnection.getEnableQueryTimeouts() && + this.timeoutInMillis != 0 + && locallyScopedConnection.versionMeetsMinimum(5, 0, 0)) { + timeoutTask = new CancelTask(); + Connection.getCancelTimer().schedule(timeoutTask, + this.timeoutInMillis); + } + + rs = locallyScopedConnection.execSQL(this, null, maxRowsToRetrieve, sendPacket, + this.resultSetType, this.resultSetConcurrency, + createStreamingResultSet, this.currentCatalog, + unpackFields, isBatch); + + if (timeoutTask != null) { + timeoutTask.cancel(); + + if (timeoutTask.caughtWhileCancelling != null) { + throw timeoutTask.caughtWhileCancelling; + } + + timeoutTask = null; + } + + synchronized (this.cancelTimeoutMutex) { + if (this.wasCancelled) { + this.wasCancelled = false; + throw new MySQLTimeoutException(); + } + } + } finally { + if (timeoutTask != null) { + timeoutTask.cancel(); + } + } + + return rs; + } catch (NullPointerException npe) { + checkClosed(); // we can't synchronize ourselves against async connection-close + // due to deadlock issues, so this is the next best thing for + // this particular corner case. + + throw npe; + } + } + + /** + * A Prepared SQL query is executed and its ResultSet is returned + * + * @return a ResultSet that contains the data produced by the query - never + * null + * + * @exception SQLException + * if a database access error occurs + */ + public java.sql.ResultSet executeQuery() throws SQLException { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + checkForDml(this.originalSql, this.firstCharOfStmt); + + CachedResultSetMetaData cachedMetadata = null; + + // We need to execute this all together + // So synchronize on the Connection's mutex (because + // even queries going through there synchronize + // on the same mutex. + synchronized (locallyScopedConn.getMutex()) { + clearWarnings(); + + this.batchedGeneratedKeys = null; + + Buffer sendPacket = fillSendPacket(); + + if (this.results != null) { + if (!this.connection.getHoldResultsOpenOverStatementClose()) { + if (!this.holdResultsOpenOverClose) { + this.results.realClose(false); + } + } + } + + String oldCatalog = null; + + if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) { + oldCatalog = locallyScopedConn.getCatalog(); + locallyScopedConn.setCatalog(this.currentCatalog); + } + + // + // Check if we have cached metadata for this query... + // + if (locallyScopedConn.getCacheResultSetMetadata()) { + cachedMetadata = locallyScopedConn.getCachedMetaData(this.originalSql); + } + + Field[] metadataFromCache = null; + + if (cachedMetadata != null) { + metadataFromCache = cachedMetadata.fields; + } + + if (locallyScopedConn.useMaxRows()) { + // If there isn't a limit clause in the SQL + // then limit the number of rows to return in + // an efficient manner. Only do this if + // setMaxRows() hasn't been used on any Statements + // generated from the current Connection (saves + // a query, and network traffic). + if (this.hasLimitClause) { + this.results = executeInternal(this.maxRows, sendPacket, + createStreamingResultSet(), true, + (cachedMetadata == null), metadataFromCache, false); + } else { + if (this.maxRows <= 0) { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, null, //$NON-NLS-1$ + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.currentCatalog, true); + } else { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=" + this.maxRows, -1, null, //$NON-NLS-1$ + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.currentCatalog, true); + } + + + + this.results = executeInternal(-1, sendPacket, + createStreamingResultSet(), true, + (cachedMetadata == null), metadataFromCache, false); + + if (oldCatalog != null) { + this.connection.setCatalog(oldCatalog); + } + } + } else { + this.results = executeInternal(-1, sendPacket, + createStreamingResultSet(), true, + (cachedMetadata == null), metadataFromCache, false); + } + + if (oldCatalog != null) { + locallyScopedConn.setCatalog(oldCatalog); + } + + if (cachedMetadata != null) { + locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, + cachedMetadata, this.results); + } else { + if (locallyScopedConn.getCacheResultSetMetadata()) { + locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, + null /* will be created */, this.results); + } + } + } + + this.lastInsertId = this.results.getUpdateID(); + + return this.results; + } + + /** + * Execute a SQL INSERT, UPDATE or DELETE statement. In addition, SQL + * statements that return nothing such as SQL DDL statements can be + * executed. + * + * @return either the row count for INSERT, UPDATE or DELETE; or 0 for SQL + * statements that return nothing. + * + * @exception SQLException + * if a database access error occurs + */ + public int executeUpdate() throws SQLException { + return executeUpdate(true, false); + } + + /* + * We need this variant, because ServerPreparedStatement calls this for + * batched updates, which will end up clobbering the warnings and generated + * keys we need to gather for the batch. + */ + protected int executeUpdate( + boolean clearBatchedGeneratedKeysAndWarnings, boolean isBatch) throws SQLException { + if (clearBatchedGeneratedKeysAndWarnings) { + clearWarnings(); + this.batchedGeneratedKeys = null; + } + + return executeUpdate(this.parameterValues, this.parameterStreams, + this.isStream, this.streamLengths, this.isNull, isBatch); + } + + /** + * Added to allow batch-updates + * + * @param batchedParameterStrings + * string values used in single statement + * @param batchedParameterStreams + * stream values used in single statement + * @param batchedIsStream + * flags for streams used in single statement + * @param batchedStreamLengths + * lengths of streams to be read. + * @param batchedIsNull + * flags for parameters that are null + * + * @return the update count + * + * @throws SQLException + * if a database error occurs + */ + protected int executeUpdate(byte[][] batchedParameterStrings, + InputStream[] batchedParameterStreams, boolean[] batchedIsStream, + int[] batchedStreamLengths, boolean[] batchedIsNull, boolean isReallyBatch) + throws SQLException { + + checkClosed(); + + Connection locallyScopedConn = this.connection; + + if (locallyScopedConn.isReadOnly()) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.34") //$NON-NLS-1$ + + Messages.getString("PreparedStatement.35"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if ((this.firstCharOfStmt == 'S') + && isSelectQuery()) { //$NON-NLS-1$ + throw SQLError.createSQLException(Messages.getString("PreparedStatement.37"), //$NON-NLS-1$ + "01S03"); //$NON-NLS-1$ + } + + if (this.results != null) { + if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) { + this.results.realClose(false); + } + } + + ResultSet rs = null; + + // The checking and changing of catalogs + // must happen in sequence, so synchronize + // on the same mutex that _conn is using + synchronized (locallyScopedConn.getMutex()) { + Buffer sendPacket = fillSendPacket(batchedParameterStrings, + batchedParameterStreams, batchedIsStream, + batchedStreamLengths); + + String oldCatalog = null; + + if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) { + oldCatalog = locallyScopedConn.getCatalog(); + locallyScopedConn.setCatalog(this.currentCatalog); + } + + // + // Only apply max_rows to selects + // + if (locallyScopedConn.useMaxRows()) { + locallyScopedConn.execSQL(this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, null, //$NON-NLS-1$ + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.currentCatalog, true); + } + + boolean oldInfoMsgState = false; + + if (this.retrieveGeneratedKeys) { + oldInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + } + + rs = executeInternal(-1, sendPacket, false, false, true, null, + isReallyBatch); + + if (this.retrieveGeneratedKeys) { + locallyScopedConn.setReadInfoMsgEnabled(oldInfoMsgState); + rs.setFirstCharOfQuery(this.firstCharOfStmt); + } + + if (oldCatalog != null) { + locallyScopedConn.setCatalog(oldCatalog); + } + } + + this.results = rs; + + this.updateCount = rs.getUpdateCount(); + + int truncatedUpdateCount = 0; + + if (this.updateCount > Integer.MAX_VALUE) { + truncatedUpdateCount = Integer.MAX_VALUE; + } else { + truncatedUpdateCount = (int) this.updateCount; + } + + this.lastInsertId = rs.getUpdateID(); + + return truncatedUpdateCount; + } + + private String extractValuesClause() throws SQLException { + if (this.batchedValuesClause == null) { + String quoteCharStr = this.connection.getMetaData() + .getIdentifierQuoteString(); + + int indexOfValues = -1; + + if (quoteCharStr.length() > 0) { + indexOfValues = StringUtils.indexOfIgnoreCaseRespectQuotes( + this.statementAfterCommentsPos, + this.originalSql, "VALUES ", quoteCharStr.charAt(0), false); + } else { + indexOfValues = StringUtils.indexOfIgnoreCase(this.statementAfterCommentsPos, + this.originalSql, + "VALUES "); + } + + if (indexOfValues == -1) { + return null; + } + + int indexOfFirstParen = this.originalSql + .indexOf('(', indexOfValues + 7); + + if (indexOfFirstParen == -1) { + return null; + } + + int indexOfLastParen = this.originalSql.lastIndexOf(')'); + + if (indexOfLastParen == -1) { + return null; + } + + this.batchedValuesClause = this.originalSql.substring(indexOfFirstParen, + indexOfLastParen + 1); + } + + return this.batchedValuesClause; + } + + /** + * Creates the packet that contains the query to be sent to the server. + * + * @return A Buffer filled with the query representing the + * PreparedStatement. + * + * @throws SQLException + * if an error occurs. + */ + protected Buffer fillSendPacket() throws SQLException { + return fillSendPacket(this.parameterValues, this.parameterStreams, + this.isStream, this.streamLengths); + } + + /** + * Creates the packet that contains the query to be sent to the server. + * + * @param batchedParameterStrings + * the parameters as strings + * @param batchedParameterStreams + * the parameters as streams + * @param batchedIsStream + * is the given parameter a stream? + * @param batchedStreamLengths + * the lengths of the streams (if appropriate) + * + * @return a Buffer filled with the query that represents this statement + * + * @throws SQLException + * if an error occurs. + */ + protected Buffer fillSendPacket(byte[][] batchedParameterStrings, + InputStream[] batchedParameterStreams, boolean[] batchedIsStream, + int[] batchedStreamLengths) throws SQLException { + Buffer sendPacket = this.connection.getIO().getSharedSendPacket(); + + sendPacket.clear(); + + sendPacket.writeByte((byte) MysqlDefs.QUERY); + + boolean useStreamLengths = this.connection + .getUseStreamLengthsInPrepStmts(); + + // + // Try and get this allocation as close as possible + // for BLOBs + // + int ensurePacketSize = 0; + + for (int i = 0; i < batchedParameterStrings.length; i++) { + if (batchedIsStream[i] && useStreamLengths) { + ensurePacketSize += batchedStreamLengths[i]; + } + } + + if (ensurePacketSize != 0) { + sendPacket.ensureCapacity(ensurePacketSize); + } + + for (int i = 0; i < batchedParameterStrings.length; i++) { + if ((batchedParameterStrings[i] == null) + && (batchedParameterStreams[i] == null)) { + throw SQLError.createSQLException(Messages + .getString("PreparedStatement.40") //$NON-NLS-1$ + + (i + 1), SQLError.SQL_STATE_WRONG_NO_OF_PARAMETERS); + } + + sendPacket.writeBytesNoNull(this.staticSqlStrings[i]); + + if (batchedIsStream[i]) { + streamToBytes(sendPacket, batchedParameterStreams[i], true, + batchedStreamLengths[i], useStreamLengths); + } else { + sendPacket.writeBytesNoNull(batchedParameterStrings[i]); + } + } + + sendPacket + .writeBytesNoNull(this.staticSqlStrings[batchedParameterStrings.length]); + + return sendPacket; + } + + private String generateBatchedInsertSQL(String valuesClause, int numBatches) { + StringBuffer newStatementSql = new StringBuffer(this.originalSql + .length() + + (numBatches * (valuesClause.length() + 1))); + + newStatementSql.append(this.originalSql); + + for (int i = 0; i < numBatches - 1; i++) { + newStatementSql.append(','); + newStatementSql.append(valuesClause); + } + + return newStatementSql.toString(); + } + + /** + * DOCUMENT ME! + * + * @param parameterIndex + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public byte[] getBytesRepresentation(int parameterIndex) + throws SQLException { + if (this.isStream[parameterIndex]) { + return streamToBytes(this.parameterStreams[parameterIndex], false, + this.streamLengths[parameterIndex], this.connection + .getUseStreamLengthsInPrepStmts()); + } + + byte[] parameterVal = this.parameterValues[parameterIndex]; + + if (parameterVal == null) { + return null; + } + + if ((parameterVal[0] == '\'') + && (parameterVal[parameterVal.length - 1] == '\'')) { + byte[] valNoQuotes = new byte[parameterVal.length - 2]; + System.arraycopy(parameterVal, 1, valNoQuotes, 0, + parameterVal.length - 2); + + return valNoQuotes; + } + + return parameterVal; + } + + // --------------------------JDBC 2.0----------------------------- + + private final String getDateTimePattern(String dt, boolean toTime) + throws Exception { + // + // Special case + // + int dtLength = (dt != null) ? dt.length() : 0; + + if ((dtLength >= 8) && (dtLength <= 10)) { + int dashCount = 0; + boolean isDateOnly = true; + + for (int i = 0; i < dtLength; i++) { + char c = dt.charAt(i); + + if (!Character.isDigit(c) && (c != '-')) { + isDateOnly = false; + + break; + } + + if (c == '-') { + dashCount++; + } + } + + if (isDateOnly && (dashCount == 2)) { + return "yyyy-MM-dd"; //$NON-NLS-1$ + } + } + + // + // Special case - time-only + // + boolean colonsOnly = true; + + for (int i = 0; i < dtLength; i++) { + char c = dt.charAt(i); + + if (!Character.isDigit(c) && (c != ':')) { + colonsOnly = false; + + break; + } + } + + if (colonsOnly) { + return "HH:mm:ss"; //$NON-NLS-1$ + } + + int n; + int z; + int count; + int maxvecs; + char c; + char separator; + StringReader reader = new StringReader(dt + " "); //$NON-NLS-1$ + ArrayList vec = new ArrayList(); + ArrayList vecRemovelist = new ArrayList(); + Object[] nv = new Object[3]; + Object[] v; + nv[0] = new Character('y'); + nv[1] = new StringBuffer(); + nv[2] = new Integer(0); + vec.add(nv); + + if (toTime) { + nv = new Object[3]; + nv[0] = new Character('h'); + nv[1] = new StringBuffer(); + nv[2] = new Integer(0); + vec.add(nv); + } + + while ((z = reader.read()) != -1) { + separator = (char) z; + maxvecs = vec.size(); + + for (count = 0; count < maxvecs; count++) { + v = (Object[]) vec.get(count); + n = ((Integer) v[2]).intValue(); + c = getSuccessor(((Character) v[0]).charValue(), n); + + if (!Character.isLetterOrDigit(separator)) { + if ((c == ((Character) v[0]).charValue()) && (c != 'S')) { + vecRemovelist.add(v); + } else { + ((StringBuffer) v[1]).append(separator); + + if ((c == 'X') || (c == 'Y')) { + v[2] = new Integer(4); + } + } + } else { + if (c == 'X') { + c = 'y'; + nv = new Object[3]; + nv[1] = (new StringBuffer(((StringBuffer) v[1]) + .toString())).append('M'); + nv[0] = new Character('M'); + nv[2] = new Integer(1); + vec.add(nv); + } else if (c == 'Y') { + c = 'M'; + nv = new Object[3]; + nv[1] = (new StringBuffer(((StringBuffer) v[1]) + .toString())).append('d'); + nv[0] = new Character('d'); + nv[2] = new Integer(1); + vec.add(nv); + } + + ((StringBuffer) v[1]).append(c); + + if (c == ((Character) v[0]).charValue()) { + v[2] = new Integer(n + 1); + } else { + v[0] = new Character(c); + v[2] = new Integer(1); + } + } + } + + int size = vecRemovelist.size(); + + for (int i = 0; i < size; i++) { + v = (Object[]) vecRemovelist.get(i); + vec.remove(v); + } + + vecRemovelist.clear(); + } + + int size = vec.size(); + + for (int i = 0; i < size; i++) { + v = (Object[]) vec.get(i); + c = ((Character) v[0]).charValue(); + n = ((Integer) v[2]).intValue(); + + boolean bk = getSuccessor(c, n) != c; + boolean atEnd = (((c == 's') || (c == 'm') || ((c == 'h') && toTime)) && bk); + boolean finishesAtDate = (bk && (c == 'd') && !toTime); + boolean containsEnd = (((StringBuffer) v[1]).toString() + .indexOf('W') != -1); + + if ((!atEnd && !finishesAtDate) || (containsEnd)) { + vecRemovelist.add(v); + } + } + + size = vecRemovelist.size(); + + for (int i = 0; i < size; i++) { + vec.remove(vecRemovelist.get(i)); + } + + vecRemovelist.clear(); + v = (Object[]) vec.get(0); // might throw exception + + StringBuffer format = (StringBuffer) v[1]; + format.setLength(format.length() - 1); + + return format.toString(); + } + + /** + * The number, types and properties of a ResultSet's columns are provided by + * the getMetaData method. + * + * @return the description of a ResultSet's columns + * + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.ResultSetMetaData getMetaData() + throws SQLException { + + // + // We could just tack on a LIMIT 0 here no matter what the + // statement, and check if a result set was returned or not, + // but I'm not comfortable with that, myself, so we take + // the "safer" road, and only allow metadata for _actual_ + // SELECTS (but not SHOWs). + // + // CALL's are trapped further up and you end up with a + // CallableStatement anyway. + // + + if (!isSelectQuery()) { + return null; + } + + PreparedStatement mdStmt = null; + java.sql.ResultSet mdRs = null; + + if (this.pstmtResultMetaData == null) { + try { + mdStmt = new PreparedStatement(this.connection, + this.originalSql, this.currentCatalog, this.parseInfo); + + mdStmt.setMaxRows(0); + + int paramCount = this.parameterValues.length; + + for (int i = 1; i <= paramCount; i++) { + mdStmt.setString(i, ""); //$NON-NLS-1$ + } + + boolean hadResults = mdStmt.execute(); + + if (hadResults) { + mdRs = mdStmt.getResultSet(); + + this.pstmtResultMetaData = mdRs.getMetaData(); + } else { + this.pstmtResultMetaData = new ResultSetMetaData( + new Field[0], + this.connection.getUseOldAliasMetadataBehavior()); + } + } finally { + SQLException sqlExRethrow = null; + + if (mdRs != null) { + try { + mdRs.close(); + } catch (SQLException sqlEx) { + sqlExRethrow = sqlEx; + } + + mdRs = null; + } + + if (mdStmt != null) { + try { + mdStmt.close(); + } catch (SQLException sqlEx) { + sqlExRethrow = sqlEx; + } + + mdStmt = null; + } + + if (sqlExRethrow != null) { + throw sqlExRethrow; + } + } + } + + return this.pstmtResultMetaData; + } + + protected boolean isSelectQuery() { + return StringUtils.startsWithIgnoreCaseAndWs( + StringUtils.stripComments(this.originalSql, + "'\"", "'\"", true, false, true, true), + "SELECT"); + } + + /** + * @see PreparedStatement#getParameterMetaData() + */ + public ParameterMetaData getParameterMetaData() + throws SQLException { + if (this.parameterMetaData == null) { + if (this.connection.getGenerateSimpleParameterMetadata()) { + this.parameterMetaData = new MysqlParameterMetadata(this.parameterCount); + } else { + this.parameterMetaData = new MysqlParameterMetadata( + null, this.parameterCount); + } + } + + return this.parameterMetaData; + } + + ParseInfo getParseInfo() { + return this.parseInfo; + } + + private final char getSuccessor(char c, int n) { + return ((c == 'y') && (n == 2)) ? 'X' + : (((c == 'y') && (n < 4)) ? 'y' + : ((c == 'y') ? 'M' + : (((c == 'M') && (n == 2)) ? 'Y' + : (((c == 'M') && (n < 3)) ? 'M' + : ((c == 'M') ? 'd' + : (((c == 'd') && (n < 2)) ? 'd' + : ((c == 'd') ? 'H' + : (((c == 'H') && (n < 2)) ? 'H' + : ((c == 'H') ? 'm' + : (((c == 'm') && (n < 2)) ? 'm' + : ((c == 'm') ? 's' + : (((c == 's') && (n < 2)) ? 's' + : 'W')))))))))))); + } + + /** + * Used to escape binary data with hex for mb charsets + * + * @param buf + * @param packet + * @param size + * @throws SQLException + */ + private final void hexEscapeBlock(byte[] buf, Buffer packet, int size) + throws SQLException { + for (int i = 0; i < size; i++) { + byte b = buf[i]; + int lowBits = (b & 0xff) / 16; + int highBits = (b & 0xff) % 16; + + packet.writeByte(HEX_DIGITS[lowBits]); + packet.writeByte(HEX_DIGITS[highBits]); + } + } + + private void initializeFromParseInfo() throws SQLException { + this.staticSqlStrings = this.parseInfo.staticSql; + this.hasLimitClause = this.parseInfo.foundLimitClause; + this.isLoadDataQuery = this.parseInfo.foundLoadData; + this.firstCharOfStmt = this.parseInfo.firstStmtChar; + + this.parameterCount = this.staticSqlStrings.length - 1; + + this.parameterValues = new byte[this.parameterCount][]; + this.parameterStreams = new InputStream[this.parameterCount]; + this.isStream = new boolean[this.parameterCount]; + this.streamLengths = new int[this.parameterCount]; + this.isNull = new boolean[this.parameterCount]; + + clearParameters(); + + for (int j = 0; j < this.parameterCount; j++) { + this.isStream[j] = false; + } + + this.statementAfterCommentsPos = this.parseInfo.statementStartPos; + } + + boolean isNull(int paramIndex) { + return this.isNull[paramIndex]; + } + + private final int readblock(InputStream i, byte[] b) throws SQLException { + try { + return i.read(b); + } catch (Throwable E) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.56") //$NON-NLS-1$ + + E.getClass().getName(), SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + private final int readblock(InputStream i, byte[] b, int length) + throws SQLException { + try { + int lengthToRead = length; + + if (lengthToRead > b.length) { + lengthToRead = b.length; + } + + return i.read(b, 0, lengthToRead); + } catch (Throwable E) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.55") //$NON-NLS-1$ + + E.getClass().getName(), SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + /** + * Closes this statement, releasing all resources + * + * @param calledExplicitly + * was this called by close()? + * + * @throws SQLException + * if an error occurs + */ + protected void realClose(boolean calledExplicitly, + boolean closeOpenResults) throws SQLException { + if (this.useUsageAdvisor) { + if (this.numberOfExecutions <= 1) { + String message = Messages.getString("PreparedStatement.43"); //$NON-NLS-1$ + + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, "", this.currentCatalog, //$NON-NLS-1$ + this.connectionId, this.getId(), -1, System + .currentTimeMillis(), 0, Constants.MILLIS_I18N, + null, + this.pointOfOrigin, message)); + } + } + + super.realClose(calledExplicitly, closeOpenResults); + + this.dbmd = null; + this.originalSql = null; + this.staticSqlStrings = null; + this.parameterValues = null; + this.parameterStreams = null; + this.isStream = null; + this.streamLengths = null; + this.isNull = null; + this.streamConvertBuf = null; + } + + /** + * JDBC 2.0 Set an Array parameter. + * + * @param i + * the first parameter is 1, the second is 2, ... + * @param x + * an object representing an SQL array + * + * @throws SQLException + * because this method is not implemented. + * @throws NotImplemented + * DOCUMENT ME! + */ + public void setArray(int i, Array x) throws SQLException { + throw new NotImplemented(); + } + + /** + * When a very large ASCII value is input to a LONGVARCHAR parameter, it may + * be more practical to send it via a java.io.InputStream. JDBC will read + * the data from the stream as needed, until it reaches end-of-file. The + * JDBC driver will do any necessary conversion from ASCII to the database + * char format. + * + *

+ * Note: This stream object can either be a standard Java stream + * object or your own subclass that implements the standard interface. + *

+ * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * @param length + * the number of bytes in the stream + * + * @exception SQLException + * if a database access error occurs + */ + public void setAsciiStream(int parameterIndex, InputStream x, + int length) throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.VARCHAR); + } else { + setBinaryStream(parameterIndex, x, length); + } + } + + /** + * Set a parameter to a java.math.BigDecimal value. The driver converts this + * to a SQL NUMERIC value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setBigDecimal(int parameterIndex, BigDecimal x) + throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.DECIMAL); + } else { + setInternal(parameterIndex, StringUtils + .fixDecimalExponent(StringUtils.consistentToString(x))); + } + } + + /** + * When a very large binary value is input to a LONGVARBINARY parameter, it + * may be more practical to send it via a java.io.InputStream. JDBC will + * read the data from the stream as needed, until it reaches end-of-file. + * + *

+ * Note: This stream object can either be a standard Java stream + * object or your own subclass that implements the standard interface. + *

+ * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * @param length + * the number of bytes to read from the stream (ignored) + * + * @throws SQLException + * if a database access error occurs + */ + public void setBinaryStream(int parameterIndex, InputStream x, int length) + throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + int parameterIndexOffset = getParameterIndexOffset(); + + if ((parameterIndex < 1) + || (parameterIndex > this.staticSqlStrings.length)) { + throw SQLError.createSQLException( + Messages.getString("PreparedStatement.2") //$NON-NLS-1$ + + parameterIndex + + Messages.getString("PreparedStatement.3") + this.staticSqlStrings.length + Messages.getString("PreparedStatement.4"), //$NON-NLS-1$ //$NON-NLS-2$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } else if (parameterIndexOffset == -1 && parameterIndex == 1) { + throw SQLError.createSQLException("Can't set IN parameter for return value of stored function call.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + + this.parameterStreams[parameterIndex - 1 + parameterIndexOffset] = x; + this.isStream[parameterIndex - 1 + parameterIndexOffset] = true; + this.streamLengths[parameterIndex - 1 + parameterIndexOffset] = length; + this.isNull[parameterIndex - 1 + parameterIndexOffset] = false; + } + } + + /** + * JDBC 2.0 Set a BLOB parameter. + * + * @param i + * the first parameter is 1, the second is 2, ... + * @param x + * an object representing a BLOB + * + * @throws SQLException + * if a database error occurs + */ + public void setBlob(int i, java.sql.Blob x) throws SQLException { + if (x == null) { + setNull(i, Types.BLOB); + } else { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + + bytesOut.write('\''); + escapeblockFast(x.getBytes(1, (int) x.length()), bytesOut, (int) x + .length()); + bytesOut.write('\''); + + setInternal(i, bytesOut.toByteArray()); + } + } + + /** + * Set a parameter to a Java boolean value. The driver converts this to a + * SQL BIT value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @throws SQLException + * if a database access error occurs + */ + public void setBoolean(int parameterIndex, boolean x) throws SQLException { + if (this.useTrueBoolean) { + setInternal(parameterIndex, x ? "1" : "0"); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + setInternal(parameterIndex, x ? "'t'" : "'f'"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Set a parameter to a Java byte value. The driver converts this to a SQL + * TINYINT value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setByte(int parameterIndex, byte x) throws SQLException { + setInternal(parameterIndex, String.valueOf(x)); + } + + /** + * Set a parameter to a Java array of bytes. The driver converts this to a + * SQL VARBINARY or LONGVARBINARY (depending on the argument's size relative + * to the driver's limits on VARBINARYs) when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setBytes(int parameterIndex, byte[] x) throws SQLException { + setBytes(parameterIndex, x, true, true); + } + + protected void setBytes(int parameterIndex, byte[] x, + boolean checkForIntroducer, boolean escapeForMBChars) + throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + String connectionEncoding = this.connection.getEncoding(); + + if (this.connection.isNoBackslashEscapesSet() + || (escapeForMBChars + && this.connection.getUseUnicode() + && connectionEncoding != null + && CharsetMapping.isMultibyteCharset(connectionEncoding))) { + + // Send as hex + + ByteArrayOutputStream bOut = new ByteArrayOutputStream( + (x.length * 2) + 3); + bOut.write('x'); + bOut.write('\''); + + for (int i = 0; i < x.length; i++) { + int lowBits = (x[i] & 0xff) / 16; + int highBits = (x[i] & 0xff) % 16; + + bOut.write(HEX_DIGITS[lowBits]); + bOut.write(HEX_DIGITS[highBits]); + } + + bOut.write('\''); + + setInternal(parameterIndex, bOut.toByteArray()); + + return; + } + + // escape them + int numBytes = x.length; + + int pad = 2; + + boolean needsIntroducer = checkForIntroducer + && this.connection.versionMeetsMinimum(4, 1, 0); + + if (needsIntroducer) { + pad += 7; + } + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(numBytes + + pad); + + if (needsIntroducer) { + bOut.write('_'); + bOut.write('b'); + bOut.write('i'); + bOut.write('n'); + bOut.write('a'); + bOut.write('r'); + bOut.write('y'); + } + bOut.write('\''); + + for (int i = 0; i < numBytes; ++i) { + byte b = x[i]; + + switch (b) { + case 0: /* Must be escaped for 'mysql' */ + bOut.write('\\'); + bOut.write('0'); + + break; + + case '\n': /* Must be escaped for logs */ + bOut.write('\\'); + bOut.write('n'); + + break; + + case '\r': + bOut.write('\\'); + bOut.write('r'); + + break; + + case '\\': + bOut.write('\\'); + bOut.write('\\'); + + break; + + case '\'': + bOut.write('\\'); + bOut.write('\''); + + break; + + case '"': /* Better safe than sorry */ + bOut.write('\\'); + bOut.write('"'); + + break; + + case '\032': /* This gives problems on Win32 */ + bOut.write('\\'); + bOut.write('Z'); + + break; + + default: + bOut.write(b); + } + } + + bOut.write('\''); + + setInternal(parameterIndex, bOut.toByteArray()); + } + } + + /** + * Used by updatable result sets for refreshRow() because the parameter has + * already been escaped for updater or inserter prepared statements. + * + * @param parameterIndex + * the parameter to set. + * @param parameterAsBytes + * the parameter as a string. + * + * @throws SQLException + * if an error occurs + */ + protected void setBytesNoEscape(int parameterIndex, byte[] parameterAsBytes) + throws SQLException { + byte[] parameterWithQuotes = new byte[parameterAsBytes.length + 2]; + parameterWithQuotes[0] = '\''; + System.arraycopy(parameterAsBytes, 0, parameterWithQuotes, 1, + parameterAsBytes.length); + parameterWithQuotes[parameterAsBytes.length + 1] = '\''; + + setInternal(parameterIndex, parameterWithQuotes); + } + + protected void setBytesNoEscapeNoQuotes(int parameterIndex, + byte[] parameterAsBytes) throws SQLException { + setInternal(parameterIndex, parameterAsBytes); + } + + /** + * JDBC 2.0 When a very large UNICODE value is input to a LONGVARCHAR + * parameter, it may be more practical to send it via a java.io.Reader. JDBC + * will read the data from the stream as needed, until it reaches + * end-of-file. The JDBC driver will do any necessary conversion from + * UNICODE to the database char format. + * + *

+ * Note: This stream object can either be a standard Java stream + * object or your own subclass that implements the standard interface. + *

+ * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param reader + * the java reader which contains the UNICODE data + * @param length + * the number of characters in the stream + * + * @exception SQLException + * if a database-access error occurs. + */ + public void setCharacterStream(int parameterIndex, java.io.Reader reader, + int length) throws SQLException { + try { + if (reader == null) { + setNull(parameterIndex, Types.LONGVARCHAR); + } else { + char[] c = null; + int len = 0; + + boolean useLength = this.connection + .getUseStreamLengthsInPrepStmts(); + + String forcedEncoding = this.connection.getClobCharacterEncoding(); + + if (useLength && (length != -1)) { + c = new char[length]; + + int numCharsRead = readFully(reader, c, length); // blocks + // until + // all + // read + + if (forcedEncoding == null) { + setString(parameterIndex, new String(c, 0, numCharsRead)); + } else { + try { + setBytes(parameterIndex, new String(c, + 0, + numCharsRead).getBytes(forcedEncoding)); + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException("Unsupported character encoding " + + forcedEncoding, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } else { + c = new char[4096]; + + StringBuffer buf = new StringBuffer(); + + while ((len = reader.read(c)) != -1) { + buf.append(c, 0, len); + } + + if (forcedEncoding == null) { + setString(parameterIndex, buf.toString()); + } else { + try { + setBytes(parameterIndex, + buf.toString().getBytes(forcedEncoding)); + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException("Unsupported character encoding " + + forcedEncoding, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + } + } catch (java.io.IOException ioEx) { + throw SQLError.createSQLException(ioEx.toString(), + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + /** + * JDBC 2.0 Set a CLOB parameter. + * + * @param i + * the first parameter is 1, the second is 2, ... + * @param x + * an object representing a CLOB + * + * @throws SQLException + * if a database error occurs + */ + public void setClob(int i, Clob x) throws SQLException { + if (x == null) { + setNull(i, Types.CLOB); + + return; + } + + String forcedEncoding = this.connection.getClobCharacterEncoding(); + + if (forcedEncoding == null) { + setString(i, x.getSubString(1L, (int) x.length())); + } else { + try { + setBytes(i, x.getSubString(1L, + (int)x.length()).getBytes(forcedEncoding)); + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException("Unsupported character encoding " + + forcedEncoding, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + + /** + * Set a parameter to a java.sql.Date value. The driver converts this to a + * SQL DATE value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception java.sql.SQLException + * if a database access error occurs + */ + public void setDate(int parameterIndex, java.sql.Date x) + throws java.sql.SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.DATE); + } else { + // FIXME: Have instance version of this, problem as it's + // not thread-safe :( + SimpleDateFormat dateFormatter = new SimpleDateFormat( + "''yyyy-MM-dd''", Locale.US); //$NON-NLS-1$ + setInternal(parameterIndex, dateFormatter.format(x)); + } + } + + /** + * Set a parameter to a java.sql.Date value. The driver converts this to a + * SQL DATE value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param x + * the parameter value + * @param cal + * the calendar to interpret the date with + * + * @exception SQLException + * if a database-access error occurs. + */ + public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) + throws SQLException { + setDate(parameterIndex, x); + } + + /** + * Set a parameter to a Java double value. The driver converts this to a SQL + * DOUBLE value when it sends it to the database + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setDouble(int parameterIndex, double x) throws SQLException { + + if (!this.connection.getAllowNanAndInf() + && (x == Double.POSITIVE_INFINITY + || x == Double.NEGATIVE_INFINITY || Double.isNaN(x))) { + throw SQLError.createSQLException("'" + x + + "' is not a valid numeric or approximate numeric value", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + + } + + setInternal(parameterIndex, StringUtils.fixDecimalExponent(String + .valueOf(x))); + } + + /** + * Set a parameter to a Java float value. The driver converts this to a SQL + * FLOAT value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setFloat(int parameterIndex, float x) throws SQLException { + setInternal(parameterIndex, StringUtils.fixDecimalExponent(String + .valueOf(x))); + } + + /** + * Set a parameter to a Java int value. The driver converts this to a SQL + * INTEGER value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setInt(int parameterIndex, int x) throws SQLException { + setInternal(parameterIndex, String.valueOf(x)); + } + + private final void setInternal(int paramIndex, byte[] val) + throws SQLException { + if (this.isClosed) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.48"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + int parameterIndexOffset = getParameterIndexOffset(); + + if ((paramIndex < 1)) { + throw SQLError.createSQLException( + Messages.getString("PreparedStatement.49") //$NON-NLS-1$ + + paramIndex + + Messages.getString("PreparedStatement.50"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } else if (paramIndex > this.parameterCount) { + throw SQLError.createSQLException( + Messages.getString("PreparedStatement.51") //$NON-NLS-1$ + + paramIndex + + Messages.getString("PreparedStatement.52") + (this.parameterValues.length) + Messages.getString("PreparedStatement.53"), //$NON-NLS-1$ //$NON-NLS-2$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } else if (parameterIndexOffset == -1 && paramIndex == 1) { + throw SQLError.createSQLException("Can't set IN parameter for return value of stored function call.", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + this.isStream[paramIndex - 1 + parameterIndexOffset] = false; + this.isNull[paramIndex - 1 + parameterIndexOffset] = false; + this.parameterStreams[paramIndex - 1 + parameterIndexOffset] = null; + this.parameterValues[paramIndex - 1 + parameterIndexOffset] = val; + } + + private final void setInternal(int paramIndex, String val) + throws SQLException { + checkClosed(); + + byte[] parameterAsBytes = null; + + if (this.charConverter != null) { + parameterAsBytes = this.charConverter.toBytes(val); + } else { + parameterAsBytes = StringUtils.getBytes(val, this.charConverter, + this.charEncoding, this.connection + .getServerCharacterEncoding(), this.connection + .parserKnowsUnicode()); + } + + setInternal(paramIndex, parameterAsBytes); + } + + /** + * Set a parameter to a Java long value. The driver converts this to a SQL + * BIGINT value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setLong(int parameterIndex, long x) throws SQLException { + setInternal(parameterIndex, String.valueOf(x)); + } + + /** + * Set a parameter to SQL NULL + * + *

+ * Note: You must specify the parameters SQL type (although MySQL + * ignores it) + *

+ * + * @param parameterIndex + * the first parameter is 1, etc... + * @param sqlType + * the SQL type code defined in java.sql.Types + * + * @exception SQLException + * if a database access error occurs + */ + public void setNull(int parameterIndex, int sqlType) throws SQLException { + setInternal(parameterIndex, "null"); //$NON-NLS-1$ + this.isNull[parameterIndex - 1] = true; + } + + /** + * Set a parameter to SQL NULL. + * + *

+ * Note: You must specify the parameter's SQL type. + *

+ * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param sqlType + * SQL type code defined by java.sql.Types + * @param arg + * argument parameters for null + * + * @exception SQLException + * if a database-access error occurs. + */ + public void setNull(int parameterIndex, int sqlType, String arg) + throws SQLException { + setNull(parameterIndex, sqlType); + } + + private void setNumericObject(int parameterIndex, Object parameterObj, int targetSqlType, int scale) throws SQLException { + Number parameterAsNum; + + if (parameterObj instanceof Boolean) { + parameterAsNum = ((Boolean) parameterObj) + .booleanValue() ? new Integer(1) : new Integer( + 0); + } else if (parameterObj instanceof String) { + switch (targetSqlType) { + case Types.BIT: + boolean parameterAsBoolean = "true" + .equalsIgnoreCase((String) parameterObj); + + parameterAsNum = parameterAsBoolean ? new Integer(1) + : new Integer(0); + + break; + + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + parameterAsNum = Integer + .valueOf((String) parameterObj); + + break; + + case Types.BIGINT: + parameterAsNum = Long + .valueOf((String) parameterObj); + + break; + + case Types.REAL: + parameterAsNum = Float + .valueOf((String) parameterObj); + + break; + + case Types.FLOAT: + case Types.DOUBLE: + parameterAsNum = Double + .valueOf((String) parameterObj); + + break; + + case Types.DECIMAL: + case Types.NUMERIC: + default: + parameterAsNum = new java.math.BigDecimal( + (String) parameterObj); + } + } else { + parameterAsNum = (Number) parameterObj; + } + + switch (targetSqlType) { + case Types.BIT: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + setInt(parameterIndex, parameterAsNum.intValue()); + + break; + + case Types.BIGINT: + setLong(parameterIndex, parameterAsNum.longValue()); + + break; + + case Types.REAL: + setFloat(parameterIndex, parameterAsNum.floatValue()); + + break; + + case Types.FLOAT: + case Types.DOUBLE: + setDouble(parameterIndex, parameterAsNum.doubleValue()); + + break; + + case Types.DECIMAL: + case Types.NUMERIC: + + if (parameterAsNum instanceof java.math.BigDecimal) { + BigDecimal scaledBigDecimal = null; + + try { + scaledBigDecimal = ((java.math.BigDecimal) parameterAsNum) + .setScale(scale); + } catch (ArithmeticException ex) { + try { + scaledBigDecimal = ((java.math.BigDecimal) parameterAsNum) + .setScale(scale, + BigDecimal.ROUND_HALF_UP); + } catch (ArithmeticException arEx) { + throw SQLError.createSQLException( + "Can't set scale of '" + + scale + + "' for DECIMAL argument '" + + parameterAsNum + "'", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + setBigDecimal(parameterIndex, scaledBigDecimal); + } else if (parameterAsNum instanceof java.math.BigInteger) { + setBigDecimal( + parameterIndex, + new java.math.BigDecimal( + (java.math.BigInteger) parameterAsNum, + scale)); + } else { + setBigDecimal(parameterIndex, + new java.math.BigDecimal(parameterAsNum + .doubleValue())); + } + + break; + } + } + + /** + * DOCUMENT ME! + * + * @param parameterIndex + * DOCUMENT ME! + * @param parameterObj + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public void setObject(int parameterIndex, Object parameterObj) + throws SQLException { + if (parameterObj == null) { + setNull(parameterIndex, java.sql.Types.OTHER); + } else { + if (parameterObj instanceof Byte) { + setInt(parameterIndex, ((Byte) parameterObj).intValue()); + } else if (parameterObj instanceof String) { + setString(parameterIndex, (String) parameterObj); + } else if (parameterObj instanceof BigDecimal) { + setBigDecimal(parameterIndex, (BigDecimal) parameterObj); + } else if (parameterObj instanceof Short) { + setShort(parameterIndex, ((Short) parameterObj).shortValue()); + } else if (parameterObj instanceof Integer) { + setInt(parameterIndex, ((Integer) parameterObj).intValue()); + } else if (parameterObj instanceof Long) { + setLong(parameterIndex, ((Long) parameterObj).longValue()); + } else if (parameterObj instanceof Float) { + setFloat(parameterIndex, ((Float) parameterObj).floatValue()); + } else if (parameterObj instanceof Double) { + setDouble(parameterIndex, ((Double) parameterObj).doubleValue()); + } else if (parameterObj instanceof byte[]) { + setBytes(parameterIndex, (byte[]) parameterObj); + } else if (parameterObj instanceof java.sql.Date) { + setDate(parameterIndex, (java.sql.Date) parameterObj); + } else if (parameterObj instanceof Time) { + setTime(parameterIndex, (Time) parameterObj); + } else if (parameterObj instanceof Timestamp) { + setTimestamp(parameterIndex, (Timestamp) parameterObj); + } else if (parameterObj instanceof Boolean) { + setBoolean(parameterIndex, ((Boolean) parameterObj) + .booleanValue()); + } else if (parameterObj instanceof InputStream) { + setBinaryStream(parameterIndex, (InputStream) parameterObj, -1); + } else if (parameterObj instanceof java.sql.Blob) { + setBlob(parameterIndex, (java.sql.Blob) parameterObj); + } else if (parameterObj instanceof java.sql.Clob) { + setClob(parameterIndex, (java.sql.Clob) parameterObj); + } else if (this.connection.getTreatUtilDateAsTimestamp() && + parameterObj instanceof java.util.Date) { + setTimestamp(parameterIndex, new Timestamp( + ((java.util.Date) parameterObj).getTime())); + } else if (parameterObj instanceof BigInteger) { + setString(parameterIndex, parameterObj.toString()); + } else { + setSerializableObject(parameterIndex, parameterObj); + } + } + } + + + /** + * DOCUMENT ME! + * + * @param parameterIndex + * DOCUMENT ME! + * @param parameterObj + * DOCUMENT ME! + * @param targetSqlType + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public void setObject(int parameterIndex, Object parameterObj, + int targetSqlType) throws SQLException { + if (!(parameterObj instanceof BigDecimal)) { + setObject(parameterIndex, parameterObj, targetSqlType, 0); + } else { + setObject(parameterIndex, parameterObj, targetSqlType, + ((BigDecimal)parameterObj).scale()); + } + } + + /** + * Set the value of a parameter using an object; use the java.lang + * equivalent objects for integral values. + * + *

+ * The given Java object will be converted to the targetSqlType before being + * sent to the database. + *

+ * + *

+ * note that this method may be used to pass database-specific abstract data + * types. This is done by using a Driver-specific Java type and using a + * targetSqlType of java.sql.Types.OTHER + *

+ * + * @param parameterIndex + * the first parameter is 1... + * @param parameterObj + * the object containing the input parameter value + * @param targetSqlType + * The SQL type to be send to the database + * @param scale + * For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types + * this is the number of digits after the decimal. For all other + * types this value will be ignored. + * + * @throws SQLException + * if a database access error occurs + */ + public void setObject(int parameterIndex, Object parameterObj, + int targetSqlType, int scale) throws SQLException { + if (parameterObj == null) { + setNull(parameterIndex, java.sql.Types.OTHER); + } else { + try { + switch (targetSqlType) { + case Types.BOOLEAN: + /* + From Table-B5 in the JDBC-3.0 Spec + + T S I B R F D D N B B C V L + I M N I E L O E U I O H A O + N A T G A O U C M T O A R N + Y L E I L A B I E L R C G + I L G N T L M R E H V + N I E T E A I A A A + T N R L C N R R + T C + H + A + R + ----------------------------------- + Boolean x x x x x x x x x x x x x x + */ + + if (parameterObj instanceof Boolean) { + setBoolean(parameterIndex, ((Boolean)parameterObj).booleanValue()); + + break; + } else if (parameterObj instanceof String) { + setBoolean(parameterIndex, "true".equalsIgnoreCase((String)parameterObj) || + !"0".equalsIgnoreCase((String)parameterObj)); + + break; + } else if (parameterObj instanceof Number) { + int intValue = ((Number)parameterObj).intValue(); + + setBoolean(parameterIndex, intValue != 0); + + break; + } else { + throw SQLError.createSQLException("No conversion from " + parameterObj.getClass().getName() + + " to Types.BOOLEAN possible.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + + case Types.BIT: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.REAL: + case Types.FLOAT: + case Types.DOUBLE: + case Types.DECIMAL: + case Types.NUMERIC: + + setNumericObject(parameterIndex, parameterObj, targetSqlType, scale); + + break; + + case Types.CHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: + if (parameterObj instanceof BigDecimal) { + setString( + parameterIndex, + (StringUtils + .fixDecimalExponent(StringUtils + .consistentToString((BigDecimal) parameterObj)))); + } else { + setString(parameterIndex, parameterObj.toString()); + } + + break; + + case Types.CLOB: + + if (parameterObj instanceof java.sql.Clob) { + setClob(parameterIndex, (java.sql.Clob) parameterObj); + } else { + setString(parameterIndex, parameterObj.toString()); + } + + break; + + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + case Types.BLOB: + + if (parameterObj instanceof byte[]) { + setBytes(parameterIndex, (byte[]) parameterObj); + } else if (parameterObj instanceof java.sql.Blob) { + setBlob(parameterIndex, (java.sql.Blob) parameterObj); + } else { + setBytes(parameterIndex, StringUtils.getBytes( + parameterObj.toString(), this.charConverter, + this.charEncoding, this.connection + .getServerCharacterEncoding(), + this.connection.parserKnowsUnicode())); + } + + break; + + case Types.DATE: + case Types.TIMESTAMP: + + java.util.Date parameterAsDate; + + if (parameterObj instanceof String) { + ParsePosition pp = new ParsePosition(0); + java.text.DateFormat sdf = new java.text.SimpleDateFormat( + getDateTimePattern((String) parameterObj, false), Locale.US); + parameterAsDate = sdf.parse((String) parameterObj, pp); + } else { + parameterAsDate = (java.util.Date) parameterObj; + } + + switch (targetSqlType) { + case Types.DATE: + + if (parameterAsDate instanceof java.sql.Date) { + setDate(parameterIndex, + (java.sql.Date) parameterAsDate); + } else { + setDate(parameterIndex, new java.sql.Date( + parameterAsDate.getTime())); + } + + break; + + case Types.TIMESTAMP: + + if (parameterAsDate instanceof java.sql.Timestamp) { + setTimestamp(parameterIndex, + (java.sql.Timestamp) parameterAsDate); + } else { + setTimestamp(parameterIndex, + new java.sql.Timestamp(parameterAsDate + .getTime())); + } + + break; + } + + break; + + case Types.TIME: + + if (parameterObj instanceof String) { + java.text.DateFormat sdf = new java.text.SimpleDateFormat( + getDateTimePattern((String) parameterObj, true), Locale.US); + setTime(parameterIndex, new java.sql.Time(sdf.parse( + (String) parameterObj).getTime())); + } else if (parameterObj instanceof Timestamp) { + Timestamp xT = (Timestamp) parameterObj; + setTime(parameterIndex, new java.sql.Time(xT.getTime())); + } else { + setTime(parameterIndex, (java.sql.Time) parameterObj); + } + + break; + + case Types.OTHER: + setSerializableObject(parameterIndex, parameterObj); + + break; + + default: + throw SQLError.createSQLException(Messages + .getString("PreparedStatement.16"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (Exception ex) { + if (ex instanceof SQLException) { + throw (SQLException) ex; + } + + throw SQLError.createSQLException( + Messages.getString("PreparedStatement.17") //$NON-NLS-1$ + + parameterObj.getClass().toString() + + Messages.getString("PreparedStatement.18") //$NON-NLS-1$ + + ex.getClass().getName() + + Messages.getString("PreparedStatement.19") + ex.getMessage(), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + } + + protected int setOneBatchedParameterSet( + java.sql.PreparedStatement batchedStatement, int batchedParamIndex, + Object paramSet) throws SQLException { + BatchParams paramArg = (BatchParams)paramSet; + + boolean[] isNullBatch = paramArg.isNull; + boolean[] isStreamBatch = paramArg.isStream; + + for (int j = 0; j < isNullBatch.length; j++) { + if (isNullBatch[j]) { + batchedStatement.setNull(batchedParamIndex++, Types.NULL); + } else { + if (isStreamBatch[j]) { + batchedStatement.setBinaryStream(batchedParamIndex++, + paramArg.parameterStreams[j], + paramArg.streamLengths[j]); + } else { + ((com.mysql.jdbc.PreparedStatement) batchedStatement) + .setBytesNoEscapeNoQuotes(batchedParamIndex++, + paramArg.parameterStrings[j]); + } + } + } + + return batchedParamIndex; + } + + /** + * JDBC 2.0 Set a REF(<structured-type>) parameter. + * + * @param i + * the first parameter is 1, the second is 2, ... + * @param x + * an object representing data of an SQL REF Type + * + * @throws SQLException + * if a database error occurs + * @throws NotImplemented + * DOCUMENT ME! + */ + public void setRef(int i, Ref x) throws SQLException { + throw new NotImplemented(); + } + + /** + * Sets the concurrency for result sets generated by this statement + * + * @param concurrencyFlag + * DOCUMENT ME! + */ + void setResultSetConcurrency(int concurrencyFlag) { + this.resultSetConcurrency = concurrencyFlag; + } + + /** + * Sets the result set type for result sets generated by this statement + * + * @param typeFlag + * DOCUMENT ME! + */ + void setResultSetType(int typeFlag) { + this.resultSetType = typeFlag; + } + + /** + * DOCUMENT ME! + * + * @param retrieveGeneratedKeys + */ + protected void setRetrieveGeneratedKeys(boolean retrieveGeneratedKeys) { + this.retrieveGeneratedKeys = retrieveGeneratedKeys; + } + + /** + * Sets the value for the placeholder as a serialized Java object (used by + * various forms of setObject() + * + * @param parameterIndex + * DOCUMENT ME! + * @param parameterObj + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + private final void setSerializableObject(int parameterIndex, + Object parameterObj) throws SQLException { + try { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut); + objectOut.writeObject(parameterObj); + objectOut.flush(); + objectOut.close(); + bytesOut.flush(); + bytesOut.close(); + + byte[] buf = bytesOut.toByteArray(); + ByteArrayInputStream bytesIn = new ByteArrayInputStream(buf); + setBinaryStream(parameterIndex, bytesIn, buf.length); + } catch (Exception ex) { + throw SQLError.createSQLException(Messages.getString("PreparedStatement.54") //$NON-NLS-1$ + + ex.getClass().getName(), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + /** + * Set a parameter to a Java short value. The driver converts this to a SQL + * SMALLINT value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setShort(int parameterIndex, short x) throws SQLException { + setInternal(parameterIndex, String.valueOf(x)); + } + + /** + * Set a parameter to a Java String value. The driver converts this to a SQL + * VARCHAR or LONGVARCHAR value (depending on the arguments size relative to + * the driver's limits on VARCHARs) when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @exception SQLException + * if a database access error occurs + */ + public void setString(int parameterIndex, String x) throws SQLException { + // if the passed string is null, then set this column to null + if (x == null) { + setNull(parameterIndex, Types.CHAR); + } else { + checkClosed(); + + int stringLength = x.length(); + + if (this.connection.isNoBackslashEscapesSet()) { + // Scan for any nasty chars + + boolean needsHexEscape = false; + + for (int i = 0; i < stringLength; ++i) { + char c = x.charAt(i); + + switch (c) { + case 0: /* Must be escaped for 'mysql' */ + + needsHexEscape = true; + break; + + case '\n': /* Must be escaped for logs */ + needsHexEscape = true; + + break; + + case '\r': + needsHexEscape = true; + break; + + case '\\': + needsHexEscape = true; + + break; + + case '\'': + needsHexEscape = true; + + break; + + case '"': /* Better safe than sorry */ + needsHexEscape = true; + + break; + + case '\032': /* This gives problems on Win32 */ + needsHexEscape = true; + break; + } + + if (needsHexEscape) { + break; // no need to scan more + } + } + + + + if (!needsHexEscape) { + byte[] parameterAsBytes = null; + + StringBuffer quotedString = new StringBuffer(x.length() + 2); + quotedString.append('\''); + quotedString.append(x); + quotedString.append('\''); + + if (!this.isLoadDataQuery) { + parameterAsBytes = StringUtils.getBytes(quotedString.toString(), + this.charConverter, this.charEncoding, + this.connection.getServerCharacterEncoding(), + this.connection.parserKnowsUnicode()); + } else { + // Send with platform character encoding + parameterAsBytes = quotedString.toString().getBytes(); + } + + setInternal(parameterIndex, parameterAsBytes); + } else { + byte[] parameterAsBytes = null; + + if (!this.isLoadDataQuery) { + parameterAsBytes = StringUtils.getBytes(x, + this.charConverter, this.charEncoding, + this.connection.getServerCharacterEncoding(), + this.connection.parserKnowsUnicode()); + } else { + // Send with platform character encoding + parameterAsBytes = x.getBytes(); + } + + setBytes(parameterIndex, parameterAsBytes); + } + + return; + } + + StringBuffer buf = new StringBuffer((int) (x.length() * 1.1)); + buf.append('\''); + + // + // Note: buf.append(char) is _faster_ than + // appending in blocks, because the block + // append requires a System.arraycopy().... + // go figure... + // + + for (int i = 0; i < stringLength; ++i) { + char c = x.charAt(i); + + switch (c) { + case 0: /* Must be escaped for 'mysql' */ + buf.append('\\'); + buf.append('0'); + + break; + + case '\n': /* Must be escaped for logs */ + buf.append('\\'); + buf.append('n'); + + break; + + case '\r': + buf.append('\\'); + buf.append('r'); + + break; + + case '\\': + buf.append('\\'); + buf.append('\\'); + + break; + + case '\'': + buf.append('\\'); + buf.append('\''); + + break; + + case '"': /* Better safe than sorry */ + if (this.usingAnsiMode) { + buf.append('\\'); + } + + buf.append('"'); + + break; + + case '\032': /* This gives problems on Win32 */ + buf.append('\\'); + buf.append('Z'); + + break; + + default: + buf.append(c); + } + } + + buf.append('\''); + + String parameterAsString = buf.toString(); + + byte[] parameterAsBytes = null; + + if (!this.isLoadDataQuery) { + parameterAsBytes = StringUtils.getBytes(parameterAsString, + this.charConverter, this.charEncoding, this.connection + .getServerCharacterEncoding(), this.connection + .parserKnowsUnicode()); + } else { + // Send with platform character encoding + parameterAsBytes = parameterAsString.getBytes(); + } + + setInternal(parameterIndex, parameterAsBytes); + } + } + + /** + * Set a parameter to a java.sql.Time value. The driver converts this to a + * SQL TIME value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param x + * the parameter value + * @param cal + * the cal specifying the timezone + * + * @throws SQLException + * if a database-access error occurs. + */ + public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) + throws SQLException { + setTimeInternal(parameterIndex, x, cal, cal.getTimeZone(), true); + } + + /** + * Set a parameter to a java.sql.Time value. The driver converts this to a + * SQL TIME value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1...)); + * @param x + * the parameter value + * + * @throws java.sql.SQLException + * if a database access error occurs + */ + public void setTime(int parameterIndex, Time x) + throws java.sql.SQLException { + setTimeInternal(parameterIndex, x, null, this.connection.getDefaultTimeZone(), false); + } + + /** + * Set a parameter to a java.sql.Time value. The driver converts this to a + * SQL TIME value when it sends it to the database, using the given + * timezone. + * + * @param parameterIndex + * the first parameter is 1...)); + * @param x + * the parameter value + * @param tz + * the timezone to use + * + * @throws java.sql.SQLException + * if a database access error occurs + */ + private void setTimeInternal(int parameterIndex, Time x, Calendar targetCalendar, + TimeZone tz, + boolean rollForward) throws java.sql.SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.TIME); + } else { + checkClosed(); + + Calendar sessionCalendar = getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + x = TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + x, tz, this.connection + .getServerTimezoneTZ(), rollForward); + } + + setInternal(parameterIndex, "'" + x.toString() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * Set a parameter to a java.sql.Timestamp value. The driver converts this + * to a SQL TIMESTAMP value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param x + * the parameter value + * @param cal + * the calendar specifying the timezone to use + * + * @throws SQLException + * if a database-access error occurs. + */ + public void setTimestamp(int parameterIndex, java.sql.Timestamp x, + Calendar cal) throws SQLException { + setTimestampInternal(parameterIndex, x, cal, cal.getTimeZone(), true); + } + + /** + * Set a parameter to a java.sql.Timestamp value. The driver converts this + * to a SQL TIMESTAMP value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * + * @throws java.sql.SQLException + * if a database access error occurs + */ + public void setTimestamp(int parameterIndex, Timestamp x) + throws java.sql.SQLException { + setTimestampInternal(parameterIndex, x, null, this.connection.getDefaultTimeZone(), false); + } + + /** + * Set a parameter to a java.sql.Timestamp value. The driver converts this + * to a SQL TIMESTAMP value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param x + * the parameter value + * @param tz + * the timezone to use + * + * @throws SQLException + * if a database-access error occurs. + */ + private void setTimestampInternal(int parameterIndex, + Timestamp x, Calendar targetCalendar, + TimeZone tz, boolean rollForward) throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.TIMESTAMP); + } else { + checkClosed(); + + String timestampString = null; + + Calendar sessionCalendar = this.connection.getUseJDBCCompliantTimezoneShift() ? + this.connection.getUtcCalendar() : + getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + x = TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + x, tz, this.connection + .getServerTimezoneTZ(), rollForward); + } + + + if (this.connection.getUseSSPSCompatibleTimezoneShift()) { + doSSPSCompatibleTimezoneShift(parameterIndex, x, sessionCalendar); + } else { + + if (this.tsdf == null) { + this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss''", Locale.US); //$NON-NLS-1$ + } + + timestampString = this.tsdf.format(x); + + setInternal(parameterIndex, timestampString); // SimpleDateFormat is not + // thread-safe + } + } + } + + private void doSSPSCompatibleTimezoneShift(int parameterIndex, Timestamp x, Calendar sessionCalendar) throws SQLException { + Calendar sessionCalendar2 = (this.connection + .getUseJDBCCompliantTimezoneShift()) ? this.connection + .getUtcCalendar() + : getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar2) { + java.util.Date oldTime = sessionCalendar2.getTime(); + + try { + sessionCalendar2.setTime(x); + + int year = sessionCalendar2.get(Calendar.YEAR); + int month = sessionCalendar2.get(Calendar.MONTH) + 1; + int date = sessionCalendar2.get(Calendar.DAY_OF_MONTH); + + int hour = sessionCalendar2.get(Calendar.HOUR_OF_DAY); + int minute = sessionCalendar2.get(Calendar.MINUTE); + int seconds = sessionCalendar2.get(Calendar.SECOND); + + StringBuffer tsBuf = new StringBuffer(); + + tsBuf.append('\''); + tsBuf.append(year); + + tsBuf.append("-"); + + if (month < 10) { + tsBuf.append('0'); + } + + tsBuf.append(month); + + tsBuf.append('-'); + + if (date < 10) { + tsBuf.append('0'); + } + + tsBuf.append(date); + + tsBuf.append(' '); + + if (hour < 10) { + tsBuf.append('0'); + } + + tsBuf.append(hour); + + tsBuf.append(':'); + + if (minute < 10) { + tsBuf.append('0'); + } + + tsBuf.append(minute); + + tsBuf.append(':'); + + if (seconds < 10) { + tsBuf.append('0'); + } + + tsBuf.append(seconds); + + tsBuf.append('\''); + + setInternal(parameterIndex, tsBuf.toString()); + + } finally { + sessionCalendar.setTime(oldTime); + } + } + } + + /** + * When a very large Unicode value is input to a LONGVARCHAR parameter, it + * may be more practical to send it via a java.io.InputStream. JDBC will + * read the data from the stream as needed, until it reaches end-of-file. + * The JDBC driver will do any necessary conversion from UNICODE to the + * database char format. + * + *

+ * Note: This stream object can either be a standard Java stream + * object or your own subclass that implements the standard interface. + *

+ * + * @param parameterIndex + * the first parameter is 1... + * @param x + * the parameter value + * @param length + * the number of bytes to read from the stream + * + * @throws SQLException + * if a database access error occurs + * + * @deprecated + */ + public void setUnicodeStream(int parameterIndex, InputStream x, int length) + throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.VARCHAR); + } else { + setBinaryStream(parameterIndex, x, length); + } + } + + /** + * @see PreparedStatement#setURL(int, URL) + */ + public void setURL(int parameterIndex, URL arg) throws SQLException { + if (arg != null) { + setString(parameterIndex, arg.toString()); + } else { + setNull(parameterIndex, Types.CHAR); + } + } + + private final void streamToBytes(Buffer packet, InputStream in, + boolean escape, int streamLength, boolean useLength) + throws SQLException { + try { + String connectionEncoding = this.connection.getEncoding(); + + boolean hexEscape = false; + + if (this.connection.isNoBackslashEscapesSet() + || (this.connection.getUseUnicode() + && connectionEncoding != null + && CharsetMapping.isMultibyteCharset(connectionEncoding) + && !this.connection.parserKnowsUnicode())) { + hexEscape = true; + } + + if (streamLength == -1) { + useLength = false; + } + + int bc = -1; + + if (useLength) { + bc = readblock(in, streamConvertBuf, streamLength); + } else { + bc = readblock(in, streamConvertBuf); + } + + int lengthLeftToRead = streamLength - bc; + + if (hexEscape) { + packet.writeStringNoNull("x"); + } else if (this.connection.getIO().versionMeetsMinimum(4, 1, 0)) { + packet.writeStringNoNull("_binary"); + } + + if (escape) { + packet.writeByte((byte) '\''); + } + + while (bc > 0) { + if (hexEscape) { + hexEscapeBlock(streamConvertBuf, packet, bc); + } else if (escape) { + escapeblockFast(streamConvertBuf, packet, bc); + } else { + packet.writeBytesNoNull(streamConvertBuf, 0, bc); + } + + if (useLength) { + bc = readblock(in, streamConvertBuf, lengthLeftToRead); + + if (bc > 0) { + lengthLeftToRead -= bc; + } + } else { + bc = readblock(in, streamConvertBuf); + } + } + + if (escape) { + packet.writeByte((byte) '\''); + } + } finally { + if (this.connection.getAutoClosePStmtStreams()) { + try { + in.close(); + } catch (IOException ioEx) { + ; + } + + in = null; + } + } + } + + private final byte[] streamToBytes(InputStream in, boolean escape, + int streamLength, boolean useLength) throws SQLException { + try { + if (streamLength == -1) { + useLength = false; + } + + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + + int bc = -1; + + if (useLength) { + bc = readblock(in, this.streamConvertBuf, streamLength); + } else { + bc = readblock(in, this.streamConvertBuf); + } + + int lengthLeftToRead = streamLength - bc; + + if (escape) { + if (this.connection.versionMeetsMinimum(4, 1, 0)) { + bytesOut.write('_'); + bytesOut.write('b'); + bytesOut.write('i'); + bytesOut.write('n'); + bytesOut.write('a'); + bytesOut.write('r'); + bytesOut.write('y'); + } + + bytesOut.write('\''); + } + + while (bc > 0) { + if (escape) { + escapeblockFast(this.streamConvertBuf, bytesOut, bc); + } else { + bytesOut.write(this.streamConvertBuf, 0, bc); + } + + if (useLength) { + bc = readblock(in, this.streamConvertBuf, lengthLeftToRead); + + if (bc > 0) { + lengthLeftToRead -= bc; + } + } else { + bc = readblock(in, this.streamConvertBuf); + } + } + + if (escape) { + bytesOut.write('\''); + } + + return bytesOut.toByteArray(); + } finally { + if (this.connection.getAutoClosePStmtStreams()) { + try { + in.close(); + } catch (IOException ioEx) { + ; + } + + in = null; + } + } + } + + /** + * Returns this PreparedStatement represented as a string. + * + * @return this PreparedStatement represented as a string. + */ + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append(super.toString()); + buf.append(": "); //$NON-NLS-1$ + + try { + buf.append(asSql()); + } catch (SQLException sqlEx) { + buf.append("EXCEPTION: " + sqlEx.toString()); + } + + return buf.toString(); + } + + /** + * For calling stored functions, this will be -1 as we don't really count + * the first '?' parameter marker, it's only syntax, but JDBC counts it + * as #1, otherwise it will return 0 + * + */ + + protected int getParameterIndexOffset() { + return 0; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ReplicationConnection.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ReplicationConnection.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ReplicationConnection.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,560 @@ +/* + Copyright (C) 2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package com.mysql.jdbc; + +import java.sql.CallableStatement; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Savepoint; +import java.sql.Statement; +import java.util.Map; +import java.util.Properties; + +/** + * Connection that opens two connections, one two a replication master, and + * another to one or more slaves, and decides to use master when the connection + * is not read-only, and use slave(s) when the connection is read-only. + * + * @version $Id: ReplicationConnection.java,v 1.1.2.1 2005/05/13 18:58:38 + * mmatthews Exp $ + */ +public class ReplicationConnection implements java.sql.Connection, PingTarget { + private Connection currentConnection; + + private Connection masterConnection; + + private Connection slavesConnection; + + public ReplicationConnection(Properties masterProperties, + Properties slaveProperties) throws SQLException { + Driver driver = new Driver(); + + StringBuffer masterUrl = new StringBuffer("jdbc:mysql://"); + StringBuffer slaveUrl = new StringBuffer("jdbc:mysql://"); + + String masterHost = masterProperties + .getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY); + + if (masterHost != null) { + masterUrl.append(masterHost); + } + + String slaveHost = slaveProperties + .getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY); + + if (slaveHost != null) { + slaveUrl.append(slaveHost); + } + + String masterDb = masterProperties + .getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY); + + masterUrl.append("/"); + + if (masterDb != null) { + masterUrl.append(masterDb); + } + + String slaveDb = slaveProperties + .getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY); + + slaveUrl.append("/"); + + if (slaveDb != null) { + slaveUrl.append(slaveDb); + } + + this.masterConnection = (com.mysql.jdbc.Connection) driver.connect( + masterUrl.toString(), masterProperties); + this.slavesConnection = (com.mysql.jdbc.Connection) driver.connect( + slaveUrl.toString(), slaveProperties); + + this.currentConnection = this.masterConnection; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#clearWarnings() + */ + public synchronized void clearWarnings() throws SQLException { + this.currentConnection.clearWarnings(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#close() + */ + public synchronized void close() throws SQLException { + this.masterConnection.close(); + this.slavesConnection.close(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#commit() + */ + public synchronized void commit() throws SQLException { + this.currentConnection.commit(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#createStatement() + */ + public Statement createStatement() throws SQLException { + Statement stmt = this.currentConnection.createStatement(); + ((com.mysql.jdbc.Statement) stmt).setPingTarget(this); + + return stmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#createStatement(int, int) + */ + public synchronized Statement createStatement(int resultSetType, + int resultSetConcurrency) throws SQLException { + Statement stmt = this.currentConnection.createStatement(resultSetType, + resultSetConcurrency); + + ((com.mysql.jdbc.Statement) stmt).setPingTarget(this); + + return stmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#createStatement(int, int, int) + */ + public synchronized Statement createStatement(int resultSetType, + int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + Statement stmt = this.currentConnection.createStatement(resultSetType, + resultSetConcurrency, resultSetHoldability); + + ((com.mysql.jdbc.Statement) stmt).setPingTarget(this); + + return stmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#getAutoCommit() + */ + public synchronized boolean getAutoCommit() throws SQLException { + return this.currentConnection.getAutoCommit(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#getCatalog() + */ + public synchronized String getCatalog() throws SQLException { + return this.currentConnection.getCatalog(); + } + + public synchronized Connection getCurrentConnection() { + return this.currentConnection; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#getHoldability() + */ + public synchronized int getHoldability() throws SQLException { + return this.currentConnection.getHoldability(); + } + + public synchronized Connection getMasterConnection() { + return this.masterConnection; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#getMetaData() + */ + public synchronized DatabaseMetaData getMetaData() throws SQLException { + return this.currentConnection.getMetaData(); + } + + public synchronized Connection getSlavesConnection() { + return this.slavesConnection; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#getTransactionIsolation() + */ + public synchronized int getTransactionIsolation() throws SQLException { + return this.currentConnection.getTransactionIsolation(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#getTypeMap() + */ + public synchronized Map getTypeMap() throws SQLException { + return this.currentConnection.getTypeMap(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#getWarnings() + */ + public synchronized SQLWarning getWarnings() throws SQLException { + return this.currentConnection.getWarnings(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#isClosed() + */ + public synchronized boolean isClosed() throws SQLException { + return this.currentConnection.isClosed(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#isReadOnly() + */ + public synchronized boolean isReadOnly() throws SQLException { + return this.currentConnection == this.slavesConnection; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#nativeSQL(java.lang.String) + */ + public synchronized String nativeSQL(String sql) throws SQLException { + return this.currentConnection.nativeSQL(sql); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareCall(java.lang.String) + */ + public CallableStatement prepareCall(String sql) throws SQLException { + return this.currentConnection.prepareCall(sql); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareCall(java.lang.String, int, int) + */ + public synchronized CallableStatement prepareCall(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException { + return this.currentConnection.prepareCall(sql, resultSetType, + resultSetConcurrency); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareCall(java.lang.String, int, int, int) + */ + public synchronized CallableStatement prepareCall(String sql, + int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return this.currentConnection.prepareCall(sql, resultSetType, + resultSetConcurrency, resultSetHoldability); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareStatement(java.lang.String) + */ + public PreparedStatement prepareStatement(String sql) throws SQLException { + PreparedStatement pstmt = this.currentConnection.prepareStatement(sql); + + ((com.mysql.jdbc.Statement) pstmt).setPingTarget(this); + + return pstmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareStatement(java.lang.String, int) + */ + public synchronized PreparedStatement prepareStatement(String sql, + int autoGeneratedKeys) throws SQLException { + PreparedStatement pstmt = this.currentConnection.prepareStatement(sql, autoGeneratedKeys); + + ((com.mysql.jdbc.Statement) pstmt).setPingTarget(this); + + return pstmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareStatement(java.lang.String, int, int) + */ + public synchronized PreparedStatement prepareStatement(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException { + PreparedStatement pstmt = this.currentConnection.prepareStatement(sql, resultSetType, + resultSetConcurrency); + + ((com.mysql.jdbc.Statement) pstmt).setPingTarget(this); + + return pstmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareStatement(java.lang.String, int, int, + * int) + */ + public synchronized PreparedStatement prepareStatement(String sql, + int resultSetType, int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + PreparedStatement pstmt = this.currentConnection.prepareStatement(sql, resultSetType, + resultSetConcurrency, resultSetHoldability); + + ((com.mysql.jdbc.Statement) pstmt).setPingTarget(this); + + return pstmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareStatement(java.lang.String, int[]) + */ + public synchronized PreparedStatement prepareStatement(String sql, + int[] columnIndexes) throws SQLException { + PreparedStatement pstmt = this.currentConnection.prepareStatement(sql, columnIndexes); + + ((com.mysql.jdbc.Statement) pstmt).setPingTarget(this); + + return pstmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#prepareStatement(java.lang.String, + * java.lang.String[]) + */ + public synchronized PreparedStatement prepareStatement(String sql, + String[] columnNames) throws SQLException { + PreparedStatement pstmt = this.currentConnection.prepareStatement(sql, columnNames); + + ((com.mysql.jdbc.Statement) pstmt).setPingTarget(this); + + return pstmt; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#releaseSavepoint(java.sql.Savepoint) + */ + public synchronized void releaseSavepoint(Savepoint savepoint) + throws SQLException { + this.currentConnection.releaseSavepoint(savepoint); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#rollback() + */ + public synchronized void rollback() throws SQLException { + this.currentConnection.rollback(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#rollback(java.sql.Savepoint) + */ + public synchronized void rollback(Savepoint savepoint) throws SQLException { + this.currentConnection.rollback(savepoint); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setAutoCommit(boolean) + */ + public synchronized void setAutoCommit(boolean autoCommit) + throws SQLException { + this.currentConnection.setAutoCommit(autoCommit); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setCatalog(java.lang.String) + */ + public synchronized void setCatalog(String catalog) throws SQLException { + this.currentConnection.setCatalog(catalog); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setHoldability(int) + */ + public synchronized void setHoldability(int holdability) + throws SQLException { + this.currentConnection.setHoldability(holdability); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setReadOnly(boolean) + */ + public synchronized void setReadOnly(boolean readOnly) throws SQLException { + if (readOnly) { + if (currentConnection != slavesConnection) { + switchToSlavesConnection(); + } + } else { + if (currentConnection != masterConnection) { + switchToMasterConnection(); + } + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setSavepoint() + */ + public synchronized Savepoint setSavepoint() throws SQLException { + return this.currentConnection.setSavepoint(); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setSavepoint(java.lang.String) + */ + public synchronized Savepoint setSavepoint(String name) throws SQLException { + return this.currentConnection.setSavepoint(name); + } + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setTransactionIsolation(int) + */ + public synchronized void setTransactionIsolation(int level) + throws SQLException { + this.currentConnection.setTransactionIsolation(level); + } + + // For testing + + /* + * (non-Javadoc) + * + * @see java.sql.Connection#setTypeMap(java.util.Map) + */ + public synchronized void setTypeMap(Map arg0) throws SQLException { + this.currentConnection.setTypeMap(arg0); + } + + private synchronized void switchToMasterConnection() throws SQLException { + swapConnections(this.masterConnection, this.slavesConnection); + } + + private synchronized void switchToSlavesConnection() throws SQLException { + swapConnections(this.slavesConnection, this.masterConnection); + } + + /** + * Swaps current context (catalog, autocommit and txn_isolation) from + * sourceConnection to targetConnection, and makes targetConnection + * the "current" connection that will be used for queries. + * + * @param switchToConnection the connection to swap from + * @param switchFromConnection the connection to swap to + * + * @throws SQLException if an error occurs + */ + private synchronized void swapConnections(Connection switchToConnection, + Connection switchFromConnection) throws SQLException { + String switchFromCatalog = switchFromConnection.getCatalog(); + String switchToCatalog = switchToConnection.getCatalog(); + + if (switchToCatalog != null && !switchToCatalog.equals(switchFromCatalog)) { + switchToConnection.setCatalog(switchFromCatalog); + } else if (switchFromCatalog != null) { + switchToConnection.setCatalog(switchFromCatalog); + } + + boolean switchToAutoCommit = switchToConnection.getAutoCommit(); + boolean switchFromConnectionAutoCommit = switchFromConnection.getAutoCommit(); + + if (switchFromConnectionAutoCommit != switchToAutoCommit) { + switchToConnection.setAutoCommit(switchFromConnectionAutoCommit); + } + + int switchToIsolation = switchToConnection + .getTransactionIsolation(); + + int switchFromIsolation = switchFromConnection.getTransactionIsolation(); + + if (switchFromIsolation != switchToIsolation) { + switchToConnection + .setTransactionIsolation(switchFromIsolation); + } + + this.currentConnection = switchToConnection; + } + + public synchronized void doPing() throws SQLException { + if (this.masterConnection != null) { + this.masterConnection.ping(); + } + + if (this.slavesConnection != null) { + this.slavesConnection.ping(); + } + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ReplicationDriver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ReplicationDriver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ReplicationDriver.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,83 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +/** + * The Java SQL framework allows for multiple database drivers. Each driver + * should supply a class that implements the Driver interface + * + *

+ * The DriverManager will try to load as many drivers as it can find and then + * for any given connection request, it will ask each driver in turn to try to + * connect to the target URL. + * + *

+ * It is strongly recommended that each Driver class should be small and + * standalone so that the Driver class can be loaded and queried without + * bringing in vast quantities of supporting code. + * + *

+ * When a Driver class is loaded, it should create an instance of itself and + * register it with the DriverManager. This means that a user can load and + * register a driver by doing Class.forName("foo.bah.Driver") + * + * @see org.gjt.mm.mysql.Connection + * @see java.sql.Driver + * @author Mark Matthews + * @version $Id: ReplicationDriver.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews + * Exp $ + */ +public class ReplicationDriver extends NonRegisteringReplicationDriver + implements java.sql.Driver { + // ~ Static fields/initializers + // --------------------------------------------- + + // + // Register ourselves with the DriverManager + // + static { + try { + java.sql.DriverManager + .registerDriver(new NonRegisteringReplicationDriver()); + } catch (SQLException E) { + throw new RuntimeException("Can't register driver!"); + } + } + + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Construct a new driver and register it with DriverManager + * + * @throws SQLException + * if a database error occurs. + */ + public ReplicationDriver() throws SQLException { + // Required for Class.forName().newInstance() + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ResultSet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Attic/ResultSet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ResultSet.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,9090 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import com.mysql.jdbc.profiler.ProfileEventSink; +import com.mysql.jdbc.profiler.ProfilerEvent; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import java.net.MalformedURLException; +import java.net.URL; + +import java.sql.Array; +import java.sql.DataTruncation; +import java.sql.Date; +import java.sql.Ref; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; + +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.TimeZone; +import java.util.TreeMap; + +/** + * A ResultSet provides access to a table of data generated by executing a + * Statement. The table rows are retrieved in sequence. Within a row its column + * values can be accessed in any order. + * + *

+ * A ResultSet maintains a cursor pointing to its current row of data. Initially + * the cursor is positioned before the first row. The 'next' method moves the + * cursor to the next row. + *

+ * + *

+ * The getXXX methods retrieve column values for the current row. You can + * retrieve values either using the index number of the column, or by using the + * name of the column. In general using the column index will be more efficient. + * Columns are numbered from 1. + *

+ * + *

+ * For maximum portability, ResultSet columns within each row should be read in + * left-to-right order and each column should be read only once. + *

+ * + *

+ * For the getXXX methods, the JDBC driver attempts to convert the underlying + * data to the specified Java type and returns a suitable Java value. See the + * JDBC specification for allowable mappings from SQL types to Java types with + * the ResultSet getXXX methods. + *

+ * + *

+ * Column names used as input to getXXX methods are case insenstive. When + * performing a getXXX using a column name, if several columns have the same + * name, then the value of the first matching column will be returned. The + * column name option is designed to be used when column names are used in the + * SQL Query. For columns that are NOT explicitly named in the query, it is best + * to use column numbers. If column names were used there is no way for the + * programmer to guarentee that they actually refer to the intended columns. + *

+ * + *

+ * A ResultSet is automatically closed by the Statement that generated it when + * that Statement is closed, re-executed, or is used to retrieve the next result + * from a sequence of multiple results. + *

+ * + *

+ * The number, types and properties of a ResultSet's columns are provided by the + * ResultSetMetaData object returned by the getMetaData method. + *

+ * + * @author Mark Matthews + * @version $Id: ResultSet.java,v 1.1 2012/08/17 14:57:08 marcin Exp $ + * + * @see ResultSetMetaData + * @see java.sql.ResultSet + */ +public class ResultSet implements java.sql.ResultSet { + + /** + * Epsillon between Float.MIN_VALUE and the double representation of said value. + */ + protected static final double MIN_DIFF_PREC = Float.parseFloat(Float.toString(Float.MIN_VALUE)) + - Double.parseDouble(Float.toString(Float.MIN_VALUE)); + + /** + * Epsillon between Float.MAX_VALUE and the double representation of said value. + */ + protected static final double MAX_DIFF_PREC = Float.parseFloat(Float.toString(Float.MAX_VALUE)) + - Double.parseDouble(Float.toString(Float.MAX_VALUE)); + + /** Counter used to generate IDs for profiling. */ + protected static int resultCounter = 1; + + /** + * Converts the given value as a java long, to an 'unsigned' long, using the + * java.math.BigInteger class. + */ + protected static BigInteger convertLongToUlong(long longVal) { + byte[] asBytes = new byte[8]; + asBytes[7] = (byte) (longVal & 0xff); + asBytes[6] = (byte) (longVal >>> 8); + asBytes[5] = (byte) (longVal >>> 16); + asBytes[4] = (byte) (longVal >>> 24); + asBytes[3] = (byte) (longVal >>> 32); + asBytes[2] = (byte) (longVal >>> 40); + asBytes[1] = (byte) (longVal >>> 48); + asBytes[0] = (byte) (longVal >>> 56); + + return new BigInteger(1, asBytes); + } + + /** The catalog that was in use when we were created */ + protected String catalog = null; + + /** Map column names (and all of their permutations) to column indices */ + protected Map columnNameToIndex = null; + + /** Keep track of columns accessed */ + protected boolean[] columnUsed = null; + + /** The Connection instance that created us */ + protected com.mysql.jdbc.Connection connection; // The connection that + // created us + + protected long connectionId = 0; + + /** The current row #, -1 == before start of result set */ + protected int currentRow = -1; // Cursor to current row; + + private TimeZone defaultTimeZone; + + /** Are we in the middle of doing updates to the current row? */ + protected boolean doingUpdates = false; + + protected ProfileEventSink eventSink = null; + + private Calendar fastDateCal = null; + + /** The direction to fetch rows (always FETCH_FORWARD) */ + protected int fetchDirection = FETCH_FORWARD; + + /** The number of rows to fetch in one go... */ + protected int fetchSize = 0; + + /** The fields for this result set */ + protected Field[] fields; // The fields + + /** + * First character of the query that created this result set...Used to + * determine whether or not to parse server info messages in certain + * circumstances. + */ + protected char firstCharOfQuery; + + /** Map of fully-specified column names to column indices */ + protected Map fullColumnNameToIndex = null; + + protected boolean hasBuiltIndexMapping = false; + + /** + * Is the data stored as strings (default) or natively (which is the case + * with results from PrepStmts) + */ + protected boolean isBinaryEncoded = false; + + /** Has this result set been closed? */ + protected boolean isClosed = false; + + protected ResultSet nextResultSet = null; + + /** Are we on the insert row? */ + protected boolean onInsertRow = false; + + /** The statement that created us */ + protected com.mysql.jdbc.Statement owningStatement; + + /** + * StackTrace generated where ResultSet was created... used when profiling + */ + protected Throwable pointOfOrigin; + + /** Are we tracking items for profileSql? */ + protected boolean profileSql = false; + + /** + * Do we actually contain rows, or just information about + * UPDATE/INSERT/DELETE? + */ + protected boolean reallyResult = false; + + /** The id (used when profiling) to identify us */ + protected int resultId; + + /** Are we read-only or updatable? */ + protected int resultSetConcurrency = 0; + + /** Are we scroll-sensitive/insensitive? */ + protected int resultSetType = 0; + + /** The actual rows */ + protected RowData rowData; // The results + + /** + * Any info message from the server that was created while generating this + * result set (if 'info parsing' is enabled for the connection). + */ + protected String serverInfo = null; + + private PreparedStatement statementUsedForFetchingRows; + + /** Pointer to current row data */ + protected Object[] thisRow = null; // Values for current row + + // These are longs for + // recent versions of the MySQL server. + // + // They get reduced to ints via the JDBC API, + // but can be retrieved through a MySQLStatement + // in their entirety. + // + + /** How many rows were affected by UPDATE/INSERT/DELETE? */ + protected long updateCount; + + /** Value generated for AUTO_INCREMENT columns */ + protected long updateId = -1; + + private boolean useStrictFloatingPoint = false; + + protected boolean useUsageAdvisor = false; + + /** The warning chain */ + protected java.sql.SQLWarning warningChain = null; + + /** Did the previous value retrieval find a NULL? */ + protected boolean wasNullFlag = false; + + protected java.sql.Statement wrapperStatement; + + protected boolean retainOwningStatement; + + protected Calendar gmtCalendar = null; + + protected boolean useFastDateParsing = false; + + private boolean padCharsWithSpace = false; + + protected final static char[] EMPTY_SPACE = new char[255]; + + static { + for (int i = 0; i < EMPTY_SPACE.length; i++) { + EMPTY_SPACE[i] = ' '; + } + } + + /** + * Create a result set for an executeUpdate statement. + * + * @param updateCount + * the number of rows affected by the update + * @param updateID + * the autoincrement value (if any) + * @param conn + * DOCUMENT ME! + * @param creatorStmt + * DOCUMENT ME! + */ + public ResultSet(long updateCount, long updateID, Connection conn, + Statement creatorStmt) { + this.updateCount = updateCount; + this.updateId = updateID; + this.reallyResult = false; + this.fields = new Field[0]; + + this.connection = conn; + this.owningStatement = creatorStmt; + + this.retainOwningStatement = false; + + if (this.connection != null) { + this.retainOwningStatement = + this.connection.getRetainStatementAfterResultSetClose(); + + this.connectionId = this.connection.getId(); + } + } + + /** + * Creates a new ResultSet object. + * + * @param catalog + * the database in use when we were created + * @param fields + * an array of Field objects (basically, the ResultSet MetaData) + * @param tuples + * actual row data + * @param conn + * the Connection that created us. + * @param creatorStmt + * DOCUMENT ME! + * + * @throws SQLException + * if an error occurs + */ + public ResultSet(String catalog, Field[] fields, RowData tuples, + Connection conn, Statement creatorStmt) throws SQLException { + this.connection = conn; + + if (this.connection != null) { + this.useStrictFloatingPoint = this.connection + .getStrictFloatingPoint(); + this.setDefaultTimeZone(this.connection.getDefaultTimeZone()); + this.connectionId = this.connection.getId(); + this.useFastDateParsing = this.connection.getUseFastDateParsing(); + this.padCharsWithSpace = this.connection.getPadCharsWithSpace(); + } + + this.owningStatement = creatorStmt; + + this.catalog = catalog; + this.profileSql = this.connection.getProfileSql(); + + this.fields = fields; + this.rowData = tuples; + this.updateCount = this.rowData.size(); + + if (Driver.DEBUG) { + System.out.println(Messages.getString("ResultSet.Retrieved__1") + + this.updateCount + " rows"); //$NON-NLS-1$ + } + + this.reallyResult = true; + + // Check for no results + if (this.rowData.size() > 0) { + if (this.updateCount == 1) { + if (this.thisRow == null) { + this.rowData.close(); // empty result set + this.updateCount = -1; + } + } + } else { + this.thisRow = null; + } + + this.rowData.setOwner(this); + + if (this.fields != null) { + initializeWithMetadata(); + } // else called by Connection.initializeResultsMetadataFromCache() when cached + + this.retainOwningStatement = false; + + if (this.connection != null) { + retainOwningStatement = + this.connection.getRetainStatementAfterResultSetClose(); + } + } + + protected void initializeWithMetadata() throws SQLException { + if (this.profileSql || this.connection.getUseUsageAdvisor()) { + this.columnUsed = new boolean[this.fields.length]; + this.pointOfOrigin = new Throwable(); + this.resultId = resultCounter++; + this.useUsageAdvisor = this.connection.getUseUsageAdvisor(); + this.eventSink = ProfileEventSink.getInstance(this.connection); + } + + if (this.connection.getGatherPerformanceMetrics()) { + this.connection.incrementNumberOfResultSetsCreated(); + + Map tableNamesMap = new HashMap(); + + for (int i = 0; i < this.fields.length; i++) { + Field f = this.fields[i]; + + String tableName = f.getOriginalTableName(); + + if (tableName == null) { + tableName = f.getTableName(); + } + + if (tableName != null) { + if (this.connection.lowerCaseTableNames()) { + tableName = tableName.toLowerCase(); // on windows, table + // names are not case-sens. + } + + tableNamesMap.put(tableName, null); + } + } + + this.connection.reportNumberOfTablesAccessed(tableNamesMap.size()); + } + + + } + + private synchronized void createCalendarIfNeeded() { + if (this.fastDateCal == null) { + this.fastDateCal = new GregorianCalendar(Locale.US); + this.fastDateCal.setTimeZone(this.getDefaultTimeZone()); + } + } + + /** + * JDBC 2.0 + * + *

+ * Move to an absolute row number in the result set. + *

+ * + *

+ * If row is positive, moves to an absolute row with respect to the + * beginning of the result set. The first row is row 1, the second is row 2, + * etc. + *

+ * + *

+ * If row is negative, moves to an absolute row position with respect to the + * end of result set. For example, calling absolute(-1) positions the cursor + * on the last row, absolute(-2) indicates the next-to-last row, etc. + *

+ * + *

+ * An attempt to position the cursor beyond the first/last row in the result + * set, leaves the cursor before/after the first/last row, respectively. + *

+ * + *

+ * Note: Calling absolute(1) is the same as calling first(). Calling + * absolute(-1) is the same as calling last(). + *

+ * + * @param row + * the row number to move to + * + * @return true if on the result set, false if off. + * + * @exception SQLException + * if a database-access error occurs, or row is 0, or result + * set type is TYPE_FORWARD_ONLY. + */ + public boolean absolute(int row) throws SQLException { + checkClosed(); + + boolean b; + + if (this.rowData.size() == 0) { + b = false; + } else { + if (row == 0) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Cannot_absolute_position_to_row_0_110"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (this.onInsertRow) { + this.onInsertRow = false; + } + + if (this.doingUpdates) { + this.doingUpdates = false; + } + + if (row == 1) { + b = first(); + } else if (row == -1) { + b = last(); + } else if (row > this.rowData.size()) { + afterLast(); + b = false; + } else { + if (row < 0) { + // adjust to reflect after end of result set + int newRowPosition = this.rowData.size() + row + 1; + + if (newRowPosition <= 0) { + beforeFirst(); + b = false; + } else { + b = absolute(newRowPosition); + } + } else { + row--; // adjust for index difference + this.rowData.setCurrentRow(row); + this.thisRow = this.rowData.getAt(row); + b = true; + } + } + } + + return b; + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the end of the result set, just after the last row. Has no + * effect if the result set contains no rows. + *

+ * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY. + */ + public void afterLast() throws SQLException { + checkClosed(); + + if (this.onInsertRow) { + this.onInsertRow = false; + } + + if (this.doingUpdates) { + this.doingUpdates = false; + } + + if (this.rowData.size() != 0) { + this.rowData.afterLast(); + this.thisRow = null; + } + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the front of the result set, just before the first row. Has no + * effect if the result set contains no rows. + *

+ * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY + */ + public void beforeFirst() throws SQLException { + checkClosed(); + + if (this.onInsertRow) { + this.onInsertRow = false; + } + + if (this.doingUpdates) { + this.doingUpdates = false; + } + + if (this.rowData.size() == 0) { + return; + } + + this.rowData.beforeFirst(); + this.thisRow = null; + } + + // --------------------------------------------------------------------- + // Traversal/Positioning + // --------------------------------------------------------------------- + + /** + * Builds a hash between column names and their indices for fast retrieval. + */ + protected void buildIndexMapping() throws SQLException { + int numFields = this.fields.length; + this.columnNameToIndex = new TreeMap(String.CASE_INSENSITIVE_ORDER); + this.fullColumnNameToIndex = new TreeMap(String.CASE_INSENSITIVE_ORDER); + + + // We do this in reverse order, so that the 'first' column + // with a given name ends up as the final mapping in the + // hashtable... + // + // Quoting the JDBC Spec: + // + // "Column names used as input to getter + // methods are case insensitive. When a getter method is called with a + // column + // name and several columns have the same name, the value of the first + // matching column will be returned. " + // + for (int i = numFields - 1; i >= 0; i--) { + Integer index = new Integer(i); + String columnName = this.fields[i].getName(); + String fullColumnName = this.fields[i].getFullName(); + + if (columnName != null) { + this.columnNameToIndex.put(columnName, index); + } + + if (fullColumnName != null) { + this.fullColumnNameToIndex.put(fullColumnName, index); + } + } + + // set the flag to prevent rebuilding... + this.hasBuiltIndexMapping = true; + } + + /** + * JDBC 2.0 The cancelRowUpdates() method may be called after calling an + * updateXXX() method(s) and before calling updateRow() to rollback the + * updates made to a row. If no updates have been made or updateRow() has + * already been called, then this method has no effect. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row. + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void cancelRowUpdates() throws SQLException { + throw new NotUpdatable(); + } + + /** + * Ensures that the result set is not closed + * + * @throws SQLException + * if the result set is closed + */ + protected final void checkClosed() throws SQLException { + if (this.isClosed) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Operation_not_allowed_after_ResultSet_closed_144"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + /** + * Checks if columnIndex is within the number of columns in this result set. + * + * @param columnIndex + * the index to check + * + * @throws SQLException + * if the index is out of bounds + */ + protected final void checkColumnBounds(int columnIndex) throws SQLException { + if ((columnIndex < 1)) { + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Column_Index_out_of_range_low", new Object[] { + new Integer(columnIndex), + new Integer(this.fields.length) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } else if ((columnIndex > this.fields.length)) { + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Column_Index_out_of_range_high", new Object[] { + new Integer(columnIndex), + new Integer(this.fields.length) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + if (this.profileSql || this.useUsageAdvisor) { + this.columnUsed[columnIndex - 1] = true; + } + } + + /** + * Ensures that the cursor is positioned on a valid row and that the result + * set is not closed + * + * @throws SQLException + * if the result set is not in a valid state for traversal + */ + protected void checkRowPos() throws SQLException { + checkClosed(); + + if (!this.rowData.isDynamic() && (this.rowData.size() == 0)) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Illegal_operation_on_empty_result_set"), + SQLError.SQL_STATE_GENERAL_ERROR); + } + + if (this.rowData.isBeforeFirst()) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Before_start_of_result_set_146"), + SQLError.SQL_STATE_GENERAL_ERROR); //$NON-NLS-1$ + } + + if (this.rowData.isAfterLast()) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.After_end_of_result_set_148"), + SQLError.SQL_STATE_GENERAL_ERROR); //$NON-NLS-1$ + } + } + + /** + * We can't do this ourselves, otherwise the contract for + * Statement.getMoreResults() won't work correctly. + */ + protected void clearNextResult() { + this.nextResultSet = null; + } + + /** + * After this call, getWarnings returns null until a new warning is reported + * for this ResultSet + * + * @exception SQLException + * if a database access error occurs + */ + public void clearWarnings() throws SQLException { + this.warningChain = null; + } + + /** + * In some cases, it is desirable to immediately release a ResultSet + * database and JDBC resources instead of waiting for this to happen when it + * is automatically closed. The close method provides this immediate + * release. + * + *

+ * Note: A ResultSet is automatically closed by the Statement the + * Statement that generated it when that Statement is closed, re-executed, + * or is used to retrieve the next result from a sequence of multiple + * results. A ResultSet is also automatically closed when it is garbage + * collected. + *

+ * + * @exception SQLException + * if a database access error occurs + */ + public void close() throws SQLException { + realClose(true); + } + + /** + * @return + */ + private int convertToZeroWithEmptyCheck() throws SQLException { + if (this.connection.getEmptyStringsConvertToZero()) { + return 0; + } + + throw SQLError.createSQLException("Can't convert empty string ('') to numeric", + SQLError.SQL_STATE_INVALID_CHARACTER_VALUE_FOR_CAST); + } + + private String convertToZeroLiteralStringWithEmptyCheck() + throws SQLException { + + if (this.connection.getEmptyStringsConvertToZero()) { + return "0"; + } + + throw SQLError.createSQLException("Can't convert empty string ('') to numeric", + SQLError.SQL_STATE_INVALID_CHARACTER_VALUE_FOR_CAST); + } + + // + // Note, row data is linked between these two result sets + // + protected final ResultSet copy() throws SQLException { + ResultSet rs = new ResultSet(this.catalog, this.fields, this.rowData, + this.connection, this.owningStatement); + + return rs; + } + + protected void redefineFieldsForDBMD(Field[] f) { + this.fields = f; + + for (int i = 0; i < this.fields.length; i++) { + this.fields[i].setUseOldNameMetadata(true); + this.fields[i].setConnection(this.connection); + } + } + + /** + * JDBC 2.0 Delete the current row from the result set and the underlying + * database. Cannot be called when on the insert row. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row. + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void deleteRow() throws SQLException { + throw new NotUpdatable(); + } + + /** + * @param columnIndex + * @param stringVal + * @param mysqlType + * @return + * @throws SQLException + */ + private String extractStringFromNativeColumn(int columnIndex, int mysqlType) + throws SQLException { + int columnIndexMinusOne = columnIndex - 1; + + this.wasNullFlag = false; + + if (this.thisRow[columnIndexMinusOne] instanceof String) { + return (String) this.thisRow[columnIndexMinusOne]; + } + + if (this.thisRow[columnIndexMinusOne] == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + String stringVal = null; + + if ((this.connection != null) && this.connection.getUseUnicode()) { + try { + String encoding = this.fields[columnIndexMinusOne] + .getCharacterSet(); + + if (encoding == null) { + stringVal = new String( + (byte[]) this.thisRow[columnIndexMinusOne]); + } else { + SingleByteCharsetConverter converter = this.connection + .getCharsetConverter(encoding); + + if (converter != null) { + stringVal = converter + .toString((byte[]) this.thisRow[columnIndexMinusOne]); + } else { + stringVal = new String( + (byte[]) this.thisRow[columnIndexMinusOne], + encoding); + } + } + } catch (java.io.UnsupportedEncodingException E) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Unsupported_character_encoding____138") //$NON-NLS-1$ + + this.connection.getEncoding() + "'.", "0S100"); + } + } else { + stringVal = StringUtils + .toAsciiString((byte[]) this.thisRow[columnIndexMinusOne]); + } + + return stringVal; + } + + private synchronized Date fastDateCreate(Calendar cal, int year, int month, + int day) { + if (cal == null) { + createCalendarIfNeeded(); + cal = this.fastDateCal; + } + + boolean useGmtMillis = this.connection.getUseGmtMillisForDatetimes(); + + return TimeUtil.fastDateCreate(useGmtMillis, + useGmtMillis ? getGmtCalendar() : null, + cal, year, month, day); + } + + private synchronized Time fastTimeCreate(Calendar cal, int hour, + int minute, int second) throws SQLException { + if (cal == null) { + createCalendarIfNeeded(); + cal = this.fastDateCal; + } + + return TimeUtil.fastTimeCreate(cal, hour, minute, second); + } + + private synchronized Timestamp fastTimestampCreate(Calendar cal, int year, + int month, int day, int hour, int minute, int seconds, + int secondsPart) { + if (cal == null) { + createCalendarIfNeeded(); + cal = this.fastDateCal; + } + + boolean useGmtMillis = this.connection.getUseGmtMillisForDatetimes(); + + return TimeUtil.fastTimestampCreate(useGmtMillis, + useGmtMillis ? getGmtCalendar() : null, + cal, year, month, day, hour, + minute, seconds, secondsPart); + } + + /* + /** + * Required by JDBC spec + */ + /* + protected void finalize() throws Throwable { + if (!this.isClosed) { + realClose(false); + } + } + */ + + // --------------------------JDBC 2.0----------------------------------- + // --------------------------------------------------------------------- + // Getter's and Setter's + // --------------------------------------------------------------------- + + + /** + * Map a ResultSet column name to a ResultSet column index + * + * @param columnName + * the name of the column + * + * @return the column index + * + * @exception SQLException + * if a database access error occurs + */ + public synchronized int findColumn(String columnName) throws SQLException { + Integer index; + + if (!this.hasBuiltIndexMapping) { + buildIndexMapping(); + } + + index = (Integer) this.columnNameToIndex.get(columnName); + + if (index == null) { + index = (Integer) this.fullColumnNameToIndex.get(columnName); + } + + if (index != null) { + return index.intValue() + 1; + } + + // Try this inefficient way, now + + for (int i = 0; i < this.fields.length; i++) { + if (this.fields[i].getName().equalsIgnoreCase(columnName)) { + return i + 1; + } else if (this.fields[i].getFullName() + .equalsIgnoreCase(columnName)) { + return i + 1; + } + } + + throw SQLError.createSQLException(Messages.getString("ResultSet.Column____112") + + columnName + + Messages.getString("ResultSet.___not_found._113"), //$NON-NLS-1$ //$NON-NLS-2$ + SQLError.SQL_STATE_COLUMN_NOT_FOUND); + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the first row in the result set. + *

+ * + * @return true if on a valid row, false if no rows in the result set. + * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY. + */ + public boolean first() throws SQLException { + checkClosed(); + + if (this.rowData.isEmpty()) { + return false; + } + + if (this.onInsertRow) { + this.onInsertRow = false; + } + + if (this.doingUpdates) { + this.doingUpdates = false; + } + + this.rowData.beforeFirst(); + this.thisRow = this.rowData.next(); + + return true; + } + + /** + * JDBC 2.0 Get an array column. + * + * @param i + * the first column is 1, the second is 2, ... + * + * @return an object representing an SQL array + * + * @throws SQLException + * if a database error occurs + * @throws NotImplemented + * DOCUMENT ME! + */ + public java.sql.Array getArray(int i) throws SQLException { + checkColumnBounds(i); + + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Get an array column. + * + * @param colName + * the column name + * + * @return an object representing an SQL array + * + * @throws SQLException + * if a database error occurs + * @throws NotImplemented + * DOCUMENT ME! + */ + public java.sql.Array getArray(String colName) throws SQLException { + return getArray(findColumn(colName)); + } + + /** + * A column value can be retrieved as a stream of ASCII characters and then + * read in chunks from the stream. This method is particulary suitable for + * retrieving large LONGVARCHAR values. The JDBC driver will do any + * necessary conversion from the database format into ASCII. + * + *

+ * Note: All the data in the returned stream must be read prior to + * getting the value of any other column. The next call to a get method + * implicitly closes the stream. Also, a stream may return 0 for available() + * whether there is data available or not. + *

+ * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return a Java InputStream that delivers the database column value as a + * stream of one byte ASCII characters. If the value is SQL NULL + * then the result is null + * + * @exception SQLException + * if a database access error occurs + * + * @see getBinaryStream + */ + public InputStream getAsciiStream(int columnIndex) throws SQLException { + checkRowPos(); + + if (!this.isBinaryEncoded) { + return getBinaryStream(columnIndex); + } + + return getNativeBinaryStream(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public InputStream getAsciiStream(String columnName) throws SQLException { + return getAsciiStream(findColumn(columnName)); + } + + /** + * JDBC 2.0 Get the value of a column in the current row as a + * java.math.BigDecimal object. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return the column value (full precision); if the value is SQL NULL, the + * result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + public BigDecimal getBigDecimal(int columnIndex) throws SQLException { + if (!this.isBinaryEncoded) { + String stringVal = getString(columnIndex); + BigDecimal val; + + if (stringVal != null) { + if (stringVal.length() == 0) { + + val = new BigDecimal( + convertToZeroLiteralStringWithEmptyCheck()); + + return val; + } + + try { + val = new BigDecimal(stringVal); + + return val; + } catch (NumberFormatException ex) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Bad_format_for_BigDecimal", + new Object[] { stringVal, + new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + return null; + } + + return getNativeBigDecimal(columnIndex); + } + + /** + * Get the value of a column in the current row as a java.math.BigDecimal + * object + * + * @param columnIndex + * the first column is 1, the second is 2... + * @param scale + * the number of digits to the right of the decimal + * + * @return the column value; if the value is SQL NULL, null + * + * @exception SQLException + * if a database access error occurs + * + * @deprecated + */ + public BigDecimal getBigDecimal(int columnIndex, int scale) + throws SQLException { + if (!this.isBinaryEncoded) { + String stringVal = getString(columnIndex); + BigDecimal val; + + if (stringVal != null) { + if (stringVal.length() == 0) { + val = new BigDecimal( + convertToZeroLiteralStringWithEmptyCheck()); + + try { + return val.setScale(scale); + } catch (ArithmeticException ex) { + try { + return val + .setScale(scale, BigDecimal.ROUND_HALF_UP); + } catch (ArithmeticException arEx) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Bad_format_for_BigDecimal____124") //$NON-NLS-1$ + + stringVal + + Messages + .getString("ResultSet.___in_column__125") + + columnIndex + + "(" //$NON-NLS-1$ + + this.fields[columnIndex - 1] + + ").", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + + try { + val = new BigDecimal(stringVal); + } catch (NumberFormatException ex) { + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex); + + val = new BigDecimal(valueAsLong); + } else { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Bad_format_for_BigDecimal", + new Object[] { new Integer(columnIndex), + stringVal }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + try { + return val.setScale(scale); + } catch (ArithmeticException ex) { + try { + return val.setScale(scale, BigDecimal.ROUND_HALF_UP); + } catch (ArithmeticException arithEx) { + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_BigDecimal", + new Object[] { new Integer(columnIndex), + stringVal }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + } + + return null; + } + + return getNativeBigDecimal(columnIndex, scale); + } + + /** + * JDBC 2.0 Get the value of a column in the current row as a + * java.math.BigDecimal object. + * + * @param columnName + * the name of the column to retrieve the value from + * + * @return the BigDecimal value in the column + * + * @throws SQLException + * if an error occurs + */ + public BigDecimal getBigDecimal(String columnName) throws SQLException { + return getBigDecimal(findColumn(columnName)); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * @param scale + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + * + * @deprecated + */ + public BigDecimal getBigDecimal(String columnName, int scale) + throws SQLException { + return getBigDecimal(findColumn(columnName), scale); + } + + private final BigDecimal getBigDecimalFromString(String stringVal, + int columnIndex, int scale) throws SQLException { + BigDecimal bdVal; + + if (stringVal != null) { + if (stringVal.length() == 0) { + bdVal = new BigDecimal(convertToZeroLiteralStringWithEmptyCheck()); + + try { + return bdVal.setScale(scale); + } catch (ArithmeticException ex) { + try { + return bdVal.setScale(scale, BigDecimal.ROUND_HALF_UP); + } catch (ArithmeticException arEx) { + throw new SQLException(Messages + .getString("ResultSet.Bad_format_for_BigDecimal", + new Object[] { stringVal, + new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + } + + try { + try { + return new BigDecimal(stringVal).setScale(scale); + } catch (ArithmeticException ex) { + try { + return new BigDecimal(stringVal).setScale(scale, + BigDecimal.ROUND_HALF_UP); + } catch (ArithmeticException arEx) { + throw new SQLException(Messages + .getString("ResultSet.Bad_format_for_BigDecimal", + new Object[] { stringVal, + new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + } catch (NumberFormatException ex) { + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex); + + try { + return new BigDecimal(valueAsLong).setScale(scale); + } catch (ArithmeticException arEx1) { + try { + return new BigDecimal(valueAsLong).setScale(scale, + BigDecimal.ROUND_HALF_UP); + } catch (ArithmeticException arEx2) { + throw new SQLException(Messages + .getString("ResultSet.Bad_format_for_BigDecimal", + new Object[] { stringVal, + new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + } + + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_TINY && + this.connection.getTinyInt1isBit() && this.fields[columnIndex - 1].getLength() == 1) { + return new BigDecimal(stringVal.equalsIgnoreCase("true") ? 1 : 0).setScale(scale); + } + + throw new SQLException(Messages + .getString("ResultSet.Bad_format_for_BigDecimal", + new Object[] { stringVal, + new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + return null; + } + + /** + * A column value can also be retrieved as a binary stream. This method is + * suitable for retrieving LONGVARBINARY values. + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return a Java InputStream that delivers the database column value as a + * stream of bytes. If the value is SQL NULL, then the result is + * null + * + * @exception SQLException + * if a database access error occurs + * + * @see getAsciiStream + * @see getUnicodeStream + */ + public InputStream getBinaryStream(int columnIndex) throws SQLException { + checkRowPos(); + + if (!this.isBinaryEncoded) { + byte[] b = getBytes(columnIndex); + + if (b != null) { + return new ByteArrayInputStream(b); + } + + return null; + } + + return getNativeBinaryStream(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public InputStream getBinaryStream(String columnName) throws SQLException { + return getBinaryStream(findColumn(columnName)); + } + + /** + * JDBC 2.0 Get a BLOB column. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return an object representing a BLOB + * + * @throws SQLException + * if an error occurs. + */ + public java.sql.Blob getBlob(int columnIndex) throws SQLException { + if (!this.isBinaryEncoded) { + checkRowPos(); + + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return null; + } + + if (!this.connection.getEmulateLocators()) { + return new Blob((byte[]) this.thisRow[columnIndex - 1]); + } + + return new BlobFromLocator(this, columnIndex); + } + + return getNativeBlob(columnIndex); + } + + /** + * JDBC 2.0 Get a BLOB column. + * + * @param colName + * the column name + * + * @return an object representing a BLOB + * + * @throws SQLException + * if an error occurs. + */ + public java.sql.Blob getBlob(String colName) throws SQLException { + return getBlob(findColumn(colName)); + } + + /** + * Get the value of a column in the current row as a Java boolean + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return the column value, false for SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public boolean getBoolean(int columnIndex) throws SQLException { + + checkColumnBounds(columnIndex); + + // + // MySQL 5.0 and newer have an actual BIT type, + // so we need to check for that here... + // + + int columnIndexMinusOne = columnIndex - 1; + + Field field = this.fields[columnIndexMinusOne]; + + if (field.getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + return byteArrayToBoolean(columnIndexMinusOne); + } + + this.wasNullFlag = false; + + int sqlType = field.getSQLType(); + + switch (sqlType) { + case Types.BIT: + case Types.BOOLEAN: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.DECIMAL: + case Types.NUMERIC: + case Types.REAL: + case Types.FLOAT: + case Types.DOUBLE: + long boolVal = getLong(columnIndex, false); + + return (boolVal == -1 || boolVal > 0); + default: + if (this.connection.getPedantic()) { + // Table B-6 from JDBC spec + switch (sqlType) { + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + case Types.DATE: + case Types.TIME: + case Types.TIMESTAMP: + case Types.CLOB: + case Types.BLOB: + case Types.ARRAY: + case Types.REF: + case Types.DATALINK: + case Types.STRUCT: + case Types.JAVA_OBJECT: + throw SQLError.createSQLException("Required type conversion not allowed", + SQLError.SQL_STATE_INVALID_CHARACTER_VALUE_FOR_CAST); + } + } + + if (sqlType == Types.BINARY || + sqlType == Types.VARBINARY || + sqlType == Types.LONGVARBINARY || + sqlType == Types.BLOB) { + return byteArrayToBoolean(columnIndexMinusOne); + } + + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getBoolean()", columnIndex, + this.thisRow[columnIndex], this.fields[columnIndex], + new int[] { + MysqlDefs.FIELD_TYPE_BIT, + MysqlDefs.FIELD_TYPE_DOUBLE, + MysqlDefs.FIELD_TYPE_TINY, + MysqlDefs.FIELD_TYPE_SHORT, + MysqlDefs.FIELD_TYPE_LONG, + MysqlDefs.FIELD_TYPE_LONGLONG, + MysqlDefs.FIELD_TYPE_FLOAT }); + } + + String stringVal = getString(columnIndex); + + return getBooleanFromString(stringVal, columnIndex); + } + } + + private boolean byteArrayToBoolean(int columnIndexMinusOne) { + if (this.thisRow[columnIndexMinusOne] == null) { + this.wasNullFlag = true; + + return false; + } + + this.wasNullFlag = false; + + if (((byte[]) this.thisRow[columnIndexMinusOne]).length == 0) { + return false; + } + + byte boolVal = ((byte[]) this.thisRow[columnIndexMinusOne])[0]; + + return (boolVal == -1 || boolVal > 0); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public boolean getBoolean(String columnName) throws SQLException { + return getBoolean(findColumn(columnName)); + } + + private final boolean getBooleanFromString(String stringVal, int columnIndex) + throws SQLException { + if ((stringVal != null) && (stringVal.length() > 0)) { + int c = Character.toLowerCase(stringVal.charAt(0)); + + return ((c == 't') || (c == 'y') || (c == '1') || stringVal + .equals("-1")); + } + + return false; + } + + /** + * Get the value of a column in the current row as a Java byte. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public byte getByte(int columnIndex) throws SQLException { + if (!this.isBinaryEncoded) { + String stringVal = getString(columnIndex); + + if (this.wasNullFlag || (stringVal == null)) { + return 0; + } + + return getByteFromString(stringVal, columnIndex); + } + + return getNativeByte(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public byte getByte(String columnName) throws SQLException { + return getByte(findColumn(columnName)); + } + + private final byte getByteFromString(String stringVal, int columnIndex) + throws SQLException { + + if (stringVal != null && stringVal.length() == 0) { + return (byte) convertToZeroWithEmptyCheck(); + } + + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + stringVal = stringVal.trim(); + + try { + int decimalIndex = stringVal.indexOf("."); + + + if (decimalIndex != -1) { + double valueAsDouble = Double.parseDouble(stringVal); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Byte.MIN_VALUE + || valueAsDouble > Byte.MAX_VALUE) { + throwRangeException(stringVal, columnIndex, + Types.TINYINT); + } + } + + return (byte) valueAsDouble; + } + + long valueAsLong = Long.parseLong(stringVal); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsLong < Byte.MIN_VALUE + || valueAsLong > Byte.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsLong), + columnIndex, Types.TINYINT); + } + } + + return (byte) valueAsLong; + } catch (NumberFormatException NFE) { + throw SQLError.createSQLException( + Messages.getString("ResultSet.Value____173") + + stringVal //$NON-NLS-1$ + + Messages + .getString("ResultSet.___is_out_of_range_[-127,127]_174"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * Get the value of a column in the current row as a Java byte array. + * + *

+ * Be warned If the blob is huge, then you may run out of memory. + *

+ * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database access error occurs + */ + public byte[] getBytes(int columnIndex) throws SQLException { + return getBytes(columnIndex, false); + } + + protected byte[] getBytes(int columnIndex, boolean noConversion) + throws SQLException { + if (!this.isBinaryEncoded) { + checkRowPos(); + + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return null; + } + + return (byte[]) this.thisRow[columnIndex - 1]; + } + + return getNativeBytes(columnIndex, noConversion); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public byte[] getBytes(String columnName) throws SQLException { + return getBytes(findColumn(columnName)); + } + + private final byte[] getBytesFromString(String stringVal, int columnIndex) + throws SQLException { + if (stringVal != null) { + return StringUtils.getBytes(stringVal, this.connection + .getEncoding(), this.connection + .getServerCharacterEncoding(), this.connection + .parserKnowsUnicode(), + this.connection); + } + + return null; + } + + /** + * Optimization to only use one calendar per-session, or calculate it for + * each call, depending on user configuration + */ + private Calendar getCalendarInstanceForSessionOrNew() { + if (this.connection != null) { + return this.connection.getCalendarInstanceForSessionOrNew(); + } else { + // punt, no connection around + return new GregorianCalendar(); + } + } + + /** + * JDBC 2.0 + * + *

+ * Get the value of a column in the current row as a java.io.Reader. + *

+ * + * @param columnIndex + * the column to get the value from + * + * @return the value in the column as a java.io.Reader. + * + * @throws SQLException + * if an error occurs + */ + public java.io.Reader getCharacterStream(int columnIndex) + throws SQLException { + if (!this.isBinaryEncoded) { + String asString = getStringForClob(columnIndex); + + if (asString == null) { + return null; + } + + return new StringReader(asString); + } + + return getNativeCharacterStream(columnIndex); + } + + /** + * JDBC 2.0 + * + *

+ * Get the value of a column in the current row as a java.io.Reader. + *

+ * + * @param columnName + * the column name to retrieve the value from + * + * @return the value as a java.io.Reader + * + * @throws SQLException + * if an error occurs + */ + public java.io.Reader getCharacterStream(String columnName) + throws SQLException { + return getCharacterStream(findColumn(columnName)); + } + + private final java.io.Reader getCharacterStreamFromString(String stringVal, + int columnIndex) throws SQLException { + if (stringVal != null) { + return new StringReader(stringVal); + } + + return null; + } + + /** + * JDBC 2.0 Get a CLOB column. + * + * @param i + * the first column is 1, the second is 2, ... + * + * @return an object representing a CLOB + * + * @throws SQLException + * if an error occurs + */ + public java.sql.Clob getClob(int i) throws SQLException { + if (!this.isBinaryEncoded) { + String asString = getStringForClob(i); + + if (asString == null) { + return null; + } + + return new com.mysql.jdbc.Clob(asString); + } + + return getNativeClob(i); + } + + /** + * JDBC 2.0 Get a CLOB column. + * + * @param colName + * the column name + * + * @return an object representing a CLOB + * + * @throws SQLException + * if an error occurs + */ + public java.sql.Clob getClob(String colName) throws SQLException { + return getClob(findColumn(colName)); + } + + private final java.sql.Clob getClobFromString(String stringVal, + int columnIndex) throws SQLException { + return new com.mysql.jdbc.Clob(stringVal); + } + + /** + * JDBC 2.0 Return the concurrency of this result set. The concurrency used + * is determined by the statement that created the result set. + * + * @return the concurrency type, CONCUR_READ_ONLY, etc. + * + * @throws SQLException + * if a database-access error occurs + */ + public int getConcurrency() throws SQLException { + return (CONCUR_READ_ONLY); + } + + /** + * Get the name of the SQL cursor used by this ResultSet + * + *

+ * In SQL, a result table is retrieved though a cursor that is named. The + * current row of a result can be updated or deleted using a positioned + * update/delete statement that references the cursor name. + *

+ * + *

+ * JDBC supports this SQL feature by providing the name of the SQL cursor + * used by a ResultSet. The current row of a ResulSet is also the current + * row of this SQL cursor. + *

+ * + *

+ * Note: If positioned update is not supported, a SQLException is + * thrown. + *

+ * + * @return the ResultSet's SQL cursor name. + * + * @exception SQLException + * if a database access error occurs + */ + public String getCursorName() throws SQLException { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Positioned_Update_not_supported"), + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); //$NON-NLS-1$ + } + + /** + * Get the value of a column in the current row as a java.sql.Date object + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return the column value; null if SQL NULL + * + * @exception java.sql.SQLException + * if a database access error occurs + */ + public java.sql.Date getDate(int columnIndex) throws java.sql.SQLException { + return getDate(columnIndex, null); + } + + /** + * JDBC 2.0 Get the value of a column in the current row as a java.sql.Date + * object. Use the calendar to construct an appropriate millisecond value + * for the Date, if the underlying database doesn't store timezone + * information. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param cal + * the calendar to use in constructing the date + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.Date getDate(int columnIndex, Calendar cal) + throws SQLException { + if (this.isBinaryEncoded) { + return getNativeDate(columnIndex, (cal != null) ? cal.getTimeZone() + : this.getDefaultTimeZone()); + } + + if (!this.useFastDateParsing) { + String stringVal = getStringInternal(columnIndex, false); + + if (stringVal == null) { + return null; + } + + return getDateFromString(stringVal, columnIndex); + } else { + checkColumnBounds(columnIndex); + + return getDateFromBytes(((byte[][])this.thisRow)[columnIndex - 1], columnIndex); + } + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws java.sql.SQLException + * DOCUMENT ME! + */ + public java.sql.Date getDate(String columnName) + throws java.sql.SQLException { + return getDate(findColumn(columnName)); + } + + /** + * Get the value of a column in the current row as a java.sql.Date object. + * Use the calendar to construct an appropriate millisecond value for the + * Date, if the underlying database doesn't store timezone information. + * + * @param columnName + * is the SQL name of the column + * @param cal + * the calendar to use in constructing the date + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.Date getDate(String columnName, Calendar cal) + throws SQLException { + return getDate(findColumn(columnName), cal); + } + + private final java.sql.Date getDateFromString(String stringVal, + int columnIndex) throws SQLException { + int year = 0; + int month = 0; + int day = 0; + + try { + this.wasNullFlag = false; + + if (stringVal == null) { + this.wasNullFlag = true; + + return null; + } + + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + stringVal = stringVal.trim(); + + if (stringVal.equals("0") || stringVal.equals("0000-00-00") + || stringVal.equals("0000-00-00 00:00:00") + || stringVal.equals("00000000000000") + || stringVal.equals("0")) { + + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '" + stringVal + + "' can not be represented as java.sql.Date", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + // We're left with the case of 'round' to a date Java _can_ + // represent, which is '0001-01-01'. + return fastDateCreate(null, 1, 1, 1); + + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) { + // Convert from TIMESTAMP + switch (stringVal.length()) { + case 21: + case 19: { // java.sql.Timestamp format + year = Integer.parseInt(stringVal.substring(0, 4)); + month = Integer.parseInt(stringVal.substring(5, 7)); + day = Integer.parseInt(stringVal.substring(8, 10)); + + return fastDateCreate(null, year, month, day); + } + + case 14: + case 8: { + year = Integer.parseInt(stringVal.substring(0, 4)); + month = Integer.parseInt(stringVal.substring(4, 6)); + day = Integer.parseInt(stringVal.substring(6, 8)); + + return fastDateCreate(null, year, month, day); + } + + case 12: + case 10: + case 6: { + year = Integer.parseInt(stringVal.substring(0, 2)); + + if (year <= 69) { + year = year + 100; + } + + month = Integer.parseInt(stringVal.substring(2, 4)); + day = Integer.parseInt(stringVal.substring(4, 6)); + + return fastDateCreate(null, year + 1900, month, day); + } + + case 4: { + year = Integer.parseInt(stringVal.substring(0, 4)); + + if (year <= 69) { + year = year + 100; + } + + month = Integer.parseInt(stringVal.substring(2, 4)); + + return fastDateCreate(null, year + 1900, month, 1); + } + + case 2: { + year = Integer.parseInt(stringVal.substring(0, 2)); + + if (year <= 69) { + year = year + 100; + } + + return fastDateCreate(null, year + 1900, 1, 1); + } + + default: + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_Date", new Object[] { + stringVal, new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } /* endswitch */ + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) { + + if (stringVal.length() == 2 || stringVal.length() == 1) { + year = Integer.parseInt(stringVal); + + if (year <= 69) { + year = year + 100; + } + + year += 1900; + } else { + year = Integer.parseInt(stringVal.substring(0, 4)); + } + + return fastDateCreate(null, year, 1, 1); + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_TIME) { + return fastDateCreate(null, 1970, 1, 1); // Return EPOCH + } else { + if (stringVal.length() < 10) { + if (stringVal.length() == 8) { + return fastDateCreate(null, 1970, 1, 1); // Return EPOCH for TIME + } + + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_Date", new Object[] { + stringVal, new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + if (stringVal.length() != 18) { + year = Integer.parseInt(stringVal.substring(0, 4)); + month = Integer.parseInt(stringVal.substring(5, 7)); + day = Integer.parseInt(stringVal.substring(8, 10)); + } else { + // JDK-1.3 timestamp format, not real easy to parse positionally :p + StringTokenizer st = new StringTokenizer(stringVal, "- "); + + year = Integer.parseInt(st.nextToken()); + month = Integer.parseInt(st.nextToken()); + day = Integer.parseInt(st.nextToken()); + } + } + + return fastDateCreate(null, year, month, day); + } catch (SQLException sqlEx) { + throw sqlEx; // don't re-wrap + } catch (Exception e) { + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_Date", new Object[] { stringVal, + new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + private final java.sql.Date getDateFromBytes(byte[] dateAsBytes, + int columnIndex) throws SQLException { + checkColumnBounds(columnIndex); + + int year = 0; + int month = 0; + int day = 0; + + try { + this.wasNullFlag = false; + + if (dateAsBytes == null) { + this.wasNullFlag = true; + + return null; + } + + + boolean allZeroDate = true; + + boolean onlyTimePresent = StringUtils.indexOf(dateAsBytes, ':') != -1; + + int length = dateAsBytes.length; + + for (int i = 0; i < length; i++) { + byte b = dateAsBytes[i]; + + if (b == ' ' || b == '-' || b == '/') { + onlyTimePresent = false; + } + + if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' + && b != '.') { + allZeroDate = false; + + break; + } + } + + if (!onlyTimePresent && allZeroDate) { + + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '" + new String(dateAsBytes) + + "' can not be represented as java.sql.Date", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + // We're left with the case of 'round' to a date Java _can_ + // represent, which is '0001-01-01'. + return fastDateCreate(null, 1, 1, 1); + + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) { + // Convert from TIMESTAMP + switch (length) { + case 21: + case 19: { // java.sql.Timestamp format + year = StringUtils.getInt(dateAsBytes, 0, 4); + month = StringUtils.getInt(dateAsBytes, 5, 7); + day = StringUtils.getInt(dateAsBytes, 8, 10); + + return fastDateCreate(null, year, month, day); + } + + case 14: + case 8: { + year = StringUtils.getInt(dateAsBytes, 0, 4); + month = StringUtils.getInt(dateAsBytes, 4, 6); + day = StringUtils.getInt(dateAsBytes, 6, 8); + + return fastDateCreate(null, year, month, day); + } + + case 12: + case 10: + case 6: { + year = StringUtils.getInt(dateAsBytes, 0, 2); + + if (year <= 69) { + year = year + 100; + } + + month = StringUtils.getInt(dateAsBytes, 2, 4); + day = StringUtils.getInt(dateAsBytes, 4, 6); + + return fastDateCreate(null, year + 1900, month, day); + } + + case 4: { + year = StringUtils.getInt(dateAsBytes, 0, 4); + + if (year <= 69) { + year = year + 100; + } + + month = StringUtils.getInt(dateAsBytes, 2, 4); + + return fastDateCreate(null, year + 1900, month, 1); + } + + case 2: { + year = StringUtils.getInt(dateAsBytes, 0, 2); + + if (year <= 69) { + year = year + 100; + } + + return fastDateCreate(null, year + 1900, 1, 1); + } + + default: + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_Date", new Object[] { + new String(dateAsBytes), new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } /* endswitch */ + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) { + + if (length == 2 || length == 1) { + year = StringUtils.getInt(dateAsBytes); + + if (year <= 69) { + year = year + 100; + } + + year += 1900; + } else { + year = StringUtils.getInt(dateAsBytes, 0, 4); + } + + return fastDateCreate(null, year, 1, 1); + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_TIME) { + return fastDateCreate(null, 1970, 1, 1); // Return EPOCH + } else { + if (length < 10) { + if (length == 8) { + return fastDateCreate(null, 1970, 1, 1); // Return EPOCH for TIME + } + + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_Date", new Object[] { + new String(dateAsBytes), new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + if (length != 18) { + year = StringUtils.getInt(dateAsBytes, 0, 4); + month = StringUtils.getInt(dateAsBytes, 5, 7); + day = StringUtils.getInt(dateAsBytes, 8, 10); + } else { + // JDK-1.3 timestamp format, not real easy to parse positionally :p + StringTokenizer st = new StringTokenizer(new String(dateAsBytes), "- "); + + year = Integer.parseInt(st.nextToken()); + month = Integer.parseInt(st.nextToken()); + day = Integer.parseInt(st.nextToken()); + } + } + + return fastDateCreate(null, year, month, day); + } catch (SQLException sqlEx) { + throw sqlEx; // don't re-wrap + } catch (Exception e) { + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_Date", new Object[] { new String(dateAsBytes), + new Integer(columnIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + private TimeZone getDefaultTimeZone() { + return this.connection.getDefaultTimeZone(); + } + + /** + * Get the value of a column in the current row as a Java double. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public double getDouble(int columnIndex) throws SQLException { + if (!this.isBinaryEncoded) { + return getDoubleInternal(columnIndex); + } + + return getNativeDouble(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public double getDouble(String columnName) throws SQLException { + return getDouble(findColumn(columnName)); + } + + private final double getDoubleFromString(String stringVal, int columnIndex) + throws SQLException { + return getDoubleInternal(stringVal, columnIndex); + } + + /** + * Converts a string representation of a number to a double. Need a faster + * way to do this. + * + * @param colIndex + * the 1-based index of the column to retrieve a double from. + * + * @return the double value represented by the string in buf + * + * @throws SQLException + * if an error occurs + */ + protected double getDoubleInternal(int colIndex) throws SQLException { + return getDoubleInternal(getString(colIndex), colIndex); + } + + /** + * Converts a string representation of a number to a double. Need a faster + * way to do this. + * + * @param stringVal + * the double as a String + * @param colIndex + * the 1-based index of the column to retrieve a double from. + * + * @return the double value represented by the string in buf + * + * @throws SQLException + * if an error occurs + */ + protected double getDoubleInternal(String stringVal, int colIndex) + throws SQLException { + try { + if ((stringVal == null)) { + return 0; + } + + if (stringVal.length() == 0) { + return convertToZeroWithEmptyCheck(); + } + + double d = Double.parseDouble(stringVal); + + if (this.useStrictFloatingPoint) { + // Fix endpoint rounding precision loss in MySQL server + if (d == 2.147483648E9) { + // Fix Odd end-point rounding on MySQL + d = 2.147483647E9; + } else if (d == 1.0000000036275E-15) { + // Fix odd end-point rounding on MySQL + d = 1.0E-15; + } else if (d == 9.999999869911E14) { + d = 9.99999999999999E14; + } else if (d == 1.4012984643248E-45) { + d = 1.4E-45; + } else if (d == 1.4013E-45) { + d = 1.4E-45; + } else if (d == 3.4028234663853E37) { + d = 3.4028235E37; + } else if (d == -2.14748E9) { + d = -2.147483648E9; + } else if (d == 3.40282E37) { + d = 3.4028235E37; + } + } + + return d; + } catch (NumberFormatException e) { + if (this.fields[colIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + long valueAsLong = getNumericRepresentationOfSQLBitType(colIndex); + + return valueAsLong; + } + + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_number", new Object[] { + stringVal, new Integer(colIndex) }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + /** + * JDBC 2.0 Returns the fetch direction for this result set. + * + * @return the fetch direction for this result set. + * + * @exception SQLException + * if a database-access error occurs + */ + public int getFetchDirection() throws SQLException { + return this.fetchDirection; + } + + /** + * JDBC 2.0 Return the fetch size for this result set. + * + * @return the fetch size for this result set. + * + * @exception SQLException + * if a database-access error occurs + */ + public int getFetchSize() throws SQLException { + return this.fetchSize; + } + + /** + * Returns the first character of the query that this result set was created + * from. + * + * @return the first character of the query...uppercased + */ + protected char getFirstCharOfQuery() { + return this.firstCharOfQuery; + } + + /** + * Get the value of a column in the current row as a Java float. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public float getFloat(int columnIndex) throws SQLException { + if (!this.isBinaryEncoded) { + String val = null; + + val = getString(columnIndex); + + return getFloatFromString(val, columnIndex); + } + + return getNativeFloat(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public float getFloat(String columnName) throws SQLException { + return getFloat(findColumn(columnName)); + } + + private final float getFloatFromString(String val, int columnIndex) + throws SQLException { + try { + if ((val != null)) { + if (val.length() == 0) { + return convertToZeroWithEmptyCheck(); + } + + float f = Float.parseFloat(val); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (f == Float.MIN_VALUE || f == Float.MAX_VALUE) { + double valAsDouble = Double.parseDouble(val); + + // Straight comparison is not reliable when at + // absolute endpoints of Float.MIN_VALUE or + // Float.MAX_VALUE, so use epsillons with DOUBLEs + + if ((valAsDouble < Float.MIN_VALUE - MIN_DIFF_PREC) + || (valAsDouble > Float.MAX_VALUE - MAX_DIFF_PREC)) { + throwRangeException(String.valueOf(valAsDouble), columnIndex, + Types.FLOAT); + } + } + } + + return f; + } + + return 0; // for NULL + } catch (NumberFormatException nfe) { + try { + Double valueAsDouble = new Double(val); + float valueAsFloat = valueAsDouble.floatValue(); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + + if (this.connection.getJdbcCompliantTruncationForReads() && + valueAsFloat == Float.NEGATIVE_INFINITY || + valueAsFloat == Float.POSITIVE_INFINITY) { + throwRangeException(valueAsDouble.toString(), + columnIndex, Types.FLOAT); + } + } + + return valueAsFloat; + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getFloat()_-____200") + + val //$NON-NLS-1$ + + Messages.getString("ResultSet.___in_column__201") + + columnIndex, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * Get the value of a column in the current row as a Java int. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public int getInt(int columnIndex) throws SQLException { + checkRowPos(); + + if (!this.isBinaryEncoded) { + if (this.connection.getUseFastIntParsing()) { + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return 0; + } + + byte[] intAsBytes = (byte[]) this.thisRow[columnIndex - 1]; + + if (intAsBytes.length == 0) { + return convertToZeroWithEmptyCheck(); + } + + boolean needsFullParse = false; + + for (int i = 0; i < intAsBytes.length; i++) { + if (((char) intAsBytes[i] == 'e') + || ((char) intAsBytes[i] == 'E')) { + needsFullParse = true; + + break; + } + } + + if (!needsFullParse) { + try { + return parseIntWithOverflowCheck(columnIndex, + intAsBytes, null); + } catch (NumberFormatException nfe) { + try { + + return parseIntAsDouble(columnIndex, new String( + intAsBytes)); + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex); + + if (this.connection.getJdbcCompliantTruncationForReads() && + (valueAsLong < Integer.MIN_VALUE + || valueAsLong > Integer.MAX_VALUE)) { + throwRangeException(String.valueOf(valueAsLong), columnIndex, + Types.INTEGER); + } + + return (int)valueAsLong; + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getInt()_-____74") + + new String(intAsBytes) //$NON-NLS-1$ + + "'", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + + String val = null; + + try { + val = getString(columnIndex); + + if ((val != null)) { + if (val.length() == 0) { + return convertToZeroWithEmptyCheck(); + } + + if ((val.indexOf("e") == -1) && (val.indexOf("E") == -1) + && (val.indexOf(".") == -1)) { + return Integer.parseInt(val); + } + + // Convert floating point + return parseIntAsDouble(columnIndex, val); + } + + return 0; + } catch (NumberFormatException nfe) { + try { + return parseIntAsDouble(columnIndex, val); + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex); + + if (this.connection.getJdbcCompliantTruncationForReads() && + (valueAsLong < Integer.MIN_VALUE + || valueAsLong > Integer.MAX_VALUE)) { + throwRangeException(String.valueOf(valueAsLong), columnIndex, + Types.INTEGER); + } + + return (int)valueAsLong; + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getInt()_-____74") + + val //$NON-NLS-1$ + + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + return getNativeInt(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public int getInt(String columnName) throws SQLException { + return getInt(findColumn(columnName)); + } + + private final int getIntFromString(String val, int columnIndex) + throws SQLException { + try { + if ((val != null)) { + + if (val.length() == 0) { + return convertToZeroWithEmptyCheck(); + } + + if ((val.indexOf("e") == -1) && (val.indexOf("E") == -1) + && (val.indexOf(".") == -1)) { + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + val = val.trim(); + + int valueAsInt = Integer.parseInt(val); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsInt == Integer.MIN_VALUE + || valueAsInt == Integer.MAX_VALUE) { + long valueAsLong = Long.parseLong(val); + + if (valueAsLong < Integer.MIN_VALUE + || valueAsLong > Integer.MAX_VALUE) { + throwRangeException( + String.valueOf(valueAsLong), + columnIndex, Types.INTEGER); + } + } + } + + return valueAsInt; + } + + // Convert floating point + + double valueAsDouble = Double.parseDouble(val); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Integer.MIN_VALUE + || valueAsDouble > Integer.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex, Types.INTEGER); + } + } + + return (int) valueAsDouble; + } + + return 0; // for NULL + } catch (NumberFormatException nfe) { + try { + double valueAsDouble = Double.parseDouble(val); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Integer.MIN_VALUE + || valueAsDouble > Integer.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex, Types.INTEGER); + } + } + + return (int) valueAsDouble; + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + throw SQLError.createSQLException(Messages + .getString("ResultSet.Invalid_value_for_getInt()_-____206") + + val //$NON-NLS-1$ + + Messages.getString("ResultSet.___in_column__207") + + columnIndex, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * Get the value of a column in the current row as a Java long. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public long getLong(int columnIndex) throws SQLException { + return getLong(columnIndex, true); + } + + private long getLong(int columnIndex, boolean overflowCheck) throws SQLException { + if (!this.isBinaryEncoded) { + checkRowPos(); + + if (this.connection.getUseFastIntParsing()) { + + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return 0; + } + + byte[] longAsBytes = (byte[]) this.thisRow[columnIndex - 1]; + + if (longAsBytes.length == 0) { + return convertToZeroWithEmptyCheck(); + } + + boolean needsFullParse = false; + + for (int i = 0; i < longAsBytes.length; i++) { + if (((char) longAsBytes[i] == 'e') + || ((char) longAsBytes[i] == 'E')) { + needsFullParse = true; + + break; + } + } + + if (!needsFullParse) { + try { + return parseLongWithOverflowCheck(columnIndex, + longAsBytes, null, overflowCheck); + } catch (NumberFormatException nfe) { + try { + // To do: Warn of over/underflow??? + return parseLongAsDouble(columnIndex, new String( + longAsBytes)); + } catch (NumberFormatException newNfe) { + // ; // ignore, it's not a number + } + + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + return getNumericRepresentationOfSQLBitType(columnIndex); + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getLong()_-____79") + + new String(longAsBytes) //$NON-NLS-1$ + + "'", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + + String val = null; + + try { + val = getString(columnIndex); + + if ((val != null)) { + if (val.length() == 0) { + return convertToZeroWithEmptyCheck(); + } + + if ((val.indexOf("e") == -1) && (val.indexOf("E") == -1)) { + return parseLongWithOverflowCheck(columnIndex, null, + val, overflowCheck); + } + + // Convert floating point + return parseLongAsDouble(columnIndex, val); + } + + return 0; // for NULL + } catch (NumberFormatException nfe) { + try { + return parseLongAsDouble(columnIndex, val); + } catch (NumberFormatException newNfe) { + // ; // ignore, it's not a number + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getLong()_-____79") + + val //$NON-NLS-1$ + + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + return getNativeLong(columnIndex, overflowCheck, true); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public long getLong(String columnName) throws SQLException { + return getLong(findColumn(columnName)); + } + + private final long getLongFromString(String val, int columnIndex) + throws SQLException { + try { + if ((val != null)) { + + if (val.length() == 0) { + return convertToZeroWithEmptyCheck(); + } + + if ((val.indexOf("e") == -1) && (val.indexOf("E") == -1)) { + return parseLongWithOverflowCheck(columnIndex, null, val, true); + } + + // Convert floating point + return parseLongAsDouble(columnIndex, val); + } + + return 0; // for NULL + } catch (NumberFormatException nfe) { + try { + // To do: Warn of over/underflow??? + return parseLongAsDouble(columnIndex, val); + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getLong()_-____211") + + val //$NON-NLS-1$ + + Messages.getString("ResultSet.___in_column__212") + + columnIndex, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * The numbers, types and properties of a ResultSet's columns are provided + * by the getMetaData method + * + * @return a description of the ResultSet's columns + * + * @exception SQLException + * if a database access error occurs + */ + public java.sql.ResultSetMetaData getMetaData() throws SQLException { + checkClosed(); + + return new com.mysql.jdbc.ResultSetMetaData(this.fields, + this.connection.getUseOldAliasMetadataBehavior()); + } + + /** + * JDBC 2.0 Get an array column. + * + * @param i + * the first column is 1, the second is 2, ... + * + * @return an object representing an SQL array + * + * @throws SQLException + * if a database error occurs + * @throws NotImplemented + * DOCUMENT ME! + */ + protected java.sql.Array getNativeArray(int i) throws SQLException { + throw new NotImplemented(); + } + + /** + * A column value can be retrieved as a stream of ASCII characters and then + * read in chunks from the stream. This method is particulary suitable for + * retrieving large LONGVARCHAR values. The JDBC driver will do any + * necessary conversion from the database format into ASCII. + * + *

+ * Note: All the data in the returned stream must be read prior to + * getting the value of any other column. The next call to a get method + * implicitly closes the stream. Also, a stream may return 0 for available() + * whether there is data available or not. + *

+ * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return a Java InputStream that delivers the database column value as a + * stream of one byte ASCII characters. If the value is SQL NULL + * then the result is null + * + * @exception SQLException + * if a database access error occurs + * + * @see getBinaryStream + */ + protected InputStream getNativeAsciiStream(int columnIndex) + throws SQLException { + checkRowPos(); + + return getNativeBinaryStream(columnIndex); + } + + /** + * JDBC 2.0 Get the value of a column in the current row as a + * java.math.BigDecimal object. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return the column value (full precision); if the value is SQL NULL, the + * result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + protected BigDecimal getNativeBigDecimal(int columnIndex) + throws SQLException { + + checkColumnBounds(columnIndex); + + int scale = this.fields[columnIndex - 1].getDecimals(); + + return getNativeBigDecimal(columnIndex, scale); + } + + /** + * Get the value of a column in the current row as a java.math.BigDecimal + * object + * + * @param columnIndex + * the first column is 1, the second is 2... + * @param scale + * the number of digits to the right of the decimal + * + * @return the column value; if the value is SQL NULL, null + * + * @exception SQLException + * if a database access error occurs + */ + protected BigDecimal getNativeBigDecimal(int columnIndex, int scale) + throws SQLException { + checkColumnBounds(columnIndex); + + String stringVal = null; + + Field f = this.fields[columnIndex - 1]; + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + switch (f.getSQLType()) { + case Types.DECIMAL: + case Types.NUMERIC: + stringVal = StringUtils + .toAsciiString((byte[]) this.thisRow[columnIndex - 1]); + break; + default: + stringVal = getNativeString(columnIndex); + } + + return getBigDecimalFromString(stringVal, columnIndex, scale); + } + + /** + * A column value can also be retrieved as a binary strea. This method is + * suitable for retrieving LONGVARBINARY values. + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return a Java InputStream that delivers the database column value as a + * stream of bytes. If the value is SQL NULL, then the result is + * null + * + * @exception SQLException + * if a database access error occurs + * + * @see getAsciiStream + * @see getUnicodeStream + */ + protected InputStream getNativeBinaryStream(int columnIndex) + throws SQLException { + checkRowPos(); + + byte[] b = getNativeBytes(columnIndex, false); + + if (b != null) { + return new ByteArrayInputStream(b); + } + + return null; + } + + /** + * JDBC 2.0 Get a BLOB column. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return an object representing a BLOB + * + * @throws SQLException + * if an error occurs. + */ + protected java.sql.Blob getNativeBlob(int columnIndex) throws SQLException { + checkRowPos(); + + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return null; + } + + int mysqlType = this.fields[columnIndex - 1].getMysqlType(); + + byte[] dataAsBytes = null; + + switch (mysqlType) { + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + case MysqlDefs.FIELD_TYPE_BLOB: + dataAsBytes = (byte[]) this.thisRow[columnIndex - 1]; + + default: + dataAsBytes = getNativeBytes(columnIndex, false); + } + + if (!this.connection.getEmulateLocators()) { + return new Blob(dataAsBytes); + } + + return new BlobFromLocator(this, columnIndex); + } + + /** + * Get the value of a column in the current row as a Java byte. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected byte getNativeByte(int columnIndex) throws SQLException { + return getNativeByte(columnIndex, true); + } + + protected byte getNativeByte(int columnIndex, boolean overflowCheck) throws SQLException { + checkRowPos(); + + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return 0; + } + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return 0; + } + + columnIndex--; + + Field field = this.fields[columnIndex]; + + switch (field.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_BIT: + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + (valueAsLong < Byte.MIN_VALUE + || valueAsLong > Byte.MAX_VALUE)) { + throwRangeException(String.valueOf(valueAsLong), columnIndex + 1, + Types.TINYINT); + } + + return (byte)valueAsLong; + case MysqlDefs.FIELD_TYPE_TINY: + byte valueAsByte = ((byte[]) this.thisRow[columnIndex])[0]; + + if (!field.isUnsigned()) { + return valueAsByte; + } + + short valueAsShort = (valueAsByte >= 0) ? + valueAsByte : (short)(valueAsByte + (short)256); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsShort > Byte.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsShort), + columnIndex + 1, Types.TINYINT); + } + } + + return (byte)valueAsShort; + + case MysqlDefs.FIELD_TYPE_SHORT: + case MysqlDefs.FIELD_TYPE_YEAR: + valueAsShort = getNativeShort(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsShort < Byte.MIN_VALUE + || valueAsShort > Byte.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsShort), + columnIndex + 1, Types.TINYINT); + } + } + + return (byte) valueAsShort; + case MysqlDefs.FIELD_TYPE_INT24: + case MysqlDefs.FIELD_TYPE_LONG: + int valueAsInt = getNativeInt(columnIndex + 1, false); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsInt < Byte.MIN_VALUE || valueAsInt > Byte.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsInt), + columnIndex + 1, Types.TINYINT); + } + } + + return (byte) valueAsInt; + + case MysqlDefs.FIELD_TYPE_FLOAT: + float valueAsFloat = getNativeFloat(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsFloat < Byte.MIN_VALUE + || valueAsFloat > Byte.MAX_VALUE) { + + throwRangeException(String.valueOf(valueAsFloat), + columnIndex + 1, Types.TINYINT); + } + } + + return (byte) valueAsFloat; + + case MysqlDefs.FIELD_TYPE_DOUBLE: + double valueAsDouble = getNativeDouble(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Byte.MIN_VALUE + || valueAsDouble > Byte.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex + 1, Types.TINYINT); + } + } + + return (byte) valueAsDouble; + + case MysqlDefs.FIELD_TYPE_LONGLONG: + valueAsLong = getNativeLong(columnIndex + 1, false, true); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsLong < Byte.MIN_VALUE + || valueAsLong > Byte.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsLong), + columnIndex + 1, Types.TINYINT); + } + } + + return (byte) valueAsLong; + + default: + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getByte()", columnIndex, + this.thisRow[columnIndex], this.fields[columnIndex], + new int[] { MysqlDefs.FIELD_TYPE_DOUBLE, + MysqlDefs.FIELD_TYPE_TINY, + MysqlDefs.FIELD_TYPE_SHORT, + MysqlDefs.FIELD_TYPE_LONG, + MysqlDefs.FIELD_TYPE_LONGLONG, + MysqlDefs.FIELD_TYPE_FLOAT }); + } + + return getByteFromString(getNativeString(columnIndex + 1), + columnIndex + 1); + } + } + + /** + * Get the value of a column in the current row as a Java byte array. + * + *

+ * Be warned If the blob is huge, then you may run out of memory. + *

+ * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database access error occurs + */ + protected byte[] getNativeBytes(int columnIndex, boolean noConversion) + throws SQLException { + checkRowPos(); + + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return null; + } + + Field field = this.fields[columnIndex - 1]; + + int mysqlType = field.getMysqlType(); + + // Workaround for emulated locators in servers > 4.1, + // as server returns SUBSTRING(blob) as STRING type... + if (noConversion) { + mysqlType = MysqlDefs.FIELD_TYPE_BLOB; + } + + switch (mysqlType) { + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + case MysqlDefs.FIELD_TYPE_BLOB: + case MysqlDefs.FIELD_TYPE_BIT: + return (byte[]) this.thisRow[columnIndex - 1]; + + default: + int sqlType = field.getSQLType(); + + if (sqlType == Types.VARBINARY || sqlType == Types.BINARY) { + return (byte[]) this.thisRow[columnIndex - 1]; + } + + return getBytesFromString(getNativeString(columnIndex), columnIndex); + } + } + + /** + * JDBC 2.0 + * + *

+ * Get the value of a column in the current row as a java.io.Reader. + *

+ * + * @param columnIndex + * the column to get the value from + * + * @return the value in the column as a java.io.Reader. + * + * @throws SQLException + * if an error occurs + */ + protected java.io.Reader getNativeCharacterStream(int columnIndex) + throws SQLException { + String asString = null; + + asString = getStringForClob(columnIndex); + + if (asString == null) { + return null; + } + return getCharacterStreamFromString(asString, columnIndex); + } + + /** + * JDBC 2.0 Get a CLOB column. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @return an object representing a CLOB + * + * @throws SQLException + * if an error occurs + */ + protected java.sql.Clob getNativeClob(int columnIndex) throws SQLException { + String stringVal = getStringForClob(columnIndex); + + if (stringVal == null) { + return null; + } + + return getClobFromString(stringVal, columnIndex); + } + + private String getNativeConvertToString(int columnIndex, + Field field) + throws SQLException { + + + int sqlType = field.getSQLType(); + int mysqlType = field.getMysqlType(); + + switch (sqlType) { + case Types.BIT: + return String.valueOf(getNumericRepresentationOfSQLBitType(columnIndex)); + case Types.BOOLEAN: + boolean booleanVal = getBoolean(columnIndex); + + if (this.wasNullFlag) { + return null; + } + + return String.valueOf(booleanVal); + + case Types.TINYINT: + byte tinyintVal = getNativeByte(columnIndex, false); + + if (this.wasNullFlag) { + return null; + } + + if (!field.isUnsigned() || tinyintVal >= 0) { + return String.valueOf(tinyintVal); + } + + short unsignedTinyVal = (short) (tinyintVal & 0xff); + + return String.valueOf(unsignedTinyVal); + + case Types.SMALLINT: + + int intVal = getNativeInt(columnIndex, false); + + if (this.wasNullFlag) { + return null; + } + + if (!field.isUnsigned() || intVal >= 0) { + return String.valueOf(intVal); + } + + intVal = intVal & 0xffff; + + return String.valueOf(intVal); + + case Types.INTEGER: + intVal = getNativeInt(columnIndex, false); + + if (this.wasNullFlag) { + return null; + } + + if (!field.isUnsigned() || intVal >= 0 + || field.getMysqlType() == MysqlDefs.FIELD_TYPE_INT24) { + + return String.valueOf(intVal); + } + + long longVal = intVal & 0xffffffffL; + + return String.valueOf(longVal); + + case Types.BIGINT: + + if (!field.isUnsigned()) { + longVal = getNativeLong(columnIndex, false, true); + + if (this.wasNullFlag) { + return null; + } + + return String.valueOf(longVal); + } + + longVal = getNativeLong(columnIndex, false, false); + + if (this.wasNullFlag) { + return null; + } + + return String.valueOf(convertLongToUlong(longVal)); + case Types.REAL: + float floatVal = getNativeFloat(columnIndex); + + if (this.wasNullFlag) { + return null; + } + + return String.valueOf(floatVal); + + case Types.FLOAT: + case Types.DOUBLE: + double doubleVal = getNativeDouble(columnIndex); + + if (this.wasNullFlag) { + return null; + } + + return String.valueOf(doubleVal); + + case Types.DECIMAL: + case Types.NUMERIC: + String stringVal = StringUtils + .toAsciiString((byte[]) this.thisRow[columnIndex - 1]); + + BigDecimal val; + + if (stringVal != null) { + this.wasNullFlag = false; + + if (stringVal.length() == 0) { + val = new BigDecimal(0); + + return val.toString(); + } + + try { + val = new BigDecimal(stringVal); + } catch (NumberFormatException ex) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Bad_format_for_BigDecimal", + new Object[] {stringVal, new Integer(columnIndex)}), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + return val.toString(); + } + + this.wasNullFlag = true; + + return null; + + case Types.CHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: + + return extractStringFromNativeColumn(columnIndex, mysqlType); + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + + if (!field.isBlob()) { + return extractStringFromNativeColumn(columnIndex, mysqlType); + } else if (!field.isBinary()) { + return extractStringFromNativeColumn(columnIndex, mysqlType); + } else { + byte[] data = getBytes(columnIndex); + Object obj = data; + + if ((data != null) && (data.length >= 2)) { + if ((data[0] == -84) && (data[1] == -19)) { + // Serialized object? + try { + ByteArrayInputStream bytesIn = new ByteArrayInputStream( + data); + ObjectInputStream objIn = new ObjectInputStream( + bytesIn); + obj = objIn.readObject(); + objIn.close(); + bytesIn.close(); + } catch (ClassNotFoundException cnfe) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Class_not_found___91") //$NON-NLS-1$ + + cnfe.toString() + + Messages + .getString("ResultSet._while_reading_serialized_object_92")); //$NON-NLS-1$ + } catch (IOException ex) { + obj = data; // not serialized? + } + } + + return obj.toString(); + } + + return extractStringFromNativeColumn(columnIndex, mysqlType); + } + + case Types.DATE: + + // The YEAR datatype needs to be handled differently here. + if (mysqlType == MysqlDefs.FIELD_TYPE_YEAR) { + short shortVal = getNativeShort(columnIndex); + + if (!this.connection.getYearIsDateType()) { + + if (this.wasNullFlag) { + return null; + } + + return String.valueOf(shortVal); + } + + if (field.getLength() == 2) { + + if (shortVal <= 69) { + shortVal = (short) (shortVal + 100); + } + + shortVal += 1900; + } + + return fastDateCreate(null, shortVal, 1, 1).toString(); + + } + + Date dt = getNativeDate(columnIndex); + + if (dt == null) { + return null; + } + + return String.valueOf(dt); + + case Types.TIME: + Time tm = getNativeTime(columnIndex, null, this.defaultTimeZone, false); + + if (tm == null) { + return null; + } + + return String.valueOf(tm); + + case Types.TIMESTAMP: + Timestamp tstamp = getNativeTimestamp(columnIndex, + null, this.defaultTimeZone, false); + + if (tstamp == null) { + return null; + } + + String result = String.valueOf(tstamp); + + if (!this.connection.getNoDatetimeStringSync()) { + return result; + } + + if (result.endsWith(".0")) { + return result.substring(0, result.length() - 2); + } + + default: + return extractStringFromNativeColumn(columnIndex, mysqlType); + } + } + + /** + * Get the value of a column in the current row as a java.sql.Date object + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return the column value; null if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected java.sql.Date getNativeDate(int columnIndex) throws SQLException { + return getNativeDate(columnIndex, null); + } + + /** + * JDBC 2.0 Get the value of a column in the current row as a java.sql.Date + * object. Use the calendar to construct an appropriate millisecond value + * for the Date, if the underlying database doesn't store timezone + * information. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param tz + * the calendar to use in constructing the date + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + protected java.sql.Date getNativeDate(int columnIndex, TimeZone tz) + throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + int mysqlType = this.fields[columnIndex - 1].getMysqlType(); + + if (mysqlType == MysqlDefs.FIELD_TYPE_DATE) { + byte[] bits = (byte[]) this.thisRow[columnIndex - 1]; + + if (bits == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + java.sql.Date dateToReturn = null; + + int year = 0; + int month = 0; + int day = 0; + + int hour = 0; + int minute = 0; + int seconds = 0; + + if (bits.length != 0) { + year = (bits[0] & 0xff) | ((bits[1] & 0xff) << 8); + + month = bits[2]; + day = bits[3]; + } + + if ((year == 0) && (month == 0) && (day == 0)) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException( + "Value '0000-00-00' can not be represented as java.sql.Date", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + year = 1; + month = 1; + day = 1; + } + + return fastDateCreate( + getCalendarInstanceForSessionOrNew(), year, month, day); + } + + boolean rollForward = (tz != null && !tz.equals(this.getDefaultTimeZone())); + + return (Date)getNativeDateTimeValue(columnIndex, null, Types.DATE, mysqlType, + tz, rollForward); + } + + private java.sql.Date getNativeDateViaParseConversion(int columnIndex) throws SQLException { + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getDate()", columnIndex, + this.thisRow[columnIndex - 1], this.fields[columnIndex - 1], + new int[] { MysqlDefs.FIELD_TYPE_DATE }); + } + + String stringVal = getNativeString(columnIndex); + + return getDateFromString(stringVal, columnIndex); + } + + /** + * Get the value of a column in the current row as a Java double. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected double getNativeDouble(int columnIndex) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + columnIndex--; // / JDBC is 1-based + + if (this.thisRow[columnIndex] == null) { + this.wasNullFlag = true; + + return 0; + } + + this.wasNullFlag = false; + + Field f= this.fields[columnIndex]; + + switch (f.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_DOUBLE: + byte[] bits = (byte[]) this.thisRow[columnIndex]; + + long valueAsLong = (bits[0] & 0xff) + | ((long) (bits[1] & 0xff) << 8) + | ((long) (bits[2] & 0xff) << 16) + | ((long) (bits[3] & 0xff) << 24) + | ((long) (bits[4] & 0xff) << 32) + | ((long) (bits[5] & 0xff) << 40) + | ((long) (bits[6] & 0xff) << 48) + | ((long) (bits[7] & 0xff) << 56); + + return Double.longBitsToDouble(valueAsLong); + case MysqlDefs.FIELD_TYPE_TINY: + if (!f.isUnsigned()) { + return (double) getNativeByte(columnIndex + 1); + } + + return (double) getNativeShort(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_SHORT: + case MysqlDefs.FIELD_TYPE_YEAR: + if (!f.isUnsigned()) { + return (double) getNativeShort(columnIndex + 1); + } + + return (double) getNativeInt(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_INT24: + case MysqlDefs.FIELD_TYPE_LONG: + if (!f.isUnsigned()) { + return (double) getNativeInt(columnIndex + 1); + } + + return (double) getNativeLong(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_LONGLONG: + valueAsLong = getNativeLong(columnIndex + 1); + + if (!f.isUnsigned()) { + return (double) valueAsLong; + } + + BigInteger asBigInt = convertLongToUlong(valueAsLong); + + // TODO: Check for overflow + + return asBigInt.doubleValue(); + case MysqlDefs.FIELD_TYPE_FLOAT: + return (double) getNativeFloat(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_BIT: + return getNumericRepresentationOfSQLBitType(columnIndex + 1); + default: + + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getDouble()", columnIndex, + this.thisRow[columnIndex], this.fields[columnIndex], + new int[] { MysqlDefs.FIELD_TYPE_DOUBLE, + MysqlDefs.FIELD_TYPE_TINY, + MysqlDefs.FIELD_TYPE_SHORT, + MysqlDefs.FIELD_TYPE_LONG, + MysqlDefs.FIELD_TYPE_LONGLONG, + MysqlDefs.FIELD_TYPE_FLOAT }); + } + + String stringVal = getNativeString(columnIndex + 1); + + return getDoubleFromString(stringVal, columnIndex + 1); + } + } + + /** + * Get the value of a column in the current row as a Java float. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected float getNativeFloat(int columnIndex) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + columnIndex--; // / JDBC is 1-based + + if (this.thisRow[columnIndex] == null) { + this.wasNullFlag = true; + + return 0; + } + + this.wasNullFlag = false; + + Field f = this.fields[columnIndex]; + + switch (f.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_BIT: + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex + 1); + + return valueAsLong; + case MysqlDefs.FIELD_TYPE_DOUBLE: + + // Only foolproof way to check for overflow + // Not efficient, but if you don't want to be inefficient, use the + // correct binding for the type! + + Double valueAsDouble = new Double(getNativeDouble(columnIndex + 1)); + + float valueAsFloat = valueAsDouble.floatValue(); + + if (this.connection.getJdbcCompliantTruncationForReads() && + valueAsFloat == Float.NEGATIVE_INFINITY || + valueAsFloat == Float.POSITIVE_INFINITY) { + throwRangeException(valueAsDouble.toString(), + columnIndex + 1, Types.FLOAT); + } + + return (float) getNativeDouble(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_TINY: + if (!f.isUnsigned()) { + return (float) getNativeByte(columnIndex + 1); + } + + return (float) getNativeShort(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_SHORT: + case MysqlDefs.FIELD_TYPE_YEAR: + if (!f.isUnsigned()) { + return (float) getNativeShort(columnIndex + 1); + } + + return (float) getNativeInt(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_INT24: + case MysqlDefs.FIELD_TYPE_LONG: + if (!f.isUnsigned()) { + return (float) getNativeInt(columnIndex + 1); + } + + return (float) getNativeLong(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_LONGLONG: + valueAsLong = getNativeLong(columnIndex + 1); + + if (!f.isUnsigned()) { + return (float) valueAsLong; + } + + BigInteger asBigInt = convertLongToUlong(valueAsLong); + + // TODO: Check for overflow + + return asBigInt.floatValue(); + case MysqlDefs.FIELD_TYPE_FLOAT: + byte[] bits = (byte[]) this.thisRow[columnIndex]; + + int asInt = (bits[0] & 0xff) | ((bits[1] & 0xff) << 8) + | ((bits[2] & 0xff) << 16) | ((bits[3] & 0xff) << 24); + + return Float.intBitsToFloat(asInt); + + default: + + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getFloat()", columnIndex, + this.thisRow[columnIndex], this.fields[columnIndex], + new int[] { MysqlDefs.FIELD_TYPE_DOUBLE, + MysqlDefs.FIELD_TYPE_TINY, + MysqlDefs.FIELD_TYPE_SHORT, + MysqlDefs.FIELD_TYPE_LONG, + MysqlDefs.FIELD_TYPE_LONGLONG, + MysqlDefs.FIELD_TYPE_FLOAT }); + } + + String stringVal = getNativeString(columnIndex + 1); + + return getFloatFromString(stringVal, columnIndex + 1); + } + } + + /** + * Get the value of a column in the current row as a Java int. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected int getNativeInt(int columnIndex) throws SQLException { + return getNativeInt(columnIndex, true); + } + + protected int getNativeInt(int columnIndex, boolean overflowCheck) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + columnIndex--; // / JDBC is 1-based + + if (this.thisRow[columnIndex] == null) { + this.wasNullFlag = true; + + return 0; + } + + this.wasNullFlag = false; + + Field f = this.fields[columnIndex]; + + switch (f.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_BIT: + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + (valueAsLong < Integer.MIN_VALUE + || valueAsLong > Integer.MAX_VALUE)) { + throwRangeException(String.valueOf(valueAsLong), columnIndex + 1, + Types.INTEGER); + } + + return (short)valueAsLong; + case MysqlDefs.FIELD_TYPE_TINY: + byte tinyintVal = getNativeByte(columnIndex + 1, false); + + if (!f.isUnsigned() || tinyintVal >= 0) { + return tinyintVal; + } + + return tinyintVal + 256; + case MysqlDefs.FIELD_TYPE_SHORT: + case MysqlDefs.FIELD_TYPE_YEAR: + short asShort = getNativeShort(columnIndex + 1, false); + + if (!f.isUnsigned() || asShort >= 0) { + return asShort; + } + + return asShort + 65536; + case MysqlDefs.FIELD_TYPE_INT24: + case MysqlDefs.FIELD_TYPE_LONG: + byte[] bits = (byte[]) this.thisRow[columnIndex]; + + int valueAsInt = (bits[0] & 0xff) | ((bits[1] & 0xff) << 8) + | ((bits[2] & 0xff) << 16) | ((bits[3] & 0xff) << 24); + + if (!f.isUnsigned()) { + return valueAsInt; + } + + valueAsLong = (valueAsInt >= 0) ? + valueAsInt : valueAsInt + 4294967296L; + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + valueAsLong > Integer.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsLong), + columnIndex + 1, Types.INTEGER); + } + + return (int)valueAsLong; + case MysqlDefs.FIELD_TYPE_LONGLONG: + valueAsLong = getNativeLong(columnIndex + 1, false, true); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsLong < Integer.MIN_VALUE + || valueAsLong > Integer.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsLong), + columnIndex + 1, Types.INTEGER); + } + } + + return (int) valueAsLong; + case MysqlDefs.FIELD_TYPE_DOUBLE: + double valueAsDouble = getNativeDouble(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Integer.MIN_VALUE + || valueAsDouble > Integer.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex + 1, Types.INTEGER); + } + } + + return (int) valueAsDouble; + case MysqlDefs.FIELD_TYPE_FLOAT: + valueAsDouble = getNativeFloat(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Integer.MIN_VALUE + || valueAsDouble > Integer.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex + 1, Types.INTEGER); + } + } + + return (int) valueAsDouble; + + default: + + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getInt()", columnIndex, + this.thisRow[columnIndex], this.fields[columnIndex], + new int[] { MysqlDefs.FIELD_TYPE_DOUBLE, + MysqlDefs.FIELD_TYPE_TINY, + MysqlDefs.FIELD_TYPE_SHORT, + MysqlDefs.FIELD_TYPE_LONG, + MysqlDefs.FIELD_TYPE_LONGLONG, + MysqlDefs.FIELD_TYPE_FLOAT }); + } + + String stringVal = getNativeString(columnIndex + 1); + + return getIntFromString(stringVal, columnIndex + 1); + } + } + + /** + * Get the value of a column in the current row as a Java long. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected long getNativeLong(int columnIndex) throws SQLException { + return getNativeLong(columnIndex, true, true); + } + + protected long getNativeLong(int columnIndex, boolean overflowCheck, + boolean expandUnsignedLong) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + columnIndex--; // / JDBC is 1-based + + if (this.thisRow[columnIndex] == null) { + this.wasNullFlag = true; + + return 0; + } + + this.wasNullFlag = false; + + Field f = this.fields[columnIndex]; + + switch (f.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_BIT: + return getNumericRepresentationOfSQLBitType(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_TINY: + if (!f.isUnsigned()) { + return getNativeByte(columnIndex + 1); + } + + return getNativeInt(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_SHORT: + if (!f.isUnsigned()) { + return getNativeShort(columnIndex + 1); + } + + return getNativeInt(columnIndex + 1, false); + case MysqlDefs.FIELD_TYPE_YEAR: + + return getNativeShort(columnIndex + 1); + case MysqlDefs.FIELD_TYPE_INT24: + case MysqlDefs.FIELD_TYPE_LONG: + int asInt = getNativeInt(columnIndex + 1, false); + + if (!f.isUnsigned() || asInt >= 0) { + return asInt; + } + + return asInt + 4294967296L; + case MysqlDefs.FIELD_TYPE_LONGLONG: + + byte[] bits = (byte[]) this.thisRow[columnIndex]; + + long valueAsLong = (bits[0] & 0xff) + | ((long) (bits[1] & 0xff) << 8) + | ((long) (bits[2] & 0xff) << 16) + | ((long) (bits[3] & 0xff) << 24) + | ((long) (bits[4] & 0xff) << 32) + | ((long) (bits[5] & 0xff) << 40) + | ((long) (bits[6] & 0xff) << 48) + | ((long) (bits[7] & 0xff) << 56); + + if (!f.isUnsigned() || !expandUnsignedLong) { + return valueAsLong; + } + + BigInteger asBigInt = convertLongToUlong(valueAsLong); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + ((asBigInt.compareTo(new BigInteger(String.valueOf(Long.MAX_VALUE))) > 0 ) || + (asBigInt.compareTo(new BigInteger(String.valueOf(Long.MIN_VALUE))) < 0))) { + throwRangeException(asBigInt.toString(), + columnIndex + 1, Types.BIGINT); + } + + return getLongFromString(asBigInt.toString(), columnIndex + 1); + + case MysqlDefs.FIELD_TYPE_DOUBLE: + double valueAsDouble = getNativeDouble(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Long.MIN_VALUE + || valueAsDouble > Long.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex + 1, Types.BIGINT); + } + } + + return (long) valueAsDouble; + case MysqlDefs.FIELD_TYPE_FLOAT: + valueAsDouble = getNativeFloat(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Long.MIN_VALUE + || valueAsDouble > Long.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex + 1, Types.BIGINT); + } + } + + return (long) valueAsDouble; + default: + + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getLong()", columnIndex, + this.thisRow[columnIndex], this.fields[columnIndex], + new int[] { MysqlDefs.FIELD_TYPE_DOUBLE, + MysqlDefs.FIELD_TYPE_TINY, + MysqlDefs.FIELD_TYPE_SHORT, + MysqlDefs.FIELD_TYPE_LONG, + MysqlDefs.FIELD_TYPE_LONGLONG, + MysqlDefs.FIELD_TYPE_FLOAT }); + } + + String stringVal = getNativeString(columnIndex + 1); + + return getLongFromString(stringVal, columnIndex + 1); + } + } + + /** + * JDBC 2.0 Get a REF(<structured-type>) column. + * + * @param i + * the first column is 1, the second is 2, ... + * + * @return an object representing data of an SQL REF type + * + * @throws SQLException + * as this is not implemented + * @throws NotImplemented + * DOCUMENT ME! + */ + protected java.sql.Ref getNativeRef(int i) throws SQLException { + throw new NotImplemented(); + } + + /** + * Get the value of a column in the current row as a Java short. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected short getNativeShort(int columnIndex) throws SQLException { + return getNativeShort(columnIndex, true); + } + + protected short getNativeShort(int columnIndex, boolean overflowCheck) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + columnIndex--; // / JDBC is 1-based + + if (this.thisRow[columnIndex] == null) { + this.wasNullFlag = true; + + return 0; + } + + this.wasNullFlag = false; + + Field f = this.fields[columnIndex]; + + switch (f.getMysqlType()) { + + case MysqlDefs.FIELD_TYPE_TINY: + byte tinyintVal = getNativeByte(columnIndex + 1, false); + + if (!f.isUnsigned() || tinyintVal >= 0) { + return tinyintVal; + } + + return (short)(tinyintVal + (short)256); + case MysqlDefs.FIELD_TYPE_SHORT: + case MysqlDefs.FIELD_TYPE_YEAR: + byte[] bits = (byte[]) this.thisRow[columnIndex]; + + short asShort = (short) ((bits[0] & 0xff) | ((bits[1] & 0xff) << 8)); + + if (!f.isUnsigned()) { + return asShort; + } + + int valueAsInt = asShort & 0xffff; + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + valueAsInt > Short.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsInt), + columnIndex + 1, Types.SMALLINT); + } + + return (short)valueAsInt; + case MysqlDefs.FIELD_TYPE_INT24: + case MysqlDefs.FIELD_TYPE_LONG: + if (!f.isUnsigned()) { + valueAsInt = getNativeInt(columnIndex + 1, false); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + valueAsInt > Short.MAX_VALUE || + valueAsInt < Short.MIN_VALUE) { + throwRangeException(String.valueOf(valueAsInt), + columnIndex + 1, Types.SMALLINT); + } + + return (short)valueAsInt; + } + + long valueAsLong = getNativeLong(columnIndex + 1, false, true); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + valueAsLong > Short.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsLong), + columnIndex + 1, Types.SMALLINT); + } + + return (short)valueAsLong; + + case MysqlDefs.FIELD_TYPE_LONGLONG: + valueAsLong = getNativeLong(columnIndex + 1, false, false); + + if (!f.isUnsigned()) { + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsLong < Short.MIN_VALUE + || valueAsLong > Short.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsLong), + columnIndex + 1, Types.SMALLINT); + } + } + + return (short) valueAsLong; + } + + BigInteger asBigInt = convertLongToUlong(valueAsLong); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads() && + ((asBigInt.compareTo(new BigInteger(String.valueOf(Short.MAX_VALUE))) > 0 ) || + (asBigInt.compareTo(new BigInteger(String.valueOf(Short.MIN_VALUE))) < 0))) { + throwRangeException(asBigInt.toString(), + columnIndex + 1, Types.SMALLINT); + } + + return (short)getIntFromString(asBigInt.toString(), columnIndex + 1); + + case MysqlDefs.FIELD_TYPE_DOUBLE: + double valueAsDouble = getNativeDouble(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Short.MIN_VALUE + || valueAsDouble > Short.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), + columnIndex + 1, Types.SMALLINT); + } + } + + return (short) valueAsDouble; + case MysqlDefs.FIELD_TYPE_FLOAT: + float valueAsFloat = getNativeFloat(columnIndex + 1); + + if (overflowCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsFloat < Short.MIN_VALUE + || valueAsFloat > Short.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsFloat), + columnIndex + 1, Types.SMALLINT); + } + } + + return (short) valueAsFloat; + default: + + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getShort()", columnIndex, + this.thisRow[columnIndex], this.fields[columnIndex], + new int[] { MysqlDefs.FIELD_TYPE_DOUBLE, + MysqlDefs.FIELD_TYPE_TINY, + MysqlDefs.FIELD_TYPE_SHORT, + MysqlDefs.FIELD_TYPE_LONG, + MysqlDefs.FIELD_TYPE_LONGLONG, + MysqlDefs.FIELD_TYPE_FLOAT }); + } + + String stringVal = getNativeString(columnIndex + 1); + + return getShortFromString(stringVal, columnIndex + 1); + } + } + + /** + * Get the value of a column in the current row as a Java String + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return the column value, null for SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + protected String getNativeString(int columnIndex) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + if (this.fields == null) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Query_generated_no_fields_for_ResultSet_133"), //$NON-NLS-1$ + SQLError.SQL_STATE_INVALID_COLUMN_NUMBER); + } + + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + String stringVal = null; + + if (this.thisRow[columnIndex - 1] instanceof String) { + return (String) this.thisRow[columnIndex - 1]; + } + + Field field = this.fields[columnIndex - 1]; + + // TODO: Check Types Here. + stringVal = getNativeConvertToString(columnIndex, field); + + if (field.isZeroFill() && (stringVal != null)) { + int origLength = stringVal.length(); + + StringBuffer zeroFillBuf = new StringBuffer(origLength); + + long numZeros = field.getLength() - origLength; + + for (long i = 0; i < numZeros; i++) { + zeroFillBuf.append('0'); + } + + zeroFillBuf.append(stringVal); + + stringVal = zeroFillBuf.toString(); + } + + return stringVal; + // } + } + + private Time getNativeTime(int columnIndex, Calendar targetCalendar, + TimeZone tz, boolean rollForward) + throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return null; + } else { + this.wasNullFlag = false; + } + + int mysqlType = this.fields[columnIndex - 1].getMysqlType(); + + if (mysqlType == MysqlDefs.FIELD_TYPE_TIME) { + + byte[] bits = (byte[]) this.thisRow[columnIndex - 1]; + + int length = bits.length; + int hour = 0; + int minute = 0; + int seconds = 0; + + if (length != 0) { + // bits[0] // skip tm->neg + // binaryData.readLong(); // skip daysPart + hour = bits[5]; + minute = bits[6]; + seconds = bits[7]; + } + + Calendar sessionCalendar = getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + Time time = TimeUtil + .fastTimeCreate(sessionCalendar, hour, + minute, seconds); + + Time adjustedTime = TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + time, + this.connection.getServerTimezoneTZ(), tz, rollForward); + + return adjustedTime; + } + } + + return (Time)getNativeDateTimeValue(columnIndex, targetCalendar, + Types.TIME, mysqlType, + tz, rollForward); + } + + private Time getNativeTimeViaParseConversion(int columnIndex, Calendar targetCalendar, + TimeZone tz, boolean rollForward) throws SQLException { + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getTime()", columnIndex, + this.thisRow[columnIndex - 1], this.fields[columnIndex - 1], + new int[] { MysqlDefs.FIELD_TYPE_TIME }); + } + + String strTime = getNativeString(columnIndex); + + return getTimeFromString(strTime, targetCalendar, columnIndex, tz, rollForward); + } + + private Timestamp getNativeTimestamp(int columnIndex, + Calendar targetCalendar, + TimeZone tz, + boolean rollForward) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + int mysqlType = this.fields[columnIndex - 1].getMysqlType(); + + switch (mysqlType) { + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + byte[] bits = (byte[]) this.thisRow[columnIndex - 1]; + + int length = bits.length; + + int year = 0; + int month = 0; + int day = 0; + + int hour = 0; + int minute = 0; + int seconds = 0; + + int nanos = 0; + + if (length != 0) { + year = (bits[0] & 0xff) | ((bits[1] & 0xff) << 8); + month = bits[2]; + day = bits[3]; + + if (length > 4) { + hour = bits[4]; + minute = bits[5]; + seconds = bits[6]; + } + + if (length > 7) { + nanos = (bits[7] & 0xff) | ((bits[8] & 0xff) << 8) + | ((bits[9] & 0xff) << 16) + | ((bits[10] & 0xff) << 24); + } + } + + if ((year == 0) && (month == 0) && (day == 0)) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException( + "Value '0000-00-00' can not be represented as java.sql.Timestamp", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + year = 1; + month = 1; + day = 1; + } + + Calendar sessionCalendar = this.connection.getUseJDBCCompliantTimezoneShift() ? + this.connection.getUtcCalendar() : + getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + Timestamp ts = fastTimestampCreate( + sessionCalendar, year, month, day, + hour, minute, seconds, nanos); + + Timestamp adjustedTs = TimeUtil.changeTimezone( + this.connection, sessionCalendar, + targetCalendar, + ts, + this.connection.getServerTimezoneTZ(), tz, rollForward); + + return adjustedTs; + } + + default: + return (Timestamp)getNativeDateTimeValue(columnIndex, targetCalendar, + Types.TIMESTAMP, mysqlType, + tz, rollForward); + } + } + + private Timestamp getNativeTimestampViaParseConversion(int columnIndex, Calendar targetCalendar, + TimeZone tz, boolean rollForward) throws SQLException { + if (this.useUsageAdvisor) { + issueConversionViaParsingWarning("getTimestamp()", columnIndex, + this.thisRow[columnIndex - 1], this.fields[columnIndex - 1], + new int[] { MysqlDefs.FIELD_TYPE_TIMESTAMP, + MysqlDefs.FIELD_TYPE_DATETIME }); + } + + String strTimestamp = getNativeString(columnIndex); + + return getTimestampFromString(columnIndex, targetCalendar, strTimestamp, tz, + rollForward); + } + + // --------------------------------------------------------------------- + // Updates + // --------------------------------------------------------------------- + + /** + * A column value can also be retrieved as a stream of Unicode characters. + * We implement this as a binary stream. + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return a Java InputStream that delivers the database column value as a + * stream of two byte Unicode characters. If the value is SQL NULL, + * then the result is null + * + * @exception SQLException + * if a database access error occurs + * + * @see getAsciiStream + * @see getBinaryStream + */ + protected InputStream getNativeUnicodeStream(int columnIndex) + throws SQLException { + checkRowPos(); + + return getBinaryStream(columnIndex); + } + + /** + * @see ResultSet#getURL(int) + */ + protected URL getNativeURL(int colIndex) throws SQLException { + String val = getString(colIndex); + + if (val == null) { + return null; + } + + try { + return new URL(val); + } catch (MalformedURLException mfe) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Malformed_URL____141") + + val + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * DOCUMENT ME! + * + * @return Returns the nextResultSet, if any, null if none exists. + */ + protected ResultSet getNextResultSet() { + return this.nextResultSet; + } + + /** + * Get the value of a column in the current row as a Java object + * + *

+ * This method will return the value of the given column as a Java object. + * The type of the Java object will be the default Java Object type + * corresponding to the column's SQL type, following the mapping specified + * in the JDBC specification. + *

+ * + *

+ * This method may also be used to read database specific abstract data + * types. + *

+ * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return a Object holding the column value + * + * @exception SQLException + * if a database access error occurs + */ + public Object getObject(int columnIndex) throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + Field field; + field = this.fields[columnIndex - 1]; + + // + // If they come from a binary-encode result set, + // no need to create another new object to represent + // the value, just return it directly, unless it's + // a byte[], which means it could be a string or blob. + // + if (this.isBinaryEncoded + && !(this.thisRow[columnIndex - 1] instanceof byte[])) { + + // + // Special case here...If this is a 'bit' type, it will actually + // have + // been returned as an Integer by the server... + // + if (field.getSQLType() == Types.BIT && field.getLength() > 0) { + // valueOf would be nicer here, but it isn't + // present in JDK-1.3.1, which is what the CTS + // uses. + return new Boolean(getBoolean(columnIndex)); + } + + Object columnValue = this.thisRow[columnIndex - 1]; + + if (columnValue == null) { + this.wasNullFlag = true; + + return null; + } + + return columnValue; + } + + switch (field.getSQLType()) { + case Types.BIT: + case Types.BOOLEAN: + if (field.getMysqlType() == MysqlDefs.FIELD_TYPE_BIT + && !field.isSingleBit()) { + return getBytes(columnIndex); + } + + // valueOf would be nicer here, but it isn't + // present in JDK-1.3.1, which is what the CTS + // uses. + return new Boolean(getBoolean(columnIndex)); + + case Types.TINYINT: + if (!field.isUnsigned()) { + return new Integer(getByte(columnIndex)); + } + + return new Integer(getInt(columnIndex)); + + case Types.SMALLINT: + + return new Integer(getInt(columnIndex)); + + case Types.INTEGER: + + if (!field.isUnsigned() || + field.getMysqlType() == MysqlDefs.FIELD_TYPE_INT24) { + return new Integer(getInt(columnIndex)); + } + + return new Long(getLong(columnIndex)); + + case Types.BIGINT: + + if (!field.isUnsigned()) { + return new Long(getLong(columnIndex)); + } + + String stringVal = getString(columnIndex); + + if (stringVal == null) { + return null; + } + + try { + return new BigInteger(stringVal); + } catch (NumberFormatException nfe) { + throw SQLError.createSQLException(Messages.getString( + "ResultSet.Bad_format_for_BigInteger", new Object[] { + new Integer(columnIndex), stringVal }), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + case Types.DECIMAL: + case Types.NUMERIC: + stringVal = getString(columnIndex); + + BigDecimal val; + + if (stringVal != null) { + if (stringVal.length() == 0) { + val = new BigDecimal(0); + + return val; + } + + try { + val = new BigDecimal(stringVal); + } catch (NumberFormatException ex) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Bad_format_for_BigDecimal____86") //$NON-NLS-1$ + + stringVal + + Messages + .getString("ResultSet.___in_column__87") + + columnIndex + "(" //$NON-NLS-1$ + + this.fields[columnIndex - 1] + ").", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + return val; + } + + return null; + + case Types.REAL: + return new Float(getFloat(columnIndex)); + + case Types.FLOAT: + case Types.DOUBLE: + return new Double(getDouble(columnIndex)); + + case Types.CHAR: + case Types.VARCHAR: + if (!field.isOpaqueBinary()) { + return getString(columnIndex); + } + + return getBytes(columnIndex); + case Types.LONGVARCHAR: + if (!field.isOpaqueBinary()) { + return getStringForClob(columnIndex); + } + + return getBytes(columnIndex); + + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + if (field.getMysqlType() == MysqlDefs.FIELD_TYPE_GEOMETRY) { + return getBytes(columnIndex); + } else if (field.isBinary() || field.isBlob()) { + byte[] data = getBytes(columnIndex); + + if (this.connection.getAutoDeserialize()) { + Object obj = data; + + if ((data != null) && (data.length >= 2)) { + if ((data[0] == -84) && (data[1] == -19)) { + // Serialized object? + try { + ByteArrayInputStream bytesIn = new ByteArrayInputStream( + data); + ObjectInputStream objIn = new ObjectInputStream( + bytesIn); + obj = objIn.readObject(); + objIn.close(); + bytesIn.close(); + } catch (ClassNotFoundException cnfe) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Class_not_found___91") //$NON-NLS-1$ + + cnfe.toString() + + Messages + .getString("ResultSet._while_reading_serialized_object_92")); //$NON-NLS-1$ + } catch (IOException ex) { + obj = data; // not serialized? + } + } else { + return getString(columnIndex); + } + } + + return obj; + } + + return data; + } + + case Types.DATE: + if (field.getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR + && !this.connection.getYearIsDateType()) { + return new Short(getShort(columnIndex)); + } + + return getDate(columnIndex); + + case Types.TIME: + return getTime(columnIndex); + + case Types.TIMESTAMP: + return getTimestamp(columnIndex); + + default: + return getString(columnIndex); + } + } + + /** + * JDBC 2.0 Returns the value of column i as a Java object. Use the map to + * determine the class from which to construct data of SQL structured and + * distinct types. + * + * @param i + * the first column is 1, the second is 2, ... + * @param map + * the mapping from SQL type names to Java classes + * + * @return an object representing the SQL value + * + * @throws SQLException + * because this is not implemented + */ + public Object getObject(int i, java.util.Map map) throws SQLException { + return getObject(i); + } + + /** + * Get the value of a column in the current row as a Java object + * + *

+ * This method will return the value of the given column as a Java object. + * The type of the Java object will be the default Java Object type + * corresponding to the column's SQL type, following the mapping specified + * in the JDBC specification. + *

+ * + *

+ * This method may also be used to read database specific abstract data + * types. + *

+ * + * @param columnName + * is the SQL name of the column + * + * @return a Object holding the column value + * + * @exception SQLException + * if a database access error occurs + */ + public Object getObject(String columnName) throws SQLException { + return getObject(findColumn(columnName)); + } + + /** + * JDBC 2.0 Returns the value of column i as a Java object. Use the map to + * determine the class from which to construct data of SQL structured and + * distinct types. + * + * @param colName + * the column name + * @param map + * the mapping from SQL type names to Java classes + * + * @return an object representing the SQL value + * + * @throws SQLException + * as this is not implemented + */ + public Object getObject(String colName, java.util.Map map) + throws SQLException { + return getObject(findColumn(colName), map); + } + + protected Object getObjectStoredProc(int columnIndex, int desiredSqlType) + throws SQLException { + checkRowPos(); + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + Field field; + field = this.fields[columnIndex - 1]; + + switch (desiredSqlType) { + case Types.BIT: + case Types.BOOLEAN: + // valueOf would be nicer here, but it isn't + // present in JDK-1.3.1, which is what the CTS + // uses. + return new Boolean(getBoolean(columnIndex)); + + case Types.TINYINT: + return new Integer(getInt(columnIndex)); + + case Types.SMALLINT: + return new Integer(getInt(columnIndex)); + + case Types.INTEGER: + + if (!field.isUnsigned() || + field.getMysqlType() == MysqlDefs.FIELD_TYPE_INT24) { + return new Integer(getInt(columnIndex)); + } + + return new Long(getLong(columnIndex)); + + case Types.BIGINT: + + if (field.isUnsigned()) { + return getBigDecimal(columnIndex); + } + + return new Long(getLong(columnIndex)); + + case Types.DECIMAL: + case Types.NUMERIC: + + String stringVal = getString(columnIndex); + BigDecimal val; + + if (stringVal != null) { + if (stringVal.length() == 0) { + val = new BigDecimal(0); + + return val; + } + + try { + val = new BigDecimal(stringVal); + } catch (NumberFormatException ex) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Bad_format_for_BigDecimal____86") //$NON-NLS-1$ + + stringVal + + Messages + .getString("ResultSet.___in_column__87") + + columnIndex + "(" //$NON-NLS-1$ + + this.fields[columnIndex - 1] + ").", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + return val; + } + + return null; + + case Types.REAL: + return new Float(getFloat(columnIndex)); + + case Types.FLOAT: + + if (!this.connection.getRunningCTS13()) { + return new Double(getFloat(columnIndex)); + } else { + return new Float(getFloat(columnIndex)); // NB - bug in JDBC + // compliance test, + // according + // to JDBC spec, FLOAT type should return DOUBLE + // but causes ClassCastException in CTS :( + } + case Types.DOUBLE: + return new Double(getDouble(columnIndex)); + + case Types.CHAR: + case Types.VARCHAR: + return getString(columnIndex); + case Types.LONGVARCHAR: + return getStringForClob(columnIndex); + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + return getBytes(columnIndex); + + case Types.DATE: + if (field.getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR + && !this.connection.getYearIsDateType()) { + return new Short(getShort(columnIndex)); + } + + return getDate(columnIndex); + + case Types.TIME: + return getTime(columnIndex); + + case Types.TIMESTAMP: + return getTimestamp(columnIndex); + + default: + return getString(columnIndex); + } + } + + protected Object getObjectStoredProc(int i, java.util.Map map, + int desiredSqlType) throws SQLException { + return getObjectStoredProc(i, desiredSqlType); + } + + protected Object getObjectStoredProc(String columnName, int desiredSqlType) + throws SQLException { + return getObjectStoredProc(findColumn(columnName), desiredSqlType); + } + + protected Object getObjectStoredProc(String colName, java.util.Map map, + int desiredSqlType) throws SQLException { + return getObjectStoredProc(findColumn(colName), map, desiredSqlType); + } + + /** + * JDBC 2.0 Get a REF(<structured-type>) column. + * + * @param i + * the first column is 1, the second is 2, ... + * + * @return an object representing data of an SQL REF type + * + * @throws SQLException + * as this is not implemented + * @throws NotImplemented + * DOCUMENT ME! + */ + public java.sql.Ref getRef(int i) throws SQLException { + checkColumnBounds(i); + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Get a REF(<structured-type>) column. + * + * @param colName + * the column name + * + * @return an object representing data of an SQL REF type + * + * @throws SQLException + * as this method is not implemented. + * @throws NotImplemented + * DOCUMENT ME! + */ + public java.sql.Ref getRef(String colName) throws SQLException { + return getRef(findColumn(colName)); + } + + /** + * JDBC 2.0 + * + *

+ * Determine the current row number. The first row is number 1, the second + * number 2, etc. + *

+ * + * @return the current row number, else return 0 if there is no current row + * + * @exception SQLException + * if a database-access error occurs. + */ + public int getRow() throws SQLException { + checkClosed(); + + int currentRowNumber = this.rowData.getCurrentRowNumber(); + int row = 0; + + // Non-dynamic result sets can be interrogated + // for this information + if (!this.rowData.isDynamic()) { + if ((currentRowNumber < 0) || this.rowData.isAfterLast() + || this.rowData.isEmpty()) { + row = 0; + } else { + row = currentRowNumber + 1; + } + } else { + // dynamic (streaming) can not + row = currentRowNumber + 1; + } + + return row; + } + + /** + * Returns the server info (if any), or null if none. + * + * @return server info created for this ResultSet + */ + protected String getServerInfo() { + return this.serverInfo; + } + + private long getNumericRepresentationOfSQLBitType(int columnIndex) throws SQLException { + + if (this.fields[columnIndex - 1].isSingleBit() || + ((byte[])this.thisRow[columnIndex - 1]).length == 1) { + return ((byte[])this.thisRow[columnIndex - 1])[0]; + } + + + byte[] asBytes = (byte[])this.thisRow[columnIndex - 1]; + + + int shift = 0; + + long[] steps = new long[asBytes.length]; + + for (int i = asBytes.length - 1; i >= 0; i--) { + steps[i] = (long)(asBytes[i] & 0xff) << shift; + shift += 8; + } + + long valueAsLong = 0; + + for (int i = 0; i < asBytes.length; i++) { + valueAsLong |= steps[i]; + } + + return valueAsLong; + } + + /** + * Get the value of a column in the current row as a Java short. + * + * @param columnIndex + * the first column is 1, the second is 2,... + * + * @return the column value; 0 if SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public short getShort(int columnIndex) throws SQLException { + if (!this.isBinaryEncoded) { + checkRowPos(); + + if (this.connection.getUseFastIntParsing()) { + + checkColumnBounds(columnIndex); + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + } else { + this.wasNullFlag = false; + } + + if (this.wasNullFlag) { + return 0; + } + + byte[] shortAsBytes = (byte[]) this.thisRow[columnIndex - 1]; + + if (shortAsBytes.length == 0) { + return (short) convertToZeroWithEmptyCheck(); + } + + boolean needsFullParse = false; + + for (int i = 0; i < shortAsBytes.length; i++) { + if (((char) shortAsBytes[i] == 'e') + || ((char) shortAsBytes[i] == 'E')) { + needsFullParse = true; + + break; + } + } + + if (!needsFullParse) { + try { + return parseShortWithOverflowCheck(columnIndex, + shortAsBytes, null); + } catch (NumberFormatException nfe) { + try { + // To do: Warn of over/underflow??? + return parseShortAsDouble(columnIndex, new String( + shortAsBytes)); + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex); + + if (this.connection.getJdbcCompliantTruncationForReads() && + (valueAsLong < Short.MIN_VALUE + || valueAsLong > Short.MAX_VALUE)) { + throwRangeException(String.valueOf(valueAsLong), columnIndex, + Types.SMALLINT); + } + + return (short)valueAsLong; + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getShort()_-____96") + + new String(shortAsBytes) //$NON-NLS-1$ + + "'", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + + String val = null; + + try { + val = getString(columnIndex); + + if ((val != null)) { + + if (val.length() == 0) { + return (short) convertToZeroWithEmptyCheck(); + } + + if ((val.indexOf("e") == -1) && (val.indexOf("E") == -1) + && (val.indexOf(".") == -1)) { + return parseShortWithOverflowCheck(columnIndex, null, + val); + } + + // Convert floating point + return parseShortAsDouble(columnIndex, val); + } + + return 0; // for NULL + } catch (NumberFormatException nfe) { + try { + return parseShortAsDouble(columnIndex, val); + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + long valueAsLong = getNumericRepresentationOfSQLBitType(columnIndex); + + if (this.connection.getJdbcCompliantTruncationForReads() && + (valueAsLong < Short.MIN_VALUE + || valueAsLong > Short.MAX_VALUE)) { + throwRangeException(String.valueOf(valueAsLong), columnIndex, + Types.SMALLINT); + } + + return (short)valueAsLong; + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getShort()_-____96") + + val //$NON-NLS-1$ + + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + return getNativeShort(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public short getShort(String columnName) throws SQLException { + return getShort(findColumn(columnName)); + } + + private final short getShortFromString(String val, int columnIndex) + throws SQLException { + try { + if ((val != null)) { + + if (val.length() == 0) { + return (short) convertToZeroWithEmptyCheck(); + } + + if ((val.indexOf("e") == -1) && (val.indexOf("E") == -1) + && (val.indexOf(".") == -1)) { + return parseShortWithOverflowCheck(columnIndex, null, val); + } + + // Convert floating point + return parseShortAsDouble(columnIndex, val); + } + + return 0; // for NULL + } catch (NumberFormatException nfe) { + try { + return parseShortAsDouble(columnIndex, val); + } catch (NumberFormatException newNfe) { + ; // ignore, it's not a number + } + + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Invalid_value_for_getShort()_-____217") + + val //$NON-NLS-1$ + + Messages.getString("ResultSet.___in_column__218") + + columnIndex, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * JDBC 2.0 Return the Statement that produced the ResultSet. + * + * @return the Statment that produced the result set, or null if the result + * was produced some other way. + * + * @exception SQLException + * if a database-access error occurs + */ + public java.sql.Statement getStatement() throws SQLException { + if (this.isClosed && !this.retainOwningStatement) { + throw SQLError.createSQLException( + "Operation not allowed on closed ResultSet. Statements " + + "can be retained over result set closure by setting the connection property " + + "\"retainStatementAfterResultSetClose\" to \"true\".", + SQLError.SQL_STATE_GENERAL_ERROR); + + } + + if (this.wrapperStatement != null) { + return this.wrapperStatement; + } + + return this.owningStatement; + } + + /** + * Get the value of a column in the current row as a Java String + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return the column value, null for SQL NULL + * + * @exception SQLException + * if a database access error occurs + */ + public String getString(int columnIndex) throws SQLException { + String stringVal = getStringInternal(columnIndex, true); + + if (stringVal != null && this.padCharsWithSpace) { + Field f = this.fields[columnIndex - 1]; + + if (f.getMysqlType() == MysqlDefs.FIELD_TYPE_STRING ) { + int fieldLength = (int)f.getLength() /* safe, bytes in a CHAR <= 1024 */ / + f.getMaxBytesPerCharacter(); /* safe, this will never be 0 */ + + int currentLength = stringVal.length(); + + if (currentLength < fieldLength) { + StringBuffer paddedBuf = new StringBuffer(fieldLength); + paddedBuf.append(stringVal); + + int difference = fieldLength - currentLength; + + paddedBuf.append(EMPTY_SPACE, 0, difference); + + stringVal = paddedBuf.toString(); + } + } + } + + return stringVal; + } + + /** + * The following routines simply convert the columnName into a columnIndex + * and then call the appropriate routine above. + * + * @param columnName + * is the SQL name of the column + * + * @return the column value + * + * @exception SQLException + * if a database access error occurs + */ + public String getString(String columnName) throws SQLException { + return getString(findColumn(columnName)); + } + + private String getStringForClob(int columnIndex) throws SQLException { + String asString = null; + + String forcedEncoding = + this.connection.getClobCharacterEncoding(); + + if (forcedEncoding == null) { + if (!this.isBinaryEncoded) { + asString = getString(columnIndex); + } else { + asString = getNativeString(columnIndex); + } + } else { + try { + byte[] asBytes = null; + + if (!this.isBinaryEncoded) { + asBytes = getBytes(columnIndex); + } else { + asBytes = getNativeBytes(columnIndex, true); + } + + if (asBytes != null) { + asString = new String(asBytes, forcedEncoding); + } + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException("Unsupported character encoding " + + forcedEncoding, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + return asString; + } + + protected String getStringInternal(int columnIndex, boolean checkDateTypes) + throws SQLException { + if (!this.isBinaryEncoded) { + checkRowPos(); + checkColumnBounds(columnIndex); + + if (this.fields == null) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Query_generated_no_fields_for_ResultSet_99"), //$NON-NLS-1$ + SQLError.SQL_STATE_INVALID_COLUMN_NUMBER); + } + + if (this.thisRow[columnIndex - 1] == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + String stringVal = null; + columnIndex--; // JDBC is 1-based, Java is not !? + + if (this.fields[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_BIT) { + if (this.fields[columnIndex].isSingleBit()) { + byte[] asBytes = (byte[])this.thisRow[columnIndex]; + + if (asBytes.length == 0) { + return String.valueOf(convertToZeroWithEmptyCheck()); + } + + return String.valueOf(asBytes[0]); + } + + return String.valueOf(getNumericRepresentationOfSQLBitType(columnIndex + 1)); + } + + String encoding = this.fields[columnIndex].getCharacterSet(); + + if ((this.connection != null) && this.connection.getUseUnicode()) { + try { + if (encoding == null) { + stringVal = new String( + (byte[]) this.thisRow[columnIndex]); + } else { + SingleByteCharsetConverter converter = this.connection + .getCharsetConverter(encoding); + + if (converter != null) { + stringVal = converter + .toString((byte[]) this.thisRow[columnIndex]); + } else { + stringVal = new String( + (byte[]) this.thisRow[columnIndex], + encoding); + } + } + } catch (java.io.UnsupportedEncodingException E) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Unsupported_character_encoding____101") //$NON-NLS-1$ + + encoding + "'.", "0S100"); + } + } else { + stringVal = StringUtils + .toAsciiString((byte[]) this.thisRow[columnIndex]); + } + + // + // Special handling for YEAR type from mysql, some people + // want it as a DATE, others want to treat it as a SHORT + // + + if (this.fields[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) { + if (!this.connection.getYearIsDateType()) { + return stringVal; + } + + Date dt = getDateFromString(stringVal, columnIndex + 1); + + if (dt == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + return dt.toString(); + } + + // Handles timezone conversion and zero-date behavior + + if (checkDateTypes && !this.connection.getNoDatetimeStringSync()) { + switch (this.fields[columnIndex].getSQLType()) { + case Types.TIME: + Time tm = getTimeFromString(stringVal, null, columnIndex + 1, + this.getDefaultTimeZone(), false); + + if (tm == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + return tm.toString(); + case Types.DATE: + + Date dt = getDateFromString(stringVal, columnIndex + 1); + + if (dt == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + return dt.toString(); + case Types.TIMESTAMP: + Timestamp ts = getTimestampFromString(columnIndex + 1, + null, stringVal, this.getDefaultTimeZone(), false); + + if (ts == null) { + this.wasNullFlag = true; + + return null; + } + + this.wasNullFlag = false; + + return ts.toString(); + default: + break; + } + } + + return stringVal; + } + + return getNativeString(columnIndex); + } + + /** + * Get the value of a column in the current row as a java.sql.Time object + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return the column value; null if SQL NULL + * + * @throws java.sql.SQLException + * if a database access error occurs + */ + public Time getTime(int columnIndex) throws java.sql.SQLException { + return getTimeInternal(columnIndex, null, this.getDefaultTimeZone(), false); + } + + /** + * Get the value of a column in the current row as a java.sql.Time object. + * Use the calendar to construct an appropriate millisecond value for the + * Time, if the underlying database doesn't store timezone information. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param cal + * the calendar to use in constructing the time + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.Time getTime(int columnIndex, Calendar cal) + throws SQLException { + return getTimeInternal(columnIndex, cal, cal.getTimeZone(), true); + } + + /** + * Get the value of a column in the current row as a java.sql.Time object. + * + * @param columnName + * is the SQL name of the column + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @throws java.sql.SQLException + * if a database-access error occurs. + */ + public Time getTime(String columnName) throws java.sql.SQLException { + return getTime(findColumn(columnName)); + } + + /** + * Get the value of a column in the current row as a java.sql.Time object. + * Use the calendar to construct an appropriate millisecond value for the + * Time, if the underlying database doesn't store timezone information. + * + * @param columnName + * is the SQL name of the column + * @param cal + * the calendar to use in constructing the time + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.Time getTime(String columnName, Calendar cal) + throws SQLException { + return getTime(findColumn(columnName), cal); + } + + private Time getTimeFromString(String timeAsString, Calendar targetCalendar, + int columnIndex, + TimeZone tz, + boolean rollForward) throws SQLException { + int hr = 0; + int min = 0; + int sec = 0; + + try { + + if (timeAsString == null) { + this.wasNullFlag = true; + + return null; + } + + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + timeAsString = timeAsString.trim(); + + if (timeAsString.equals("0") + || timeAsString.equals("0000-00-00") + || timeAsString.equals("0000-00-00 00:00:00") + || timeAsString.equals("00000000000000")) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '" + timeAsString + + "' can not be represented as java.sql.Time", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + // We're left with the case of 'round' to a time Java _can_ + // represent, which is '00:00:00' + return fastTimeCreate(null, 0, 0, 0); + } + + this.wasNullFlag = false; + + Field timeColField = this.fields[columnIndex - 1]; + + if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) { + // It's a timestamp + int length = timeAsString.length(); + + switch (length) { + case 19: { // YYYY-MM-DD hh:mm:ss + + hr = Integer.parseInt(timeAsString.substring(length - 8, + length - 6)); + min = Integer.parseInt(timeAsString.substring(length - 5, + length - 3)); + sec = Integer.parseInt(timeAsString.substring(length - 2, + length)); + } + + break; + case 14: + case 12: { + hr = Integer.parseInt(timeAsString.substring(length - 6, + length - 4)); + min = Integer.parseInt(timeAsString.substring(length - 4, + length - 2)); + sec = Integer.parseInt(timeAsString.substring(length - 2, + length)); + } + + break; + + case 10: { + hr = Integer.parseInt(timeAsString.substring(6, 8)); + min = Integer.parseInt(timeAsString.substring(8, 10)); + sec = 0; + } + + break; + + default: + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Timestamp_too_small_to_convert_to_Time_value_in_column__257") //$NON-NLS-1$ + + columnIndex + + "(" + + this.fields[columnIndex - 1] + ").", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } /* endswitch */ + + SQLWarning precisionLost = new SQLWarning( + Messages + .getString("ResultSet.Precision_lost_converting_TIMESTAMP_to_Time_with_getTime()_on_column__261") //$NON-NLS-1$ + + columnIndex + + "(" + + this.fields[columnIndex - 1] + ")."); + + if (this.warningChain == null) { + this.warningChain = precisionLost; + } else { + this.warningChain.setNextWarning(precisionLost); + } + } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATETIME) { + hr = Integer.parseInt(timeAsString.substring(11, 13)); + min = Integer.parseInt(timeAsString.substring(14, 16)); + sec = Integer.parseInt(timeAsString.substring(17, 19)); + + SQLWarning precisionLost = new SQLWarning( + Messages + .getString("ResultSet.Precision_lost_converting_DATETIME_to_Time_with_getTime()_on_column__264") //$NON-NLS-1$ + + columnIndex + + "(" + + this.fields[columnIndex - 1] + ")."); + + if (this.warningChain == null) { + this.warningChain = precisionLost; + } else { + this.warningChain.setNextWarning(precisionLost); + } + } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) { + return fastTimeCreate(null, 0, 0, 0); // midnight on the given + // date + } else { + // convert a String to a Time + if ((timeAsString.length() != 5) + && (timeAsString.length() != 8)) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Bad_format_for_Time____267") //$NON-NLS-1$ + + timeAsString + + Messages.getString("ResultSet.___in_column__268") + + columnIndex, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + hr = Integer.parseInt(timeAsString.substring(0, 2)); + min = Integer.parseInt(timeAsString.substring(3, 5)); + sec = (timeAsString.length() == 5) ? 0 : Integer + .parseInt(timeAsString.substring(6)); + } + + Calendar sessionCalendar = this.getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimeCreate( + sessionCalendar, hr, min, sec), + this.connection.getServerTimezoneTZ(), + tz, rollForward); + } + } catch (Exception ex) { + throw SQLError.createSQLException(ex.toString(), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + private Time getTimeFromBytes(byte[] timeAsBytes, Calendar targetCalendar, + int columnIndex, + TimeZone tz, + boolean rollForward) throws SQLException { + checkColumnBounds(columnIndex); + + int hr = 0; + int min = 0; + int sec = 0; + + try { + + if (timeAsBytes == null) { + this.wasNullFlag = true; + + return null; + } + + int length = timeAsBytes.length; + + boolean allZeroTime = true; + boolean onlyTimePresent = StringUtils.indexOf(timeAsBytes, ':') != -1; + + for (int i = 0; i < length; i++) { + byte b = timeAsBytes[i]; + + if (b == ' ' || b == '-' || b == '/') { + onlyTimePresent = false; + } + + if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' + && b != '.') { + allZeroTime = false; + + break; + } + } + + if (!onlyTimePresent && allZeroTime) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '" + new String(timeAsBytes) + + "' can not be represented as java.sql.Time", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + // We're left with the case of 'round' to a time Java _can_ + // represent, which is '00:00:00' + return fastTimeCreate(null, 0, 0, 0); + } + + this.wasNullFlag = false; + + Field timeColField = this.fields[columnIndex - 1]; + + if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) { + + switch (length) { + case 19: { // YYYY-MM-DD hh:mm:ss + + hr = StringUtils.getInt(timeAsBytes, length - 8, + length - 6); + min = StringUtils.getInt(timeAsBytes, length - 5, + length - 3); + sec = StringUtils.getInt(timeAsBytes, length - 2, + length); + } + + break; + case 14: + case 12: { + hr = StringUtils.getInt(timeAsBytes, length - 6, + length - 4); + min = StringUtils.getInt(timeAsBytes, length - 4, + length - 2); + sec = StringUtils.getInt(timeAsBytes, length - 2, + length); + } + + break; + + case 10: { + hr = StringUtils.getInt(timeAsBytes, 6, 8); + min = StringUtils.getInt(timeAsBytes, 8, 10); + sec = 0; + } + + break; + + default: + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Timestamp_too_small_to_convert_to_Time_value_in_column__257") //$NON-NLS-1$ + + columnIndex + + "(" + + this.fields[columnIndex - 1] + ").", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } /* endswitch */ + + SQLWarning precisionLost = new SQLWarning( + Messages + .getString("ResultSet.Precision_lost_converting_TIMESTAMP_to_Time_with_getTime()_on_column__261") //$NON-NLS-1$ + + columnIndex + + "(" + + this.fields[columnIndex - 1] + ")."); + + if (this.warningChain == null) { + this.warningChain = precisionLost; + } else { + this.warningChain.setNextWarning(precisionLost); + } + } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATETIME) { + hr = StringUtils.getInt(timeAsBytes, 11, 13); + min = StringUtils.getInt(timeAsBytes, 14, 16); + sec = StringUtils.getInt(timeAsBytes, 17, 19); + + SQLWarning precisionLost = new SQLWarning( + Messages + .getString("ResultSet.Precision_lost_converting_DATETIME_to_Time_with_getTime()_on_column__264") //$NON-NLS-1$ + + columnIndex + + "(" + + this.fields[columnIndex - 1] + ")."); + + if (this.warningChain == null) { + this.warningChain = precisionLost; + } else { + this.warningChain.setNextWarning(precisionLost); + } + } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) { + return fastTimeCreate(null, 0, 0, 0); // midnight on the given + // date + } else { + // convert a String to a Time + if ((length != 5) + && (length != 8)) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Bad_format_for_Time____267") //$NON-NLS-1$ + + new String(timeAsBytes) + + Messages.getString("ResultSet.___in_column__268") + + columnIndex, SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + hr = StringUtils.getInt(timeAsBytes, 0, 2); + min = StringUtils.getInt(timeAsBytes, 3, 5); + sec = (length == 5) ? 0 : StringUtils.getInt(timeAsBytes, 6, 8); + } + + Calendar sessionCalendar = this.getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimeCreate( + sessionCalendar, hr, min, sec), + this.connection.getServerTimezoneTZ(), + tz, rollForward); + } + } catch (Exception ex) { + throw SQLError.createSQLException(ex.toString(), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + /** + * Get the value of a column in the current row as a java.sql.Time object in + * the given timezone + * + * @param columnIndex + * the first column is 1, the second is 2... + * @param tz + * the Timezone to use + * + * @return the column value; null if SQL NULL + * + * @exception java.sql.SQLException + * if a database access error occurs + */ + private Time getTimeInternal(int columnIndex, Calendar targetCalendar, + TimeZone tz, + boolean rollForward) throws java.sql.SQLException { + if (this.isBinaryEncoded) { + return getNativeTime(columnIndex, targetCalendar, tz, rollForward); + } + + if (!this.useFastDateParsing) { + String timeAsString = getStringInternal(columnIndex, false); + + return getTimeFromString(timeAsString, targetCalendar, + columnIndex, tz, rollForward); + } else { + checkColumnBounds(columnIndex); + + return getTimeFromBytes(((byte[][])this.thisRow)[columnIndex - 1], targetCalendar, + columnIndex, tz, rollForward); + } + } + + /** + * Get the value of a column in the current row as a java.sql.Timestamp + * object + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return the column value; null if SQL NULL + * + * @exception java.sql.SQLException + * if a database access error occurs + */ + public Timestamp getTimestamp(int columnIndex) throws java.sql.SQLException { + checkColumnBounds(columnIndex); + + return getTimestampInternal(columnIndex, null, this.getDefaultTimeZone(), + false); + } + + /** + * Get the value of a column in the current row as a java.sql.Timestamp + * object. Use the calendar to construct an appropriate millisecond value + * for the Timestamp, if the underlying database doesn't store timezone + * information. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param cal + * the calendar to use in constructing the timestamp + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.Timestamp getTimestamp(int columnIndex, Calendar cal) + throws SQLException { + return getTimestampInternal(columnIndex, cal, cal.getTimeZone(), true); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws java.sql.SQLException + * DOCUMENT ME! + */ + public Timestamp getTimestamp(String columnName) + throws java.sql.SQLException { + return getTimestamp(findColumn(columnName)); + } + + /** + * Get the value of a column in the current row as a java.sql.Timestamp + * object. Use the calendar to construct an appropriate millisecond value + * for the Timestamp, if the underlying database doesn't store timezone + * information. + * + * @param columnName + * is the SQL name of the column + * @param cal + * the calendar to use in constructing the timestamp + * + * @return the column value; if the value is SQL NULL, the result is null + * + * @exception SQLException + * if a database-access error occurs. + */ + public java.sql.Timestamp getTimestamp(String columnName, Calendar cal) + throws SQLException { + return getTimestamp(findColumn(columnName), cal); + } + + private Timestamp getTimestampFromString(int columnIndex, + Calendar targetCalendar, + String timestampValue, TimeZone tz, boolean rollForward) + throws java.sql.SQLException { + try { + this.wasNullFlag = false; + + if (timestampValue == null) { + this.wasNullFlag = true; + + return null; + } + + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + timestampValue = timestampValue.trim(); + + int length = timestampValue.length(); + + Calendar sessionCalendar = this.connection.getUseJDBCCompliantTimezoneShift() ? + this.connection.getUtcCalendar() : + getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + if ((length > 0) + && (timestampValue.charAt(0) == '0') + && (timestampValue.equals("0000-00-00") + || timestampValue.equals("0000-00-00 00:00:00") + || timestampValue.equals("00000000000000") || timestampValue + .equals("0"))) { + + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '" + timestampValue + + "' can not be represented as java.sql.Timestamp", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + // We're left with the case of 'round' to a date Java _can_ + // represent, which is '0001-01-01'. + return fastTimestampCreate(null, 1, 1, 1, 0, 0, 0, 0); + + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) { + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, + Integer + .parseInt(timestampValue.substring(0, 4)), 1, + 1, 0, 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + + } else { + if (timestampValue.endsWith(".")) { + timestampValue = timestampValue.substring(0, timestampValue + .length() - 1); + } + + // Convert from TIMESTAMP or DATE + switch (length) { + case 26: + case 25: + case 24: + case 23: + case 22: + case 21: + case 20: + case 19: { + int year = Integer.parseInt(timestampValue.substring(0, 4)); + int month = Integer + .parseInt(timestampValue.substring(5, 7)); + int day = Integer.parseInt(timestampValue.substring(8, 10)); + int hour = Integer.parseInt(timestampValue + .substring(11, 13)); + int minutes = Integer.parseInt(timestampValue.substring(14, + 16)); + int seconds = Integer.parseInt(timestampValue.substring(17, + 19)); + + int nanos = 0; + + if (length > 19) { + int decimalIndex = timestampValue.lastIndexOf('.'); + + if (decimalIndex != -1) { + if ((decimalIndex + 2) <= timestampValue.length()) { + nanos = Integer.parseInt(timestampValue + .substring(decimalIndex + 1)); + } else { + throw new IllegalArgumentException(); // re-thrown + // further + // down + // with + // a + // much better error message + } + } + } + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year, month, day, hour, + minutes, seconds, nanos), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 14: { + int year = Integer.parseInt(timestampValue.substring(0, 4)); + int month = Integer + .parseInt(timestampValue.substring(4, 6)); + int day = Integer.parseInt(timestampValue.substring(6, 8)); + int hour = Integer + .parseInt(timestampValue.substring(8, 10)); + int minutes = Integer.parseInt(timestampValue.substring(10, + 12)); + int seconds = Integer.parseInt(timestampValue.substring(12, + 14)); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year, month, day, hour, + minutes, seconds, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 12: { + int year = Integer.parseInt(timestampValue.substring(0, 2)); + + if (year <= 69) { + year = (year + 100); + } + + int month = Integer + .parseInt(timestampValue.substring(2, 4)); + int day = Integer.parseInt(timestampValue.substring(4, 6)); + int hour = Integer.parseInt(timestampValue.substring(6, 8)); + int minutes = Integer.parseInt(timestampValue.substring(8, + 10)); + int seconds = Integer.parseInt(timestampValue.substring(10, + 12)); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year + 1900, month, day, + hour, minutes, seconds, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 10: { + int year; + int month; + int day; + int hour; + int minutes; + + if ((this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) + || (timestampValue.indexOf("-") != -1)) { + year = Integer.parseInt(timestampValue.substring(0, 4)); + month = Integer + .parseInt(timestampValue.substring(5, 7)); + day = Integer.parseInt(timestampValue.substring(8, 10)); + hour = 0; + minutes = 0; + } else { + year = Integer.parseInt(timestampValue.substring(0, 2)); + + if (year <= 69) { + year = (year + 100); + } + + month = Integer + .parseInt(timestampValue.substring(2, 4)); + day = Integer.parseInt(timestampValue.substring(4, 6)); + hour = Integer.parseInt(timestampValue.substring(6, 8)); + minutes = Integer.parseInt(timestampValue.substring(8, + 10)); + + year += 1900; // two-digit year + } + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year, month, day, hour, + minutes, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 8: { + if (timestampValue.indexOf(":") != -1) { + int hour = Integer.parseInt(timestampValue.substring(0, + 2)); + int minutes = Integer.parseInt(timestampValue + .substring(3, 5)); + int seconds = Integer.parseInt(timestampValue + .substring(6, 8)); + + return TimeUtil + .changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, 1970, 1, 1, + hour, minutes, seconds, 0), + this.connection.getServerTimezoneTZ(), + tz, rollForward); + + } + + int year = Integer.parseInt(timestampValue.substring(0, 4)); + int month = Integer + .parseInt(timestampValue.substring(4, 6)); + int day = Integer.parseInt(timestampValue.substring(6, 8)); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year - 1900, month - 1, + day, 0, 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 6: { + int year = Integer.parseInt(timestampValue.substring(0, 2)); + + if (year <= 69) { + year = (year + 100); + } + + int month = Integer + .parseInt(timestampValue.substring(2, 4)); + int day = Integer.parseInt(timestampValue.substring(4, 6)); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year + 1900, month, day, + 0, 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 4: { + int year = Integer.parseInt(timestampValue.substring(0, 2)); + + if (year <= 69) { + year = (year + 100); + } + + int month = Integer + .parseInt(timestampValue.substring(2, 4)); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year + 1900, month, 1, 0, + 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 2: { + int year = Integer.parseInt(timestampValue.substring(0, 2)); + + if (year <= 69) { + year = (year + 100); + } + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(null, year + 1900, 1, 1, 0, 0, + 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + default: + throw new java.sql.SQLException( + "Bad format for Timestamp '" + timestampValue + + "' in column " + columnIndex + ".", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + } catch (Exception e) { + throw new java.sql.SQLException("Cannot convert value '" + + timestampValue + "' from column " + columnIndex + + " to TIMESTAMP.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + } + + private Timestamp getTimestampFromBytes(int columnIndex, + Calendar targetCalendar, + byte[] timestampAsBytes, TimeZone tz, boolean rollForward) + throws java.sql.SQLException { + checkColumnBounds(columnIndex); + + try { + this.wasNullFlag = false; + + if (timestampAsBytes == null) { + this.wasNullFlag = true; + + return null; + } + + int length = timestampAsBytes.length; + + Calendar sessionCalendar = this.connection.getUseJDBCCompliantTimezoneShift() ? + this.connection.getUtcCalendar() : + getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + boolean allZeroTimestamp = true; + + boolean onlyTimePresent = StringUtils.indexOf(timestampAsBytes, ':') != -1; + + for (int i = 0; i < length; i++) { + byte b = timestampAsBytes[i]; + + if (b == ' ' || b == '-' || b == '/') { + onlyTimePresent = false; + } + + if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' + && b != '.') { + allZeroTimestamp = false; + + break; + } + } + + if (!onlyTimePresent && allZeroTimestamp) { + + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw SQLError.createSQLException("Value '" + timestampAsBytes + + "' can not be represented as java.sql.Timestamp", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + // We're left with the case of 'round' to a date Java _can_ + // represent, which is '0001-01-01'. + return fastTimestampCreate(null, 1, 1, 1, 0, 0, 0, 0); + + } else if (this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) { + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, + StringUtils.getInt(timestampAsBytes, 0, 4), 1, + 1, 0, 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + + } else { + if (timestampAsBytes[length - 1] == '.') { + length--; + } + + // Convert from TIMESTAMP or DATE + switch (length) { + case 26: + case 25: + case 24: + case 23: + case 22: + case 21: + case 20: + case 19: { + int year = StringUtils.getInt(timestampAsBytes, 0, 4); + int month = StringUtils.getInt(timestampAsBytes, 5, 7); + int day = StringUtils.getInt(timestampAsBytes, 8, 10); + int hour = StringUtils.getInt(timestampAsBytes, 11, 13); + int minutes = StringUtils.getInt(timestampAsBytes, 14, 16); + int seconds = StringUtils.getInt(timestampAsBytes, 17, 19); + + int nanos = 0; + + if (length > 19) { + int decimalIndex = StringUtils.lastIndexOf(timestampAsBytes, '.'); + + if (decimalIndex != -1) { + if ((decimalIndex + 2) <= length) { + nanos = StringUtils.getInt(timestampAsBytes, decimalIndex + 1, length); + } else { + throw new IllegalArgumentException(); // re-thrown + // further + // down + // with + // a + // much better error message + } + } + } + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year, month, day, hour, + minutes, seconds, nanos), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 14: { + int year = StringUtils.getInt(timestampAsBytes, 0, 4); + int month = StringUtils.getInt(timestampAsBytes, 4, 6); + int day = StringUtils.getInt(timestampAsBytes, 6, 8); + int hour = StringUtils.getInt(timestampAsBytes, 8, 10); + int minutes = StringUtils.getInt(timestampAsBytes, 10, 12); + int seconds = StringUtils.getInt(timestampAsBytes, 12, 14); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year, month, day, hour, + minutes, seconds, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 12: { + int year = StringUtils.getInt(timestampAsBytes, 0, 2); + + if (year <= 69) { + year = (year + 100); + } + + int month = StringUtils.getInt(timestampAsBytes, 2, 4); + int day = StringUtils.getInt(timestampAsBytes, 4, 6); + int hour = StringUtils.getInt(timestampAsBytes, 6, 8); + int minutes = StringUtils.getInt(timestampAsBytes, 8, 10); + int seconds = StringUtils.getInt(timestampAsBytes, 10, 12); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year + 1900, month, day, + hour, minutes, seconds, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 10: { + int year; + int month; + int day; + int hour; + int minutes; + + if ((this.fields[columnIndex - 1].getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) + || (StringUtils.indexOf(timestampAsBytes, '-') != -1)) { + year = StringUtils.getInt(timestampAsBytes, 0, 4); + month = StringUtils.getInt(timestampAsBytes, 5, 7); + day = StringUtils.getInt(timestampAsBytes, 8, 10); + hour = 0; + minutes = 0; + } else { + year = StringUtils.getInt(timestampAsBytes, 0, 2); + + if (year <= 69) { + year = (year + 100); + } + + month = StringUtils.getInt(timestampAsBytes, 2, 4); + day = StringUtils.getInt(timestampAsBytes, 4, 6); + hour = StringUtils.getInt(timestampAsBytes, 6, 8); + minutes = StringUtils.getInt(timestampAsBytes, 8, 10); + + year += 1900; // two-digit year + } + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year, month, day, hour, + minutes, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 8: { + if (StringUtils.indexOf(timestampAsBytes, ':') != -1) { + int hour = StringUtils.getInt(timestampAsBytes, 0, 2); + int minutes = StringUtils.getInt(timestampAsBytes, 3, 5); + int seconds = StringUtils.getInt(timestampAsBytes, 6, 8); + + return TimeUtil + .changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, 1970, 1, 1, + hour, minutes, seconds, 0), + this.connection.getServerTimezoneTZ(), + tz, rollForward); + + } + + int year = StringUtils.getInt(timestampAsBytes, 0, 4); + int month = StringUtils.getInt(timestampAsBytes, 4, 6); + int day = StringUtils.getInt(timestampAsBytes, 6, 8); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year - 1900, month - 1, + day, 0, 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 6: { + int year = StringUtils.getInt(timestampAsBytes, 0, 2); + + if (year <= 69) { + year = (year + 100); + } + + int month = StringUtils.getInt(timestampAsBytes, 2, 4); + int day = StringUtils.getInt(timestampAsBytes, 4, 6); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year + 1900, month, day, + 0, 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 4: { + int year = StringUtils.getInt(timestampAsBytes, 0, 2); + + if (year <= 69) { + year = (year + 100); + } + + int month = StringUtils.getInt(timestampAsBytes, 2, 4); + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(sessionCalendar, year + 1900, month, 1, 0, + 0, 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + case 2: { + int year = StringUtils.getInt(timestampAsBytes, 0, 2); + + if (year <= 69) { + year = (year + 100); + } + + return TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + fastTimestampCreate(null, year + 1900, 1, 1, 0, 0, + 0, 0), this.connection + .getServerTimezoneTZ(), tz, rollForward); + } + + default: + throw new java.sql.SQLException( + "Bad format for Timestamp '" + new String(timestampAsBytes) + + "' in column " + columnIndex + ".", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + } catch (Exception e) { + throw new java.sql.SQLException("Cannot convert value '" + + new String(timestampAsBytes) + "' from column " + columnIndex + + " to TIMESTAMP.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + + /** + * Get the value of a column in the current row as a java.sql.Timestamp + * object in the given timezone + * + * @param columnIndex + * the first column is 1, the second is 2... + * @param tz + * the timezone to use + * + * @return the column value; null if SQL NULL + * + * @exception java.sql.SQLException + * if a database access error occurs + */ + private Timestamp getTimestampInternal(int columnIndex, Calendar targetCalendar, + TimeZone tz, + boolean rollForward) throws java.sql.SQLException { + if (this.isBinaryEncoded) { + return getNativeTimestamp(columnIndex, targetCalendar, tz, rollForward); + } + + + if (!this.useFastDateParsing) { + String timestampValue = getStringInternal(columnIndex, false); + + return getTimestampFromString(columnIndex, targetCalendar, + timestampValue, tz, + rollForward); + } else { + return getTimestampFromBytes(columnIndex, targetCalendar, + ((byte[][])this.thisRow)[columnIndex - 1], tz, + rollForward); + } + } + + /** + * JDBC 2.0 Return the type of this result set. The type is determined based + * on the statement that created the result set. + * + * @return TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, or + * TYPE_SCROLL_SENSITIVE + * + * @exception SQLException + * if a database-access error occurs + */ + public int getType() throws SQLException { + return this.resultSetType; + } + + /** + * A column value can also be retrieved as a stream of Unicode characters. + * We implement this as a binary stream. + * + * @param columnIndex + * the first column is 1, the second is 2... + * + * @return a Java InputStream that delivers the database column value as a + * stream of two byte Unicode characters. If the value is SQL NULL, + * then the result is null + * + * @exception SQLException + * if a database access error occurs + * + * @see getAsciiStream + * @see getBinaryStream + * @deprecated + */ + public InputStream getUnicodeStream(int columnIndex) throws SQLException { + if (!this.isBinaryEncoded) { + checkRowPos(); + + return getBinaryStream(columnIndex); + } + + return getNativeBinaryStream(columnIndex); + } + + /** + * DOCUMENT ME! + * + * @param columnName + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + * + * @deprecated + */ + public InputStream getUnicodeStream(String columnName) throws SQLException { + return getUnicodeStream(findColumn(columnName)); + } + + long getUpdateCount() { + return this.updateCount; + } + + long getUpdateID() { + return this.updateId; + } + + /** + * @see ResultSet#getURL(int) + */ + public URL getURL(int colIndex) throws SQLException { + String val = getString(colIndex); + + if (val == null) { + return null; + } + + try { + return new URL(val); + } catch (MalformedURLException mfe) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Malformed_URL____104") + + val + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * @see ResultSet#getURL(String) + */ + public URL getURL(String colName) throws SQLException { + String val = getString(colName); + + if (val == null) { + return null; + } + + try { + return new URL(val); + } catch (MalformedURLException mfe) { + throw SQLError.createSQLException(Messages + .getString("ResultSet.Malformed_URL____107") + + val + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * The first warning reported by calls on this ResultSet is returned. + * Subsequent ResultSet warnings will be chained to this + * java.sql.SQLWarning. + * + *

+ * The warning chain is automatically cleared each time a new row is read. + *

+ * + *

+ * Note: This warning chain only covers warnings caused by ResultSet + * methods. Any warnings caused by statement methods (such as reading OUT + * parameters) will be chained on the Statement object. + *

+ * + * @return the first java.sql.SQLWarning or null; + * + * @exception SQLException + * if a database access error occurs. + */ + public java.sql.SQLWarning getWarnings() throws SQLException { + return this.warningChain; + } + + /** + * JDBC 2.0 Insert the contents of the insert row into the result set and + * the database. Must be on the insert row when this method is called. + * + * @exception SQLException + * if a database-access error occurs, if called when not on + * the insert row, or if all non-nullable columns in the + * insert row have not been given a value + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void insertRow() throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is after the last row in the result set. + *

+ * + * @return true if after the last row, false otherwise. Returns false when + * the result set contains no rows. + * + * @exception SQLException + * if a database-access error occurs. + */ + public boolean isAfterLast() throws SQLException { + checkClosed(); + + boolean b = this.rowData.isAfterLast(); + + return b; + } + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is before the first row in the result set. + *

+ * + * @return true if before the first row, false otherwise. Returns false when + * the result set contains no rows. + * + * @exception SQLException + * if a database-access error occurs. + */ + public boolean isBeforeFirst() throws SQLException { + checkClosed(); + + return this.rowData.isBeforeFirst(); + } + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is on the first row of the result set. + *

+ * + * @return true if on the first row, false otherwise. + * + * @exception SQLException + * if a database-access error occurs. + */ + public boolean isFirst() throws SQLException { + checkClosed(); + + return this.rowData.isFirst(); + } + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is on the last row of the result set. Note: + * Calling isLast() may be expensive since the JDBC driver might need to + * fetch ahead one row in order to determine whether the current row is the + * last row in the result set. + *

+ * + * @return true if on the last row, false otherwise. + * + * @exception SQLException + * if a database-access error occurs. + */ + public boolean isLast() throws SQLException { + checkClosed(); + + return this.rowData.isLast(); + } + + /** + * @param string + * @param mysqlType + * @param s + */ + private void issueConversionViaParsingWarning(String methodName, + int columnIndex, Object value, Field fieldInfo, + int[] typesWithNoParseConversion) throws SQLException { + + StringBuffer originalQueryBuf = new StringBuffer(); + + if (this.owningStatement != null + && this.owningStatement instanceof com.mysql.jdbc.PreparedStatement) { + originalQueryBuf.append(Messages.getString("ResultSet.CostlyConversionCreatedFromQuery")); + originalQueryBuf + .append(((com.mysql.jdbc.PreparedStatement) this.owningStatement).originalSql); + originalQueryBuf.append("\n\n"); + } else { + originalQueryBuf.append("."); + } + + StringBuffer convertibleTypesBuf = new StringBuffer(); + + for (int i = 0; i < typesWithNoParseConversion.length; i++) { + convertibleTypesBuf.append(MysqlDefs.typeToName(typesWithNoParseConversion[i])); + convertibleTypesBuf.append("\n"); + } + + String message = Messages.getString("ResultSet.CostlyConversion", new Object[] { + methodName, + new Integer(columnIndex + 1), + fieldInfo.getOriginalName(), + fieldInfo.getOriginalTableName(), + originalQueryBuf.toString(), + value != null ? value.getClass().getName() : ResultSetMetaData.getClassNameForJavaType( + fieldInfo.getSQLType(), + fieldInfo.isUnsigned(), + fieldInfo.getMysqlType(), + fieldInfo.isBinary() || fieldInfo.isBlob(), + fieldInfo.isOpaqueBinary()), + MysqlDefs.typeToName(fieldInfo.getMysqlType()), + convertibleTypesBuf.toString()}); + + this.eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_WARN, + "", (this.owningStatement == null) ? "N/A" + : this.owningStatement.currentCatalog, + this.connectionId, (this.owningStatement == null) ? (-1) + : this.owningStatement.getId(), this.resultId, System + .currentTimeMillis(), 0, Constants.MILLIS_I18N, null, + this.pointOfOrigin, message)); + + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the last row in the result set. + *

+ * + * @return true if on a valid row, false if no rows in the result set. + * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY. + */ + public boolean last() throws SQLException { + checkClosed(); + + if (this.rowData.size() == 0) { + return false; + } + + if (this.onInsertRow) { + this.onInsertRow = false; + } + + if (this.doingUpdates) { + this.doingUpdates = false; + } + + this.rowData.beforeLast(); + this.thisRow = this.rowData.next(); + + return true; + } + + // ///////////////////////////////////////// + // + // These number conversion routines save + // a ton of "new()s", especially for the heavily + // used getInt() and getDouble() methods + // + // ///////////////////////////////////////// + + /** + * JDBC 2.0 Move the cursor to the remembered cursor position, usually the + * current row. Has no effect unless the cursor is on the insert row. + * + * @exception SQLException + * if a database-access error occurs, or the result set is + * not updatable + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void moveToCurrentRow() throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Move to the insert row. The current cursor position is + * remembered while the cursor is positioned on the insert row. The insert + * row is a special row associated with an updatable result set. It is + * essentially a buffer where a new row may be constructed by calling the + * updateXXX() methods prior to inserting the row into the result set. Only + * the updateXXX(), getXXX(), and insertRow() methods may be called when the + * cursor is on the insert row. All of the columns in a result set must be + * given a value each time this method is called before calling insertRow(). + * UpdateXXX()must be called before getXXX() on a column. + * + * @exception SQLException + * if a database-access error occurs, or the result set is + * not updatable + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void moveToInsertRow() throws SQLException { + throw new NotUpdatable(); + } + + /** + * A ResultSet is initially positioned before its first row, the first call + * to next makes the first row the current row; the second call makes the + * second row the current row, etc. + * + *

+ * If an input stream from the previous row is open, it is implicitly + * closed. The ResultSet's warning chain is cleared when a new row is read + *

+ * + * @return true if the new current is valid; false if there are no more rows + * + * @exception SQLException + * if a database access error occurs + */ + public boolean next() throws SQLException { + checkClosed(); + + if (this.onInsertRow) { + this.onInsertRow = false; + } + + if (this.doingUpdates) { + this.doingUpdates = false; + } + + boolean b; + + if (!reallyResult()) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.ResultSet_is_from_UPDATE._No_Data_115"), + SQLError.SQL_STATE_GENERAL_ERROR); //$NON-NLS-1$ + } + + if (this.rowData.size() == 0) { + b = false; + } else { + if (!this.rowData.hasNext()) { + // force scroll past end + this.rowData.next(); + b = false; + } else { + clearWarnings(); + this.thisRow = this.rowData.next(); + b = true; + } + } + + return b; + } + + private int parseIntAsDouble(int columnIndex, String val) + throws NumberFormatException, SQLException { + if (val == null) { + return 0; + } + + double valueAsDouble = Double.parseDouble(val); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Integer.MIN_VALUE + || valueAsDouble > Integer.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), columnIndex, + Types.INTEGER); + } + } + + return (int) valueAsDouble; + } + + private int parseIntWithOverflowCheck(int columnIndex, byte[] valueAsBytes, + String valueAsString) throws NumberFormatException, SQLException { + + int intValue = 0; + + if (valueAsBytes == null && valueAsString == null) { + return 0; + } + + if (valueAsBytes != null) { + intValue = StringUtils.getInt(valueAsBytes); + } else { + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + valueAsString = valueAsString.trim(); + + intValue = Integer.parseInt(valueAsString); + } + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (intValue == Integer.MIN_VALUE || intValue == Integer.MAX_VALUE) { + long valueAsLong = Long + .parseLong(valueAsString == null ? new String( + valueAsBytes) : valueAsString); + + if (valueAsLong < Integer.MIN_VALUE + || valueAsLong > Integer.MAX_VALUE) { + throwRangeException(valueAsString == null ? new String( + valueAsBytes) : valueAsString, columnIndex, + Types.INTEGER); + } + } + } + + return intValue; + } + + private long parseLongAsDouble(int columnIndex, String val) + throws NumberFormatException, SQLException { + if (val == null) { + return 0; + } + + double valueAsDouble = Double.parseDouble(val); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Long.MIN_VALUE + || valueAsDouble > Long.MAX_VALUE) { + throwRangeException(val, columnIndex, Types.BIGINT); + } + } + + return (long) valueAsDouble; + } + + private long parseLongWithOverflowCheck(int columnIndex, + byte[] valueAsBytes, String valueAsString, boolean doCheck) + throws NumberFormatException, SQLException { + + long longValue = 0; + + if (valueAsBytes == null && valueAsString == null) { + return 0; + } + + if (valueAsBytes != null) { + longValue = StringUtils.getLong(valueAsBytes); + } else { + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + valueAsString = valueAsString.trim(); + + longValue = Long.parseLong(valueAsString); + } + + if (doCheck && this.connection.getJdbcCompliantTruncationForReads()) { + if (longValue == Long.MIN_VALUE + || longValue == Long.MAX_VALUE) { + double valueAsDouble = Double + .parseDouble(valueAsString == null ? new String( + valueAsBytes) : valueAsString); + + if (valueAsDouble < Long.MIN_VALUE + || valueAsDouble > Long.MAX_VALUE) { + throwRangeException(valueAsString == null ? new String( + valueAsBytes) : valueAsString, columnIndex, + Types.BIGINT); + } + } + } + + return longValue; + } + + private short parseShortAsDouble(int columnIndex, String val) + throws NumberFormatException, SQLException { + if (val == null) { + return 0; + } + + double valueAsDouble = Double.parseDouble(val); + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (valueAsDouble < Short.MIN_VALUE + || valueAsDouble > Short.MAX_VALUE) { + throwRangeException(String.valueOf(valueAsDouble), columnIndex, + Types.SMALLINT); + } + } + + return (short) valueAsDouble; + } + + private short parseShortWithOverflowCheck(int columnIndex, + byte[] valueAsBytes, String valueAsString) + throws NumberFormatException, SQLException { + + short shortValue = 0; + + if (valueAsBytes == null && valueAsString == null) { + return 0; + } + + if (valueAsBytes != null) { + shortValue = StringUtils.getShort(valueAsBytes); + } else { + // + // JDK-6 doesn't like trailing whitespace + // + // Note this isn't a performance issue, other + // than the iteration over the string, as String.trim() + // will return a new string only if whitespace is present + // + + valueAsString = valueAsString.trim(); + + shortValue = Short.parseShort(valueAsString); + } + + if (this.connection.getJdbcCompliantTruncationForReads()) { + if (shortValue == Short.MIN_VALUE || shortValue == Short.MAX_VALUE) { + long valueAsLong = Long + .parseLong(valueAsString == null ? new String( + valueAsBytes) : valueAsString); + + if (valueAsLong < Short.MIN_VALUE + || valueAsLong > Short.MAX_VALUE) { + throwRangeException(valueAsString == null ? new String( + valueAsBytes) : valueAsString, columnIndex, + Types.SMALLINT); + } + } + } + + return shortValue; + } + + // --------------------------JDBC 2.0----------------------------------- + // --------------------------------------------------------------------- + // Getter's and Setter's + // --------------------------------------------------------------------- + + /** + * The prev method is not part of JDBC, but because of the architecture of + * this driver it is possible to move both forward and backward within the + * result set. + * + *

+ * If an input stream from the previous row is open, it is implicitly + * closed. The ResultSet's warning chain is cleared when a new row is read + *

+ * + * @return true if the new current is valid; false if there are no more rows + * + * @exception java.sql.SQLException + * if a database access error occurs + */ + public boolean prev() throws java.sql.SQLException { + checkClosed(); + + int rowIndex = this.rowData.getCurrentRowNumber(); + + if ((rowIndex - 1) >= 0) { + rowIndex--; + this.rowData.setCurrentRow(rowIndex); + this.thisRow = this.rowData.getAt(rowIndex); + + return true; + } else if ((rowIndex - 1) == -1) { + rowIndex--; + this.rowData.setCurrentRow(rowIndex); + this.thisRow = null; + + return false; + } else { + return false; + } + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the previous row in the result set. + *

+ * + *

+ * Note: previous() is not the same as relative(-1) since it makes sense to + * call previous() when there is no current row. + *

+ * + * @return true if on a valid row, false if off the result set. + * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWAR_DONLY. + */ + public boolean previous() throws SQLException { + if (this.onInsertRow) { + this.onInsertRow = false; + } + + if (this.doingUpdates) { + this.doingUpdates = false; + } + + return prev(); + } + + /** + * Closes this ResultSet and releases resources. + * + * @param calledExplicitly + * was this called by close()? + * + * @throws SQLException + * if an error occurs + */ + protected void realClose(boolean calledExplicitly) throws SQLException { + if (this.isClosed) { + return; + } + + try { + if (this.useUsageAdvisor) { + + // Report on result set closed by driver instead of application + + if (!calledExplicitly) { + this.eventSink + .consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, + "", + (this.owningStatement == null) ? "N/A" + : this.owningStatement.currentCatalog, + this.connectionId, + (this.owningStatement == null) ? (-1) + : this.owningStatement.getId(), + this.resultId, + System.currentTimeMillis(), + 0, + Constants.MILLIS_I18N, + null, + this.pointOfOrigin, + Messages + .getString("ResultSet.ResultSet_implicitly_closed_by_driver"))); //$NON-NLS-1$ + } + + if (this.rowData instanceof RowDataStatic) { + + // Report on possibly too-large result sets + + if (this.rowData.size() > this.connection + .getResultSetSizeThreshold()) { + this.eventSink + .consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, + "", + (this.owningStatement == null) ? Messages + .getString("ResultSet.N/A_159") + : this.owningStatement.currentCatalog, //$NON-NLS-1$ + this.connectionId, + (this.owningStatement == null) ? (-1) + : this.owningStatement.getId(), + this.resultId, + System.currentTimeMillis(), + 0, + Constants.MILLIS_I18N, + null, + this.pointOfOrigin, + Messages + .getString( + "ResultSet.Too_Large_Result_Set", + new Object[] { + new Integer( + this.rowData + .size()), + new Integer( + this.connection + .getResultSetSizeThreshold()) }))); + } + + if (!isLast() && !isAfterLast() && (this.rowData.size() != 0)) { + + this.eventSink + .consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, + "", + (this.owningStatement == null) ? Messages + .getString("ResultSet.N/A_159") + : this.owningStatement.currentCatalog, //$NON-NLS-1$ + this.connectionId, + (this.owningStatement == null) ? (-1) + : this.owningStatement.getId(), + this.resultId, + System.currentTimeMillis(), + 0, + Constants.MILLIS_I18N, + null, + this.pointOfOrigin, + Messages + .getString( + "ResultSet.Possible_incomplete_traversal_of_result_set", //$NON-NLS-1$ + new Object[] { + new Integer( + getRow()), + new Integer( + this.rowData + .size()) }))); + } + } + + // + // Report on any columns that were selected but + // not referenced + // + + if (this.columnUsed.length > 0 && !this.rowData.wasEmpty()) { + StringBuffer buf = new StringBuffer( + Messages + .getString("ResultSet.The_following_columns_were_never_referenced")); //$NON-NLS-1$ + + boolean issueWarn = false; + + for (int i = 0; i < this.columnUsed.length; i++) { + if (!this.columnUsed[i]) { + if (!issueWarn) { + issueWarn = true; + } else { + buf.append(", "); + } + + buf.append(this.fields[i].getFullName()); + } + } + + if (issueWarn) { + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, "", + (this.owningStatement == null) ? "N/A" + : this.owningStatement.currentCatalog, + this.connectionId, + (this.owningStatement == null) ? (-1) + : this.owningStatement.getId(), 0, + System.currentTimeMillis(), 0, + Constants.MILLIS_I18N, null, + this.pointOfOrigin, buf.toString())); + } + } + } + } finally { + SQLException exceptionDuringClose = null; + + if (this.rowData != null) { + try { + this.rowData.close(); + } catch (SQLException sqlEx) { + exceptionDuringClose = sqlEx; + } + } + + this.rowData = null; + this.defaultTimeZone = null; + this.fields = null; + this.columnNameToIndex = null; + this.fullColumnNameToIndex = null; + + this.eventSink = null; + this.warningChain = null; + + if (!this.retainOwningStatement) { + this.owningStatement = null; + } + + this.catalog = null; + this.serverInfo = null; + this.thisRow = null; + this.fastDateCal = null; + this.connection = null; + + this.isClosed = true; + + if (exceptionDuringClose != null) { + throw exceptionDuringClose; + } + } + } + + boolean reallyResult() { + if (this.rowData != null) { + return true; + } + + return this.reallyResult; + } + + /** + * JDBC 2.0 Refresh the value of the current row with its current value in + * the database. Cannot be called when on the insert row. The refreshRow() + * method provides a way for an application to explicitly tell the JDBC + * driver to refetch a row(s) from the database. An application may want to + * call refreshRow() when caching or prefetching is being done by the JDBC + * driver to fetch the latest value of a row from the database. The JDBC + * driver may actually refresh multiple rows at once if the fetch size is + * greater than one. All values are refetched subject to the transaction + * isolation level and cursor sensitivity. If refreshRow() is called after + * calling updateXXX(), but before calling updateRow() then the updates made + * to the row are lost. Calling refreshRow() frequently will likely slow + * performance. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row. + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void refreshRow() throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 + * + *

+ * Moves a relative number of rows, either positive or negative. Attempting + * to move beyond the first/last row in the result set positions the cursor + * before/after the the first/last row. Calling relative(0) is valid, but + * does not change the cursor position. + *

+ * + *

+ * Note: Calling relative(1) is different than calling next() since is makes + * sense to call next() when there is no current row, for example, when the + * cursor is positioned before the first row or after the last row of the + * result set. + *

+ * + * @param rows + * the number of relative rows to move the cursor. + * + * @return true if on a row, false otherwise. + * + * @throws SQLException + * if a database-access error occurs, or there is no current + * row, or result set type is TYPE_FORWARD_ONLY. + */ + public boolean relative(int rows) throws SQLException { + checkClosed(); + + if (this.rowData.size() == 0) { + return false; + } + + this.rowData.moveRowRelative(rows); + this.thisRow = this.rowData.getAt(this.rowData.getCurrentRowNumber()); + + return (!this.rowData.isAfterLast() && !this.rowData.isBeforeFirst()); + } + + /** + * JDBC 2.0 Determine if this row has been deleted. A deleted row may leave + * a visible "hole" in a result set. This method can be used to detect holes + * in a result set. The value returned depends on whether or not the result + * set can detect deletions. + * + * @return true if deleted and deletes are detected + * + * @exception SQLException + * if a database-access error occurs + * @throws NotImplemented + * DOCUMENT ME! + * + * @see DatabaseMetaData#deletesAreDetected + */ + public boolean rowDeleted() throws SQLException { + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Determine if the current row has been inserted. The value + * returned depends on whether or not the result set can detect visible + * inserts. + * + * @return true if inserted and inserts are detected + * + * @exception SQLException + * if a database-access error occurs + * @throws NotImplemented + * DOCUMENT ME! + * + * @see DatabaseMetaData#insertsAreDetected + */ + public boolean rowInserted() throws SQLException { + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Determine if the current row has been updated. The value + * returned depends on whether or not the result set can detect updates. + * + * @return true if the row has been visibly updated by the owner or another, + * and updates are detected + * + * @exception SQLException + * if a database-access error occurs + * @throws NotImplemented + * DOCUMENT ME! + * + * @see DatabaseMetaData#updatesAreDetected + */ + public boolean rowUpdated() throws SQLException { + throw new NotImplemented(); + } + + /** + * Flag that this result set is 'binary' encoded (from a PreparedStatement), + * not stored as strings. + */ + protected void setBinaryEncoded() { + this.isBinaryEncoded = true; + } + + private void setDefaultTimeZone(TimeZone defaultTimeZone) { + this.defaultTimeZone = defaultTimeZone; + } + + /** + * JDBC 2.0 Give a hint as to the direction in which the rows in this result + * set will be processed. The initial value is determined by the statement + * that produced the result set. The fetch direction may be changed at any + * time. + * + * @param direction + * the direction to fetch rows in. + * + * @exception SQLException + * if a database-access error occurs, or the result set type + * is TYPE_FORWARD_ONLY and direction is not FETCH_FORWARD. + * MM.MySQL actually ignores this, because it has the whole + * result set anyway, so the direction is immaterial. + */ + public void setFetchDirection(int direction) throws SQLException { + if ((direction != FETCH_FORWARD) && (direction != FETCH_REVERSE) + && (direction != FETCH_UNKNOWN)) { + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Illegal_value_for_fetch_direction_64"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + this.fetchDirection = direction; + } + + /** + * JDBC 2.0 Give the JDBC driver a hint as to the number of rows that should + * be fetched from the database when more rows are needed for this result + * set. If the fetch size specified is zero, then the JDBC driver ignores + * the value, and is free to make its own best guess as to what the fetch + * size should be. The default value is set by the statement that creates + * the result set. The fetch size may be changed at any time. + * + * @param rows + * the number of rows to fetch + * + * @exception SQLException + * if a database-access error occurs, or the condition 0 lteq + * rows lteq this.getMaxRows() is not satisfied. Currently + * ignored by this driver. + */ + public void setFetchSize(int rows) throws SQLException { + if (rows < 0) { /* || rows > getMaxRows() */ + throw SQLError.createSQLException( + Messages + .getString("ResultSet.Value_must_be_between_0_and_getMaxRows()_66"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + this.fetchSize = rows; + } + + /** + * Sets the first character of the query that this result set was created + * from. + * + * @param c + * the first character of the query...uppercased + */ + protected void setFirstCharOfQuery(char c) { + this.firstCharOfQuery = c; + } + + /** + * DOCUMENT ME! + * + * @param nextResultSet + * Sets the next result set in the result set chain for multiple + * result sets. + */ + protected void setNextResultSet(ResultSet nextResultSet) { + this.nextResultSet = nextResultSet; + } + + protected void setOwningStatement(com.mysql.jdbc.Statement owningStatement) { + this.owningStatement = owningStatement; + } + + /** + * Sets the concurrency (JDBC2) + * + * @param concurrencyFlag + * CONCUR_UPDATABLE or CONCUR_READONLY + */ + protected void setResultSetConcurrency(int concurrencyFlag) { + this.resultSetConcurrency = concurrencyFlag; + } + + /** + * Sets the result set type for (JDBC2) + * + * @param typeFlag + * SCROLL_SENSITIVE or SCROLL_INSENSITIVE (we only support + * SCROLL_INSENSITIVE) + */ + protected void setResultSetType(int typeFlag) { + this.resultSetType = typeFlag; + } + + /** + * Sets server info (if any) + * + * @param info + * the server info message + */ + protected void setServerInfo(String info) { + this.serverInfo = info; + } + + void setStatementUsedForFetchingRows(PreparedStatement stmt) { + this.statementUsedForFetchingRows = stmt; + } + + /** + * @param wrapperStatement + * The wrapperStatement to set. + */ + public void setWrapperStatement(java.sql.Statement wrapperStatement) { + this.wrapperStatement = wrapperStatement; + } + + private void throwRangeException(String valueAsString, int columnIndex, + int jdbcType) throws SQLException { + String datatype = null; + + switch (jdbcType) { + case Types.TINYINT: + datatype = "TINYINT"; + break; + case Types.SMALLINT: + datatype = "SMALLINT"; + break; + case Types.INTEGER: + datatype = "INTEGER"; + break; + case Types.BIGINT: + datatype = "BIGINT"; + break; + case Types.REAL: + datatype = "REAL"; + break; + case Types.FLOAT: + datatype = "FLOAT"; + break; + case Types.DOUBLE: + datatype = "DOUBLE"; + break; + case Types.DECIMAL: + datatype = "DECIMAL"; + break; + default: + datatype = " (JDBC type '" + jdbcType + "')"; + } + + throw SQLError.createSQLException("'" + valueAsString + "' in column '" + + columnIndex + "' is outside valid range for the datatype " + + datatype + ".", SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String toString() { + if (this.reallyResult) { + return super.toString(); + } + + return "Result set representing update count of " + this.updateCount; + } + + /** + * @see ResultSet#updateArray(int, Array) + */ + public void updateArray(int arg0, Array arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see ResultSet#updateArray(String, Array) + */ + public void updateArray(String arg0, Array arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Update a column with an ascii stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param length + * the length of the stream + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateAsciiStream(int columnIndex, java.io.InputStream x, + int length) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with an ascii stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * @param length + * of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateAsciiStream(String columnName, java.io.InputStream x, + int length) throws SQLException { + updateAsciiStream(findColumn(columnName), x, length); + } + + /** + * JDBC 2.0 Update a column with a BigDecimal value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateBigDecimal(int columnIndex, BigDecimal x) + throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a BigDecimal value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateBigDecimal(String columnName, BigDecimal x) + throws SQLException { + updateBigDecimal(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a binary stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param length + * the length of the stream + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateBinaryStream(int columnIndex, java.io.InputStream x, + int length) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a binary stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * @param length + * of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateBinaryStream(String columnName, java.io.InputStream x, + int length) throws SQLException { + updateBinaryStream(findColumn(columnName), x, length); + } + + /** + * @see ResultSet#updateBlob(int, Blob) + */ + public void updateBlob(int arg0, java.sql.Blob arg1) throws SQLException { + throw new NotUpdatable(); + } + + /** + * @see ResultSet#updateBlob(String, Blob) + */ + public void updateBlob(String arg0, java.sql.Blob arg1) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a boolean value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateBoolean(int columnIndex, boolean x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a boolean value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateBoolean(String columnName, boolean x) throws SQLException { + updateBoolean(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a byte value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateByte(int columnIndex, byte x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a byte value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateByte(String columnName, byte x) throws SQLException { + updateByte(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a byte array value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateBytes(int columnIndex, byte[] x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a byte array value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateBytes(String columnName, byte[] x) throws SQLException { + updateBytes(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a character stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param length + * the length of the stream + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateCharacterStream(int columnIndex, java.io.Reader x, + int length) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a character stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnName + * the name of the column + * @param reader + * the stream to update the column with + * @param length + * of the stream + * + * @throws SQLException + * if a database-access error occurs + */ + public void updateCharacterStream(String columnName, java.io.Reader reader, + int length) throws SQLException { + updateCharacterStream(findColumn(columnName), reader, length); + } + + /** + * @see ResultSet#updateClob(int, Clob) + */ + public void updateClob(int arg0, java.sql.Clob arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see ResultSet#updateClob(String, Clob) + */ + public void updateClob(String columnName, java.sql.Clob clob) + throws SQLException { + updateClob(findColumn(columnName), clob); + } + + /** + * JDBC 2.0 Update a column with a Date value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateDate(int columnIndex, java.sql.Date x) + throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a Date value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateDate(String columnName, java.sql.Date x) + throws SQLException { + updateDate(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a Double value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateDouble(int columnIndex, double x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a double value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateDouble(String columnName, double x) throws SQLException { + updateDouble(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a float value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateFloat(int columnIndex, float x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a float value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateFloat(String columnName, float x) throws SQLException { + updateFloat(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with an integer value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateInt(int columnIndex, int x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with an integer value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateInt(String columnName, int x) throws SQLException { + updateInt(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a long value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateLong(int columnIndex, long x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a long value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateLong(String columnName, long x) throws SQLException { + updateLong(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Give a nullable column a null value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateNull(int columnIndex) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a null value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateNull(String columnName) throws SQLException { + updateNull(findColumn(columnName)); + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateObject(int columnIndex, Object x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param scale + * For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types + * this is the number of digits after the decimal. For all other + * types this value will be ignored. + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateObject(int columnIndex, Object x, int scale) + throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateObject(String columnName, Object x) throws SQLException { + updateObject(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * @param scale + * For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types + * this is the number of digits after the decimal. For all other + * types this value will be ignored. + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateObject(String columnName, Object x, int scale) + throws SQLException { + updateObject(findColumn(columnName), x); + } + + /** + * @see ResultSet#updateRef(int, Ref) + */ + public void updateRef(int arg0, Ref arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see ResultSet#updateRef(String, Ref) + */ + public void updateRef(String arg0, Ref arg1) throws SQLException { + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Update the underlying database with the new contents of the + * current row. Cannot be called when on the insert row. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateRow() throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a short value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateShort(int columnIndex, short x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a short value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateShort(String columnName, short x) throws SQLException { + updateShort(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a String value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateString(int columnIndex, String x) throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a String value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateString(String columnName, String x) throws SQLException { + updateString(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a Time value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateTime(int columnIndex, java.sql.Time x) + throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a Time value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateTime(String columnName, java.sql.Time x) + throws SQLException { + updateTime(findColumn(columnName), x); + } + + + /** + * JDBC 2.0 Update a column with a Timestamp value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + * @throws NotUpdatable + * DOCUMENT ME! + */ + public void updateTimestamp(int columnIndex, java.sql.Timestamp x) + throws SQLException { + throw new NotUpdatable(); + } + + /** + * JDBC 2.0 Update a column with a Timestamp value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public void updateTimestamp(String columnName, java.sql.Timestamp x) + throws SQLException { + updateTimestamp(findColumn(columnName), x); + } + + /** + * A column may have the value of SQL NULL; wasNull() reports whether the + * last column read had this special value. Note that you must first call + * getXXX on a column to try to read its value and then call wasNull() to + * find if the value was SQL NULL + * + * @return true if the last column read was SQL NULL + * + * @exception SQLException + * if a database access error occurred + */ + public boolean wasNull() throws SQLException { + return this.wasNullFlag; + } + + protected Calendar getGmtCalendar() { + + // Worst case we allocate this twice and the other gets GC'd, + // however prevents deadlock + if (this.gmtCalendar == null) { + this.gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + } + + return this.gmtCalendar; + } + + private Object getNativeDateTimeValue(int columnIndex, Calendar targetCalendar, + int jdbcType, + int mysqlType, TimeZone tz, boolean rollForward) + throws SQLException { + + int year = 0; + int month = 0; + int day = 0; + + int hour = 0; + int minute = 0; + int seconds = 0; + + int nanos = 0; + + byte[] bits = (byte[]) this.thisRow[columnIndex - 1]; + + if (bits == null) { + this.wasNullFlag = true; + + return null; + } + + Calendar sessionCalendar = this.connection.getUseJDBCCompliantTimezoneShift() ? + this.connection.getUtcCalendar() : + getCalendarInstanceForSessionOrNew(); + + this.wasNullFlag = false; + + boolean populatedFromDateTimeValue = false; + + switch (mysqlType) { + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + populatedFromDateTimeValue = true; + + int length = bits.length; + + if (length != 0) { + year = (bits[0] & 0xff) | ((bits[1] & 0xff) << 8); + month = bits[2]; + day = bits[3]; + + if (length > 4) { + hour = bits[4]; + minute = bits[5]; + seconds = bits[6]; + } + + if (length > 7) { + nanos = (bits[7] & 0xff) | ((bits[8] & 0xff) << 8) + | ((bits[9] & 0xff) << 16) + | ((bits[10] & 0xff) << 24); + } + } + + break; + case MysqlDefs.FIELD_TYPE_DATE: + populatedFromDateTimeValue = true; + + if (bits.length != 0) { + year = (bits[0] & 0xff) | ((bits[1] & 0xff) << 8); + month = bits[2]; + day = bits[3]; + } + + break; + case MysqlDefs.FIELD_TYPE_TIME: + populatedFromDateTimeValue = true; + + if (bits.length != 0) { + // bits[0] // skip tm->neg + // binaryData.readLong(); // skip daysPart + hour = bits[5]; + minute = bits[6]; + seconds = bits[7]; + } + + year = 1970; + month = 1; + day = 1; + + break; + default: + populatedFromDateTimeValue = false; + } + + switch (jdbcType) { + case Types.TIME: + if (populatedFromDateTimeValue) { + Time time = TimeUtil.fastTimeCreate( + getCalendarInstanceForSessionOrNew(), hour, minute, + seconds); + + Time adjustedTime = TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + time, this.connection.getServerTimezoneTZ(), tz, + rollForward); + + return adjustedTime; + } + + return getNativeTimeViaParseConversion(columnIndex, targetCalendar, + tz, rollForward); + + case Types.DATE: + if (populatedFromDateTimeValue) { + if ((year == 0) && (month == 0) && (day == 0)) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw new SQLException( + "Value '0000-00-00' can not be represented as java.sql.Date", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + year = 1; + month = 1; + day = 1; + } + + return fastDateCreate(getCalendarInstanceForSessionOrNew(), + year, month, day); + } + + return getNativeDateViaParseConversion(columnIndex); + case Types.TIMESTAMP: + if (populatedFromDateTimeValue) { + if ((year == 0) && (month == 0) && (day == 0)) { + if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL + .equals(this.connection.getZeroDateTimeBehavior())) { + this.wasNullFlag = true; + + return null; + } else if (ConnectionProperties.ZERO_DATETIME_BEHAVIOR_EXCEPTION + .equals(this.connection.getZeroDateTimeBehavior())) { + throw new SQLException( + "Value '0000-00-00' can not be represented as java.sql.Timestamp", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + year = 1; + month = 1; + day = 1; + } + + Timestamp ts = fastTimestampCreate( + getCalendarInstanceForSessionOrNew(), year, month, day, + hour, minute, seconds, nanos); + + Timestamp adjustedTs = TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + ts, this.connection.getServerTimezoneTZ(), tz, + rollForward); + + return adjustedTs; + } + + return getNativeTimestampViaParseConversion(columnIndex, targetCalendar, tz, rollForward); + + default: + throw new SQLException("Internal error - conversion method doesn't support this type", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ResultSetMetaData.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ResultSetMetaData.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ResultSetMetaData.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,809 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.sql.SQLException; +import java.sql.Types; + +/** + * A ResultSetMetaData object can be used to find out about the types and + * properties of the columns in a ResultSet + * + * @author Mark Matthews + * @version $Id: ResultSetMetaData.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews + * Exp $ + * + * @see java.sql.ResultSetMetaData + */ +public class ResultSetMetaData implements java.sql.ResultSetMetaData { + private static int clampedGetLength(Field f) { + long fieldLength = f.getLength(); + + if (fieldLength > Integer.MAX_VALUE) { + fieldLength = Integer.MAX_VALUE; + } + + return (int) fieldLength; + } + + /** + * Checks if the SQL Type is a Decimal/Number Type + * + * @param type + * SQL Type + * + * @return ... + */ + private static final boolean isDecimalType(int type) { + switch (type) { + case Types.BIT: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.FLOAT: + case Types.REAL: + case Types.DOUBLE: + case Types.NUMERIC: + case Types.DECIMAL: + return true; + } + + return false; + } + + Field[] fields; + boolean useOldAliasBehavior = false; + + /** + * Initialise for a result with a tuple set and a field descriptor set + * + * @param fields + * the array of field descriptors + */ + public ResultSetMetaData(Field[] fields, boolean useOldAliasBehavior) { + this.fields = fields; + this.useOldAliasBehavior = useOldAliasBehavior; + } + + /** + * What's a column's table's catalog name? + * + * @param column + * the first column is 1, the second is 2... + * + * @return catalog name, or "" if not applicable + * + * @throws SQLException + * if a database access error occurs + */ + public String getCatalogName(int column) throws SQLException { + Field f = getField(column); + + String database = f.getDatabaseName(); + + return (database == null) ? "" : database; //$NON-NLS-1$ + } + + /** + * What's the Java character encoding name for the given column? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return the Java character encoding name for the given column, or null if + * no Java character encoding maps to the MySQL character set for + * the given column. + * + * @throws SQLException + * if an invalid column index is given. + */ + public String getColumnCharacterEncoding(int column) throws SQLException { + String mysqlName = getColumnCharacterSet(column); + + String javaName = null; + + if (mysqlName != null) { + javaName = CharsetMapping.getJavaEncodingForMysqlEncoding( + mysqlName, null); + } + + return javaName; + } + + /** + * What's the MySQL character set name for the given column? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return the MySQL character set name for the given column + * + * @throws SQLException + * if an invalid column index is given. + */ + public String getColumnCharacterSet(int column) throws SQLException { + return getField(column).getCharacterSet(); + } + + // --------------------------JDBC 2.0----------------------------------- + + /** + * JDBC 2.0 + * + *

+ * Return the fully qualified name of the Java class whose instances are + * manufactured if ResultSet.getObject() is called to retrieve a value from + * the column. ResultSet.getObject() may return a subClass of the class + * returned by this method. + *

+ * + * @param column + * the column number to retrieve information for + * + * @return the fully qualified name of the Java class whose instances are + * manufactured if ResultSet.getObject() is called to retrieve a + * value from the column. + * + * @throws SQLException + * if an error occurs + */ + public String getColumnClassName(int column) throws SQLException { + Field f = getField(column); + + return getClassNameForJavaType(f.getSQLType(), + f.isUnsigned(), + f.getMysqlType(), + f.isBinary() || f.isBlob(), + f.isOpaqueBinary()); + } + + /** + * Whats the number of columns in the ResultSet? + * + * @return the number + * + * @throws SQLException + * if a database access error occurs + */ + public int getColumnCount() throws SQLException { + return this.fields.length; + } + + /** + * What is the column's normal maximum width in characters? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return the maximum width + * + * @throws SQLException + * if a database access error occurs + */ + public int getColumnDisplaySize(int column) throws SQLException { + Field f = getField(column); + + int lengthInBytes = clampedGetLength(f); + + return lengthInBytes / f.getMaxBytesPerCharacter(); + } + + /** + * What is the suggested column title for use in printouts and displays? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return the column label + * + * @throws SQLException + * if a database access error occurs + */ + public String getColumnLabel(int column) throws SQLException { + if (this.useOldAliasBehavior) { + return getColumnName(column); + } + + return getField(column).getColumnLabel(); + } + + /** + * What's a column's name? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return the column name + * + * @throws SQLException + * if a databvase access error occurs + */ + public String getColumnName(int column) throws SQLException { + if (this.useOldAliasBehavior) { + return getField(column).getName(); + } + + String name = getField(column).getNameNoAliases(); + + if (name != null && name.length() == 0) { + return getField(column).getName(); + } + + return name; + } + + /** + * What is a column's SQL Type? (java.sql.Type int) + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return the java.sql.Type value + * + * @throws SQLException + * if a database access error occurs + * + * @see java.sql.Types + */ + public int getColumnType(int column) throws SQLException { + return getField(column).getSQLType(); + } + + /** + * Whats is the column's data source specific type name? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return the type name + * + * @throws SQLException + * if a database access error occurs + */ + public String getColumnTypeName(int column) throws java.sql.SQLException { + Field field = getField(column); + + int mysqlType = field.getMysqlType(); + int jdbcType = field.getSQLType(); + + switch (mysqlType) { + case MysqlDefs.FIELD_TYPE_BIT: + return "BIT"; + case MysqlDefs.FIELD_TYPE_DECIMAL: + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + return field.isUnsigned() ? "DECIMAL UNSIGNED" : "DECIMAL"; + + case MysqlDefs.FIELD_TYPE_TINY: + return field.isUnsigned() ? "TINYINT UNSIGNED" : "TINYINT"; + + case MysqlDefs.FIELD_TYPE_SHORT: + return field.isUnsigned() ? "SMALLINT UNSIGNED" : "SMALLINT"; + + case MysqlDefs.FIELD_TYPE_LONG: + return field.isUnsigned() ? "INT UNSIGNED" : "INT"; + + case MysqlDefs.FIELD_TYPE_FLOAT: + return field.isUnsigned() ? "FLOAT UNSIGNED" : "FLOAT"; + + case MysqlDefs.FIELD_TYPE_DOUBLE: + return field.isUnsigned() ? "DOUBLE UNSIGNED" : "DOUBLE"; + + case MysqlDefs.FIELD_TYPE_NULL: + return "NULL"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + return "TIMESTAMP"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_LONGLONG: + return field.isUnsigned() ? "BIGINT UNSIGNED" : "BIGINT"; + + case MysqlDefs.FIELD_TYPE_INT24: + return field.isUnsigned() ? "MEDIUMINT UNSIGNED" : "MEDIUMINT"; + + case MysqlDefs.FIELD_TYPE_DATE: + return "DATE"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_TIME: + return "TIME"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_DATETIME: + return "DATETIME"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + return "TINYBLOB"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + return "MEDIUMBLOB"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + return "LONGBLOB"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_BLOB: + if (getField(column).isBinary()) { + return "BLOB";//$NON-NLS-1$ + } + + return "TEXT";//$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_VARCHAR: + return "VARCHAR"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_VAR_STRING: + if (jdbcType == Types.VARBINARY) { + return "VARBINARY"; + } + + return "VARCHAR"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_STRING: + if (jdbcType == Types.BINARY) { + return "BINARY"; + } + + return "CHAR"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_ENUM: + return "ENUM"; //$NON-NLS-1$ + + case MysqlDefs.FIELD_TYPE_YEAR: + return "YEAR"; // $NON_NLS-1$ + + case MysqlDefs.FIELD_TYPE_SET: + return "SET"; //$NON-NLS-1$ + + default: + return "UNKNOWN"; //$NON-NLS-1$ + } + } + + /** + * Returns the field instance for the given column index + * + * @param columnIndex + * the column number to retrieve a field instance for + * + * @return the field instance for the given column index + * + * @throws SQLException + * if an error occurs + */ + protected Field getField(int columnIndex) throws SQLException { + if ((columnIndex < 1) || (columnIndex > this.fields.length)) { + throw SQLError.createSQLException(Messages.getString("ResultSetMetaData.46"), //$NON-NLS-1$ + SQLError.SQL_STATE_INVALID_COLUMN_NUMBER); + } + + return this.fields[columnIndex - 1]; + } + + /** + * What is a column's number of decimal digits. + * + * @param column + * the first column is 1, the second is 2... + * + * @return the precision + * + * @throws SQLException + * if a database access error occurs + */ + public int getPrecision(int column) throws SQLException { + Field f = getField(column); + + // if (f.getMysqlType() == MysqlDefs.FIELD_TYPE_NEW_DECIMAL) { + // return f.getLength(); + // } + + if (isDecimalType(f.getSQLType())) { + if (f.getDecimals() > 0) { + return clampedGetLength(f) - 1 + f.getPrecisionAdjustFactor(); + } + + return clampedGetLength(f) + f.getPrecisionAdjustFactor(); + } + + switch (f.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_TINY_BLOB: + case MysqlDefs.FIELD_TYPE_BLOB: + case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB: + case MysqlDefs.FIELD_TYPE_LONG_BLOB: + return clampedGetLength(f); // this may change in the future + // for now, the server only + // returns FIELD_TYPE_BLOB for _all_ + // BLOB types, but varying lengths + // indicating the _maximum_ size + // for each BLOB type. + default: + return clampedGetLength(f) / f.getMaxBytesPerCharacter(); + + } + } + + /** + * What is a column's number of digits to the right of the decimal point? + * + * @param column + * the first column is 1, the second is 2... + * + * @return the scale + * + * @throws SQLException + * if a database access error occurs + */ + public int getScale(int column) throws SQLException { + Field f = getField(column); + + if (isDecimalType(f.getSQLType())) { + return f.getDecimals(); + } + + return 0; + } + + /** + * What is a column's table's schema? This relies on us knowing the table + * name. The JDBC specification allows us to return "" if this is not + * applicable. + * + * @param column + * the first column is 1, the second is 2... + * + * @return the Schema + * + * @throws SQLException + * if a database access error occurs + */ + public String getSchemaName(int column) throws SQLException { + return ""; //$NON-NLS-1$ + } + + /** + * Whats a column's table's name? + * + * @param column + * the first column is 1, the second is 2... + * + * @return column name, or "" if not applicable + * + * @throws SQLException + * if a database access error occurs + */ + public String getTableName(int column) throws SQLException { + if (this.useOldAliasBehavior) { + return getField(column).getTableName(); + } + + return getField(column).getTableNameNoAliases(); + } + + /** + * Is the column automatically numbered (and thus read-only) + * + * @param column + * the first column is 1, the second is 2... + * + * @return true if so + * + * @throws SQLException + * if a database access error occurs + */ + public boolean isAutoIncrement(int column) throws SQLException { + Field f = getField(column); + + return f.isAutoIncrement(); + } + + /** + * Does a column's case matter? + * + * @param column + * the first column is 1, the second is 2... + * + * @return true if so + * + * @throws java.sql.SQLException + * if a database access error occurs + */ + public boolean isCaseSensitive(int column) throws java.sql.SQLException { + Field field = getField(column); + + int sqlType = field.getSQLType(); + + switch (sqlType) { + case Types.BIT: + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.FLOAT: + case Types.REAL: + case Types.DOUBLE: + case Types.DATE: + case Types.TIME: + case Types.TIMESTAMP: + return false; + + case Types.CHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: + + if (field.isBinary()) { + return true; + } + + String collationName = field.getCollation(); + + return ((collationName != null) && !collationName.endsWith("_ci")); + + default: + return true; + } + } + + /** + * Is the column a cash value? + * + * @param column + * the first column is 1, the second is 2... + * + * @return true if its a cash column + * + * @throws SQLException + * if a database access error occurs + */ + public boolean isCurrency(int column) throws SQLException { + return false; + } + + /** + * Will a write on this column definately succeed? + * + * @param column + * the first column is 1, the second is 2, etc.. + * + * @return true if so + * + * @throws SQLException + * if a database access error occurs + */ + public boolean isDefinitelyWritable(int column) throws SQLException { + return isWritable(column); + } + + /** + * Can you put a NULL in this column? + * + * @param column + * the first column is 1, the second is 2... + * + * @return one of the columnNullable values + * + * @throws SQLException + * if a database access error occurs + */ + public int isNullable(int column) throws SQLException { + if (!getField(column).isNotNull()) { + return java.sql.ResultSetMetaData.columnNullable; + } + + return java.sql.ResultSetMetaData.columnNoNulls; + } + + /** + * Is the column definitely not writable? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return true if so + * + * @throws SQLException + * if a database access error occurs + */ + public boolean isReadOnly(int column) throws SQLException { + return getField(column).isReadOnly(); + } + + /** + * Can the column be used in a WHERE clause? Basically for this, I split the + * functions into two types: recognised types (which are always useable), + * and OTHER types (which may or may not be useable). The OTHER types, for + * now, I will assume they are useable. We should really query the catalog + * to see if they are useable. + * + * @param column + * the first column is 1, the second is 2... + * + * @return true if they can be used in a WHERE clause + * + * @throws SQLException + * if a database access error occurs + */ + public boolean isSearchable(int column) throws SQLException { + return true; + } + + /** + * Is the column a signed number? + * + * @param column + * the first column is 1, the second is 2... + * + * @return true if so + * + * @throws SQLException + * if a database access error occurs + */ + public boolean isSigned(int column) throws SQLException { + Field f = getField(column); + int sqlType = f.getSQLType(); + + switch (sqlType) { + case Types.TINYINT: + case Types.SMALLINT: + case Types.INTEGER: + case Types.BIGINT: + case Types.FLOAT: + case Types.REAL: + case Types.DOUBLE: + case Types.NUMERIC: + case Types.DECIMAL: + return !f.isUnsigned(); + + case Types.DATE: + case Types.TIME: + case Types.TIMESTAMP: + return false; + + default: + return false; + } + } + + /** + * Is it possible for a write on the column to succeed? + * + * @param column + * the first column is 1, the second is 2, etc. + * + * @return true if so + * + * @throws SQLException + * if a database access error occurs + */ + public boolean isWritable(int column) throws SQLException { + return !isReadOnly(column); + } + + /** + * Returns a string representation of this object + * + * @return ... + */ + public String toString() { + StringBuffer toStringBuf = new StringBuffer(); + toStringBuf.append(super.toString()); + toStringBuf.append(" - Field level information: "); //$NON-NLS-1$ + + for (int i = 0; i < this.fields.length; i++) { + toStringBuf.append("\n\t"); //$NON-NLS-1$ + toStringBuf.append(this.fields[i].toString()); + } + + return toStringBuf.toString(); + } + + static String getClassNameForJavaType(int javaType, + boolean isUnsigned, int mysqlTypeIfKnown, + boolean isBinaryOrBlob, + boolean isOpaqueBinary) { + switch (javaType) { + case Types.BIT: + case Types.BOOLEAN: + return "java.lang.Boolean"; //$NON-NLS-1$ + + case Types.TINYINT: + + if (isUnsigned) { + return "java.lang.Integer"; //$NON-NLS-1$ + } + + return "java.lang.Integer"; //$NON-NLS-1$ + + case Types.SMALLINT: + + if (isUnsigned) { + return "java.lang.Integer"; //$NON-NLS-1$ + } + + return "java.lang.Integer"; //$NON-NLS-1$ + + case Types.INTEGER: + + if (!isUnsigned || + mysqlTypeIfKnown == MysqlDefs.FIELD_TYPE_INT24) { + return "java.lang.Integer"; //$NON-NLS-1$ + } + + return "java.lang.Long"; //$NON-NLS-1$ + + case Types.BIGINT: + + if (!isUnsigned) { + return "java.lang.Long"; //$NON-NLS-1$ + } + + return "java.math.BigInteger"; //$NON-NLS-1$ + + case Types.DECIMAL: + case Types.NUMERIC: + return "java.math.BigDecimal"; //$NON-NLS-1$ + + case Types.REAL: + return "java.lang.Float"; //$NON-NLS-1$ + + case Types.FLOAT: + case Types.DOUBLE: + return "java.lang.Double"; //$NON-NLS-1$ + + case Types.CHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: + if (!isOpaqueBinary) { + return "java.lang.String"; //$NON-NLS-1$ + } + + return "[B"; + + case Types.BINARY: + case Types.VARBINARY: + case Types.LONGVARBINARY: + + if (mysqlTypeIfKnown == MysqlDefs.FIELD_TYPE_GEOMETRY) { + return "[B"; + } else if (isBinaryOrBlob) { + return "[B"; + } else { + return "java.lang.String"; + } + + case Types.DATE: + return "java.sql.Date"; //$NON-NLS-1$ + + case Types.TIME: + return "java.sql.Time"; //$NON-NLS-1$ + + case Types.TIMESTAMP: + return "java.sql.Timestamp"; //$NON-NLS-1$ + + default: + return "java.lang.Object"; //$NON-NLS-1$ + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/RowData.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/RowData.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/RowData.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,242 @@ +/* + Copyright (C) 2002-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +/** + * This interface abstracts away how row data is accessed by the result set. It + * is meant to allow a static implementation (Current version), and a streaming + * one. + * + * @author dgan + */ +public interface RowData { + // ~ Static fields/initializers + // --------------------------------------------- + + /** + * What's returned for the size of a result set when its size can not be + * determined. + */ + public static final int RESULT_SET_SIZE_UNKNOWN = -1; + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Adds a row to this row data. + * + * @param row + * the row to add + * @throws SQLException + * if a database error occurs + */ + void addRow(byte[][] row) throws SQLException; + + /** + * Moves to after last. + * + * @throws SQLException + * if a database error occurs + */ + void afterLast() throws SQLException; + + /** + * Moves to before first. + * + * @throws SQLException + * if a database error occurs + */ + void beforeFirst() throws SQLException; + + /** + * Moves to before last so next el is the last el. + * + * @throws SQLException + * if a database error occurs + */ + void beforeLast() throws SQLException; + + /** + * We're done. + * + * @throws SQLException + * if a database error occurs + */ + void close() throws SQLException; + + /** + * Only works on non dynamic result sets. + * + * @param index + * row number to get at + * @return row data at index + * @throws SQLException + * if a database error occurs + */ + Object[] getAt(int index) throws SQLException; + + /** + * Returns the current position in the result set as a row number. + * + * @return the current row number + * @throws SQLException + * if a database error occurs + */ + int getCurrentRowNumber() throws SQLException; + + /** + * Returns the result set that 'owns' this RowData + */ + ResultSet getOwner(); + + /** + * Returns true if another row exsists. + * + * @return true if more rows + * @throws SQLException + * if a database error occurs + */ + boolean hasNext() throws SQLException; + + /** + * Returns true if we got the last element. + * + * @return true if after last row + * @throws SQLException + * if a database error occurs + */ + boolean isAfterLast() throws SQLException; + + /** + * Returns if iteration has not occured yet. + * + * @return true if before first row + * @throws SQLException + * if a database error occurs + */ + boolean isBeforeFirst() throws SQLException; + + /** + * Returns true if the result set is dynamic. + * + * This means that move back and move forward won't work because we do not + * hold on to the records. + * + * @return true if this result set is streaming from the server + * @throws SQLException + * if a database error occurs + */ + boolean isDynamic() throws SQLException; + + /** + * Has no records. + * + * @return true if no records + * @throws SQLException + * if a database error occurs + */ + boolean isEmpty() throws SQLException; + + /** + * Are we on the first row of the result set? + * + * @return true if on first row + * @throws SQLException + * if a database error occurs + */ + boolean isFirst() throws SQLException; + + /** + * Are we on the last row of the result set? + * + * @return true if on last row + * @throws SQLException + * if a database error occurs + */ + boolean isLast() throws SQLException; + + /** + * Moves the current position relative 'rows' from the current position. + * + * @param rows + * the relative number of rows to move + * @throws SQLException + * if a database error occurs + */ + void moveRowRelative(int rows) throws SQLException; + + /** + * Returns the next row. + * + * @return the next row value + * @throws SQLException + * if a database error occurs + */ + Object[] next() throws SQLException; + + /** + * Removes the row at the given index. + * + * @param index + * the row to move to + * @throws SQLException + * if a database error occurs + */ + void removeRow(int index) throws SQLException; + + /** + * Moves the current position in the result set to the given row number. + * + * @param rowNumber + * row to move to + * @throws SQLException + * if a database error occurs + */ + void setCurrentRow(int rowNumber) throws SQLException; + + /** + * Set the result set that 'owns' this RowData + * + * @param rs + * the result set that 'owns' this RowData + */ + void setOwner(ResultSet rs); + + /** + * Only works on non dynamic result sets. + * + * @return the size of this row data + * @throws SQLException + * if a database error occurs + */ + int size() throws SQLException; + + /** + * Did this result set have no rows? + */ + boolean wasEmpty(); +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/RowDataDynamic.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/RowDataDynamic.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/RowDataDynamic.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,455 @@ +/* + Copyright (C) 2002-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.SQLException; + +import com.mysql.jdbc.profiler.ProfileEventSink; +import com.mysql.jdbc.profiler.ProfilerEvent; + +/** + * Allows streaming of MySQL data. + * + * @author dgan + * @version $Id: RowDataDynamic.java,v 1.1 2012/08/17 14:57:09 marcin Exp $ + */ +public class RowDataDynamic implements RowData { + // ~ Instance fields + // -------------------------------------------------------- + + class OperationNotSupportedException extends SQLException { + OperationNotSupportedException() { + super( + Messages.getString("RowDataDynamic.10"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + private int columnCount; + + private Field[] fields; + + private int index = -1; + + private MysqlIO io; + + private boolean isAfterEnd = false; + + private boolean isAtEnd = false; + + private boolean isBinaryEncoded = false; + + private Object[] nextRow; + + private ResultSet owner; + + private boolean streamerClosed = false; + + private boolean wasEmpty = false; // we don't know until we attempt to traverse + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Creates a new RowDataDynamic object. + * + * @param io + * the connection to MySQL that this data is coming from + * @param fields + * the fields that describe this data + * @param isBinaryEncoded + * is this data in native format? + * @param colCount + * the number of columns + * @throws SQLException + * if the next record can not be found + */ + public RowDataDynamic(MysqlIO io, int colCount, Field[] fields, + boolean isBinaryEncoded) throws SQLException { + this.io = io; + this.columnCount = colCount; + this.isBinaryEncoded = isBinaryEncoded; + this.fields = fields; + nextRecord(); + } + + /** + * Adds a row to this row data. + * + * @param row + * the row to add + * @throws SQLException + * if a database error occurs + */ + public void addRow(byte[][] row) throws SQLException { + notSupported(); + } + + /** + * Moves to after last. + * + * @throws SQLException + * if a database error occurs + */ + public void afterLast() throws SQLException { + notSupported(); + } + + /** + * Moves to before first. + * + * @throws SQLException + * if a database error occurs + */ + public void beforeFirst() throws SQLException { + notSupported(); + } + + /** + * Moves to before last so next el is the last el. + * + * @throws SQLException + * if a database error occurs + */ + public void beforeLast() throws SQLException { + notSupported(); + } + + /** + * We're done. + * + * @throws SQLException + * if a database error occurs + */ + public void close() throws SQLException { + + boolean hadMore = false; + int howMuchMore = 0; + + // drain the rest of the records. + while (this.hasNext()) { + this.next(); + hadMore = true; + howMuchMore++; + + if (howMuchMore % 100 == 0) { + Thread.yield(); + } + } + + if (this.owner != null) { + Connection conn = this.owner.connection; + + if (conn != null && conn.getUseUsageAdvisor()) { + if (hadMore) { + + ProfileEventSink eventSink = ProfileEventSink + .getInstance(conn); + + eventSink + .consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, + "", //$NON-NLS-1$ + this.owner.owningStatement == null ? "N/A" : this.owner.owningStatement.currentCatalog, //$NON-NLS-1$ + this.owner.connectionId, + this.owner.owningStatement == null ? -1 + : this.owner.owningStatement + .getId(), + -1, + System.currentTimeMillis(), + 0, + Constants.MILLIS_I18N, + null, + null, + Messages.getString("RowDataDynamic.2") //$NON-NLS-1$ + + howMuchMore + + Messages + .getString("RowDataDynamic.3") //$NON-NLS-1$ + + Messages + .getString("RowDataDynamic.4") //$NON-NLS-1$ + + Messages + .getString("RowDataDynamic.5") //$NON-NLS-1$ + + Messages + .getString("RowDataDynamic.6") //$NON-NLS-1$ + + this.owner.pointOfOrigin)); + } + } + } + + this.fields = null; + this.owner = null; + } + + /** + * Only works on non dynamic result sets. + * + * @param index + * row number to get at + * @return row data at index + * @throws SQLException + * if a database error occurs + */ + public Object[] getAt(int ind) throws SQLException { + notSupported(); + + return null; + } + + /** + * Returns the current position in the result set as a row number. + * + * @return the current row number + * @throws SQLException + * if a database error occurs + */ + public int getCurrentRowNumber() throws SQLException { + notSupported(); + + return -1; + } + + /** + * @see com.mysql.jdbc.RowData#getOwner() + */ + public ResultSet getOwner() { + return this.owner; + } + + /** + * Returns true if another row exsists. + * + * @return true if more rows + * @throws SQLException + * if a database error occurs + */ + public boolean hasNext() throws SQLException { + boolean hasNext = (this.nextRow != null); + + if (!hasNext && !this.streamerClosed) { + this.io.closeStreamer(this); + this.streamerClosed = true; + } + + return hasNext; + } + + /** + * Returns true if we got the last element. + * + * @return true if after last row + * @throws SQLException + * if a database error occurs + */ + public boolean isAfterLast() throws SQLException { + return this.isAfterEnd; + } + + /** + * Returns if iteration has not occured yet. + * + * @return true if before first row + * @throws SQLException + * if a database error occurs + */ + public boolean isBeforeFirst() throws SQLException { + return this.index < 0; + } + + /** + * Returns true if the result set is dynamic. + * + * This means that move back and move forward won't work because we do not + * hold on to the records. + * + * @return true if this result set is streaming from the server + */ + public boolean isDynamic() { + return true; + } + + /** + * Has no records. + * + * @return true if no records + * @throws SQLException + * if a database error occurs + */ + public boolean isEmpty() throws SQLException { + notSupported(); + + return false; + } + + /** + * Are we on the first row of the result set? + * + * @return true if on first row + * @throws SQLException + * if a database error occurs + */ + public boolean isFirst() throws SQLException { + notSupported(); + + return false; + } + + /** + * Are we on the last row of the result set? + * + * @return true if on last row + * @throws SQLException + * if a database error occurs + */ + public boolean isLast() throws SQLException { + notSupported(); + + return false; + } + + /** + * Moves the current position relative 'rows' from the current position. + * + * @param rows + * the relative number of rows to move + * @throws SQLException + * if a database error occurs + */ + public void moveRowRelative(int rows) throws SQLException { + notSupported(); + } + + /** + * Returns the next row. + * + * @return the next row value + * @throws SQLException + * if a database error occurs + */ + public Object[] next() throws SQLException { + if (this.index != Integer.MAX_VALUE) { + this.index++; + } + + Object[] ret = this.nextRow; + nextRecord(); + + return ret; + } + + + private void nextRecord() throws SQLException { + + try { + if (!this.isAtEnd) { + + this.nextRow = this.io.nextRow(this.fields, this.columnCount, + this.isBinaryEncoded, + java.sql.ResultSet.CONCUR_READ_ONLY); + + if (this.nextRow == null) { + this.isAtEnd = true; + + if (this.index == -1) { + this.wasEmpty = true; + } + } + } else { + this.isAfterEnd = true; + } + } catch (CommunicationsException comEx) { + // Give a better error message + comEx.setWasStreamingResults(); + + throw comEx; + } catch (SQLException sqlEx) { + // don't wrap SQLExceptions + throw sqlEx; + } catch (Exception ex) { + String exceptionType = ex.getClass().getName(); + String exceptionMessage = ex.getMessage(); + + exceptionMessage += Messages.getString("RowDataDynamic.7"); //$NON-NLS-1$ + exceptionMessage += Util.stackTraceToString(ex); + + throw new java.sql.SQLException( + Messages.getString("RowDataDynamic.8") //$NON-NLS-1$ + + exceptionType + + Messages.getString("RowDataDynamic.9") + exceptionMessage, SQLError.SQL_STATE_GENERAL_ERROR); //$NON-NLS-1$ + } + } + + private void notSupported() throws SQLException { + throw new OperationNotSupportedException(); + } + + /** + * Removes the row at the given index. + * + * @param index + * the row to move to + * @throws SQLException + * if a database error occurs + */ + public void removeRow(int ind) throws SQLException { + notSupported(); + } + + // ~ Inner Classes + // ---------------------------------------------------------- + + /** + * Moves the current position in the result set to the given row number. + * + * @param rowNumber + * row to move to + * @throws SQLException + * if a database error occurs + */ + public void setCurrentRow(int rowNumber) throws SQLException { + notSupported(); + } + + /** + * @see com.mysql.jdbc.RowData#setOwner(com.mysql.jdbc.ResultSet) + */ + public void setOwner(ResultSet rs) { + this.owner = rs; + } + + /** + * Only works on non dynamic result sets. + * + * @return the size of this row data + */ + public int size() { + return RESULT_SET_SIZE_UNKNOWN; + } + + public boolean wasEmpty() { + return this.wasEmpty; + } + + + +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/RowDataStatic.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/RowDataStatic.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/RowDataStatic.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,260 @@ +/* + Copyright (C) 2002-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents an in-memory result set + * + * @author dgan + * @version $Id: RowDataStatic.java,v 1.1 2012/08/17 14:57:10 marcin Exp $ + */ +public class RowDataStatic implements RowData { + private int index; + + ResultSet owner; + + private List rows; + + /** + * Creates a new RowDataStatic object. + * + * @param rows + * DOCUMENT ME! + */ + public RowDataStatic(ArrayList rows) { + this.index = -1; + this.rows = rows; + } + + /** + * DOCUMENT ME! + * + * @param row + * DOCUMENT ME! + */ + public void addRow(byte[][] row) { + this.rows.add(row); + } + + /** + * Moves to after last. + */ + public void afterLast() { + this.index = this.rows.size(); + } + + /** + * Moves to before first. + */ + public void beforeFirst() { + this.index = -1; + } + + /** + * DOCUMENT ME! + */ + public void beforeLast() { + this.index = this.rows.size() - 2; + } + + /** + * DOCUMENT ME! + */ + public void close() { + } + + /** + * DOCUMENT ME! + * + * @param atIndex + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Object[] getAt(int atIndex) { + if ((atIndex < 0) || (atIndex >= this.rows.size())) { + return null; + } + + return (Object[]) this.rows.get(atIndex); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getCurrentRowNumber() { + return this.index; + } + + /** + * @see com.mysql.jdbc.RowData#getOwner() + */ + public ResultSet getOwner() { + return this.owner; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean hasNext() { + boolean hasMore = (this.index + 1) < this.rows.size(); + + return hasMore; + } + + /** + * Returns true if we got the last element. + * + * @return DOCUMENT ME! + */ + public boolean isAfterLast() { + return this.index >= this.rows.size(); + } + + /** + * Returns if iteration has not occured yet. + * + * @return DOCUMENT ME! + */ + public boolean isBeforeFirst() { + return (this.index == -1) && (this.rows.size() != 0); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isDynamic() { + return false; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isEmpty() { + return this.rows.size() == 0; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isFirst() { + return this.index == 0; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isLast() { + // + // You can never be on the 'last' row of + // an empty result set + // + if (this.rows.size() == 0) { + return false; + } + + return (this.index == (this.rows.size() - 1)); + } + + /** + * DOCUMENT ME! + * + * @param rows + * DOCUMENT ME! + */ + public void moveRowRelative(int rowsToMove) { + this.index += rowsToMove; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Object[] next() { + this.index++; + + if (this.index < this.rows.size()) { + return (Object[]) this.rows.get(this.index); + } + + return null; + } + + /** + * DOCUMENT ME! + * + * @param atIndex + * DOCUMENT ME! + */ + public void removeRow(int atIndex) { + this.rows.remove(atIndex); + } + + /** + * DOCUMENT ME! + * + * @param newIndex + * DOCUMENT ME! + */ + public void setCurrentRow(int newIndex) { + this.index = newIndex; + } + + /** + * @see com.mysql.jdbc.RowData#setOwner(com.mysql.jdbc.ResultSet) + */ + public void setOwner(ResultSet rs) { + this.owner = rs; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int size() { + return this.rows.size(); + } + + public boolean wasEmpty() { + return (this.rows != null && this.rows.size() == 0); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/SQLError.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/SQLError.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/SQLError.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,948 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.DataTruncation; +import java.sql.SQLException; +import java.sql.SQLWarning; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; +import java.util.TreeMap; + +import com.mysql.jdbc.exceptions.MySQLDataException; +import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException; +import com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException; +import com.mysql.jdbc.exceptions.MySQLSyntaxErrorException; +import com.mysql.jdbc.exceptions.MySQLTransactionRollbackException; + +/** + * SQLError is a utility class that maps MySQL error codes to X/Open error codes + * as is required by the JDBC spec. + * + * @author Mark Matthews + * @version $Id: SQLError.java,v 1.1 2012/08/17 14:57:10 marcin Exp $ + */ +public class SQLError { + static final int ER_WARNING_NOT_COMPLETE_ROLLBACK = 1196; + + private static Map mysqlToSql99State; + + private static Map mysqlToSqlState; + + public static final String SQL_STATE_BASE_TABLE_NOT_FOUND = "S0002"; //$NON-NLS-1$ + + public static final String SQL_STATE_BASE_TABLE_OR_VIEW_ALREADY_EXISTS = "S0001"; //$NON-NLS-1$ + + public static final String SQL_STATE_BASE_TABLE_OR_VIEW_NOT_FOUND = "42S02"; //$NON-NLS-1$ + + public static final String SQL_STATE_COLUMN_ALREADY_EXISTS = "S0021"; //$NON-NLS-1$ + + public static final String SQL_STATE_COLUMN_NOT_FOUND = "S0022"; //$NON-NLS-1$ + + public static final String SQL_STATE_COMMUNICATION_LINK_FAILURE = "08S01"; //$NON-NLS-1$ + + public static final String SQL_STATE_CONNECTION_FAIL_DURING_TX = "08007"; //$NON-NLS-1$ + + public static final String SQL_STATE_CONNECTION_IN_USE = "08002"; //$NON-NLS-1$ + + public static final String SQL_STATE_CONNECTION_NOT_OPEN = "08003"; //$NON-NLS-1$ + + public static final String SQL_STATE_CONNECTION_REJECTED = "08004"; //$NON-NLS-1$ + + public static final String SQL_STATE_DATE_TRUNCATED = "01004"; //$NON-NLS-1$ + + public static final String SQL_STATE_DATETIME_FIELD_OVERFLOW = "22008"; //$NON-NLS-1$ + + public static final String SQL_STATE_DEADLOCK = "41000"; //$NON-NLS-1$ + + public static final String SQL_STATE_DISCONNECT_ERROR = "01002"; //$NON-NLS-1$ + + public static final String SQL_STATE_DIVISION_BY_ZERO = "22012"; //$NON-NLS-1$ + + public static final String SQL_STATE_DRIVER_NOT_CAPABLE = "S1C00"; //$NON-NLS-1$ + + public static final String SQL_STATE_ERROR_IN_ROW = "01S01"; //$NON-NLS-1$ + + public static final String SQL_STATE_GENERAL_ERROR = "S1000"; //$NON-NLS-1$ + + public static final String SQL_STATE_ILLEGAL_ARGUMENT = "S1009"; //$NON-NLS-1$ + + public static final String SQL_STATE_INDEX_ALREADY_EXISTS = "S0011"; //$NON-NLS-1$ + + public static final String SQL_STATE_INDEX_NOT_FOUND = "S0012"; //$NON-NLS-1$ + + public static final String SQL_STATE_INSERT_VALUE_LIST_NO_MATCH_COL_LIST = "21S01"; //$NON-NLS-1$ + + public static final String SQL_STATE_INVALID_AUTH_SPEC = "28000"; //$NON-NLS-1$ + + public static final String SQL_STATE_INVALID_CHARACTER_VALUE_FOR_CAST = "22018"; // $NON_NLS-1$ + + public static final String SQL_STATE_INVALID_COLUMN_NUMBER = "S1002"; //$NON-NLS-1$ + + public static final String SQL_STATE_INVALID_CONNECTION_ATTRIBUTE = "01S00"; //$NON-NLS-1$ + + public static final String SQL_STATE_MEMORY_ALLOCATION_FAILURE = "S1001"; //$NON-NLS-1$ + + public static final String SQL_STATE_MORE_THAN_ONE_ROW_UPDATED_OR_DELETED = "01S04"; //$NON-NLS-1$ + + public static final String SQL_STATE_NO_DEFAULT_FOR_COLUMN = "S0023"; //$NON-NLS-1$ + + public static final String SQL_STATE_NO_ROWS_UPDATED_OR_DELETED = "01S03"; //$NON-NLS-1$ + + public static final String SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE = "22003"; //$NON-NLS-1$ + + public static final String SQL_STATE_PRIVILEGE_NOT_REVOKED = "01006"; //$NON-NLS-1$ + + public static final String SQL_STATE_SYNTAX_ERROR = "42000"; //$NON-NLS-1$ + + public static final String SQL_STATE_TIMEOUT_EXPIRED = "S1T00"; //$NON-NLS-1$ + + public static final String SQL_STATE_TRANSACTION_RESOLUTION_UNKNOWN = "08007"; // $NON_NLS-1$ + + public static final String SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE = "08001"; //$NON-NLS-1$ + + public static final String SQL_STATE_WRONG_NO_OF_PARAMETERS = "07001"; //$NON-NLS-1$ + + public static final String SQL_STATE_INVALID_TRANSACTION_TERMINATION = "2D000"; //$NON_NLS-1$ + + private static Map sqlStateMessages; + + static { + sqlStateMessages = new HashMap(); + sqlStateMessages.put(SQL_STATE_DISCONNECT_ERROR, Messages + .getString("SQLError.35")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_DATE_TRUNCATED, Messages + .getString("SQLError.36")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_PRIVILEGE_NOT_REVOKED, Messages + .getString("SQLError.37")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, Messages + .getString("SQLError.38")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_ERROR_IN_ROW, Messages + .getString("SQLError.39")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_NO_ROWS_UPDATED_OR_DELETED, Messages + .getString("SQLError.40")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_MORE_THAN_ONE_ROW_UPDATED_OR_DELETED, + Messages.getString("SQLError.41")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_WRONG_NO_OF_PARAMETERS, Messages + .getString("SQLError.42")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, + Messages.getString("SQLError.43")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_CONNECTION_IN_USE, Messages + .getString("SQLError.44")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_CONNECTION_NOT_OPEN, Messages + .getString("SQLError.45")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_CONNECTION_REJECTED, Messages + .getString("SQLError.46")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_CONNECTION_FAIL_DURING_TX, Messages + .getString("SQLError.47")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_COMMUNICATION_LINK_FAILURE, Messages + .getString("SQLError.48")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_INSERT_VALUE_LIST_NO_MATCH_COL_LIST, + Messages.getString("SQLError.49")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE, Messages + .getString("SQLError.50")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_DATETIME_FIELD_OVERFLOW, Messages + .getString("SQLError.51")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_DIVISION_BY_ZERO, Messages + .getString("SQLError.52")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_DEADLOCK, Messages + .getString("SQLError.53")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_INVALID_AUTH_SPEC, Messages + .getString("SQLError.54")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_SYNTAX_ERROR, Messages + .getString("SQLError.55")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_BASE_TABLE_OR_VIEW_NOT_FOUND, Messages + .getString("SQLError.56")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_BASE_TABLE_OR_VIEW_ALREADY_EXISTS, + Messages.getString("SQLError.57")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_BASE_TABLE_NOT_FOUND, Messages + .getString("SQLError.58")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_INDEX_ALREADY_EXISTS, Messages + .getString("SQLError.59")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_INDEX_NOT_FOUND, Messages + .getString("SQLError.60")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_COLUMN_ALREADY_EXISTS, Messages + .getString("SQLError.61")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_COLUMN_NOT_FOUND, Messages + .getString("SQLError.62")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_NO_DEFAULT_FOR_COLUMN, Messages + .getString("SQLError.63")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_GENERAL_ERROR, Messages + .getString("SQLError.64")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_MEMORY_ALLOCATION_FAILURE, Messages + .getString("SQLError.65")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_INVALID_COLUMN_NUMBER, Messages + .getString("SQLError.66")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_ILLEGAL_ARGUMENT, Messages + .getString("SQLError.67")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_DRIVER_NOT_CAPABLE, Messages + .getString("SQLError.68")); //$NON-NLS-1$ + sqlStateMessages.put(SQL_STATE_TIMEOUT_EXPIRED, Messages + .getString("SQLError.69")); //$NON-NLS-1$ + + mysqlToSqlState = new Hashtable(); + + // + // Communications Errors + // + // ER_CON_COUNT_ERROR 1040 + // ER_BAD_HOST_ERROR 1042 + // ER_HANDSHAKE_ERROR 1043 + // ER_UNKNOWN_COM_ERROR 1047 + // ER_IPSOCK_ERROR 1081 + // + mysqlToSqlState.put(new Integer(1040), SQL_STATE_CONNECTION_REJECTED); + mysqlToSqlState.put(new Integer(1042), SQL_STATE_CONNECTION_REJECTED); + mysqlToSqlState.put(new Integer(1043), SQL_STATE_CONNECTION_REJECTED); + mysqlToSqlState.put(new Integer(1047), + SQL_STATE_COMMUNICATION_LINK_FAILURE); + mysqlToSqlState.put(new Integer(1081), + SQL_STATE_COMMUNICATION_LINK_FAILURE); + + // ER_HOST_IS_BLOCKED 1129 + // ER_HOST_NOT_PRIVILEGED 1130 + mysqlToSqlState.put(new Integer(1129), SQL_STATE_CONNECTION_REJECTED); + mysqlToSqlState.put(new Integer(1130), SQL_STATE_CONNECTION_REJECTED); + + // + // Authentication Errors + // + // ER_ACCESS_DENIED_ERROR 1045 + // + mysqlToSqlState.put(new Integer(1045), SQL_STATE_INVALID_AUTH_SPEC); + + // + // Resource errors + // + // ER_CANT_CREATE_FILE 1004 + // ER_CANT_CREATE_TABLE 1005 + // ER_CANT_LOCK 1015 + // ER_DISK_FULL 1021 + // ER_CON_COUNT_ERROR 1040 + // ER_OUT_OF_RESOURCES 1041 + // + // Out-of-memory errors + // + // ER_OUTOFMEMORY 1037 + // ER_OUT_OF_SORTMEMORY 1038 + // + mysqlToSqlState.put(new Integer(1037), + SQL_STATE_MEMORY_ALLOCATION_FAILURE); + mysqlToSqlState.put(new Integer(1038), + SQL_STATE_MEMORY_ALLOCATION_FAILURE); + + // + // Syntax Errors + // + // ER_PARSE_ERROR 1064 + // ER_EMPTY_QUERY 1065 + // + mysqlToSqlState.put(new Integer(1064), SQL_STATE_SYNTAX_ERROR); + mysqlToSqlState.put(new Integer(1065), SQL_STATE_SYNTAX_ERROR); + + // + // Invalid argument errors + // + // ER_WRONG_FIELD_WITH_GROUP 1055 + // ER_WRONG_GROUP_FIELD 1056 + // ER_WRONG_SUM_SELECT 1057 + // ER_TOO_LONG_IDENT 1059 + // ER_DUP_FIELDNAME 1060 + // ER_DUP_KEYNAME 1061 + // ER_DUP_ENTRY 1062 + // ER_WRONG_FIELD_SPEC 1063 + // ER_NONUNIQ_TABLE 1066 + // ER_INVALID_DEFAULT 1067 + // ER_MULTIPLE_PRI_KEY 1068 + // ER_TOO_MANY_KEYS 1069 + // ER_TOO_MANY_KEY_PARTS 1070 + // ER_TOO_LONG_KEY 1071 + // ER_KEY_COLUMN_DOES_NOT_EXIST 1072 + // ER_BLOB_USED_AS_KEY 1073 + // ER_TOO_BIG_FIELDLENGTH 1074 + // ER_WRONG_AUTO_KEY 1075 + // ER_NO_SUCH_INDEX 1082 + // ER_WRONG_FIELD_TERMINATORS 1083 + // ER_BLOBS_AND_NO_TERMINATED 1084 + // + mysqlToSqlState.put(new Integer(1055), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1056), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1057), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1059), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1060), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1061), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1062), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1063), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1066), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1067), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1068), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1069), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1070), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1071), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1072), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1073), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1074), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1075), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1082), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1083), SQL_STATE_ILLEGAL_ARGUMENT); + mysqlToSqlState.put(new Integer(1084), SQL_STATE_ILLEGAL_ARGUMENT); + + // + // ER_WRONG_VALUE_COUNT 1058 + // + mysqlToSqlState.put(new Integer(1058), + SQL_STATE_INSERT_VALUE_LIST_NO_MATCH_COL_LIST); + + // ER_CANT_CREATE_DB 1006 + // ER_DB_CREATE_EXISTS 1007 + // ER_DB_DROP_EXISTS 1008 + // ER_DB_DROP_DELETE 1009 + // ER_DB_DROP_RMDIR 1010 + // ER_CANT_DELETE_FILE 1011 + // ER_CANT_FIND_SYSTEM_REC 1012 + // ER_CANT_GET_STAT 1013 + // ER_CANT_GET_WD 1014 + // ER_UNEXPECTED_EOF 1039 + // ER_CANT_OPEN_FILE 1016 + // ER_FILE_NOT_FOUND 1017 + // ER_CANT_READ_DIR 1018 + // ER_CANT_SET_WD 1019 + // ER_CHECKREAD 1020 + // ER_DUP_KEY 1022 + // ER_ERROR_ON_CLOSE 1023 + // ER_ERROR_ON_READ 1024 + // ER_ERROR_ON_RENAME 1025 + // ER_ERROR_ON_WRITE 1026 + // ER_FILE_USED 1027 + // ER_FILSORT_ABORT 1028 + // ER_FORM_NOT_FOUND 1029 + // ER_GET_ERRNO 1030 + // ER_ILLEGAL_HA 1031 + // ER_KEY_NOT_FOUND 1032 + // ER_NOT_FORM_FILE 1033 + // ER_DBACCESS_DENIED_ERROR 1044 + // ER_NO_DB_ERROR 1046 + // ER_BAD_NULL_ERROR 1048 + // ER_BAD_DB_ERROR 1049 + // ER_TABLE_EXISTS_ERROR 1050 + // ER_BAD_TABLE_ERROR 1051 + mysqlToSqlState.put(new Integer(1051), + SQL_STATE_BASE_TABLE_OR_VIEW_NOT_FOUND); + + // ER_NON_UNIQ_ERROR 1052 + // ER_BAD_FIELD_ERROR 1054 + mysqlToSqlState.put(new Integer(1054), SQL_STATE_COLUMN_NOT_FOUND); + + // ER_TEXTFILE_NOT_READABLE 1085 + // ER_FILE_EXISTS_ERROR 1086 + // ER_LOAD_INFO 1087 + // ER_ALTER_INFO 1088 + // ER_WRONG_SUB_KEY 1089 + // ER_CANT_REMOVE_ALL_FIELDS 1090 + // ER_CANT_DROP_FIELD_OR_KEY 1091 + // ER_INSERT_INFO 1092 + // ER_INSERT_TABLE_USED 1093 + // ER_LOCK_DEADLOCK 1213 + mysqlToSqlState.put(new Integer(1205), SQL_STATE_DEADLOCK); + mysqlToSqlState.put(new Integer(1213), SQL_STATE_DEADLOCK); + + mysqlToSql99State = new HashMap(); + + mysqlToSql99State.put(new Integer(1205), SQL_STATE_DEADLOCK); + mysqlToSql99State.put(new Integer(1213), SQL_STATE_DEADLOCK); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_DUP_KEY), + "23000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_OUTOFMEMORY), + "HY001"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_OUT_OF_SORTMEMORY), "HY001"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_CON_COUNT_ERROR), "08004"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_BAD_HOST_ERROR), + "08S01"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_HANDSHAKE_ERROR), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_DBACCESS_DENIED_ERROR), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_ACCESS_DENIED_ERROR), "28000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TABLE_EXISTS_ERROR), "42S01"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_BAD_TABLE_ERROR), "42S02"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_NON_UNIQ_ERROR), + "23000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_SERVER_SHUTDOWN), "08S01"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_BAD_FIELD_ERROR), "42S22"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_FIELD_WITH_GROUP), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_GROUP_FIELD), "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_WRONG_SUM_SELECT), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_VALUE_COUNT), "21S01"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_TOO_LONG_IDENT), + "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_DUP_FIELDNAME), + "42S21"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_DUP_KEYNAME), + "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_DUP_ENTRY), + "23000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_WRONG_FIELD_SPEC), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_PARSE_ERROR), + "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_EMPTY_QUERY), + "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_NONUNIQ_TABLE), + "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_INVALID_DEFAULT), "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_MULTIPLE_PRI_KEY), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_TOO_MANY_KEYS), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TOO_MANY_KEY_PARTS), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_TOO_LONG_KEY), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_KEY_COLUMN_DOES_NOT_EXITS), "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_BLOB_USED_AS_KEY), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TOO_BIG_FIELDLENGTH), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_WRONG_AUTO_KEY), + "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_FORCING_CLOSE), + "08S01"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_IPSOCK_ERROR), + "08S01"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_NO_SUCH_INDEX), + "42S12"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_FIELD_TERMINATORS), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_BLOBS_AND_NO_TERMINATED), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_CANT_REMOVE_ALL_FIELDS), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_CANT_DROP_FIELD_OR_KEY), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_BLOB_CANT_HAVE_DEFAULT), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_WRONG_DB_NAME), + "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_WRONG_TABLE_NAME), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_TOO_BIG_SELECT), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_UNKNOWN_PROCEDURE), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_PARAMCOUNT_TO_PROCEDURE), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_UNKNOWN_TABLE), + "42S02"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_FIELD_SPECIFIED_TWICE), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_UNSUPPORTED_EXTENSION), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TABLE_MUST_HAVE_COLUMNS), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_UNKNOWN_CHARACTER_SET), "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_TOO_BIG_ROWSIZE), "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_WRONG_OUTER_JOIN), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NULL_COLUMN_IN_INDEX), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_PASSWORD_ANONYMOUS_USER), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_PASSWORD_NOT_ALLOWED), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_PASSWORD_NO_MATCH), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_VALUE_COUNT_ON_ROW), "21S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_INVALID_USE_OF_NULL), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_REGEXP_ERROR), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_MIX_OF_GROUP_FUNC_AND_FIELDS), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NONEXISTING_GRANT), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TABLEACCESS_DENIED_ERROR), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_COLUMNACCESS_DENIED_ERROR), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_ILLEGAL_GRANT_FOR_TABLE), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_GRANT_WRONG_HOST_OR_USER), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_NO_SUCH_TABLE), + "42S02"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NONEXISTING_TABLE_GRANT), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NOT_ALLOWED_COMMAND), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_SYNTAX_ERROR), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_ABORTING_CONNECTION), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NET_PACKET_TOO_LARGE), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NET_READ_ERROR_FROM_PIPE), "08S01"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_NET_FCNTL_ERROR), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NET_PACKETS_OUT_OF_ORDER), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NET_UNCOMPRESS_ERROR), "08S01"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_NET_READ_ERROR), + "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NET_READ_INTERRUPTED), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NET_ERROR_ON_WRITE), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NET_WRITE_INTERRUPTED), "08S01"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_TOO_LONG_STRING), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TABLE_CANT_HANDLE_BLOB), "42000"); + mysqlToSql99State + .put(new Integer( + MysqlErrorNumbers.ER_TABLE_CANT_HANDLE_AUTO_INCREMENT), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_COLUMN_NAME), "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_WRONG_KEY_COLUMN), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_DUP_UNIQUE), + "23000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_BLOB_KEY_WITHOUT_LENGTH), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_PRIMARY_CANT_HAVE_NULL), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_TOO_MANY_ROWS), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_REQUIRES_PRIMARY_KEY), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_CHECK_NO_SUCH_TABLE), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_CHECK_NOT_IMPLEMENTED), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_CANT_DO_THIS_DURING_AN_TRANSACTION), + "25000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NEW_ABORTING_CONNECTION), "08S01"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_MASTER_NET_READ), "08S01"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_MASTER_NET_WRITE), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TOO_MANY_USER_CONNECTIONS), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_READ_ONLY_TRANSACTION), "25000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NO_PERMISSION_TO_CREATE_USER), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_LOCK_DEADLOCK), + "40001"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NO_REFERENCED_ROW), "23000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_ROW_IS_REFERENCED), "23000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_CONNECT_TO_MASTER), "08S01"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT), + "21000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_USER_LIMIT_REACHED), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_NO_DEFAULT), + "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_VALUE_FOR_VAR), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_TYPE_FOR_VAR), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_CANT_USE_OPTION_HERE), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NOT_SUPPORTED_YET), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_WRONG_FK_DEF), + "42000"); + mysqlToSql99State.put( + new Integer(MysqlErrorNumbers.ER_OPERAND_COLUMNS), "21000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_SUBQUERY_NO_1_ROW), "21000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_ILLEGAL_REFERENCE), "42S22"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_DERIVED_MUST_HAVE_ALIAS), "42000"); + mysqlToSql99State.put(new Integer(MysqlErrorNumbers.ER_SELECT_REDUCED), + "01000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_TABLENAME_NOT_ALLOWED_HERE), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_NOT_SUPPORTED_AUTH_MODE), "08004"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_SPATIAL_CANT_HAVE_NULL), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_COLLATION_CHARSET_MISMATCH), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WARN_TOO_FEW_RECORDS), "01000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WARN_TOO_MANY_RECORDS), "01000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WARN_NULL_TO_NOTNULL), "01000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WARN_DATA_OUT_OF_RANGE), "01000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WARN_DATA_TRUNCATED), "01000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_NAME_FOR_INDEX), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_WRONG_NAME_FOR_CATALOG), "42000"); + mysqlToSql99State.put(new Integer( + MysqlErrorNumbers.ER_UNKNOWN_STORAGE_ENGINE), "42000"); + } + + /** + * Turns output of 'SHOW WARNINGS' into JDBC SQLWarning instances. + * + * If 'forTruncationOnly' is true, only looks for truncation warnings, and + * actually throws DataTruncation as an exception. + * + * @param connection + * the connection to use for getting warnings. + * + * @return the SQLWarning chain (or null if no warnings) + * + * @throws SQLException + * if the warnings could not be retrieved + */ + static SQLWarning convertShowWarningsToSQLWarnings(Connection connection) + throws SQLException { + return convertShowWarningsToSQLWarnings(connection, 0, false); + } + + /** + * Turns output of 'SHOW WARNINGS' into JDBC SQLWarning instances. + * + * If 'forTruncationOnly' is true, only looks for truncation warnings, and + * actually throws DataTruncation as an exception. + * + * @param connection + * the connection to use for getting warnings. + * @param warningCountIfKnown + * the warning count (if known), otherwise set it to 0. + * @param forTruncationOnly + * if this method should only scan for data truncation warnings + * + * @return the SQLWarning chain (or null if no warnings) + * + * @throws SQLException + * if the warnings could not be retrieved, or if data truncation + * is being scanned for and truncations were found. + */ + static SQLWarning convertShowWarningsToSQLWarnings(Connection connection, + int warningCountIfKnown, boolean forTruncationOnly) + throws SQLException { + java.sql.Statement stmt = null; + java.sql.ResultSet warnRs = null; + + SQLWarning currentWarning = null; + + try { + if (warningCountIfKnown < 100) { + stmt = connection.createStatement(); + + if (stmt.getMaxRows() != 0) { + stmt.setMaxRows(0); + } + } else { + // stream large warning counts + stmt = connection.createStatement( + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY); + stmt.setFetchSize(Integer.MIN_VALUE); + } + + /* + * +---------+------+---------------------------------------------+ | + * Level | Code | Message | + * +---------+------+---------------------------------------------+ | + * Warning | 1265 | Data truncated for column 'field1' at row 1 | + * +---------+------+---------------------------------------------+ + */ + warnRs = stmt.executeQuery("SHOW WARNINGS"); //$NON-NLS-1$ + + while (warnRs.next()) { + int code = warnRs.getInt("Code"); //$NON-NLS-1$ + + if (forTruncationOnly) { + if (code == 1265 || code == 1264) { + DataTruncation newTruncation = new MysqlDataTruncation( + warnRs.getString("Message"), 0, false, false, 0, 0); //$NON-NLS-1$ + + if (currentWarning == null) { + currentWarning = newTruncation; + } else { + currentWarning.setNextWarning(newTruncation); + } + } + } else { + String level = warnRs.getString("Level"); //$NON-NLS-1$ + String message = warnRs.getString("Message"); //$NON-NLS-1$ + + SQLWarning newWarning = new SQLWarning(message, SQLError + .mysqlToSqlState(code, connection + .getUseSqlStateCodes()), code); + + if (currentWarning == null) { + currentWarning = newWarning; + } else { + currentWarning.setNextWarning(newWarning); + } + } + } + + if (forTruncationOnly && (currentWarning != null)) { + throw currentWarning; + } + + return currentWarning; + } finally { + SQLException reThrow = null; + + if (warnRs != null) { + try { + warnRs.close(); + } catch (SQLException sqlEx) { + reThrow = sqlEx; + } + } + + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { + // ideally, we'd use chained exceptions here, + // but we still support JDK-1.2.x with this driver + // which doesn't have them.... + reThrow = sqlEx; + } + } + + if (reThrow != null) { + throw reThrow; + } + } + } + + public static void dumpSqlStatesMappingsAsXml() throws Exception { + TreeMap allErrorNumbers = new TreeMap(); + Map mysqlErrorNumbersToNames = new HashMap(); + + Integer errorNumber = null; + + // + // First create a list of all 'known' error numbers that + // are mapped. + // + for (Iterator mysqlErrorNumbers = mysqlToSql99State.keySet().iterator(); mysqlErrorNumbers + .hasNext();) { + errorNumber = (Integer) mysqlErrorNumbers.next(); + allErrorNumbers.put(errorNumber, errorNumber); + } + + for (Iterator mysqlErrorNumbers = mysqlToSqlState.keySet().iterator(); mysqlErrorNumbers + .hasNext();) { + errorNumber = (Integer) mysqlErrorNumbers.next(); + allErrorNumbers.put(errorNumber, errorNumber); + } + + // + // Now create a list of the actual MySQL error numbers we know about + // + java.lang.reflect.Field[] possibleFields = MysqlErrorNumbers.class + .getDeclaredFields(); + + for (int i = 0; i < possibleFields.length; i++) { + String fieldName = possibleFields[i].getName(); + + if (fieldName.startsWith("ER_")) { + mysqlErrorNumbersToNames.put(possibleFields[i].get(null), + fieldName); + } + } + + System.out.println(""); + + for (Iterator allErrorNumbersIter = allErrorNumbers.keySet().iterator(); allErrorNumbersIter + .hasNext();) { + errorNumber = (Integer) allErrorNumbersIter.next(); + + String sql92State = mysqlToSql99(errorNumber.intValue()); + String oldSqlState = mysqlToXOpen(errorNumber.intValue()); + + System.out.println(" "); + } + + System.out.println(""); + } + + static String get(String stateCode) { + return (String) sqlStateMessages.get(stateCode); + } + + private static String mysqlToSql99(int errno) { + Integer err = new Integer(errno); + + if (mysqlToSql99State.containsKey(err)) { + return (String) mysqlToSql99State.get(err); + } + + return "HY000"; + } + + /** + * Map MySQL error codes to X/Open or SQL-92 error codes + * + * @param errno + * the MySQL error code + * + * @return the corresponding X/Open or SQL-92 error code + */ + static String mysqlToSqlState(int errno, boolean useSql92States) { + if (useSql92States) { + return mysqlToSql99(errno); + } + + return mysqlToXOpen(errno); + } + + private static String mysqlToXOpen(int errno) { + Integer err = new Integer(errno); + + if (mysqlToSqlState.containsKey(err)) { + return (String) mysqlToSqlState.get(err); + } + + return SQL_STATE_GENERAL_ERROR; + } + + /* + * SQL State Class SQLNonTransientException Subclass 08 + * SQLNonTransientConnectionException 22 SQLDataException 23 + * SQLIntegrityConstraintViolationException N/A + * SQLInvalidAuthorizationException 42 SQLSyntaxErrorException + * + * SQL State Class SQLTransientException Subclass 08 + * SQLTransientConnectionException 40 SQLTransactionRollbackException N/A + * SQLTimeoutException + */ + + public static SQLException createSQLException(String message, + String sqlState) { + if (sqlState != null) { + if (sqlState.startsWith("08")) { + return new MySQLNonTransientConnectionException(message, + sqlState); + } + + if (sqlState.startsWith("22")) { + return new MySQLDataException(message, sqlState); + } + + if (sqlState.startsWith("23")) { + return new MySQLIntegrityConstraintViolationException(message, + sqlState); + } + + if (sqlState.startsWith("42")) { + return new MySQLSyntaxErrorException(message, sqlState); + } + + if (sqlState.startsWith("40")) { + return new MySQLTransactionRollbackException(message, sqlState); + } + } + + return new SQLException(message, sqlState); + } + + public static SQLException createSQLException(String message) { + return new SQLException(message); + } + + public static SQLException createSQLException(String message, + String sqlState, int vendorErrorCode) { + if (sqlState != null) { + if (sqlState.startsWith("08")) { + return new MySQLNonTransientConnectionException(message, + sqlState, vendorErrorCode); + } + + if (sqlState.startsWith("22")) { + return new MySQLDataException(message, sqlState, + vendorErrorCode); + } + + if (sqlState.startsWith("23")) { + return new MySQLIntegrityConstraintViolationException(message, + sqlState, vendorErrorCode); + } + + if (sqlState.startsWith("42")) { + return new MySQLSyntaxErrorException(message, sqlState, + vendorErrorCode); + } + + if (sqlState.startsWith("40")) { + return new MySQLTransactionRollbackException(message, sqlState, + vendorErrorCode); + } + } + + return new SQLException(message, sqlState, vendorErrorCode); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Security.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Security.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Security.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,353 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * Methods for doing secure authentication with MySQL-4.1 and newer. + * + * @author Mark Matthews + * + * @version $Id: Security.java,v 1.1 2012/08/17 14:57:08 marcin Exp $ + */ +class Security { + private static final char PVERSION41_CHAR = '*'; + + private static final int SHA1_HASH_SIZE = 20; + + /** + * Returns hex value for given char + */ + private static int charVal(char c) { + return ((c >= '0') && (c <= '9')) ? (c - '0') + : (((c >= 'A') && (c <= 'Z')) ? (c - 'A' + 10) : (c - 'a' + 10)); + } + + /* + * Convert password in salted form to binary string password and hash-salt + * For old password this involes one more hashing + * + * SYNOPSIS get_hash_and_password() salt IN Salt to convert from pversion IN + * Password version to use hash OUT Store zero ended hash here bin_password + * OUT Store binary password here (no zero at the end) + * + * RETURN 0 for pre 4.1 passwords !0 password version char for newer + * passwords + */ + + /** + * Creates key from old password to decode scramble Used in 4.1 + * authentication with passwords stored pre-4.1 hashing. + * + * @param passwd + * the password to create the key from + * + * @return 20 byte generated key + * + * @throws NoSuchAlgorithmException + * if the message digest 'SHA-1' is not available. + */ + static byte[] createKeyFromOldPassword(String passwd) + throws NoSuchAlgorithmException { + /* At first hash password to the string stored in password */ + passwd = makeScrambledPassword(passwd); + + /* Now convert it to the salt form */ + int[] salt = getSaltFromPassword(passwd); + + /* Finally get hash and bin password from salt */ + return getBinaryPassword(salt, false); + } + + /** + * DOCUMENT ME! + * + * @param salt + * DOCUMENT ME! + * @param usingNewPasswords + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws NoSuchAlgorithmException + * if the message digest 'SHA-1' is not available. + */ + static byte[] getBinaryPassword(int[] salt, boolean usingNewPasswords) + throws NoSuchAlgorithmException { + int val = 0; + + byte[] binaryPassword = new byte[SHA1_HASH_SIZE]; /* + * Binary password + * loop pointer + */ + + if (usingNewPasswords) /* New password version assumed */{ + int pos = 0; + + for (int i = 0; i < 4; i++) /* Iterate over these elements */{ + val = salt[i]; + + for (int t = 3; t >= 0; t--) { + binaryPassword[pos++] = (byte) (val & 255); + val >>= 8; /* Scroll 8 bits to get next part */ + } + } + + return binaryPassword; + } + + int offset = 0; + + for (int i = 0; i < 2; i++) /* Iterate over these elements */{ + val = salt[i]; + + for (int t = 3; t >= 0; t--) { + binaryPassword[t + offset] = (byte) (val % 256); + val >>= 8; /* Scroll 8 bits to get next part */ + } + + offset += 4; + } + + MessageDigest md = MessageDigest.getInstance("SHA-1"); //$NON-NLS-1$ + + md.update(binaryPassword, 0, 8); + + return md.digest(); + } + + private static int[] getSaltFromPassword(String password) { + int[] result = new int[6]; + + if ((password == null) || (password.length() == 0)) { + return result; + } + + if (password.charAt(0) == PVERSION41_CHAR) { + // new password + String saltInHex = password.substring(1, 5); + + int val = 0; + + for (int i = 0; i < 4; i++) { + val = (val << 4) + charVal(saltInHex.charAt(i)); + } + + return result; + } + + int resultPos = 0; + int pos = 0; + int length = password.length(); + + while (pos < length) { + int val = 0; + + for (int i = 0; i < 8; i++) { + val = (val << 4) + charVal(password.charAt(pos++)); + } + + result[resultPos++] = val; + } + + return result; + } + + private static String longToHex(long val) { + String longHex = Long.toHexString(val); + + int length = longHex.length(); + + if (length < 8) { + int padding = 8 - length; + StringBuffer buf = new StringBuffer(); + + for (int i = 0; i < padding; i++) { + buf.append("0"); //$NON-NLS-1$ + } + + buf.append(longHex); + + return buf.toString(); + } + + return longHex.substring(0, 8); + } + + /** + * Creates password to be stored in user database from raw string. + * + * Handles Pre-MySQL 4.1 passwords. + * + * @param password + * plaintext password + * + * @return scrambled password + * + * @throws NoSuchAlgorithmException + * if the message digest 'SHA-1' is not available. + */ + static String makeScrambledPassword(String password) + throws NoSuchAlgorithmException { + long[] passwordHash = Util.newHash(password); + StringBuffer scramble = new StringBuffer(); + + scramble.append(longToHex(passwordHash[0])); + scramble.append(longToHex(passwordHash[1])); + + return scramble.toString(); + } + + /** + * Encrypt/Decrypt function used for password encryption in authentication + * + * Simple XOR is used here but it is OK as we crypt random strings + * + * @param from + * IN Data for encryption + * @param to + * OUT Encrypt data to the buffer (may be the same) + * @param password + * IN Password used for encryption (same length) + * @param length + * IN Length of data to encrypt + */ + static void passwordCrypt(byte[] from, byte[] to, byte[] password, + int length) { + int pos = 0; + + while ((pos < from.length) && (pos < length)) { + to[pos] = (byte) (from[pos] ^ password[pos]); + pos++; + } + } + + /** + * Stage one password hashing, used in MySQL 4.1 password handling + * + * @param password + * plaintext password + * + * @return stage one hash of password + * + * @throws NoSuchAlgorithmException + * if the message digest 'SHA-1' is not available. + */ + static byte[] passwordHashStage1(String password) + throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-1"); //$NON-NLS-1$ + StringBuffer cleansedPassword = new StringBuffer(); + + int passwordLength = password.length(); + + for (int i = 0; i < passwordLength; i++) { + char c = password.charAt(i); + + if ((c == ' ') || (c == '\t')) { + continue; /* skip space in password */ + } + + cleansedPassword.append(c); + } + + return md.digest(cleansedPassword.toString().getBytes()); + } + + /** + * Stage two password hashing used in MySQL 4.1 password handling + * + * @param hash + * from passwordHashStage1 + * @param salt + * salt used for stage two hashing + * + * @return result of stage two password hash + * + * @throws NoSuchAlgorithmException + * if the message digest 'SHA-1' is not available. + */ + static byte[] passwordHashStage2(byte[] hashedPassword, byte[] salt) + throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-1"); //$NON-NLS-1$ + + // hash 4 bytes of salt + md.update(salt, 0, 4); + + md.update(hashedPassword, 0, SHA1_HASH_SIZE); + + return md.digest(); + } + + // SERVER: public_seed=create_random_string() + // send(public_seed) + // + // CLIENT: recv(public_seed) + // hash_stage1=sha1("password") + // hash_stage2=sha1(hash_stage1) + // reply=xor(hash_stage1, sha1(public_seed,hash_stage2) + // + // // this three steps are done in scramble() + // + // send(reply) + // + // + // SERVER: recv(reply) + // hash_stage1=xor(reply, sha1(public_seed,hash_stage2)) + // candidate_hash2=sha1(hash_stage1) + // check(candidate_hash2==hash_stage2) + static byte[] scramble411(String password, String seed) + throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-1"); //$NON-NLS-1$ + + byte[] passwordHashStage1 = md.digest(password.getBytes()); + md.reset(); + + byte[] passwordHashStage2 = md.digest(passwordHashStage1); + md.reset(); + + byte[] seedAsBytes = seed.getBytes(); // for debugging + md.update(seedAsBytes); + md.update(passwordHashStage2); + + byte[] toBeXord = md.digest(); + + int numToXor = toBeXord.length; + + for (int i = 0; i < numToXor; i++) { + toBeXord[i] = (byte) (toBeXord[i] ^ passwordHashStage1[i]); + } + + return toBeXord; + } + + /** + * Prevent construction. + */ + private Security() { + super(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/ServerPreparedStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/ServerPreparedStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/ServerPreparedStatement.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,2722 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import com.mysql.jdbc.PreparedStatement.BatchParams; +import com.mysql.jdbc.Statement.CancelTask; +import com.mysql.jdbc.exceptions.MySQLTimeoutException; +import com.mysql.jdbc.profiler.ProfileEventSink; +import com.mysql.jdbc.profiler.ProfilerEvent; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.UnsupportedEncodingException; + +import java.math.BigDecimal; + +import java.net.URL; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.ParameterMetaData; +import java.sql.Ref; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.Calendar; +import java.util.Locale; +import java.util.TimeZone; + +/** + * JDBC Interface for MySQL-4.1 and newer server-side PreparedStatements. + * + * @author Mark Matthews + * @version $Id: ServerPreparedStatement.java,v 1.1.2.2 2005/05/17 14:58:56 + * mmatthews Exp $ + */ +public class ServerPreparedStatement extends PreparedStatement { + protected static final int BLOB_STREAM_READ_BUF_SIZE = 8192; + + static class BatchedBindValues { + BindValue[] batchedParameterValues; + + BatchedBindValues(BindValue[] paramVals) { + int numParams = paramVals.length; + + this.batchedParameterValues = new BindValue[numParams]; + + for (int i = 0; i < numParams; i++) { + this.batchedParameterValues[i] = new BindValue(paramVals[i]); + } + } + } + + static class BindValue { + + long boundBeforeExecutionNum = 0; + + long bindLength; /* Default length of data */ + + int bufferType; /* buffer type */ + + byte byteBinding; + + double doubleBinding; + + float floatBinding; + + int intBinding; + + boolean isLongData; /* long data indicator */ + + boolean isNull; /* NULL indicator */ + + boolean isSet = false; /* has this parameter been set? */ + + long longBinding; + + short shortBinding; + + Object value; /* The value to store */ + + BindValue() { + } + + BindValue(BindValue copyMe) { + this.value = copyMe.value; + this.isSet = copyMe.isSet; + this.isLongData = copyMe.isLongData; + this.isNull = copyMe.isNull; + this.bufferType = copyMe.bufferType; + this.bindLength = copyMe.bindLength; + this.byteBinding = copyMe.byteBinding; + this.shortBinding = copyMe.shortBinding; + this.intBinding = copyMe.intBinding; + this.longBinding = copyMe.longBinding; + this.floatBinding = copyMe.floatBinding; + this.doubleBinding = copyMe.doubleBinding; + } + + void reset() { + this.isSet = false; + this.value = null; + this.isLongData = false; + + this.byteBinding = 0; + this.shortBinding = 0; + this.intBinding = 0; + this.longBinding = 0L; + this.floatBinding = 0; + this.doubleBinding = 0D; + } + + public String toString() { + return toString(false); + } + + public String toString(boolean quoteIfNeeded) { + if (this.isLongData) { + return "' STREAM DATA '"; + } + + switch (this.bufferType) { + case MysqlDefs.FIELD_TYPE_TINY: + return String.valueOf(byteBinding); + case MysqlDefs.FIELD_TYPE_SHORT: + return String.valueOf(shortBinding); + case MysqlDefs.FIELD_TYPE_LONG: + return String.valueOf(intBinding); + case MysqlDefs.FIELD_TYPE_LONGLONG: + return String.valueOf(longBinding); + case MysqlDefs.FIELD_TYPE_FLOAT: + return String.valueOf(floatBinding); + case MysqlDefs.FIELD_TYPE_DOUBLE: + return String.valueOf(doubleBinding); + case MysqlDefs.FIELD_TYPE_TIME: + case MysqlDefs.FIELD_TYPE_DATE: + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + case MysqlDefs.FIELD_TYPE_VAR_STRING: + case MysqlDefs.FIELD_TYPE_STRING: + case MysqlDefs.FIELD_TYPE_VARCHAR: + if (quoteIfNeeded) { + return "'" + String.valueOf(value) + "'"; + } else { + return String.valueOf(value); + } + default: + if (value instanceof byte[]) { + return "byte data"; + + } else { + if (quoteIfNeeded) { + return "'" + String.valueOf(value) + "'"; + } else { + return String.valueOf(value); + } + } + } + } + + long getBoundLength() { + if (isNull) { + return 0; + } + + if (isLongData) { + return bindLength; + } + + switch (bufferType) { + + case MysqlDefs.FIELD_TYPE_TINY: + return 1; + case MysqlDefs.FIELD_TYPE_SHORT: + return 2; + case MysqlDefs.FIELD_TYPE_LONG: + return 4; + case MysqlDefs.FIELD_TYPE_LONGLONG: + return 8; + case MysqlDefs.FIELD_TYPE_FLOAT: + return 4; + case MysqlDefs.FIELD_TYPE_DOUBLE: + return 8; + case MysqlDefs.FIELD_TYPE_TIME: + return 9; + case MysqlDefs.FIELD_TYPE_DATE: + return 7; + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + return 11; + case MysqlDefs.FIELD_TYPE_VAR_STRING: + case MysqlDefs.FIELD_TYPE_STRING: + case MysqlDefs.FIELD_TYPE_VARCHAR: + case MysqlDefs.FIELD_TYPE_DECIMAL: + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + if (value instanceof byte[]) { + return ((byte[]) value).length; + } else { + return ((String) value).length(); + } + default: + return 0; + } + } + } + + /* 1 (length) + 2 (year) + 1 (month) + 1 (day) */ + private static final byte MAX_DATE_REP_LENGTH = (byte) 5; + + /* + * 1 (length) + 2 (year) + 1 (month) + 1 (day) + 1 (hour) + 1 (minute) + 1 + * (second) + 4 (microseconds) + */ + private static final byte MAX_DATETIME_REP_LENGTH = 12; + + /* + * 1 (length) + 1 (is negative) + 4 (day count) + 1 (hour) + 1 (minute) + 1 + * (seconds) + 4 (microseconds) + */ + private static final byte MAX_TIME_REP_LENGTH = 13; + + private void storeTime(Buffer intoBuf, Time tm) throws SQLException { + + intoBuf.ensureCapacity(9); + intoBuf.writeByte((byte) 8); // length + intoBuf.writeByte((byte) 0); // neg flag + intoBuf.writeLong(0); // tm->day, not used + + Calendar sessionCalendar = getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + java.util.Date oldTime = sessionCalendar.getTime(); + try { + sessionCalendar.setTime(tm); + intoBuf.writeByte((byte) sessionCalendar.get(Calendar.HOUR_OF_DAY)); + intoBuf.writeByte((byte) sessionCalendar.get(Calendar.MINUTE)); + intoBuf.writeByte((byte) sessionCalendar.get(Calendar.SECOND)); + + // intoBuf.writeLongInt(0); // tm-second_part + } finally { + sessionCalendar.setTime(oldTime); + } + } + } + + /** + * Flag indicating whether or not the long parameters have been 'switched' + * back to normal parameters. We can not execute() if clearParameters() + * hasn't been called in this case. + */ + private boolean detectedLongParameterSwitch = false; + + /** + * The number of fields in the result set (if any) for this + * PreparedStatement. + */ + private int fieldCount; + + /** Has this prepared statement been marked invalid? */ + private boolean invalid = false; + + /** If this statement has been marked invalid, what was the reason? */ + private SQLException invalidationException; + + /** Does this query modify data? */ + private boolean isSelectQuery; + + private Buffer outByteBuffer; + + /** Bind values for individual fields */ + private BindValue[] parameterBindings; + + /** Field-level metadata for parameters */ + private Field[] parameterFields; + + /** Field-level metadata for result sets. */ + private Field[] resultFields; + + /** Do we need to send/resend types to the server? */ + private boolean sendTypesToServer = false; + + /** The ID that the server uses to identify this PreparedStatement */ + private long serverStatementId; + + /** The type used for string bindings, changes from version-to-version */ + private int stringTypeCode = MysqlDefs.FIELD_TYPE_STRING; + + private boolean serverNeedsResetBeforeEachExecution; + + /** + * Creates a new ServerPreparedStatement object. + * + * @param conn + * the connection creating us. + * @param sql + * the SQL containing the statement to prepare. + * @param catalog + * the catalog in use when we were created. + * + * @throws SQLException + * If an error occurs + */ + public ServerPreparedStatement(Connection conn, String sql, String catalog, + int resultSetType, int resultSetConcurrency) + throws SQLException { + super(conn, catalog); + + checkNullOrEmptyQuery(sql); + + this.isSelectQuery = StringUtils.startsWithIgnoreCaseAndWs(sql, + "SELECT"); //$NON-NLS-1$ + + if (this.connection.versionMeetsMinimum(5, 0, 0)) { + this.serverNeedsResetBeforeEachExecution = + !this.connection.versionMeetsMinimum(5, 0, 3); + } else { + this.serverNeedsResetBeforeEachExecution = + !this.connection.versionMeetsMinimum(4, 1, 10); + } + + this.useTrueBoolean = this.connection.versionMeetsMinimum(3, 21, 23); + this.hasLimitClause = (StringUtils.indexOfIgnoreCase(sql, "LIMIT") != -1); //$NON-NLS-1$ + this.firstCharOfStmt = StringUtils.firstNonWsCharUc(sql); + this.originalSql = sql; + + if (this.connection.versionMeetsMinimum(4, 1, 2)) { + this.stringTypeCode = MysqlDefs.FIELD_TYPE_VAR_STRING; + } else { + this.stringTypeCode = MysqlDefs.FIELD_TYPE_STRING; + } + + try { + serverPrepare(sql); + } catch (SQLException sqlEx) { + realClose(false, true); + // don't wrap SQLExceptions + throw sqlEx; + } catch (Exception ex) { + realClose(false, true); + + throw SQLError.createSQLException(ex.toString(), + SQLError.SQL_STATE_GENERAL_ERROR); + } + + setResultSetType(resultSetType); + setResultSetConcurrency(resultSetConcurrency); + } + + /** + * JDBC 2.0 Add a set of parameters to the batch. + * + * @exception SQLException + * if a database-access error occurs. + * + * @see Statement#addBatch + */ + public synchronized void addBatch() throws SQLException { + checkClosed(); + + if (this.batchedArgs == null) { + this.batchedArgs = new ArrayList(); + } + + this.batchedArgs.add(new BatchedBindValues(this.parameterBindings)); + } + + protected String asSql(boolean quoteStreamsAndUnknowns) throws SQLException { + + if (this.isClosed) { + return "statement has been closed, no further internal information available"; + } + + PreparedStatement pStmtForSub = null; + + try { + pStmtForSub = new PreparedStatement(this.connection, + this.originalSql, this.currentCatalog); + + int numParameters = pStmtForSub.parameterCount; + int ourNumParameters = this.parameterCount; + + for (int i = 0; (i < numParameters) && (i < ourNumParameters); i++) { + if (this.parameterBindings[i] != null) { + if (this.parameterBindings[i].isNull) { + pStmtForSub.setNull(i + 1, Types.NULL); + } else { + BindValue bindValue = this.parameterBindings[i]; + + // + // Handle primitives first + // + switch (bindValue.bufferType) { + + case MysqlDefs.FIELD_TYPE_TINY: + pStmtForSub.setByte(i + 1, bindValue.byteBinding); + break; + case MysqlDefs.FIELD_TYPE_SHORT: + pStmtForSub.setShort(i + 1, bindValue.shortBinding); + break; + case MysqlDefs.FIELD_TYPE_LONG: + pStmtForSub.setInt(i + 1, bindValue.intBinding); + break; + case MysqlDefs.FIELD_TYPE_LONGLONG: + pStmtForSub.setLong(i + 1, bindValue.longBinding); + break; + case MysqlDefs.FIELD_TYPE_FLOAT: + pStmtForSub.setFloat(i + 1, bindValue.floatBinding); + break; + case MysqlDefs.FIELD_TYPE_DOUBLE: + pStmtForSub.setDouble(i + 1, + bindValue.doubleBinding); + break; + default: + pStmtForSub.setObject(i + 1, + this.parameterBindings[i].value); + break; + } + } + } + } + + return pStmtForSub.asSql(quoteStreamsAndUnknowns); + } finally { + if (pStmtForSub != null) { + try { + pStmtForSub.close(); + } catch (SQLException sqlEx) { + ; // ignore + } + } + } + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.Statement#checkClosed() + */ + protected void checkClosed() throws SQLException { + if (this.invalid) { + throw this.invalidationException; + } + + super.checkClosed(); + } + + /** + * @see java.sql.PreparedStatement#clearParameters() + */ + public void clearParameters() throws SQLException { + checkClosed(); + clearParametersInternal(true); + } + + private void clearParametersInternal(boolean clearServerParameters) + throws SQLException { + boolean hadLongData = false; + + if (this.parameterBindings != null) { + for (int i = 0; i < this.parameterCount; i++) { + if ((this.parameterBindings[i] != null) + && this.parameterBindings[i].isLongData) { + hadLongData = true; + } + + this.parameterBindings[i].reset(); + } + } + + if (clearServerParameters && hadLongData) { + serverResetStatement(); + + this.detectedLongParameterSwitch = false; + } + } + + protected boolean isCached = false; + + protected void setClosed(boolean flag) { + this.isClosed = flag; + } + /** + * @see java.sql.Statement#close() + */ + public void close() throws SQLException { + if (this.isCached) { + this.isClosed = true; + this.connection.recachePreparedStatement(this); + return; + } + + realClose(true, true); + } + + private void dumpCloseForTestcase() { + StringBuffer buf = new StringBuffer(); + this.connection.generateConnectionCommentBlock(buf); + buf.append("DEALLOCATE PREPARE debug_stmt_"); + buf.append(this.statementId); + buf.append(";\n"); + + this.connection.dumpTestcaseQuery(buf.toString()); + } + + private void dumpExecuteForTestcase() throws SQLException { + StringBuffer buf = new StringBuffer(); + + for (int i = 0; i < this.parameterCount; i++) { + this.connection.generateConnectionCommentBlock(buf); + + buf.append("SET @debug_stmt_param"); + buf.append(this.statementId); + buf.append("_"); + buf.append(i); + buf.append("="); + + if (this.parameterBindings[i].isNull) { + buf.append("NULL"); + } else { + buf.append(this.parameterBindings[i].toString(true)); + } + + buf.append(";\n"); + } + + this.connection.generateConnectionCommentBlock(buf); + + buf.append("EXECUTE debug_stmt_"); + buf.append(this.statementId); + + if (this.parameterCount > 0) { + buf.append(" USING "); + for (int i = 0; i < this.parameterCount; i++) { + if (i > 0) { + buf.append(", "); + } + + buf.append("@debug_stmt_param"); + buf.append(this.statementId); + buf.append("_"); + buf.append(i); + + } + } + + buf.append(";\n"); + + this.connection.dumpTestcaseQuery(buf.toString()); + } + + private void dumpPrepareForTestcase() throws SQLException { + + StringBuffer buf = new StringBuffer(this.originalSql.length() + 64); + + this.connection.generateConnectionCommentBlock(buf); + + buf.append("PREPARE debug_stmt_"); + buf.append(this.statementId); + buf.append(" FROM \""); + buf.append(this.originalSql); + buf.append("\";\n"); + + this.connection.dumpTestcaseQuery(buf.toString()); + } + + /** + * @see java.sql.Statement#executeBatch() + */ + public synchronized int[] executeBatchSerially() throws SQLException { + if (this.connection.isReadOnly()) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.2") //$NON-NLS-1$ + + Messages.getString("ServerPreparedStatement.3"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + checkClosed(); + + synchronized (this.connection.getMutex()) { + clearWarnings(); + + // Store this for later, we're going to 'swap' them out + // as we execute each batched statement... + BindValue[] oldBindValues = this.parameterBindings; + + try { + int[] updateCounts = null; + + if (this.batchedArgs != null) { + int nbrCommands = this.batchedArgs.size(); + updateCounts = new int[nbrCommands]; + + if (this.retrieveGeneratedKeys) { + this.batchedGeneratedKeys = new ArrayList(nbrCommands); + } + + for (int i = 0; i < nbrCommands; i++) { + updateCounts[i] = -3; + } + + SQLException sqlEx = null; + + int commandIndex = 0; + + BindValue[] previousBindValuesForBatch = null; + + for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) { + Object arg = this.batchedArgs.get(commandIndex); + + if (arg instanceof String) { + updateCounts[commandIndex] = executeUpdate((String) arg); + } else { + this.parameterBindings = ((BatchedBindValues) arg).batchedParameterValues; + + try { + // We need to check types each time, as + // the user might have bound different + // types in each addBatch() + + if (previousBindValuesForBatch != null) { + for (int j = 0; j < this.parameterBindings.length; j++) { + if (this.parameterBindings[j].bufferType != previousBindValuesForBatch[j].bufferType) { + this.sendTypesToServer = true; + + break; + } + } + } + + try { + updateCounts[commandIndex] = executeUpdate(false, true); + } finally { + previousBindValuesForBatch = this.parameterBindings; + } + + if (this.retrieveGeneratedKeys) { + java.sql.ResultSet rs = null; + + try { + // we don't want to use our version, + // because we've altered the behavior of + // ours to support batch updates + // (catch-22) + // Ideally, what we need here is + // super.super.getGeneratedKeys() + // but that construct doesn't exist in + // Java, so that's why there's + // this kludge. + rs = getGeneratedKeysInternal(); + + while (rs.next()) { + this.batchedGeneratedKeys + .add(new byte[][] { rs + .getBytes(1) }); + } + } finally { + if (rs != null) { + rs.close(); + } + } + } + } catch (SQLException ex) { + updateCounts[commandIndex] = EXECUTE_FAILED; + + if (this.continueBatchOnError) { + sqlEx = ex; + } else { + int[] newUpdateCounts = new int[commandIndex]; + System.arraycopy(updateCounts, 0, + newUpdateCounts, 0, commandIndex); + + throw new java.sql.BatchUpdateException(ex + .getMessage(), ex.getSQLState(), ex + .getErrorCode(), newUpdateCounts); + } + } + } + } + + if (sqlEx != null) { + throw new java.sql.BatchUpdateException(sqlEx + .getMessage(), sqlEx.getSQLState(), sqlEx + .getErrorCode(), updateCounts); + } + } + + return (updateCounts != null) ? updateCounts : new int[0]; + } finally { + this.parameterBindings = oldBindValues; + this.sendTypesToServer = true; + + clearBatch(); + } + } + } + + /** + * @see com.mysql.jdbc.PreparedStatement#executeInternal(int, + * com.mysql.jdbc.Buffer, boolean, boolean) + */ + protected com.mysql.jdbc.ResultSet executeInternal(int maxRowsToRetrieve, + Buffer sendPacket, boolean createStreamingResultSet, + boolean queryIsSelectOnly, boolean unpackFields, Field[] metadataFromCache, + boolean isBatch) + throws SQLException { + this.numberOfExecutions++; + + // We defer to server-side execution + try { + return serverExecute(maxRowsToRetrieve, createStreamingResultSet, + unpackFields, metadataFromCache); + } catch (SQLException sqlEx) { + // don't wrap SQLExceptions + if (this.connection.getEnablePacketDebug()) { + this.connection.getIO().dumpPacketRingBuffer(); + } + + if (this.connection.getDumpQueriesOnException()) { + String extractedSql = toString(); + StringBuffer messageBuf = new StringBuffer(extractedSql + .length() + 32); + messageBuf + .append("\n\nQuery being executed when exception was thrown:\n\n"); + messageBuf.append(extractedSql); + + sqlEx = Connection.appendMessageToException(sqlEx, messageBuf + .toString()); + } + + throw sqlEx; + } catch (Exception ex) { + if (this.connection.getEnablePacketDebug()) { + this.connection.getIO().dumpPacketRingBuffer(); + } + + SQLException sqlEx = SQLError.createSQLException(ex.toString(), + SQLError.SQL_STATE_GENERAL_ERROR); + + if (this.connection.getDumpQueriesOnException()) { + String extractedSql = toString(); + StringBuffer messageBuf = new StringBuffer(extractedSql + .length() + 32); + messageBuf + .append("\n\nQuery being executed when exception was thrown:\n\n"); + messageBuf.append(extractedSql); + + sqlEx = Connection.appendMessageToException(sqlEx, messageBuf + .toString()); + } + + throw sqlEx; + } + } + + /** + * @see com.mysql.jdbc.PreparedStatement#fillSendPacket() + */ + protected Buffer fillSendPacket() throws SQLException { + return null; // we don't use this type of packet + } + + /** + * @see com.mysql.jdbc.PreparedStatement#fillSendPacket(byte, + * java.io.InputStream, boolean, int) + */ + protected Buffer fillSendPacket(byte[][] batchedParameterStrings, + InputStream[] batchedParameterStreams, boolean[] batchedIsStream, + int[] batchedStreamLengths) throws SQLException { + return null; // we don't use this type of packet + } + + /** + * Returns the structure representing the value that (can be)/(is) + * bound at the given parameter index. + * + * @param parameterIndex 1-based + * @param forLongData is this for a stream? + * @return + * @throws SQLException + */ + private BindValue getBinding(int parameterIndex, boolean forLongData) + throws SQLException { + checkClosed(); + + if (this.parameterBindings.length == 0) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.8"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + parameterIndex--; + + if ((parameterIndex < 0) + || (parameterIndex >= this.parameterBindings.length)) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.9") //$NON-NLS-1$ + + (parameterIndex + 1) + + Messages.getString("ServerPreparedStatement.10") //$NON-NLS-1$ + + this.parameterBindings.length, + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (this.parameterBindings[parameterIndex] == null) { + this.parameterBindings[parameterIndex] = new BindValue(); + } else { + if (this.parameterBindings[parameterIndex].isLongData + && !forLongData) { + this.detectedLongParameterSwitch = true; + } + } + + this.parameterBindings[parameterIndex].isSet = true; + this.parameterBindings[parameterIndex].boundBeforeExecutionNum = this.numberOfExecutions; + + return this.parameterBindings[parameterIndex]; + } + + /** + * @see com.mysql.jdbc.PreparedStatement#getBytes(int) + */ + byte[] getBytes(int parameterIndex) throws SQLException { + BindValue bindValue = getBinding(parameterIndex, false); + + if (bindValue.isNull) { + return null; + } else if (bindValue.isLongData) { + throw new NotImplemented(); + } else { + if (this.outByteBuffer == null) { + this.outByteBuffer = new Buffer(this.connection + .getNetBufferLength()); + } + + this.outByteBuffer.clear(); + + int originalPosition = this.outByteBuffer.getPosition(); + + storeBinding(this.outByteBuffer, bindValue, this.connection.getIO()); + + int newPosition = this.outByteBuffer.getPosition(); + + int length = newPosition - originalPosition; + + byte[] valueAsBytes = new byte[length]; + + System.arraycopy(this.outByteBuffer.getByteBuffer(), + originalPosition, valueAsBytes, 0, length); + + return valueAsBytes; + } + } + + /** + * @see java.sql.PreparedStatement#getMetaData() + */ + public java.sql.ResultSetMetaData getMetaData() throws SQLException { + checkClosed(); + + if (this.resultFields == null) { + return null; + } + + return new ResultSetMetaData(this.resultFields, + this.connection.getUseOldAliasMetadataBehavior()); + } + + /** + * @see java.sql.PreparedStatement#getParameterMetaData() + */ + public ParameterMetaData getParameterMetaData() throws SQLException { + checkClosed(); + + if (this.parameterMetaData == null) { + this.parameterMetaData = new MysqlParameterMetadata( + this.parameterFields, this.parameterCount); + } + + return this.parameterMetaData; + } + + /** + * @see com.mysql.jdbc.PreparedStatement#isNull(int) + */ + boolean isNull(int paramIndex) { + throw new IllegalArgumentException(Messages + .getString("ServerPreparedStatement.7")); //$NON-NLS-1$ + } + + /** + * Closes this connection and frees all resources. + * + * @param calledExplicitly + * was this called from close()? + * + * @throws SQLException + * if an error occurs + */ + protected void realClose(boolean calledExplicitly, + boolean closeOpenResults) throws SQLException { + if (this.isClosed) { + return; + } + + if (this.connection != null) { + if (this.connection.getAutoGenerateTestcaseScript()) { + dumpCloseForTestcase(); + } + + synchronized (this.connection.getMutex()) { + + // + // Don't communicate with the server if we're being + // called from the finalizer... + // + // This will leak server resources, but if we don't do this, + // we'll deadlock (potentially, because there's no guarantee + // when, what order, and what concurrency finalizers will be + // called with). Well-behaved programs won't rely on finalizers + // to clean up their statements. + // + + SQLException exceptionDuringClose = null; + + + if (calledExplicitly) { + try { + + MysqlIO mysql = this.connection.getIO(); + + Buffer packet = mysql.getSharedSendPacket(); + + packet.writeByte((byte) MysqlDefs.COM_CLOSE_STATEMENT); + packet.writeLong(this.serverStatementId); + + mysql.sendCommand(MysqlDefs.COM_CLOSE_STATEMENT, null, + packet, true, null); + } catch (SQLException sqlEx) { + exceptionDuringClose = sqlEx; + } + + } + + super.realClose(calledExplicitly, closeOpenResults); + + clearParametersInternal(false); + this.parameterBindings = null; + + this.parameterFields = null; + this.resultFields = null; + + if (exceptionDuringClose != null) { + throw exceptionDuringClose; + } + } + } + } + + /** + * Used by Connection when auto-reconnecting to retrieve 'lost' prepared + * statements. + * + * @throws SQLException + * if an error occurs. + */ + protected void rePrepare() throws SQLException { + this.invalidationException = null; + + try { + serverPrepare(this.originalSql); + } catch (SQLException sqlEx) { + // don't wrap SQLExceptions + this.invalidationException = sqlEx; + } catch (Exception ex) { + this.invalidationException = SQLError.createSQLException(ex.toString(), + SQLError.SQL_STATE_GENERAL_ERROR); + } + + if (this.invalidationException != null) { + this.invalid = true; + + this.parameterBindings = null; + + this.parameterFields = null; + this.resultFields = null; + + if (this.results != null) { + try { + this.results.close(); + } catch (Exception ex) { + ; + } + } + + if (this.connection != null) { + if (this.maxRowsChanged) { + this.connection.unsetMaxRows(this); + } + + if (!this.connection.getDontTrackOpenResources()) { + this.connection.unregisterStatement(this); + } + } + } + } + + /** + * Tells the server to execute this prepared statement with the current + * parameter bindings. + * + *
+	 * 
+	 * 
+	 *    -   Server gets the command 'COM_EXECUTE' to execute the
+	 *        previously         prepared query. If there is any param markers;
+	 *  then client will send the data in the following format:
+	 * 
+	 *  [COM_EXECUTE:1]
+	 *  [STMT_ID:4]
+	 *  [NULL_BITS:(param_count+7)/8)]
+	 *  [TYPES_SUPPLIED_BY_CLIENT(0/1):1]
+	 *  [[length]data]
+	 *  [[length]data] .. [[length]data].
+	 * 
+	 *  (Note: Except for string/binary types; all other types will not be
+	 *  supplied with length field)
+	 * 
+	 *  
+	 * 
+ * + * @param maxRowsToRetrieve + * DOCUMENT ME! + * @param createStreamingResultSet + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + */ + private com.mysql.jdbc.ResultSet serverExecute(int maxRowsToRetrieve, + boolean createStreamingResultSet, boolean unpackFields, + Field[] metadataFromCache) throws SQLException { + synchronized (this.connection.getMutex()) { + if (this.detectedLongParameterSwitch) { + // Check when values were bound + boolean firstFound = false; + long boundTimeToCheck = 0; + + for (int i = 0; i < this.parameterCount - 1; i++) { + if (this.parameterBindings[i].isLongData) { + if (firstFound && boundTimeToCheck != + this.parameterBindings[i].boundBeforeExecutionNum) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.11") //$NON-NLS-1$ + + Messages.getString("ServerPreparedStatement.12"), //$NON-NLS-1$ + SQLError.SQL_STATE_DRIVER_NOT_CAPABLE); + } else { + firstFound = true; + boundTimeToCheck = this.parameterBindings[i].boundBeforeExecutionNum; + } + } + } + + // Okay, we've got all "newly"-bound streams, so reset + // server-side state to clear out previous bindings + + serverResetStatement(); + } + + + // Check bindings + for (int i = 0; i < this.parameterCount; i++) { + if (!this.parameterBindings[i].isSet) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.13") + (i + 1) //$NON-NLS-1$ + + Messages.getString("ServerPreparedStatement.14"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + // + // Send all long data + // + for (int i = 0; i < this.parameterCount; i++) { + if (this.parameterBindings[i].isLongData) { + serverLongData(i, this.parameterBindings[i]); + } + } + + if (this.connection.getAutoGenerateTestcaseScript()) { + dumpExecuteForTestcase(); + } + + // + // store the parameter values + // + MysqlIO mysql = this.connection.getIO(); + + Buffer packet = mysql.getSharedSendPacket(); + + packet.clear(); + packet.writeByte((byte) MysqlDefs.COM_EXECUTE); + packet.writeLong(this.serverStatementId); + + boolean usingCursor = false; + + if (this.connection.versionMeetsMinimum(4, 1, 2)) { + // we only create cursor-backed result sets if + // a) The query is a SELECT + // b) The server supports it + // c) We know it is forward-only (note this doesn't + // preclude updatable result sets) + // d) The user has set a fetch size + if (this.resultFields != null && + this.connection.isCursorFetchEnabled() + && getResultSetType() == ResultSet.TYPE_FORWARD_ONLY + && getResultSetConcurrency() == ResultSet.CONCUR_READ_ONLY + && getFetchSize() > 0) { + packet.writeByte(MysqlDefs.OPEN_CURSOR_FLAG); + usingCursor = true; + } else { + packet.writeByte((byte) 0); // placeholder for flags + } + + packet.writeLong(1); // placeholder for parameter + // iterations + } + + /* Reserve place for null-marker bytes */ + int nullCount = (this.parameterCount + 7) / 8; + + // if (mysql.versionMeetsMinimum(4, 1, 2)) { + // nullCount = (this.parameterCount + 9) / 8; + // } + int nullBitsPosition = packet.getPosition(); + + for (int i = 0; i < nullCount; i++) { + packet.writeByte((byte) 0); + } + + byte[] nullBitsBuffer = new byte[nullCount]; + + /* In case if buffers (type) altered, indicate to server */ + packet.writeByte(this.sendTypesToServer ? (byte) 1 : (byte) 0); + + if (this.sendTypesToServer) { + /* + * Store types of parameters in first in first package that is + * sent to the server. + */ + for (int i = 0; i < this.parameterCount; i++) { + packet.writeInt(this.parameterBindings[i].bufferType); + } + } + + // + // store the parameter values + // + for (int i = 0; i < this.parameterCount; i++) { + if (!this.parameterBindings[i].isLongData) { + if (!this.parameterBindings[i].isNull) { + storeBinding(packet, this.parameterBindings[i], mysql); + } else { + nullBitsBuffer[i / 8] |= (1 << (i & 7)); + } + } + } + + // + // Go back and write the NULL flags + // to the beginning of the packet + // + int endPosition = packet.getPosition(); + packet.setPosition(nullBitsPosition); + packet.writeBytesNoNull(nullBitsBuffer); + packet.setPosition(endPosition); + + long begin = 0; + + boolean logSlowQueries = this.connection.getLogSlowQueries(); + boolean gatherPerformanceMetrics = this.connection + .getGatherPerformanceMetrics(); + + if (this.profileSQL || logSlowQueries || gatherPerformanceMetrics) { + begin = mysql.getCurrentTimeNanosOrMillis(); + } + + synchronized (this.cancelTimeoutMutex) { + this.wasCancelled = false; + } + + CancelTask timeoutTask = null; + + try { + if (this.connection.getEnableQueryTimeouts() && + this.timeoutInMillis != 0 + && this.connection.versionMeetsMinimum(5, 0, 0)) { + timeoutTask = new CancelTask(); + this.connection.getCancelTimer().schedule(timeoutTask, + this.timeoutInMillis); + } + + Buffer resultPacket = mysql.sendCommand(MysqlDefs.COM_EXECUTE, + null, packet, false, null); + + long queryEndTime = 0L; + + if (logSlowQueries || gatherPerformanceMetrics || this.profileSQL) { + queryEndTime = mysql.getCurrentTimeNanosOrMillis(); + } + + if (timeoutTask != null) { + timeoutTask.cancel(); + + if (timeoutTask.caughtWhileCancelling != null) { + throw timeoutTask.caughtWhileCancelling; + } + + timeoutTask = null; + } + + synchronized (this.cancelTimeoutMutex) { + if (this.wasCancelled) { + this.wasCancelled = false; + throw new MySQLTimeoutException(); + } + } + + boolean queryWasSlow = false; + + if (logSlowQueries || gatherPerformanceMetrics) { + long elapsedTime = queryEndTime - begin; + + if (logSlowQueries + && (elapsedTime >= mysql.getSlowQueryThreshold())) { + queryWasSlow = true; + + StringBuffer mesgBuf = new StringBuffer( + 48 + this.originalSql.length()); + mesgBuf.append(Messages + .getString("ServerPreparedStatement.15")); //$NON-NLS-1$ + mesgBuf.append(mysql.getSlowQueryThreshold()); + mesgBuf.append(Messages + .getString("ServerPreparedStatement.15a")); //$NON-NLS-1$ + mesgBuf.append(elapsedTime); + mesgBuf.append(Messages + .getString("ServerPreparedStatement.16")); //$NON-NLS-1$ + + mesgBuf.append("as prepared: "); + mesgBuf.append(this.originalSql); + mesgBuf.append("\n\n with parameters bound:\n\n"); + mesgBuf.append(asSql(true)); + + this.eventSink + .consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_SLOW_QUERY, + "", this.currentCatalog, this.connection.getId(), //$NON-NLS-1$ + getId(), 0, System.currentTimeMillis(), + elapsedTime, mysql + .getQueryTimingUnits(), null, + new Throwable(), mesgBuf.toString())); + } + + if (gatherPerformanceMetrics) { + this.connection.registerQueryExecutionTime(elapsedTime); + } + } + + this.connection.incrementNumberOfPreparedExecutes(); + + if (this.profileSQL) { + this.eventSink = ProfileEventSink + .getInstance(this.connection); + + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_EXECUTE, + "", this.currentCatalog, //$NON-NLS-1$ + this.connectionId, this.statementId, -1, System + .currentTimeMillis(), (int) (mysql + .getCurrentTimeNanosOrMillis() - begin), + mysql.getQueryTimingUnits(), null, new Throwable(), + truncateQueryToLog(asSql(true)))); + } + + com.mysql.jdbc.ResultSet rs = mysql.readAllResults(this, + maxRowsToRetrieve, this.resultSetType, + this.resultSetConcurrency, createStreamingResultSet, + this.currentCatalog, resultPacket, true, this.fieldCount, + unpackFields, metadataFromCache); + + if (this.profileSQL) { + long fetchEndTime = mysql.getCurrentTimeNanosOrMillis(); + + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_FETCH, + "", this.currentCatalog, this.connection.getId(), //$NON-NLS-1$ + getId(), rs.resultId, System.currentTimeMillis(), + (fetchEndTime - queryEndTime), mysql + .getQueryTimingUnits(), null, + new Throwable(), null)); + } + + if (queryWasSlow && this.connection.getExplainSlowQueries()) { + String queryAsString = asSql(true); + + mysql.explainSlowQuery(queryAsString.getBytes(), + queryAsString); + } + + if (!createStreamingResultSet && + this.serverNeedsResetBeforeEachExecution) { + serverResetStatement(); // clear any long data... + } + + + this.sendTypesToServer = false; + this.results = rs; + + if (mysql.hadWarnings()) { + mysql.scanForAndThrowDataTruncation(); + } + + return rs; + } finally { + if (timeoutTask != null) { + timeoutTask.cancel(); + } + } + } + } + + /** + * Sends stream-type data parameters to the server. + * + *
+	 * 
+	 *  Long data handling:
+	 * 
+	 *  - Server gets the long data in pieces with command type 'COM_LONG_DATA'.
+	 *  - The packet recieved will have the format as:
+	 *    [COM_LONG_DATA:     1][STMT_ID:4][parameter_number:2][type:2][data]
+	 *  - Checks if the type is specified by client, and if yes reads the type,
+	 *    and  stores the data in that format.
+	 *  - It's up to the client to check for read data ended. The server doesn't
+	 *    care;  and also server doesn't notify to the client that it got the
+	 *    data  or not; if there is any error; then during execute; the error
+	 *    will  be returned
+	 *  
+	 * 
+ * + * @param parameterIndex + * DOCUMENT ME! + * @param longData + * DOCUMENT ME! + * + * @throws SQLException + * if an error occurs. + */ + private void serverLongData(int parameterIndex, BindValue longData) + throws SQLException { + synchronized (this.connection.getMutex()) { + MysqlIO mysql = this.connection.getIO(); + + Buffer packet = mysql.getSharedSendPacket(); + + Object value = longData.value; + + if (value instanceof byte[]) { + packet.clear(); + packet.writeByte((byte) MysqlDefs.COM_LONG_DATA); + packet.writeLong(this.serverStatementId); + packet.writeInt((parameterIndex)); + + packet.writeBytesNoNull((byte[]) longData.value); + + mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, true, + null); + } else if (value instanceof InputStream) { + storeStream(mysql, parameterIndex, packet, (InputStream) value); + } else if (value instanceof java.sql.Blob) { + storeStream(mysql, parameterIndex, packet, + ((java.sql.Blob) value).getBinaryStream()); + } else if (value instanceof Reader) { + storeReader(mysql, parameterIndex, packet, (Reader) value); + } else { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.18") //$NON-NLS-1$ + + value.getClass().getName() + "'", //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } + } + + private void serverPrepare(String sql) throws SQLException { + synchronized (this.connection.getMutex()) { + MysqlIO mysql = this.connection.getIO(); + + if (this.connection.getAutoGenerateTestcaseScript()) { + dumpPrepareForTestcase(); + } + + try { + long begin = 0; + + if (StringUtils.startsWithIgnoreCaseAndWs(sql, "LOAD DATA")) { //$NON-NLS-1$ + this.isLoadDataQuery = true; + } else { + this.isLoadDataQuery = false; + } + + if (this.connection.getProfileSql()) { + begin = mysql.getCurrentTimeNanosOrMillis(); + } + + String characterEncoding = null; + String connectionEncoding = this.connection.getEncoding(); + + if (!this.isLoadDataQuery && this.connection.getUseUnicode() + && (connectionEncoding != null)) { + characterEncoding = connectionEncoding; + } + + Buffer prepareResultPacket = mysql.sendCommand( + MysqlDefs.COM_PREPARE, sql, null, false, + characterEncoding); + + if (this.connection.versionMeetsMinimum(4, 1, 1)) { + // 4.1.1 and newer use the first byte + // as an 'ok' or 'error' flag, so move + // the buffer pointer past it to + // start reading the statement id. + prepareResultPacket.setPosition(1); + } else { + // 4.1.0 doesn't use the first byte as an + // 'ok' or 'error' flag + prepareResultPacket.setPosition(0); + } + + this.serverStatementId = prepareResultPacket.readLong(); + this.fieldCount = prepareResultPacket.readInt(); + this.parameterCount = prepareResultPacket.readInt(); + this.parameterBindings = new BindValue[this.parameterCount]; + + for (int i = 0; i < this.parameterCount; i++) { + this.parameterBindings[i] = new BindValue(); + } + + this.connection.incrementNumberOfPrepares(); + + if (this.profileSQL) { + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_PREPARE, + "", this.currentCatalog, //$NON-NLS-1$ + this.connectionId, this.statementId, -1, + System.currentTimeMillis(), + mysql.getCurrentTimeNanosOrMillis() - begin, + mysql.getQueryTimingUnits(), null, + new Throwable(), truncateQueryToLog(sql))); + } + + if (this.parameterCount > 0) { + if (this.connection.versionMeetsMinimum(4, 1, 2) + && !mysql.isVersion(5, 0, 0)) { + this.parameterFields = new Field[this.parameterCount]; + + Buffer metaDataPacket = mysql.readPacket(); + + int i = 0; + + while (!metaDataPacket.isLastDataPacket() + && (i < this.parameterCount)) { + this.parameterFields[i++] = mysql.unpackField( + metaDataPacket, false); + metaDataPacket = mysql.readPacket(); + } + } + } + + if (this.fieldCount > 0) { + this.resultFields = new Field[this.fieldCount]; + + Buffer fieldPacket = mysql.readPacket(); + + int i = 0; + + // Read in the result set column information + while (!fieldPacket.isLastDataPacket() + && (i < this.fieldCount)) { + this.resultFields[i++] = mysql.unpackField(fieldPacket, + false); + fieldPacket = mysql.readPacket(); + } + } + } catch (SQLException sqlEx) { + if (this.connection.getDumpQueriesOnException()) { + StringBuffer messageBuf = new StringBuffer(this.originalSql + .length() + 32); + messageBuf + .append("\n\nQuery being prepared when exception was thrown:\n\n"); + messageBuf.append(this.originalSql); + + sqlEx = Connection.appendMessageToException(sqlEx, + messageBuf.toString()); + } + + throw sqlEx; + } finally { + // Leave the I/O channel in a known state...there might be + // packets out there + // that we're not interested in + this.connection.getIO().clearInputStream(); + } + } + } + + private String truncateQueryToLog(String sql) { + String query = null; + + if (sql.length() > this.connection.getMaxQuerySizeToLog()) { + StringBuffer queryBuf = new StringBuffer( + this.connection.getMaxQuerySizeToLog() + 12); + queryBuf.append(sql.substring(0, this.connection.getMaxQuerySizeToLog())); + queryBuf.append(Messages.getString("MysqlIO.25")); + + query = queryBuf.toString(); + } else { + query = sql; + } + + return query; + } + + private void serverResetStatement() throws SQLException { + synchronized (this.connection.getMutex()) { + + MysqlIO mysql = this.connection.getIO(); + + Buffer packet = mysql.getSharedSendPacket(); + + packet.clear(); + packet.writeByte((byte) MysqlDefs.COM_RESET_STMT); + packet.writeLong(this.serverStatementId); + + try { + mysql.sendCommand(MysqlDefs.COM_RESET_STMT, null, packet, + !this.connection.versionMeetsMinimum(4, 1, 2), null); + } catch (SQLException sqlEx) { + throw sqlEx; + } catch (Exception ex) { + throw SQLError.createSQLException(ex.toString(), + SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + mysql.clearInputStream(); + } + } + } + + /** + * @see java.sql.PreparedStatement#setArray(int, java.sql.Array) + */ + public void setArray(int i, Array x) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, + * int) + */ + public void setAsciiStream(int parameterIndex, InputStream x, int length) + throws SQLException { + checkClosed(); + + if (x == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + BindValue binding = getBinding(parameterIndex, true); + setType(binding, MysqlDefs.FIELD_TYPE_BLOB); + + binding.value = x; + binding.isNull = false; + binding.isLongData = true; + + if (this.connection.getUseStreamLengthsInPrepStmts()) { + binding.bindLength = length; + } else { + binding.bindLength = -1; + } + } + } + + /** + * @see java.sql.PreparedStatement#setBigDecimal(int, java.math.BigDecimal) + */ + public void setBigDecimal(int parameterIndex, BigDecimal x) + throws SQLException { + checkClosed(); + + if (x == null) { + setNull(parameterIndex, java.sql.Types.DECIMAL); + } else { + + BindValue binding = getBinding(parameterIndex, false); + + if (this.connection.versionMeetsMinimum(5, 0, 3)) { + setType(binding, MysqlDefs.FIELD_TYPE_NEW_DECIMAL); + } else { + setType(binding, this.stringTypeCode); + } + + binding.value = StringUtils + .fixDecimalExponent(StringUtils.consistentToString(x)); + binding.isNull = false; + binding.isLongData = false; + } + } + + /** + * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, + * int) + */ + public void setBinaryStream(int parameterIndex, InputStream x, int length) + throws SQLException { + checkClosed(); + + if (x == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + BindValue binding = getBinding(parameterIndex, true); + setType(binding, MysqlDefs.FIELD_TYPE_BLOB); + + binding.value = x; + binding.isNull = false; + binding.isLongData = true; + + if (this.connection.getUseStreamLengthsInPrepStmts()) { + binding.bindLength = length; + } else { + binding.bindLength = -1; + } + } + } + + /** + * @see java.sql.PreparedStatement#setBlob(int, java.sql.Blob) + */ + public void setBlob(int parameterIndex, Blob x) throws SQLException { + checkClosed(); + + if (x == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + BindValue binding = getBinding(parameterIndex, true); + setType(binding, MysqlDefs.FIELD_TYPE_BLOB); + + binding.value = x; + binding.isNull = false; + binding.isLongData = true; + + if (this.connection.getUseStreamLengthsInPrepStmts()) { + binding.bindLength = x.length(); + } else { + binding.bindLength = -1; + } + } + } + + /** + * @see java.sql.PreparedStatement#setBoolean(int, boolean) + */ + public void setBoolean(int parameterIndex, boolean x) throws SQLException { + setByte(parameterIndex, (x ? (byte) 1 : (byte) 0)); + } + + /** + * @see java.sql.PreparedStatement#setByte(int, byte) + */ + public void setByte(int parameterIndex, byte x) throws SQLException { + checkClosed(); + + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_TINY); + + binding.value = null; + binding.byteBinding = x; + binding.isNull = false; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setBytes(int, byte) + */ + public void setBytes(int parameterIndex, byte[] x) throws SQLException { + checkClosed(); + + if (x == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_VAR_STRING); + + binding.value = x; + binding.isNull = false; + binding.isLongData = false; + } + } + + /** + * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, + * int) + */ + public void setCharacterStream(int parameterIndex, Reader reader, int length) + throws SQLException { + checkClosed(); + + if (reader == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + BindValue binding = getBinding(parameterIndex, true); + setType(binding, MysqlDefs.FIELD_TYPE_BLOB); + + binding.value = reader; + binding.isNull = false; + binding.isLongData = true; + + if (this.connection.getUseStreamLengthsInPrepStmts()) { + binding.bindLength = length; + } else { + binding.bindLength = -1; + } + } + } + + /** + * @see java.sql.PreparedStatement#setClob(int, java.sql.Clob) + */ + public void setClob(int parameterIndex, Clob x) throws SQLException { + checkClosed(); + + if (x == null) { + setNull(parameterIndex, java.sql.Types.BINARY); + } else { + BindValue binding = getBinding(parameterIndex, true); + setType(binding, MysqlDefs.FIELD_TYPE_BLOB); + + binding.value = x.getCharacterStream(); + binding.isNull = false; + binding.isLongData = true; + + if (this.connection.getUseStreamLengthsInPrepStmts()) { + binding.bindLength = x.length(); + } else { + binding.bindLength = -1; + } + } + } + + /** + * Set a parameter to a java.sql.Date value. The driver converts this to a + * SQL DATE value when it sends 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. + */ + public void setDate(int parameterIndex, Date x) throws SQLException { + setDate(parameterIndex, x, null); + } + + /** + * Set a parameter to a java.sql.Date value. The driver converts this to a + * SQL DATE value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param x + * the parameter value + * @param cal + * the calendar to interpret the date with + * + * @exception SQLException + * if a database-access error occurs. + */ + public void setDate(int parameterIndex, Date x, Calendar cal) + throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.DATE); + } else { + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_DATE); + + binding.value = x; + binding.isNull = false; + binding.isLongData = false; + } + } + + /** + * @see java.sql.PreparedStatement#setDouble(int, double) + */ + public void setDouble(int parameterIndex, double x) throws SQLException { + checkClosed(); + + if (!this.connection.getAllowNanAndInf() + && (x == Double.POSITIVE_INFINITY + || x == Double.NEGATIVE_INFINITY || Double.isNaN(x))) { + throw SQLError.createSQLException("'" + x + + "' is not a valid numeric or approximate numeric value", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + + } + + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_DOUBLE); + + binding.value = null; + binding.doubleBinding = x; + binding.isNull = false; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setFloat(int, float) + */ + public void setFloat(int parameterIndex, float x) throws SQLException { + checkClosed(); + + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_FLOAT); + + binding.value = null; + binding.floatBinding = x; + binding.isNull = false; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setInt(int, int) + */ + public void setInt(int parameterIndex, int x) throws SQLException { + checkClosed(); + + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_LONG); + + binding.value = null; + binding.intBinding = x; + binding.isNull = false; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setLong(int, long) + */ + public void setLong(int parameterIndex, long x) throws SQLException { + checkClosed(); + + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_LONGLONG); + + binding.value = null; + binding.longBinding = x; + binding.isNull = false; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setNull(int, int) + */ + public void setNull(int parameterIndex, int sqlType) throws SQLException { + checkClosed(); + + BindValue binding = getBinding(parameterIndex, false); + + // + // Don't re-set types, but use something if this + // parameter was never specified + // + if (binding.bufferType == 0) { + setType(binding, MysqlDefs.FIELD_TYPE_NULL); + } + + binding.value = null; + binding.isNull = true; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setNull(int, int, java.lang.String) + */ + public void setNull(int parameterIndex, int sqlType, String typeName) + throws SQLException { + checkClosed(); + + BindValue binding = getBinding(parameterIndex, false); + + // + // Don't re-set types, but use something if this + // parameter was never specified + // + if (binding.bufferType == 0) { + setType(binding, MysqlDefs.FIELD_TYPE_NULL); + } + + binding.value = null; + binding.isNull = true; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setRef(int, java.sql.Ref) + */ + public void setRef(int i, Ref x) throws SQLException { + throw new NotImplemented(); + } + + /** + * @see java.sql.PreparedStatement#setShort(int, short) + */ + public void setShort(int parameterIndex, short x) throws SQLException { + checkClosed(); + + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_SHORT); + + binding.value = null; + binding.shortBinding = x; + binding.isNull = false; + binding.isLongData = false; + } + + /** + * @see java.sql.PreparedStatement#setString(int, java.lang.String) + */ + public void setString(int parameterIndex, String x) throws SQLException { + checkClosed(); + + if (x == null) { + setNull(parameterIndex, java.sql.Types.CHAR); + } else { + BindValue binding = getBinding(parameterIndex, false); + + setType(binding, this.stringTypeCode); + + binding.value = x; + binding.isNull = false; + binding.isLongData = false; + } + } + + /** + * Set a parameter to a java.sql.Time value. + * + * @param parameterIndex + * the first parameter is 1...)); + * @param x + * the parameter value + * + * @throws SQLException + * if a database access error occurs + */ + public void setTime(int parameterIndex, java.sql.Time x) + throws SQLException { + setTimeInternal(parameterIndex, x, null, this.connection.getDefaultTimeZone(), false); + } + + /** + * Set a parameter to a java.sql.Time value. The driver converts this to a + * SQL TIME value when it sends it to the database, using the given + * timezone. + * + * @param parameterIndex + * the first parameter is 1...)); + * @param x + * the parameter value + * @param cal + * the timezone to use + * + * @throws SQLException + * if a database access error occurs + */ + public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) + throws SQLException { + setTimeInternal(parameterIndex, x, cal, cal.getTimeZone(), true); + } + + /** + * Set a parameter to a java.sql.Time value. The driver converts this to a + * SQL TIME value when it sends it to the database, using the given + * timezone. + * + * @param parameterIndex + * the first parameter is 1...)); + * @param x + * the parameter value + * @param tz + * the timezone to use + * + * @throws SQLException + * if a database access error occurs + */ + public void setTimeInternal(int parameterIndex, java.sql.Time x, + Calendar targetCalendar, + TimeZone tz, boolean rollForward) throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.TIME); + } else { + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_TIME); + + Calendar sessionCalendar = getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + binding.value = TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + x, tz, + this.connection.getServerTimezoneTZ(), + rollForward); + } + + binding.isNull = false; + binding.isLongData = false; + } + } + + /** + * Set a parameter to a java.sql.Timestamp value. The driver converts this + * to a SQL TIMESTAMP value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param x + * the parameter value + * + * @throws SQLException + * if a database-access error occurs. + */ + public void setTimestamp(int parameterIndex, java.sql.Timestamp x) + throws SQLException { + setTimestampInternal(parameterIndex, x, null, this.connection.getDefaultTimeZone(), false); + } + + /** + * Set a parameter to a java.sql.Timestamp value. The driver converts this + * to a SQL TIMESTAMP value when it sends it to the database. + * + * @param parameterIndex + * the first parameter is 1, the second is 2, ... + * @param x + * the parameter value + * @param cal + * the timezone to use + * + * @throws SQLException + * if a database-access error occurs. + */ + public void setTimestamp(int parameterIndex, java.sql.Timestamp x, + Calendar cal) throws SQLException { + setTimestampInternal(parameterIndex, x, cal, cal.getTimeZone(), true); + } + + protected void setTimestampInternal(int parameterIndex, + java.sql.Timestamp x, Calendar targetCalendar, + TimeZone tz, boolean rollForward) + throws SQLException { + if (x == null) { + setNull(parameterIndex, java.sql.Types.TIMESTAMP); + } else { + BindValue binding = getBinding(parameterIndex, false); + setType(binding, MysqlDefs.FIELD_TYPE_DATETIME); + + Calendar sessionCalendar = this.connection.getUseJDBCCompliantTimezoneShift() ? + this.connection.getUtcCalendar() : + getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + binding.value = TimeUtil.changeTimezone(this.connection, + sessionCalendar, + targetCalendar, + x, tz, + this.connection.getServerTimezoneTZ(), + rollForward); + } + + binding.isNull = false; + binding.isLongData = false; + } + } + + private void setType(BindValue oldValue, int bufferType) { + if (oldValue.bufferType != bufferType) { + this.sendTypesToServer = true; + } + + oldValue.bufferType = bufferType; + } + + /** + * DOCUMENT ME! + * + * @param parameterIndex + * DOCUMENT ME! + * @param x + * DOCUMENT ME! + * @param length + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + * @throws NotImplemented + * DOCUMENT ME! + * + * @see java.sql.PreparedStatement#setUnicodeStream(int, + * java.io.InputStream, int) + * @deprecated + */ + public void setUnicodeStream(int parameterIndex, InputStream x, int length) + throws SQLException { + checkClosed(); + + throw new NotImplemented(); + } + + /** + * @see java.sql.PreparedStatement#setURL(int, java.net.URL) + */ + public void setURL(int parameterIndex, URL x) throws SQLException { + checkClosed(); + + setString(parameterIndex, x.toString()); + } + + /** + * Method storeBinding. + * + * @param packet + * @param bindValue + * @param mysql + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + private void storeBinding(Buffer packet, BindValue bindValue, MysqlIO mysql) + throws SQLException { + try { + Object value = bindValue.value; + + // + // Handle primitives first + // + switch (bindValue.bufferType) { + + case MysqlDefs.FIELD_TYPE_TINY: + packet.writeByte(bindValue.byteBinding); + return; + case MysqlDefs.FIELD_TYPE_SHORT: + packet.ensureCapacity(2); + packet.writeInt(bindValue.shortBinding); + return; + case MysqlDefs.FIELD_TYPE_LONG: + packet.ensureCapacity(4); + packet.writeLong(bindValue.intBinding); + return; + case MysqlDefs.FIELD_TYPE_LONGLONG: + packet.ensureCapacity(8); + packet.writeLongLong(bindValue.longBinding); + return; + case MysqlDefs.FIELD_TYPE_FLOAT: + packet.ensureCapacity(4); + packet.writeFloat(bindValue.floatBinding); + return; + case MysqlDefs.FIELD_TYPE_DOUBLE: + packet.ensureCapacity(8); + packet.writeDouble(bindValue.doubleBinding); + return; + case MysqlDefs.FIELD_TYPE_TIME: + storeTime(packet, (Time) value); + return; + case MysqlDefs.FIELD_TYPE_DATE: + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + storeDateTime(packet, (java.util.Date) value, mysql); + return; + case MysqlDefs.FIELD_TYPE_VAR_STRING: + case MysqlDefs.FIELD_TYPE_STRING: + case MysqlDefs.FIELD_TYPE_VARCHAR: + case MysqlDefs.FIELD_TYPE_DECIMAL: + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + if (value instanceof byte[]) { + packet.writeLenBytes((byte[]) value); + } else if (!this.isLoadDataQuery) { + packet.writeLenString((String) value, this.charEncoding, + this.connection.getServerCharacterEncoding(), + this.charConverter, this.connection + .parserKnowsUnicode(), + this.connection); + } else { + packet.writeLenBytes(((String) value).getBytes()); + } + + return; + } + + + } catch (UnsupportedEncodingException uEE) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.22") //$NON-NLS-1$ + + this.connection.getEncoding() + "'", //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); + } + } + + private void storeDataTime412AndOlder(Buffer intoBuf, java.util.Date dt) + throws SQLException { + + Calendar sessionCalendar = getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + java.util.Date oldTime = sessionCalendar.getTime(); + + try { + intoBuf.ensureCapacity(8); + intoBuf.writeByte((byte) 7); // length + + sessionCalendar.setTime(dt); + + int year = sessionCalendar.get(Calendar.YEAR); + int month = sessionCalendar.get(Calendar.MONTH) + 1; + int date = sessionCalendar.get(Calendar.DATE); + + intoBuf.writeInt(year); + intoBuf.writeByte((byte) month); + intoBuf.writeByte((byte) date); + + if (dt instanceof java.sql.Date) { + intoBuf.writeByte((byte) 0); + intoBuf.writeByte((byte) 0); + intoBuf.writeByte((byte) 0); + } else { + intoBuf.writeByte((byte) sessionCalendar + .get(Calendar.HOUR_OF_DAY)); + intoBuf.writeByte((byte) sessionCalendar + .get(Calendar.MINUTE)); + intoBuf.writeByte((byte) sessionCalendar + .get(Calendar.SECOND)); + } + } finally { + sessionCalendar.setTime(oldTime); + } + } + } + + private void storeDateTime(Buffer intoBuf, java.util.Date dt, MysqlIO mysql) + throws SQLException { + if (this.connection.versionMeetsMinimum(4, 1, 3)) { + storeDateTime413AndNewer(intoBuf, dt); + } else { + storeDataTime412AndOlder(intoBuf, dt); + } + } + + private void storeDateTime413AndNewer(Buffer intoBuf, java.util.Date dt) + throws SQLException { + Calendar sessionCalendar = (dt instanceof Timestamp && + this.connection.getUseJDBCCompliantTimezoneShift()) ? + this.connection.getUtcCalendar() : getCalendarInstanceForSessionOrNew(); + + synchronized (sessionCalendar) { + java.util.Date oldTime = sessionCalendar.getTime(); + + + try { + sessionCalendar.setTime(dt); + + if (dt instanceof java.sql.Date) { + sessionCalendar.set(Calendar.HOUR_OF_DAY, 0); + sessionCalendar.set(Calendar.MINUTE, 0); + sessionCalendar.set(Calendar.SECOND, 0); + } + + byte length = (byte) 7; + + if (dt instanceof java.sql.Timestamp) { + length = (byte) 11; + } + + intoBuf.ensureCapacity(length); + + intoBuf.writeByte(length); // length + + int year = sessionCalendar.get(Calendar.YEAR); + int month = sessionCalendar.get(Calendar.MONTH) + 1; + int date = sessionCalendar.get(Calendar.DAY_OF_MONTH); + + intoBuf.writeInt(year); + intoBuf.writeByte((byte) month); + intoBuf.writeByte((byte) date); + + if (dt instanceof java.sql.Date) { + intoBuf.writeByte((byte) 0); + intoBuf.writeByte((byte) 0); + intoBuf.writeByte((byte) 0); + } else { + intoBuf.writeByte((byte) sessionCalendar + .get(Calendar.HOUR_OF_DAY)); + intoBuf.writeByte((byte) sessionCalendar + .get(Calendar.MINUTE)); + intoBuf.writeByte((byte) sessionCalendar + .get(Calendar.SECOND)); + } + + if (length == 11) { + // MySQL expects microseconds, not nanos + intoBuf.writeLong(((java.sql.Timestamp) dt).getNanos() / 1000); + } + + } finally { + sessionCalendar.setTime(oldTime); + } + } + } + + // + // TO DO: Investigate using NIO to do this faster + // + private void storeReader(MysqlIO mysql, int parameterIndex, Buffer packet, + Reader inStream) throws SQLException { + String forcedEncoding = this.connection.getClobCharacterEncoding(); + + String clobEncoding = + (forcedEncoding == null ? this.connection.getEncoding() : forcedEncoding); + + int maxBytesChar = 2; + + if (clobEncoding != null) { + if (!clobEncoding.equals("UTF-16")) { + maxBytesChar = this.connection.getMaxBytesPerChar(clobEncoding); + + if (maxBytesChar == 1) { + maxBytesChar = 2; // for safety + } + } else { + maxBytesChar = 4; + } + } + + char[] buf = new char[BLOB_STREAM_READ_BUF_SIZE / maxBytesChar]; + + int numRead = 0; + + int bytesInPacket = 0; + int totalBytesRead = 0; + int bytesReadAtLastSend = 0; + int packetIsFullAt = this.connection.getBlobSendChunkSize(); + + + + try { + packet.clear(); + packet.writeByte((byte) MysqlDefs.COM_LONG_DATA); + packet.writeLong(this.serverStatementId); + packet.writeInt((parameterIndex)); + + boolean readAny = false; + + while ((numRead = inStream.read(buf)) != -1) { + readAny = true; + + byte[] valueAsBytes = StringUtils.getBytes(buf, null, + clobEncoding, this.connection + .getServerCharacterEncoding(), 0, numRead, + this.connection.parserKnowsUnicode()); + + packet.writeBytesNoNull(valueAsBytes, 0, valueAsBytes.length); + + bytesInPacket += valueAsBytes.length; + totalBytesRead += valueAsBytes.length; + + if (bytesInPacket >= packetIsFullAt) { + bytesReadAtLastSend = totalBytesRead; + + mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, + true, null); + + bytesInPacket = 0; + packet.clear(); + packet.writeByte((byte) MysqlDefs.COM_LONG_DATA); + packet.writeLong(this.serverStatementId); + packet.writeInt((parameterIndex)); + } + } + + if (totalBytesRead != bytesReadAtLastSend) { + mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, true, + null); + } + + if (!readAny) { + mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, true, + null); + } + } catch (IOException ioEx) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.24") //$NON-NLS-1$ + + ioEx.toString(), SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + if (this.connection.getAutoClosePStmtStreams()) { + if (inStream != null) { + try { + inStream.close(); + } catch (IOException ioEx) { + ; // ignore + } + } + } + } + } + + private void storeStream(MysqlIO mysql, int parameterIndex, Buffer packet, + InputStream inStream) throws SQLException { + byte[] buf = new byte[BLOB_STREAM_READ_BUF_SIZE]; + + int numRead = 0; + + try { + int bytesInPacket = 0; + int totalBytesRead = 0; + int bytesReadAtLastSend = 0; + int packetIsFullAt = this.connection.getBlobSendChunkSize(); + + packet.clear(); + packet.writeByte((byte) MysqlDefs.COM_LONG_DATA); + packet.writeLong(this.serverStatementId); + packet.writeInt((parameterIndex)); + + boolean readAny = false; + + while ((numRead = inStream.read(buf)) != -1) { + + readAny = true; + + packet.writeBytesNoNull(buf, 0, numRead); + bytesInPacket += numRead; + totalBytesRead += numRead; + + if (bytesInPacket >= packetIsFullAt) { + bytesReadAtLastSend = totalBytesRead; + + mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, + true, null); + + bytesInPacket = 0; + packet.clear(); + packet.writeByte((byte) MysqlDefs.COM_LONG_DATA); + packet.writeLong(this.serverStatementId); + packet.writeInt((parameterIndex)); + } + } + + if (totalBytesRead != bytesReadAtLastSend) { + mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, true, + null); + } + + if (!readAny) { + mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, true, + null); + } + } catch (IOException ioEx) { + throw SQLError.createSQLException(Messages + .getString("ServerPreparedStatement.25") //$NON-NLS-1$ + + ioEx.toString(), SQLError.SQL_STATE_GENERAL_ERROR); + } finally { + if (this.connection.getAutoClosePStmtStreams()) { + if (inStream != null) { + try { + inStream.close(); + } catch (IOException ioEx) { + ; // ignore + } + } + } + } + } + + /** + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuffer toStringBuf = new StringBuffer(); + + toStringBuf.append("com.mysql.jdbc.ServerPreparedStatement["); //$NON-NLS-1$ + toStringBuf.append(this.serverStatementId); + toStringBuf.append("] - "); //$NON-NLS-1$ + + try { + toStringBuf.append(asSql()); + } catch (SQLException sqlEx) { + toStringBuf.append(Messages.getString("ServerPreparedStatement.6")); //$NON-NLS-1$ + toStringBuf.append(sqlEx); + } + + return toStringBuf.toString(); + } + + protected long getServerStatementId() { + return serverStatementId; + } + + public synchronized boolean canRewriteAsMultivalueInsertStatement() { + if (!super.canRewriteAsMultivalueInsertStatement()) { + return false; + } + + BindValue[] currentBindValues = null; + BindValue[] previousBindValues = null; + + int nbrCommands = this.batchedArgs.size(); + + // Can't have type changes between sets of bindings for this to work... + + for (int commandIndex = 0; commandIndex < nbrCommands; commandIndex++) { + Object arg = this.batchedArgs.get(commandIndex); + + if (!(arg instanceof String)) { + + currentBindValues = ((BatchedBindValues) arg).batchedParameterValues; + + // We need to check types each time, as + // the user might have bound different + // types in each addBatch() + + if (previousBindValues != null) { + for (int j = 0; j < this.parameterBindings.length; j++) { + if (currentBindValues[j].bufferType != previousBindValues[j].bufferType) { + return false; + } + } + } + } + } + + return true; + } + + /** + * Computes the maximum parameter set size, and entire batch size given + * the number of arguments in the batch. + */ + protected long[] computeMaxParameterSetSizeAndBatchSize(int numBatchedArgs) { + long sizeOfEntireBatch = 1 + /* com_execute */ + 4 /* stmt id */ + 1 /* flags */ + 4 /* batch count padding */; + long maxSizeOfParameterSet = 0; + + for (int i = 0; i < numBatchedArgs; i++) { + BindValue[] paramArg = ((BatchedBindValues) this.batchedArgs.get(i)).batchedParameterValues; + + long sizeOfParameterSet = 0; + + sizeOfParameterSet += (this.parameterCount + 7) / 8; // for isNull + + sizeOfParameterSet += this.parameterCount * 2; // have to send types + + for (int j = 0; j < this.parameterBindings.length; j++) { + if (!paramArg[j].isNull) { + + long size = paramArg[j].getBoundLength(); + + if (paramArg[j].isLongData) { + if (size != -1) { + sizeOfParameterSet += size; + } + } else { + sizeOfParameterSet += size; + } + } + } + + sizeOfEntireBatch += sizeOfParameterSet; + + if (sizeOfParameterSet > maxSizeOfParameterSet) { + maxSizeOfParameterSet = sizeOfParameterSet; + } + } + + return new long[] {maxSizeOfParameterSet, sizeOfEntireBatch}; + } + + protected int setOneBatchedParameterSet( + java.sql.PreparedStatement batchedStatement, int batchedParamIndex, + Object paramSet) throws SQLException { + BindValue[] paramArg = ((BatchedBindValues) paramSet).batchedParameterValues; + + for (int j = 0; j < paramArg.length; j++) { + if (paramArg[j].isNull) { + batchedStatement.setNull(batchedParamIndex++, Types.NULL); + } else { + if (paramArg[j].isLongData) { + Object value = paramArg[j].value; + + if (value instanceof InputStream) { + batchedStatement.setBinaryStream(batchedParamIndex++, + (InputStream) value, + (int) paramArg[j].bindLength); + } else { + batchedStatement.setCharacterStream( + batchedParamIndex++, (Reader) value, + (int) paramArg[j].bindLength); + } + } else { + + switch (paramArg[j].bufferType) { + + case MysqlDefs.FIELD_TYPE_TINY: + batchedStatement.setByte(batchedParamIndex++, + paramArg[j].byteBinding); + break; + case MysqlDefs.FIELD_TYPE_SHORT: + batchedStatement.setShort(batchedParamIndex++, + paramArg[j].shortBinding); + break; + case MysqlDefs.FIELD_TYPE_LONG: + batchedStatement.setInt(batchedParamIndex++, + paramArg[j].intBinding); + break; + case MysqlDefs.FIELD_TYPE_LONGLONG: + batchedStatement.setLong(batchedParamIndex++, + paramArg[j].longBinding); + break; + case MysqlDefs.FIELD_TYPE_FLOAT: + batchedStatement.setFloat(batchedParamIndex++, + paramArg[j].floatBinding); + break; + case MysqlDefs.FIELD_TYPE_DOUBLE: + batchedStatement.setDouble(batchedParamIndex++, + paramArg[j].doubleBinding); + break; + case MysqlDefs.FIELD_TYPE_TIME: + batchedStatement.setTime(batchedParamIndex++, + (Time) paramArg[j].value); + break; + case MysqlDefs.FIELD_TYPE_DATE: + batchedStatement.setDate(batchedParamIndex++, + (Date) paramArg[j].value); + break; + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + batchedStatement.setTimestamp(batchedParamIndex++, + (Timestamp) paramArg[j].value); + break; + case MysqlDefs.FIELD_TYPE_VAR_STRING: + case MysqlDefs.FIELD_TYPE_STRING: + case MysqlDefs.FIELD_TYPE_VARCHAR: + case MysqlDefs.FIELD_TYPE_DECIMAL: + case MysqlDefs.FIELD_TYPE_NEW_DECIMAL: + Object value = paramArg[j].value; + + if (value instanceof byte[]) { + batchedStatement.setBytes(batchedParamIndex, + (byte[]) value); + } else { + batchedStatement.setString(batchedParamIndex, + (String) value); + } + + BindValue asBound = ((ServerPreparedStatement) batchedStatement) + .getBinding( + batchedParamIndex + 1 /* + * uses 1-based + * offset + */, + false); + asBound.bufferType = paramArg[j].bufferType; + + batchedParamIndex++; + + break; + default: + throw new IllegalArgumentException( + "Unknown type when re-binding parameter into batched statement for parameter index " + + batchedParamIndex); + } + } + } + } + + return batchedParamIndex; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/SingleByteCharsetConverter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/SingleByteCharsetConverter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/SingleByteCharsetConverter.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,288 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.UnsupportedEncodingException; + +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +/** + * Converter for char[]->byte[] and byte[]->char[] for single-byte character + * sets. + * + * Much faster (5-6x) than the built-in solution that ships with the JVM, even + * with JDK-1.4.x and NewIo. + * + * @author Mark Matthews + */ +public class SingleByteCharsetConverter { + + private static final int BYTE_RANGE = (1 + Byte.MAX_VALUE) - Byte.MIN_VALUE; + private static byte[] allBytes = new byte[BYTE_RANGE]; + private static final Map CONVERTER_MAP = new HashMap(); + + private final static byte[] EMPTY_BYTE_ARRAY = new byte[0]; + + // The initial charToByteMap, with all char mappings mapped + // to (byte) '?', so that unknown characters are mapped to '?' + // instead of '\0' (which means end-of-string to MySQL). + private static byte[] unknownCharsMap = new byte[65536]; + + static { + for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) { + allBytes[i - Byte.MIN_VALUE] = (byte) i; + } + + for (int i = 0; i < unknownCharsMap.length; i++) { + unknownCharsMap[i] = (byte) '?'; // use something 'sane' for + // unknown chars + } + } + + // ~ Instance fields + // -------------------------------------------------------- + + /** + * Get a converter for the given encoding name + * + * @param encodingName + * the Java character encoding name + * + * @return a converter for the given encoding name + * @throws UnsupportedEncodingException + * if the character encoding is not supported + */ + public static synchronized SingleByteCharsetConverter getInstance( + String encodingName, Connection conn) + throws UnsupportedEncodingException, SQLException { + SingleByteCharsetConverter instance = (SingleByteCharsetConverter) CONVERTER_MAP + .get(encodingName); + + if (instance == null) { + instance = initCharset(encodingName); + } + + return instance; + } + + /** + * Initialize the shared instance of a converter for the given character + * encoding. + * + * @param javaEncodingName + * the Java name for the character set to initialize + * @return a converter for the given character set + * @throws UnsupportedEncodingException + * if the character encoding is not supported + */ + public static SingleByteCharsetConverter initCharset(String javaEncodingName) + throws UnsupportedEncodingException, SQLException { + if (CharsetMapping.isMultibyteCharset(javaEncodingName)) { + return null; + } + + SingleByteCharsetConverter converter = new SingleByteCharsetConverter( + javaEncodingName); + + CONVERTER_MAP.put(javaEncodingName, converter); + + return converter; + } + + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Convert the byte buffer from startPos to a length of length to a string + * using the default platform encoding. + * + * @param buffer + * the bytes to convert + * @param startPos + * the index to start at + * @param length + * the number of bytes to convert + * @return the String representation of the given bytes + */ + public static String toStringDefaultEncoding(byte[] buffer, int startPos, + int length) { + return new String(buffer, startPos, length); + } + + // ~ Methods + // ---------------------------------------------------------------- + + private char[] byteToChars = new char[BYTE_RANGE]; + + private byte[] charToByteMap = new byte[65536]; + + /** + * Prevent instantiation, called out of static method initCharset(). + * + * @param encodingName + * a JVM character encoding + * @throws UnsupportedEncodingException + * if the JVM does not support the encoding + */ + private SingleByteCharsetConverter(String encodingName) + throws UnsupportedEncodingException { + String allBytesString = new String(allBytes, 0, BYTE_RANGE, + encodingName); + int allBytesLen = allBytesString.length(); + + System.arraycopy(unknownCharsMap, 0, this.charToByteMap, 0, + this.charToByteMap.length); + + for (int i = 0; i < BYTE_RANGE && i < allBytesLen; i++) { + char c = allBytesString.charAt(i); + this.byteToChars[i] = c; + this.charToByteMap[c] = allBytes[i]; + } + } + + public final byte[] toBytes(char[] c) { + if (c == null) { + return null; + } + + int length = c.length; + byte[] bytes = new byte[length]; + + for (int i = 0; i < length; i++) { + bytes[i] = this.charToByteMap[c[i]]; + } + + return bytes; + } + + public final byte[] toBytes(char[] chars, int offset, int length) { + if (chars == null) { + return null; + } + + if (length == 0) { + return EMPTY_BYTE_ARRAY; + } + + byte[] bytes = new byte[length]; + + for (int i = 0; (i < length); i++) { + bytes[i] = this.charToByteMap[chars[i + offset]]; + } + + return bytes; + } + + /** + * Convert the given string to an array of bytes. + * + * @param s + * the String to convert + * @return the bytes that make up the String + */ + public final byte[] toBytes(String s) { + if (s == null) { + return null; + } + + int length = s.length(); + byte[] bytes = new byte[length]; + + for (int i = 0; i < length; i++) { + bytes[i] = this.charToByteMap[s.charAt(i)]; + } + + return bytes; + } + + /** + * Convert the given string to an array of bytes. + * + * @param s + * the String to convert + * @param offset + * the offset to start at + * @param length + * length (max) to convert + * + * @return the bytes that make up the String + */ + public final byte[] toBytes(String s, int offset, int length) { + if (s == null) { + return null; + } + + if (length == 0) { + return EMPTY_BYTE_ARRAY; + } + + byte[] bytes = new byte[length]; + + for (int i = 0; (i < length); i++) { + char c = s.charAt(i + offset); + bytes[i] = this.charToByteMap[c]; + } + + return bytes; + } + + /** + * Convert the byte buffer to a string using this instance's character + * encoding. + * + * @param buffer + * the bytes to convert to a String + * @return the converted String + */ + public final String toString(byte[] buffer) { + return toString(buffer, 0, buffer.length); + } + + /** + * Convert the byte buffer from startPos to a length of length to a string + * using this instance's character encoding. + * + * @param buffer + * the bytes to convert + * @param startPos + * the index to start at + * @param length + * the number of bytes to convert + * @return the String representation of the given bytes + */ + public final String toString(byte[] buffer, int startPos, int length) { + char[] charArray = new char[length]; + int readpoint = startPos; + + for (int i = 0; i < length; i++) { + charArray[i] = this.byteToChars[buffer[readpoint] - Byte.MIN_VALUE]; + readpoint++; + } + + return new String(charArray); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/SocketFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/SocketFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/SocketFactory.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,98 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.IOException; + +import java.net.Socket; +import java.net.SocketException; + +import java.util.Properties; + +/** + * Interface to allow pluggable socket creation in the driver + * + * @author Mark Matthews + */ +public interface SocketFactory { + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Called by the driver after issuing the MySQL protocol handshake and + * reading the results of the handshake. + * + * @throws SocketException + * if a socket error occurs + * @throws IOException + * if an I/O error occurs + * + * @return the socket to use after the handshake + */ + Socket afterHandshake() throws SocketException, IOException; + + /** + * Called by the driver before issuing the MySQL protocol handshake. Should + * return the socket instance that should be used during the handshake. + * + * @throws SocketException + * if a socket error occurs + * @throws IOException + * if an I/O error occurs + * + * @return the socket to use before the handshake + */ + Socket beforeHandshake() throws SocketException, IOException; + + /** + * Creates a new socket using the given properties. Properties are parsed by + * the driver from the URL. All properties other than sensitive ones (user + * and password) are passed to this method. The driver will instantiate the + * socket factory with the class name given in the property + * "socketFactory", where the standard is + * com.mysql.jdbc.StandardSocketFactory Implementing classes + * are responsible for handling synchronization of this method (if needed). + * + * @param host + * the hostname passed in the JDBC URL. It will be a single + * hostname, as the driver parses multi-hosts (for failover) and + * calls this method for each host connection attempt. + * + * @param portNumber + * the port number to connect to (if required). + * + * @param props + * properties passed to the driver via the URL and/or properties + * instance. + * + * @return a socket connected to the given host + * @throws SocketException + * if a socket error occurs + * @throws IOException + * if an I/O error occurs + */ + Socket connect(String host, int portNumber, Properties props) + throws SocketException, IOException; +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/StandardSocketFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/StandardSocketFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/StandardSocketFactory.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,409 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.IOException; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import java.net.InetAddress; +import java.net.Socket; +import java.net.SocketException; + +import java.util.Properties; + +/** + * Socket factory for vanilla TCP/IP sockets (the standard) + * + * @author Mark Matthews + */ +public class StandardSocketFactory implements SocketFactory { + + public static final String TCP_NO_DELAY_PROPERTY_NAME = "tcpNoDelay"; + + public static final String TCP_KEEP_ALIVE_DEFAULT_VALUE = "true"; + + public static final String TCP_KEEP_ALIVE_PROPERTY_NAME = "tcpKeepAlive"; + + public static final String TCP_RCV_BUF_PROPERTY_NAME = "tcpRcvBuf"; + + public static final String TCP_SND_BUF_PROPERTY_NAME = "tcpSndBuf"; + + public static final String TCP_TRAFFIC_CLASS_PROPERTY_NAME = "tcpTrafficClass"; + + public static final String TCP_RCV_BUF_DEFAULT_VALUE = "0"; + + public static final String TCP_SND_BUF_DEFAULT_VALUE = "0"; + + public static final String TCP_TRAFFIC_CLASS_DEFAULT_VALUE = "0"; + + public static final String TCP_NO_DELAY_DEFAULT_VALUE = "true"; + + /** Use reflection for pre-1.4 VMs */ + + private static Method setTraficClassMethod; + + static { + try { + setTraficClassMethod = Socket.class.getMethod("setTrafficClass", + new Class[] { Integer.TYPE }); + } catch (SecurityException e) { + setTraficClassMethod = null; + } catch (NoSuchMethodException e) { + setTraficClassMethod = null; + } + } + + /** The hostname to connect to */ + protected String host = null; + + /** The port number to connect to */ + protected int port = 3306; + + /** The underlying TCP/IP socket to use */ + protected Socket rawSocket = null; + + /** + * Called by the driver after issuing the MySQL protocol handshake and + * reading the results of the handshake. + * + * @throws SocketException + * if a socket error occurs + * @throws IOException + * if an I/O error occurs + * + * @return The socket to use after the handshake + */ + public Socket afterHandshake() throws SocketException, IOException { + return this.rawSocket; + } + + /** + * Called by the driver before issuing the MySQL protocol handshake. Should + * return the socket instance that should be used during the handshake. + * + * @throws SocketException + * if a socket error occurs + * @throws IOException + * if an I/O error occurs + * + * @return the socket to use before the handshake + */ + public Socket beforeHandshake() throws SocketException, IOException { + return this.rawSocket; + } + + /** + * Configures socket properties based on properties from the connection + * (tcpNoDelay, snd/rcv buf, traffic class, etc). + * + * @param props + * @throws SocketException + * @throws IOException + */ + private void configureSocket(Socket sock, Properties props) throws SocketException, + IOException { + try { + sock.setTcpNoDelay(Boolean.valueOf( + props.getProperty(TCP_NO_DELAY_PROPERTY_NAME, + TCP_NO_DELAY_DEFAULT_VALUE)).booleanValue()); + + String keepAlive = props.getProperty(TCP_KEEP_ALIVE_PROPERTY_NAME, + TCP_KEEP_ALIVE_DEFAULT_VALUE); + + if (keepAlive != null && keepAlive.length() > 0) { + sock.setKeepAlive(Boolean.valueOf(keepAlive) + .booleanValue()); + } + + int receiveBufferSize = Integer.parseInt(props.getProperty( + TCP_RCV_BUF_PROPERTY_NAME, TCP_RCV_BUF_DEFAULT_VALUE)); + + if (receiveBufferSize > 0) { + sock.setReceiveBufferSize(receiveBufferSize); + } + + int sendBufferSize = Integer.parseInt(props.getProperty( + TCP_SND_BUF_PROPERTY_NAME, TCP_SND_BUF_DEFAULT_VALUE)); + + if (sendBufferSize > 0) { + sock.setSendBufferSize(sendBufferSize); + } + + int trafficClass = Integer.parseInt(props.getProperty( + TCP_TRAFFIC_CLASS_PROPERTY_NAME, + TCP_TRAFFIC_CLASS_DEFAULT_VALUE)); + + if (trafficClass > 0 && setTraficClassMethod != null) { + setTraficClassMethod.invoke(sock, + new Object[] { new Integer(trafficClass) }); + } + } catch (Throwable t) { + unwrapExceptionToProperClassAndThrowIt(t); + } + } + + /** + * @see com.mysql.jdbc.SocketFactory#createSocket(Properties) + */ + public Socket connect(String hostname, int portNumber, Properties props) + throws SocketException, IOException { + + if (props != null) { + this.host = hostname; + + this.port = portNumber; + + Method connectWithTimeoutMethod = null; + Method socketBindMethod = null; + Class socketAddressClass = null; + + String localSocketHostname = props + .getProperty("localSocketAddress"); + + String connectTimeoutStr = props.getProperty("connectTimeout"); + + int connectTimeout = 0; + + boolean wantsTimeout = (connectTimeoutStr != null + && connectTimeoutStr.length() > 0 && !connectTimeoutStr + .equals("0")); + + boolean wantsLocalBind = (localSocketHostname != null && localSocketHostname + .length() > 0); + + boolean needsConfigurationBeforeConnect = socketNeedsConfigurationBeforeConnect(props); + + if (wantsTimeout || wantsLocalBind || needsConfigurationBeforeConnect) { + + if (connectTimeoutStr != null) { + try { + connectTimeout = Integer.parseInt(connectTimeoutStr); + } catch (NumberFormatException nfe) { + throw new SocketException("Illegal value '" + + connectTimeoutStr + "' for connectTimeout"); + } + } + + try { + // Have to do this with reflection, otherwise older JVMs + // croak + socketAddressClass = Class + .forName("java.net.SocketAddress"); + + connectWithTimeoutMethod = Socket.class.getMethod( + "connect", new Class[] { socketAddressClass, + Integer.TYPE }); + + socketBindMethod = Socket.class.getMethod("bind", + new Class[] { socketAddressClass }); + + } catch (NoClassDefFoundError noClassDefFound) { + // ignore, we give a better error below if needed + } catch (NoSuchMethodException noSuchMethodEx) { + // ignore, we give a better error below if needed + } catch (Throwable catchAll) { + // ignore, we give a better error below if needed + } + + if (wantsLocalBind && socketBindMethod == null) { + throw new SocketException( + "Can't specify \"localSocketAddress\" on JVMs older than 1.4"); + } + + if (wantsTimeout && connectWithTimeoutMethod == null) { + throw new SocketException( + "Can't specify \"connectTimeout\" on JVMs older than 1.4"); + } + } + + if (this.host != null) { + if (!(wantsLocalBind || wantsTimeout || needsConfigurationBeforeConnect)) { + InetAddress[] possibleAddresses = InetAddress + .getAllByName(this.host); + + Throwable caughtWhileConnecting = null; + + // Need to loop through all possible addresses, in case + // someone has IPV6 configured (SuSE, for example...) + + for (int i = 0; i < possibleAddresses.length; i++) { + try { + this.rawSocket = new Socket(possibleAddresses[i], + port); + + configureSocket(this.rawSocket, props); + + break; + } catch (Exception ex) { + caughtWhileConnecting = ex; + } + } + + if (rawSocket == null) { + unwrapExceptionToProperClassAndThrowIt(caughtWhileConnecting); + } + } else { + // must explicitly state this due to classloader issues + // when running on older JVMs :( + try { + + InetAddress[] possibleAddresses = InetAddress + .getAllByName(this.host); + + Throwable caughtWhileConnecting = null; + + Object localSockAddr = null; + + Class inetSocketAddressClass = null; + + Constructor addrConstructor = null; + + try { + inetSocketAddressClass = Class + .forName("java.net.InetSocketAddress"); + + addrConstructor = inetSocketAddressClass + .getConstructor(new Class[] { + InetAddress.class, Integer.TYPE }); + + if (wantsLocalBind) { + localSockAddr = addrConstructor + .newInstance(new Object[] { + InetAddress + .getByName(localSocketHostname), + new Integer(0 /* + * use ephemeral + * port + */) }); + + } + } catch (Throwable ex) { + unwrapExceptionToProperClassAndThrowIt(ex); + } + + // Need to loop through all possible addresses, in case + // someone has IPV6 configured (SuSE, for example...) + + for (int i = 0; i < possibleAddresses.length; i++) { + + try { + this.rawSocket = new Socket(); + + configureSocket(this.rawSocket, props); + + Object sockAddr = addrConstructor + .newInstance(new Object[] { + possibleAddresses[i], + new Integer(port) }); + // bind to the local port, null is 'ok', it + // means + // use the ephemeral port + socketBindMethod.invoke(rawSocket, + new Object[] { localSockAddr }); + + connectWithTimeoutMethod.invoke(rawSocket, + new Object[] { sockAddr, + new Integer(connectTimeout) }); + + break; + } catch (Exception ex) { + this.rawSocket = null; + + caughtWhileConnecting = ex; + } + } + + if (this.rawSocket == null) { + unwrapExceptionToProperClassAndThrowIt(caughtWhileConnecting); + } + + } catch (Throwable t) { + unwrapExceptionToProperClassAndThrowIt(t); + } + } + + return this.rawSocket; + } + } + + throw new SocketException("Unable to create socket"); + } + + /** + * Does the configureSocket() need to be called before the socket is + * connect()d based on the properties supplied? + * + */ + private boolean socketNeedsConfigurationBeforeConnect(Properties props) { + int receiveBufferSize = Integer.parseInt(props.getProperty( + TCP_RCV_BUF_PROPERTY_NAME, TCP_RCV_BUF_DEFAULT_VALUE)); + + if (receiveBufferSize > 0) { + return true; + } + + int sendBufferSize = Integer.parseInt(props.getProperty( + TCP_SND_BUF_PROPERTY_NAME, TCP_SND_BUF_DEFAULT_VALUE)); + + if (sendBufferSize > 0) { + return true; + } + + int trafficClass = Integer.parseInt(props.getProperty( + TCP_TRAFFIC_CLASS_PROPERTY_NAME, + TCP_TRAFFIC_CLASS_DEFAULT_VALUE)); + + if (trafficClass > 0 && setTraficClassMethod != null) { + return true; + } + + return false; + } + + private void unwrapExceptionToProperClassAndThrowIt( + Throwable caughtWhileConnecting) throws SocketException, + IOException { + if (caughtWhileConnecting instanceof InvocationTargetException) { + + // Replace it with the target, don't use 1.4 chaining as this still + // needs to run on older VMs + caughtWhileConnecting = ((InvocationTargetException) caughtWhileConnecting) + .getTargetException(); + } + + if (caughtWhileConnecting instanceof SocketException) { + throw (SocketException) caughtWhileConnecting; + } + + if (caughtWhileConnecting instanceof IOException) { + throw (IOException) caughtWhileConnecting; + } + + throw new SocketException(caughtWhileConnecting.toString()); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Statement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Statement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Statement.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,2368 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import com.mysql.jdbc.exceptions.MySQLTimeoutException; +import com.mysql.jdbc.profiler.ProfileEventSink; +import com.mysql.jdbc.profiler.ProfilerEvent; +import com.mysql.jdbc.util.LRUCache; + +import java.sql.DataTruncation; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Types; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.TimerTask; + +/** + * A Statement object is used for executing a static SQL statement and obtaining + * the results produced by it. + * + *

+ * Only one ResultSet per Statement can be open at any point in time. Therefore, + * if the reading of one ResultSet is interleaved with the reading of another, + * each must have been generated by different Statements. All statement execute + * methods implicitly close a statement's current ResultSet if an open one + * exists. + *

+ * + * @author Mark Matthews + * @version $Id: Statement.java 4624 2005-11-28 14:24:29 -0600 (Mon, 28 Nov + * 2005) mmatthews $ + * + * @see java.sql.Statement + * @see ResultSet + */ +public class Statement implements java.sql.Statement { + protected static final String PING_MARKER = "/* ping */"; + + /** + * Thread used to implement query timeouts...Eventually we could be more + * efficient and have one thread with timers, but this is a straightforward + * and simple way to implement a feature that isn't used all that often. + */ + class CancelTask extends TimerTask { + + long connectionId = 0; + SQLException caughtWhileCancelling = null; + + CancelTask() throws SQLException { + connectionId = connection.getIO().getThreadId(); + } + + public void run() { + + Thread cancelThread = new Thread() { + + public void run() { + Connection cancelConn = null; + java.sql.Statement cancelStmt = null; + + try { + synchronized (cancelTimeoutMutex) { + cancelConn = connection.duplicate(); + cancelStmt = cancelConn.createStatement(); + cancelStmt.execute("KILL QUERY " + connectionId); + wasCancelled = true; + } + } catch (SQLException sqlEx) { + caughtWhileCancelling = sqlEx; + } catch (NullPointerException npe) { + // Case when connection closed while starting to cancel + // We can't easily synchronize this, because then one thread + // can't cancel() a running query + + // ignore, we shouldn't re-throw this, because the connection's + // already closed, so the statement has been timed out. + } finally { + if (cancelStmt != null) { + try { + cancelStmt.close(); + } catch (SQLException sqlEx) { + throw new RuntimeException(sqlEx.toString()); + } + } + + if (cancelConn != null) { + try { + cancelConn.close(); + } catch (SQLException sqlEx) { + throw new RuntimeException(sqlEx.toString()); + } + } + } + } + }; + + cancelThread.start(); + } + } + + /** Mutex to prevent race between returning query results and noticing + that we're timed-out or cancelled. */ + + protected Object cancelTimeoutMutex = new Object(); + + /** Used to generate IDs when profiling. */ + protected static int statementCounter = 1; + + public final static byte USES_VARIABLES_FALSE = 0; + + public final static byte USES_VARIABLES_TRUE = 1; + + public final static byte USES_VARIABLES_UNKNOWN = -1; + + protected boolean wasCancelled = false; + + /** Holds batched commands */ + protected List batchedArgs; + + /** The character converter to use (if available) */ + protected SingleByteCharsetConverter charConverter = null; + + /** The character encoding to use (if available) */ + protected String charEncoding = null; + + /** The connection that created us */ + protected Connection connection = null; + + protected long connectionId = 0; + + /** The catalog in use */ + protected String currentCatalog = null; + + /** Should we process escape codes? */ + protected boolean doEscapeProcessing = true; + + /** If we're profiling, where should events go to? */ + protected ProfileEventSink eventSink = null; + + /** The number of rows to fetch at a time (currently ignored) */ + private int fetchSize = 0; + + /** Has this statement been closed? */ + protected boolean isClosed = false; + + /** The auto_increment value for the last insert */ + protected long lastInsertId = -1; + + /** The max field size for this statement */ + protected int maxFieldSize = MysqlIO.getMaxBuf(); + + /** + * The maximum number of rows to return for this statement (-1 means _all_ + * rows) + */ + protected int maxRows = -1; + + /** Has someone changed this for this statement? */ + protected boolean maxRowsChanged = false; + + /** List of currently-open ResultSets */ + protected List openResults = new ArrayList(); + + /** Are we in pedantic mode? */ + protected boolean pedantic = false; + + /** + * Where this statement was created, only used if profileSql or + * useUsageAdvisor set to true. + */ + protected Throwable pointOfOrigin; + + /** Should we profile? */ + protected boolean profileSQL = false; + + /** The current results */ + protected ResultSet results = null; + + /** The concurrency for this result set (updatable or not) */ + protected int resultSetConcurrency = 0; + + /** The type of this result set (scroll sensitive or in-sensitive) */ + protected int resultSetType = 0; + + /** Used to identify this statement when profiling. */ + protected int statementId; + + /** The timeout for a query */ + protected int timeoutInMillis = 0; + + /** The update count for this statement */ + protected long updateCount = -1; + + /** Should we use the usage advisor? */ + protected boolean useUsageAdvisor = false; + + /** The warnings chain. */ + protected SQLWarning warningChain = null; + + /** + * Should this statement hold results open over .close() irregardless of + * connection's setting? + */ + protected boolean holdResultsOpenOverClose = false; + + protected ArrayList batchedGeneratedKeys = null; + + protected boolean retrieveGeneratedKeys = false; + + protected boolean continueBatchOnError = false; + + protected PingTarget pingTarget = null; + + + /** + * Constructor for a Statement. + * + * @param c + * the Connection instantation that creates us + * @param catalog + * the database name in use when we were created + * + * @throws SQLException + * if an error occurs. + */ + public Statement(Connection c, String catalog) throws SQLException { + if ((c == null) || c.isClosed()) { + throw SQLError.createSQLException( + Messages.getString("Statement.0"), //$NON-NLS-1$ + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); //$NON-NLS-1$ //$NON-NLS-2$ + } + + this.connection = c; + this.connectionId = this.connection.getId(); + + this.currentCatalog = catalog; + this.pedantic = this.connection.getPedantic(); + this.continueBatchOnError = this.connection.getContinueBatchOnError(); + + if (!this.connection.getDontTrackOpenResources()) { + this.connection.registerStatement(this); + } + + // + // Adjust, if we know it + // + + if (this.connection != null) { + this.maxFieldSize = this.connection.getMaxAllowedPacket(); + + int defaultFetchSize = this.connection.getDefaultFetchSize(); + + if (defaultFetchSize != 0) { + setFetchSize(defaultFetchSize); + } + } + + if (this.connection.getUseUnicode()) { + this.charEncoding = this.connection.getEncoding(); + + this.charConverter = this.connection + .getCharsetConverter(this.charEncoding); + } + + boolean profiling = this.connection.getProfileSql() + || this.connection.getUseUsageAdvisor(); + + if (this.connection.getAutoGenerateTestcaseScript() || profiling) { + this.statementId = statementCounter++; + } + + if (profiling) { + this.pointOfOrigin = new Throwable(); + this.profileSQL = this.connection.getProfileSql(); + this.useUsageAdvisor = this.connection.getUseUsageAdvisor(); + this.eventSink = ProfileEventSink.getInstance(this.connection); + } + + int maxRowsConn = this.connection.getMaxRows(); + + if (maxRowsConn != -1) { + setMaxRows(maxRowsConn); + } + } + + /** + * DOCUMENT ME! + * + * @param sql + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public synchronized void addBatch(String sql) throws SQLException { + if (this.batchedArgs == null) { + this.batchedArgs = new ArrayList(); + } + + if (sql != null) { + this.batchedArgs.add(sql); + } + } + + /** + * Cancels this Statement object if both the DBMS and driver support + * aborting an SQL statement. This method can be used by one thread to + * cancel a statement that is being executed by another thread. + */ + public void cancel() throws SQLException { + if (!this.isClosed && + this.connection != null && + this.connection.versionMeetsMinimum(5, 0, 0)) { + Connection cancelConn = null; + java.sql.Statement cancelStmt = null; + + try { + synchronized (this.cancelTimeoutMutex) { + cancelConn = this.connection.duplicate(); + cancelStmt = cancelConn.createStatement(); + cancelStmt.execute("KILL QUERY " + + this.connection.getIO().getThreadId()); + this.wasCancelled = true; + } + } catch (NullPointerException npe) { + // Case when connection closed while starting to cancel + // We can't easily synchronize this, because then one thread + // can't cancel() a running query + + throw SQLError.createSQLException(Messages + .getString("Statement.49"), //$NON-NLS-1$ + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); //$NON-NLS-1$ + } finally { + if (cancelStmt != null) { + cancelStmt.close(); + } + + if (cancelConn != null) { + cancelConn.close(); + } + } + + } + } + + // --------------------------JDBC 2.0----------------------------- + + /** + * Checks if closed() has been called, and throws an exception if so + * + * @throws SQLException + * if this statement has been closed + */ + protected void checkClosed() throws SQLException { + if (this.isClosed) { + throw SQLError.createSQLException(Messages + .getString("Statement.49"), //$NON-NLS-1$ + SQLError.SQL_STATE_CONNECTION_NOT_OPEN); //$NON-NLS-1$ + } + } + + /** + * Checks if the given SQL query with the given first non-ws char is a DML + * statement. Throws an exception if it is. + * + * @param sql + * the SQL to check + * @param firstStatementChar + * the UC first non-ws char of the statement + * + * @throws SQLException + * if the statement contains DML + */ + protected void checkForDml(String sql, char firstStatementChar) + throws SQLException { + if ((firstStatementChar == 'I') || (firstStatementChar == 'U') + || (firstStatementChar == 'D') || (firstStatementChar == 'A') + || (firstStatementChar == 'C')) { + String noCommentSql = StringUtils.stripComments(sql, + "'\"", "'\"", true, false, true, true); + + if (StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "INSERT") //$NON-NLS-1$ + || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "UPDATE") //$NON-NLS-1$ + || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DELETE") //$NON-NLS-1$ + || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DROP") //$NON-NLS-1$ + || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "CREATE") //$NON-NLS-1$ + || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "ALTER")) { //$NON-NLS-1$ + throw SQLError.createSQLException(Messages + .getString("Statement.57"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + } + + /** + * Method checkNullOrEmptyQuery. + * + * @param sql + * the SQL to check + * + * @throws SQLException + * if query is null or empty. + */ + protected void checkNullOrEmptyQuery(String sql) throws SQLException { + if (sql == null) { + throw SQLError.createSQLException(Messages + .getString("Statement.59"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (sql.length() == 0) { + throw SQLError.createSQLException(Messages + .getString("Statement.61"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * JDBC 2.0 Make the set of commands in the current batch empty. This method + * is optional. + * + * @exception SQLException + * if a database-access error occurs, or the driver does not + * support batch statements + */ + public synchronized void clearBatch() throws SQLException { + if (this.batchedArgs != null) { + this.batchedArgs.clear(); + } + } + + /** + * After this call, getWarnings returns null until a new warning is reported + * for this Statement. + * + * @exception SQLException + * if a database access error occurs (why?) + */ + public void clearWarnings() throws SQLException { + this.warningChain = null; + } + + /** + * In many cases, it is desirable to immediately release a Statement's + * database and JDBC resources instead of waiting for this to happen when it + * is automatically closed. The close method provides this immediate + * release. + * + *

+ * Note: A Statement is automatically closed when it is garbage + * collected. When a Statement is closed, its current ResultSet, if one + * exists, is also closed. + *

+ * + * @exception SQLException + * if a database access error occurs + */ + public void close() throws SQLException { + realClose(true, true); + } + + /** + * Close any open result sets that have been 'held open' + */ + protected void closeAllOpenResults() { + if (this.openResults != null) { + for (Iterator iter = this.openResults.iterator(); iter.hasNext();) { + ResultSet element = (ResultSet) iter.next(); + + try { + element.realClose(false); + } catch (SQLException sqlEx) { + AssertionFailedException.shouldNotHappen(sqlEx); + } + } + + this.openResults.clear(); + } + } + + /** + * @param sql + * @return + */ + private ResultSet createResultSetUsingServerFetch(String sql) + throws SQLException { + java.sql.PreparedStatement pStmt = this.connection.prepareStatement( + sql, this.resultSetType, this.resultSetConcurrency); + + pStmt.setFetchSize(this.fetchSize); + + if (this.maxRows > -1) { + pStmt.setMaxRows(this.maxRows); + } + + pStmt.execute(); + + // + // Need to be able to get resultset irrespective if we issued DML or + // not to make this work. + // + ResultSet rs = ((com.mysql.jdbc.Statement) pStmt) + .getResultSetInternal(); + + rs + .setStatementUsedForFetchingRows((com.mysql.jdbc.PreparedStatement) pStmt); + + this.results = rs; + + return rs; + } + + /** + * We only stream result sets when they are forward-only, read-only, and the + * fetch size has been set to Integer.MIN_VALUE + * + * @return true if this result set should be streamed row at-a-time, rather + * than read all at once. + */ + protected boolean createStreamingResultSet() { + return ((this.resultSetType == java.sql.ResultSet.TYPE_FORWARD_ONLY) + && (this.resultSetConcurrency == java.sql.ResultSet.CONCUR_READ_ONLY) && (this.fetchSize == Integer.MIN_VALUE)); + } + + /** + * Workaround for containers that 'check' for sane values of + * Statement.setFetchSize(). + * + * @throws SQLException + */ + public void enableStreamingResults() throws SQLException { + setFetchSize(Integer.MIN_VALUE); + setResultSetType(ResultSet.TYPE_FORWARD_ONLY); + } + + /** + * Execute a SQL statement that may return multiple results. We don't have + * to worry about this since we do not support multiple ResultSets. You can + * use getResultSet or getUpdateCount to retrieve the result. + * + * @param sql + * any SQL statement + * + * @return true if the next result is a ResulSet, false if it is an update + * count or there are no more results + * + * @exception SQLException + * if a database access error occurs + */ + public boolean execute(String sql) throws SQLException { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + synchronized (this.cancelTimeoutMutex) { + this.wasCancelled = false; + } + + checkNullOrEmptyQuery(sql); + + checkClosed(); + + char firstNonWsChar = StringUtils.firstNonWsCharUc(sql); + + boolean isSelect = true; + + if (firstNonWsChar != 'S') { + isSelect = false; + + if (locallyScopedConn.isReadOnly()) { + throw SQLError.createSQLException(Messages + .getString("Statement.27") //$NON-NLS-1$ + + Messages.getString("Statement.28"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + if (this.doEscapeProcessing) { + Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, + locallyScopedConn.serverSupportsConvertFn(), locallyScopedConn); + + if (escapedSqlResult instanceof String) { + sql = (String) escapedSqlResult; + } else { + sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql; + } + } + + if (this.results != null) { + if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) { + this.results.realClose(false); + } + } + + if (firstNonWsChar == '/') { + if (sql.startsWith(PING_MARKER)) { + doPingInstead(); + + return true; + } + } + + CachedResultSetMetaData cachedMetaData = null; + + ResultSet rs = null; + + // If there isn't a limit clause in the SQL + // then limit the number of rows to return in + // an efficient manner. Only do this if + // setMaxRows() hasn't been used on any Statements + // generated from the current Connection (saves + // a query, and network traffic). + + this.batchedGeneratedKeys = null; + + if (useServerFetch()) { + rs = createResultSetUsingServerFetch(sql); + } else { + CancelTask timeoutTask = null; + + String oldCatalog = null; + + try { + if (locallyScopedConn.getEnableQueryTimeouts() && + this.timeoutInMillis != 0 + && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) { + timeoutTask = new CancelTask(); + Connection.getCancelTimer().schedule(timeoutTask, + this.timeoutInMillis); + } + + + + if (!locallyScopedConn.getCatalog().equals( + this.currentCatalog)) { + oldCatalog = locallyScopedConn.getCatalog(); + locallyScopedConn.setCatalog(this.currentCatalog); + } + + // + // Check if we have cached metadata for this query... + // + if (locallyScopedConn.getCacheResultSetMetadata()) { + cachedMetaData = locallyScopedConn.getCachedMetaData(sql); + } + + // + // Only apply max_rows to selects + // + if (locallyScopedConn.useMaxRows()) { + int rowLimit = -1; + + if (isSelect) { + if (StringUtils.indexOfIgnoreCase(sql, "LIMIT") != -1) { //$NON-NLS-1$ + rowLimit = this.maxRows; + } else { + if (this.maxRows <= 0) { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, //$NON-NLS-1$ + null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, + this.currentCatalog, true); //$NON-NLS-1$ + } else { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=" + this.maxRows, //$NON-NLS-1$ + -1, + null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, + this.currentCatalog, true); //$NON-NLS-1$ + } + } + } else { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, null, //$NON-NLS-1$ + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.currentCatalog, + true); //$NON-NLS-1$ + } + + // Finally, execute the query + rs = locallyScopedConn.execSQL(this, sql, rowLimit, null, + this.resultSetType, this.resultSetConcurrency, + createStreamingResultSet(), + this.currentCatalog, (cachedMetaData == null)); + } else { + rs = locallyScopedConn.execSQL(this, sql, -1, null, + this.resultSetType, this.resultSetConcurrency, + createStreamingResultSet(), + this.currentCatalog, (cachedMetaData == null)); + } + + if (timeoutTask != null) { + if (timeoutTask.caughtWhileCancelling != null) { + throw timeoutTask.caughtWhileCancelling; + } + + timeoutTask.cancel(); + timeoutTask = null; + } + + synchronized (this.cancelTimeoutMutex) { + if (this.wasCancelled) { + this.wasCancelled = false; + throw new MySQLTimeoutException(); + } + } + } finally { + if (timeoutTask != null) { + timeoutTask.cancel(); + } + + if (oldCatalog != null) { + locallyScopedConn.setCatalog(oldCatalog); + } + } + } + + this.lastInsertId = rs.getUpdateID(); + + if (rs != null) { + this.results = rs; + + rs.setFirstCharOfQuery(firstNonWsChar); + + if (rs.reallyResult()) { + if (cachedMetaData != null) { + locallyScopedConn.initializeResultsMetadataFromCache(sql, cachedMetaData, + this.results); + } else { + if (this.connection.getCacheResultSetMetadata()) { + locallyScopedConn.initializeResultsMetadataFromCache(sql, + null /* will be created */, this.results); + } + } + } + } + + return ((rs != null) && rs.reallyResult()); + } + } + + /** + * @see Statement#execute(String, int) + */ + public boolean execute(String sql, int returnGeneratedKeys) + throws SQLException { + + + if (returnGeneratedKeys == java.sql.Statement.RETURN_GENERATED_KEYS) { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + // If this is a 'REPLACE' query, we need to be able to parse + // the 'info' message returned from the server to determine + // the actual number of keys generated. + boolean readInfoMsgState = this.connection + .isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + + try { + return execute(sql); + } finally { + locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState); + } + } + } + + return execute(sql); + } + + /** + * @see Statement#execute(String, int[]) + */ + public boolean execute(String sql, int[] generatedKeyIndices) + throws SQLException { + if ((generatedKeyIndices != null) && (generatedKeyIndices.length > 0)) { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + // If this is a 'REPLACE' query, we need to be able to parse + // the 'info' message returned from the server to determine + // the actual number of keys generated. + boolean readInfoMsgState = locallyScopedConn + .isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + + try { + return execute(sql); + } finally { + locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState); + } + } + } + + return execute(sql); + } + + /** + * @see Statement#execute(String, String[]) + */ + public boolean execute(String sql, String[] generatedKeyNames) + throws SQLException { + if ((generatedKeyNames != null) && (generatedKeyNames.length > 0)) { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + // If this is a 'REPLACE' query, we need to be able to parse + // the 'info' message returned from the server to determine + // the actual number of keys generated. + boolean readInfoMsgState = this.connection + .isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + + try { + return execute(sql); + } finally { + locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState); + } + } + } + + return execute(sql); + } + + /** + * JDBC 2.0 Submit a batch of commands to the database for execution. This + * method is optional. + * + * @return an array of update counts containing one element for each command + * in the batch. The array is ordered according to the order in + * which commands were inserted into the batch + * + * @exception SQLException + * if a database-access error occurs, or the driver does not + * support batch statements + * @throws java.sql.BatchUpdateException + * DOCUMENT ME! + */ + public synchronized int[] executeBatch() throws SQLException { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + if (locallyScopedConn.isReadOnly()) { + throw SQLError.createSQLException(Messages + .getString("Statement.34") //$NON-NLS-1$ + + Messages.getString("Statement.35"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + if (this.results != null) { + if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) { + this.results.realClose(false); + } + } + + synchronized (locallyScopedConn.getMutex()) { + if (this.batchedArgs == null || this.batchedArgs.size() == 0) { + return new int[0]; + } + + try { + this.retrieveGeneratedKeys = true; + + int[] updateCounts = null; + + if (this.batchedArgs != null) { + int nbrCommands = this.batchedArgs.size(); + + this.batchedGeneratedKeys = new ArrayList(this.batchedArgs.size()); + + boolean multiQueriesEnabled = locallyScopedConn.getAllowMultiQueries(); + + if (locallyScopedConn.versionMeetsMinimum(4, 1, 1) && + (multiQueriesEnabled || + (locallyScopedConn.getRewriteBatchedStatements() && + nbrCommands > 4))) { + return executeBatchUsingMultiQueries(multiQueriesEnabled, nbrCommands); + } + + updateCounts = new int[nbrCommands]; + + for (int i = 0; i < nbrCommands; i++) { + updateCounts[i] = -3; + } + + SQLException sqlEx = null; + + int commandIndex = 0; + + for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) { + try { + updateCounts[commandIndex] = executeUpdate((String) this.batchedArgs + .get(commandIndex), true); + getBatchedGeneratedKeys(); + } catch (SQLException ex) { + updateCounts[commandIndex] = EXECUTE_FAILED; + + if (this.continueBatchOnError) { + sqlEx = ex; + } else { + int[] newUpdateCounts = new int[commandIndex]; + System.arraycopy(updateCounts, 0, + newUpdateCounts, 0, commandIndex); + + throw new java.sql.BatchUpdateException(ex + .getMessage(), ex.getSQLState(), ex + .getErrorCode(), newUpdateCounts); + } + } + } + + if (sqlEx != null) { + throw new java.sql.BatchUpdateException(sqlEx + .getMessage(), sqlEx.getSQLState(), sqlEx + .getErrorCode(), updateCounts); + } + } + + return (updateCounts != null) ? updateCounts : new int[0]; + } finally { + this.retrieveGeneratedKeys = false; + + clearBatch(); + } + } + } + + /** + * Rewrites batch into a single query to send to the server. This method + * will constrain each batch to be shorter than max_allowed_packet on the + * server. + * + * @return update counts in the same manner as executeBatch() + * @throws SQLException + */ + private int[] executeBatchUsingMultiQueries(boolean multiQueriesEnabled, + int nbrCommands) throws SQLException { + + Connection locallyScopedConn = this.connection; + + if (!multiQueriesEnabled) { + locallyScopedConn.getIO().enableMultiQueries(); + } + + java.sql.Statement batchStmt = null; + + try { + int[] updateCounts = new int[nbrCommands]; + + for (int i = 0; i < nbrCommands; i++) { + updateCounts[i] = -3; + } + + int commandIndex = 0; + + StringBuffer queryBuf = new StringBuffer(); + + + + batchStmt = locallyScopedConn.createStatement(); + + + int counter = 0; + + int numberOfBytesPerChar = 1; + + String connectionEncoding = locallyScopedConn.getEncoding(); + + if (StringUtils.startsWithIgnoreCase(connectionEncoding, "utf")) { + numberOfBytesPerChar = 3; + } else if (CharsetMapping.isMultibyteCharset(connectionEncoding)) { + numberOfBytesPerChar = 2; + } + + int escapeAdjust = 1; + + if (this.doEscapeProcessing) { + escapeAdjust = 2; /* We assume packet _could_ grow by this amount, as we're not + sure how big statement will end up after + escape processing */ + } + + for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) { + String nextQuery = (String) this.batchedArgs.get(commandIndex); + + if (((((queryBuf.length() + nextQuery.length()) + * numberOfBytesPerChar) + 1 /* for semicolon */ + + MysqlIO.HEADER_LENGTH) * escapeAdjust) + 32 > this.connection + .getMaxAllowedPacket()) { + batchStmt.execute(queryBuf.toString()); + + updateCounts[counter++] = batchStmt.getUpdateCount(); + long generatedKeyStart = ((com.mysql.jdbc.Statement)batchStmt).getLastInsertID(); + byte[][] row = new byte[1][]; + row[0] = Long.toString(generatedKeyStart++).getBytes(); + this.batchedGeneratedKeys.add(row); + + while (batchStmt.getMoreResults() + || batchStmt.getUpdateCount() != -1) { + updateCounts[counter++] = batchStmt.getUpdateCount(); + row = new byte[1][]; + row[0] = Long.toString(generatedKeyStart++).getBytes(); + this.batchedGeneratedKeys.add(row); + } + + queryBuf = new StringBuffer(); + } + + queryBuf.append(nextQuery); + queryBuf.append(";"); + } + + if (queryBuf.length() > 0) { + batchStmt.execute(queryBuf.toString()); + + long generatedKeyStart = ((com.mysql.jdbc.Statement)batchStmt).getLastInsertID(); + byte[][] row = new byte[1][]; + row[0] = Long.toString(generatedKeyStart++).getBytes(); + this.batchedGeneratedKeys.add(row); + + updateCounts[counter++] = batchStmt.getUpdateCount(); + + while (batchStmt.getMoreResults() + || batchStmt.getUpdateCount() != -1) { + updateCounts[counter++] = batchStmt.getUpdateCount(); + row = new byte[1][]; + row[0] = Long.toString(generatedKeyStart++).getBytes(); + this.batchedGeneratedKeys.add(row); + } + } + + return (updateCounts != null) ? updateCounts : new int[0]; + } finally { + try { + if (batchStmt != null) { + batchStmt.close(); + } + } finally { + if (!multiQueriesEnabled) { + locallyScopedConn.getIO().disableMultiQueries(); + } + } + } + } + + /** + * Execute a SQL statement that retruns a single ResultSet + * + * @param sql + * typically a static SQL SELECT statement + * + * @return a ResulSet that contains the data produced by the query + * + * @exception SQLException + * if a database access error occurs + */ + public java.sql.ResultSet executeQuery(String sql) + throws SQLException { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + synchronized (this.cancelTimeoutMutex) { + this.wasCancelled = false; + } + + checkNullOrEmptyQuery(sql); + + if (this.doEscapeProcessing) { + Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, + locallyScopedConn.serverSupportsConvertFn(), this.connection); + + if (escapedSqlResult instanceof String) { + sql = (String) escapedSqlResult; + } else { + sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql; + } + } + + char firstStatementChar = StringUtils.firstNonWsCharUc(sql, + findStartOfStatement(sql)); + + if (sql.charAt(0) == '/') { + if (sql.startsWith(PING_MARKER)) { + doPingInstead(); + + return this.results; + } + } + + checkForDml(sql, firstStatementChar); + + if (this.results != null) { + if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) { + this.results.realClose(false); + } + } + + CachedResultSetMetaData cachedMetaData = null; + + // If there isn't a limit clause in the SQL + // then limit the number of rows to return in + // an efficient manner. Only do this if + // setMaxRows() hasn't been used on any Statements + // generated from the current Connection (saves + // a query, and network traffic). + + if (useServerFetch()) { + this.results = createResultSetUsingServerFetch(sql); + + return this.results; + } + + CancelTask timeoutTask = null; + + String oldCatalog = null; + + try { + if (locallyScopedConn.getEnableQueryTimeouts() && + this.timeoutInMillis != 0 + && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) { + timeoutTask = new CancelTask(); + Connection.getCancelTimer().schedule(timeoutTask, + this.timeoutInMillis); + } + + if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) { + oldCatalog = locallyScopedConn.getCatalog(); + locallyScopedConn.setCatalog(this.currentCatalog); + } + + // + // Check if we have cached metadata for this query... + // + if (locallyScopedConn.getCacheResultSetMetadata()) { + cachedMetaData = locallyScopedConn.getCachedMetaData(sql); + } + + if (locallyScopedConn.useMaxRows()) { + // We need to execute this all together + // So synchronize on the Connection's mutex (because + // even queries going through there synchronize + // on the connection + if (StringUtils.indexOfIgnoreCase(sql, "LIMIT") != -1) { //$NON-NLS-1$ + this.results = locallyScopedConn.execSQL(this, sql, + this.maxRows, null, this.resultSetType, + this.resultSetConcurrency, + createStreamingResultSet(), + this.currentCatalog, (cachedMetaData == null)); + } else { + if (this.maxRows <= 0) { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", -1, null, //$NON-NLS-1$ + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.currentCatalog, + true); //$NON-NLS-1$ + } else { + locallyScopedConn + .execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=" + this.maxRows, -1, //$NON-NLS-1$ + null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, + false, this.currentCatalog, + true); //$NON-NLS-1$ + } + + this.results = locallyScopedConn.execSQL(this, sql, -1, + null, this.resultSetType, + this.resultSetConcurrency, + createStreamingResultSet(), + this.currentCatalog, (cachedMetaData == null)); + + if (oldCatalog != null) { + locallyScopedConn.setCatalog(oldCatalog); + } + } + } else { + this.results = locallyScopedConn.execSQL(this, sql, -1, null, + this.resultSetType, this.resultSetConcurrency, + createStreamingResultSet(), + this.currentCatalog, (cachedMetaData == null)); + } + + if (timeoutTask != null) { + if (timeoutTask.caughtWhileCancelling != null) { + throw timeoutTask.caughtWhileCancelling; + } + + timeoutTask.cancel(); + timeoutTask = null; + } + + synchronized (this.cancelTimeoutMutex) { + if (this.wasCancelled) { + this.wasCancelled = false; + throw new MySQLTimeoutException(); + } + } + } finally { + if (timeoutTask != null) { + timeoutTask.cancel(); + } + + if (oldCatalog != null) { + locallyScopedConn.setCatalog(oldCatalog); + } + } + + this.lastInsertId = this.results.getUpdateID(); + + if (cachedMetaData != null) { + locallyScopedConn.initializeResultsMetadataFromCache(sql, cachedMetaData, + this.results); + } else { + if (this.connection.getCacheResultSetMetadata()) { + locallyScopedConn.initializeResultsMetadataFromCache(sql, + null /* will be created */, this.results); + } + } + + return this.results; + } + } + + protected void doPingInstead() throws SQLException { + if (this.pingTarget != null) { + this.pingTarget.doPing(); + } else { + this.connection.ping(); + } + + ResultSet fakeSelectOneResultSet = generatePingResultSet(); + this.results = fakeSelectOneResultSet; + } + + protected ResultSet generatePingResultSet() throws SQLException { + Field[] fields = { new Field(null, "1", Types.BIGINT, 1) }; + ArrayList rows = new ArrayList(); + byte[] colVal = new byte[] { (byte) '1' }; + + rows.add(new byte[][] { colVal }); + + return (ResultSet) DatabaseMetaData.buildResultSet(fields, rows, + this.connection); + } + + /** + * Execute a SQL INSERT, UPDATE or DELETE statement. In addition SQL + * statements that return nothing such as SQL DDL statements can be executed + * Any IDs generated for AUTO_INCREMENT fields can be retrieved by casting + * this Statement to org.gjt.mm.mysql.Statement and calling the + * getLastInsertID() method. + * + * @param sql + * a SQL statement + * + * @return either a row count, or 0 for SQL commands + * + * @exception SQLException + * if a database access error occurs + */ + public int executeUpdate(String sql) throws SQLException { + return executeUpdate(sql, false); + } + + protected int executeUpdate(String sql, boolean isBatch) + throws SQLException { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + char firstStatementChar = StringUtils.firstNonWsCharUc(sql, + findStartOfStatement(sql)); + + ResultSet rs = null; + + synchronized (locallyScopedConn.getMutex()) { + synchronized (this.cancelTimeoutMutex) { + this.wasCancelled = false; + } + + checkNullOrEmptyQuery(sql); + + if (this.doEscapeProcessing) { + Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, + this.connection.serverSupportsConvertFn(), this.connection); + + if (escapedSqlResult instanceof String) { + sql = (String) escapedSqlResult; + } else { + sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql; + } + } + + if (locallyScopedConn.isReadOnly()) { + throw SQLError.createSQLException(Messages + .getString("Statement.42") //$NON-NLS-1$ + + Messages.getString("Statement.43"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + if (StringUtils.startsWithIgnoreCaseAndWs(sql, "select")) { //$NON-NLS-1$ + throw SQLError.createSQLException(Messages + .getString("Statement.46"), //$NON-NLS-1$ + "01S03"); //$NON-NLS-1$ + } + + if (this.results != null) { + if (!locallyScopedConn.getHoldResultsOpenOverStatementClose()) { + this.results.realClose(false); + } + } + + // The checking and changing of catalogs + // must happen in sequence, so synchronize + // on the same mutex that _conn is using + + CancelTask timeoutTask = null; + + String oldCatalog = null; + + try { + if (locallyScopedConn.getEnableQueryTimeouts() && + this.timeoutInMillis != 0 + && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) { + timeoutTask = new CancelTask(); + Connection.getCancelTimer().schedule(timeoutTask, + this.timeoutInMillis); + } + + if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) { + oldCatalog = locallyScopedConn.getCatalog(); + locallyScopedConn.setCatalog(this.currentCatalog); + } + + // + // Only apply max_rows to selects + // + if (locallyScopedConn.useMaxRows()) { + locallyScopedConn.execSQL( + this, + "SET OPTION SQL_SELECT_LIMIT=DEFAULT", //$NON-NLS-1$ + -1, null, java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.currentCatalog, true); + } + + rs = locallyScopedConn.execSQL(this, sql, -1, null, + java.sql.ResultSet.TYPE_FORWARD_ONLY, + java.sql.ResultSet.CONCUR_READ_ONLY, false, + this.currentCatalog, + true /* force read of field info on DML */, + isBatch); + + if (timeoutTask != null) { + if (timeoutTask.caughtWhileCancelling != null) { + throw timeoutTask.caughtWhileCancelling; + } + + timeoutTask.cancel(); + timeoutTask = null; + } + + synchronized (this.cancelTimeoutMutex) { + if (this.wasCancelled) { + this.wasCancelled = false; + throw new MySQLTimeoutException(); + } + } + } finally { + if (timeoutTask != null) { + timeoutTask.cancel(); + } + + if (oldCatalog != null) { + locallyScopedConn.setCatalog(oldCatalog); + } + } + } + + this.results = rs; + + rs.setFirstCharOfQuery(firstStatementChar); + + this.updateCount = rs.getUpdateCount(); + + int truncatedUpdateCount = 0; + + if (this.updateCount > Integer.MAX_VALUE) { + truncatedUpdateCount = Integer.MAX_VALUE; + } else { + truncatedUpdateCount = (int) this.updateCount; + } + + this.lastInsertId = rs.getUpdateID(); + + return truncatedUpdateCount; + } + + /** + * @see Statement#executeUpdate(String, int) + */ + public int executeUpdate(String sql, int returnGeneratedKeys) + throws SQLException { + if (returnGeneratedKeys == java.sql.Statement.RETURN_GENERATED_KEYS) { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + // If this is a 'REPLACE' query, we need to be able to parse + // the 'info' message returned from the server to determine + // the actual number of keys generated. + boolean readInfoMsgState = locallyScopedConn + .isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + + try { + return executeUpdate(sql); + } finally { + locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState); + } + } + } + + return executeUpdate(sql); + } + + /** + * @see Statement#executeUpdate(String, int[]) + */ + public int executeUpdate(String sql, int[] generatedKeyIndices) + throws SQLException { + if ((generatedKeyIndices != null) && (generatedKeyIndices.length > 0)) { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + // If this is a 'REPLACE' query, we need to be able to parse + // the 'info' message returned from the server to determine + // the actual number of keys generated. + boolean readInfoMsgState = locallyScopedConn + .isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + + try { + return executeUpdate(sql); + } finally { + locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState); + } + } + } + + return executeUpdate(sql); + } + + /** + * @see Statement#executeUpdate(String, String[]) + */ + public int executeUpdate(String sql, String[] generatedKeyNames) + throws SQLException { + if ((generatedKeyNames != null) && (generatedKeyNames.length > 0)) { + checkClosed(); + + Connection locallyScopedConn = this.connection; + + synchronized (locallyScopedConn.getMutex()) { + // If this is a 'REPLACE' query, we need to be able to parse + // the 'info' message returned from the server to determine + // the actual number of keys generated. + boolean readInfoMsgState = this.connection + .isReadInfoMsgEnabled(); + locallyScopedConn.setReadInfoMsgEnabled(true); + + try { + return executeUpdate(sql); + } finally { + locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState); + } + } + } + + return executeUpdate(sql); + } + + + + /** + * Optimization to only use one calendar per-session, or calculate it for + * each call, depending on user configuration + */ + protected Calendar getCalendarInstanceForSessionOrNew() { + if (this.connection != null) { + return this.connection.getCalendarInstanceForSessionOrNew(); + } else { + // punt, no connection around + return new GregorianCalendar(); + } + } + + /** + * JDBC 2.0 Return the Connection that produced the Statement. + * + * @return the Connection that produced the Statement + * + * @throws SQLException + * if an error occurs + */ + public java.sql.Connection getConnection() throws SQLException { + return this.connection; + } + + /** + * JDBC 2.0 Determine the fetch direction. + * + * @return the default fetch direction + * + * @exception SQLException + * if a database-access error occurs + */ + public int getFetchDirection() throws SQLException { + return java.sql.ResultSet.FETCH_FORWARD; + } + + /** + * JDBC 2.0 Determine the default fetch size. + * + * @return the number of rows to fetch at a time + * + * @throws SQLException + * if an error occurs + */ + public int getFetchSize() throws SQLException { + return this.fetchSize; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public java.sql.ResultSet getGeneratedKeys() + throws SQLException { + if (this.batchedGeneratedKeys == null) { + return getGeneratedKeysInternal(); + } + + Field[] fields = new Field[1]; + fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 17); //$NON-NLS-1$ //$NON-NLS-2$ + fields[0].setConnection(this.connection); + + return new com.mysql.jdbc.ResultSet(this.currentCatalog, fields, + new RowDataStatic(this.batchedGeneratedKeys), this.connection, + this); + } + + /* + * Needed because there's no concept of super.super to get to this + * implementation from ServerPreparedStatement when dealing with batched + * updates. + */ + protected java.sql.ResultSet getGeneratedKeysInternal() + throws SQLException { + Field[] fields = new Field[1]; + fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 17); //$NON-NLS-1$ //$NON-NLS-2$ + fields[0].setConnection(this.connection); + + ArrayList rowSet = new ArrayList(); + + long beginAt = getLastInsertID(); + int numKeys = getUpdateCount(); + + if (this.results != null) { + String serverInfo = this.results.getServerInfo(); + + // + // Only parse server info messages for 'REPLACE' + // queries + // + if ((numKeys > 0) && (this.results.getFirstCharOfQuery() == 'R') + && (serverInfo != null) && (serverInfo.length() > 0)) { + numKeys = getRecordCountFromInfo(serverInfo); + } + + if ((beginAt > 0) && (numKeys > 0)) { + for (int i = 0; i < numKeys; i++) { + byte[][] row = new byte[1][]; + row[0] = Long.toString(beginAt++).getBytes(); + rowSet.add(row); + } + } + } + + return new com.mysql.jdbc.ResultSet(this.currentCatalog, fields, + new RowDataStatic(rowSet), this.connection, this); + } + + /** + * Returns the id used when profiling + * + * @return the id used when profiling. + */ + protected int getId() { + return this.statementId; + } + + /** + * getLastInsertID returns the value of the auto_incremented key after an + * executeQuery() or excute() call. + * + *

+ * This gets around the un-threadsafe behavior of "select LAST_INSERT_ID()" + * which is tied to the Connection that created this Statement, and + * therefore could have had many INSERTS performed before one gets a chance + * to call "select LAST_INSERT_ID()". + *

+ * + * @return the last update ID. + */ + public long getLastInsertID() { + return this.lastInsertId; + } + + /** + * getLongUpdateCount returns the current result as an update count, if the + * result is a ResultSet or there are no more results, -1 is returned. It + * should only be called once per result. + * + *

+ * This method returns longs as MySQL server versions newer than 3.22.4 + * return 64-bit values for update counts + *

+ * + * @return the current update count. + */ + public long getLongUpdateCount() { + if (this.results == null) { + return -1; + } + + if (this.results.reallyResult()) { + return -1; + } + + return this.updateCount; + } + + /** + * The maxFieldSize limit (in bytes) is the maximum amount of data returned + * for any column value; it only applies to BINARY, VARBINARY, + * LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR columns. If the limit is + * exceeded, the excess data is silently discarded. + * + * @return the current max column size limit; zero means unlimited + * + * @exception SQLException + * if a database access error occurs + */ + public int getMaxFieldSize() throws SQLException { + return this.maxFieldSize; + } + + /** + * The maxRows limit is set to limit the number of rows that any ResultSet + * can contain. If the limit is exceeded, the excess rows are silently + * dropped. + * + * @return the current maximum row limit; zero means unlimited + * + * @exception SQLException + * if a database access error occurs + */ + public int getMaxRows() throws SQLException { + if (this.maxRows <= 0) { + return 0; + } + + return this.maxRows; + } + + /** + * getMoreResults moves to a Statement's next result. If it returns true, + * this result is a ResulSet. + * + * @return true if the next ResultSet is valid + * + * @exception SQLException + * if a database access error occurs + */ + public boolean getMoreResults() throws SQLException { + return getMoreResults(CLOSE_CURRENT_RESULT); + } + + /** + * @see Statement#getMoreResults(int) + */ + public boolean getMoreResults(int current) throws SQLException { + + if (this.results == null) { + return false; + } + + ResultSet nextResultSet = this.results.getNextResultSet(); + + switch (current) { + case java.sql.Statement.CLOSE_CURRENT_RESULT: + + if (this.results != null) { + this.results.close(); + this.results.clearNextResult(); + } + + break; + + case java.sql.Statement.CLOSE_ALL_RESULTS: + + if (this.results != null) { + this.results.close(); + this.results.clearNextResult(); + } + + closeAllOpenResults(); + + break; + + case java.sql.Statement.KEEP_CURRENT_RESULT: + if (!this.connection.getDontTrackOpenResources()) { + this.openResults.add(this.results); + } + + this.results.clearNextResult(); // nobody besides us should + // ever need this value... + break; + + default: + throw SQLError.createSQLException(Messages + .getString("Statement.19"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + this.results = nextResultSet; + + if (this.results == null) { + this.updateCount = -1; + this.lastInsertId = -1; + } else if (this.results.reallyResult()) { + this.updateCount = -1; + this.lastInsertId = -1; + } else { + this.updateCount = this.results.getUpdateCount(); + this.lastInsertId = this.results.getUpdateID(); + } + + return ((this.results != null) && this.results.reallyResult()) ? true + : false; + } + + /** + * The queryTimeout limit is the number of seconds the driver will wait for + * a Statement to execute. If the limit is exceeded, a SQLException is + * thrown. + * + * @return the current query timeout limit in seconds; 0 = unlimited + * + * @exception SQLException + * if a database access error occurs + */ + public int getQueryTimeout() throws SQLException { + return this.timeoutInMillis / 1000; + } + + /** + * Parses actual record count from 'info' message + * + * @param serverInfo + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private int getRecordCountFromInfo(String serverInfo) { + StringBuffer recordsBuf = new StringBuffer(); + int recordsCount = 0; + int duplicatesCount = 0; + + char c = (char) 0; + + int length = serverInfo.length(); + int i = 0; + + for (; i < length; i++) { + c = serverInfo.charAt(i); + + if (Character.isDigit(c)) { + break; + } + } + + recordsBuf.append(c); + i++; + + for (; i < length; i++) { + c = serverInfo.charAt(i); + + if (!Character.isDigit(c)) { + break; + } + + recordsBuf.append(c); + } + + recordsCount = Integer.parseInt(recordsBuf.toString()); + + StringBuffer duplicatesBuf = new StringBuffer(); + + for (; i < length; i++) { + c = serverInfo.charAt(i); + + if (Character.isDigit(c)) { + break; + } + } + + duplicatesBuf.append(c); + i++; + + for (; i < length; i++) { + c = serverInfo.charAt(i); + + if (!Character.isDigit(c)) { + break; + } + + duplicatesBuf.append(c); + } + + duplicatesCount = Integer.parseInt(duplicatesBuf.toString()); + + return recordsCount - duplicatesCount; + } + + /** + * getResultSet returns the current result as a ResultSet. It should only be + * called once per result. + * + * @return the current result set; null if there are no more + * + * @exception SQLException + * if a database access error occurs (why?) + */ + public java.sql.ResultSet getResultSet() throws SQLException { + return ((this.results != null) && this.results.reallyResult()) ? (java.sql.ResultSet) this.results + : null; + } + + /** + * JDBC 2.0 Determine the result set concurrency. + * + * @return CONCUR_UPDATABLE or CONCUR_READONLY + * + * @throws SQLException + * if an error occurs + */ + public int getResultSetConcurrency() throws SQLException { + return this.resultSetConcurrency; + } + + /** + * @see Statement#getResultSetHoldability() + */ + public int getResultSetHoldability() throws SQLException { + return java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT; + } + + protected ResultSet getResultSetInternal() { + return this.results; + } + + /** + * JDBC 2.0 Determine the result set type. + * + * @return the ResultSet type (SCROLL_SENSITIVE or SCROLL_INSENSITIVE) + * + * @throws SQLException + * if an error occurs. + */ + public int getResultSetType() throws SQLException { + return this.resultSetType; + } + + /** + * getUpdateCount returns the current result as an update count, if the + * result is a ResultSet or there are no more results, -1 is returned. It + * should only be called once per result. + * + * @return the current result as an update count. + * + * @exception SQLException + * if a database access error occurs + */ + public int getUpdateCount() throws SQLException { + if (this.results == null) { + return -1; + } + + if (this.results.reallyResult()) { + return -1; + } + + int truncatedUpdateCount = 0; + + if (this.results.getUpdateCount() > Integer.MAX_VALUE) { + truncatedUpdateCount = Integer.MAX_VALUE; + } else { + truncatedUpdateCount = (int) this.results.getUpdateCount(); + } + + return truncatedUpdateCount; + } + + /** + * The first warning reported by calls on this Statement is returned. A + * Statement's execute methods clear its java.sql.SQLWarning chain. + * Subsequent Statement warnings will be chained to this + * java.sql.SQLWarning. + * + *

+ * The Warning chain is automatically cleared each time a statement is + * (re)executed. + *

+ * + *

+ * Note: If you are processing a ResultSet then any warnings + * associated with ResultSet reads will be chained on the ResultSet object. + *

+ * + * @return the first java.sql.SQLWarning or null + * + * @exception SQLException + * if a database access error occurs + */ + public java.sql.SQLWarning getWarnings() throws SQLException { + checkClosed(); + + if (this.connection != null && !this.connection.isClosed() + && this.connection.versionMeetsMinimum(4, 1, 0)) { + SQLWarning pendingWarningsFromServer = SQLError + .convertShowWarningsToSQLWarnings(this.connection); + + if (this.warningChain != null) { + this.warningChain.setNextWarning(pendingWarningsFromServer); + } else { + this.warningChain = pendingWarningsFromServer; + } + + return this.warningChain; + } + + return this.warningChain; + } + + + + /** + * Closes this statement, and frees resources. + * + * @param calledExplicitly + * was this called from close()? + * + * @throws SQLException + * if an error occurs + */ + protected void realClose(boolean calledExplicitly, boolean closeOpenResults) + throws SQLException { + if (this.isClosed) { + return; + } + + if (this.useUsageAdvisor) { + if (!calledExplicitly) { + String message = Messages.getString("Statement.63") //$NON-NLS-1$ + + Messages.getString("Statement.64"); //$NON-NLS-1$ + + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, + "", //$NON-NLS-1$ + this.currentCatalog, this.connectionId, this.getId(), + -1, System.currentTimeMillis(), 0, + Constants.MILLIS_I18N, null, this.pointOfOrigin, + message)); + } + } + + if (this.results != null) { + if (closeOpenResults) { + closeOpenResults = !this.holdResultsOpenOverClose; + } + + if (closeOpenResults && this.connection != null + && !this.connection.getHoldResultsOpenOverStatementClose()) { + try { + this.results.close(); + } catch (Exception ex) { + ; + } + + this.closeAllOpenResults(); + } + } + + if (this.connection != null) { + if (this.maxRowsChanged) { + this.connection.unsetMaxRows(this); + } + + if (!this.connection.getDontTrackOpenResources()) { + this.connection.unregisterStatement(this); + } + } + + this.isClosed = true; + + this.results = null; + this.connection = null; + this.warningChain = null; + this.openResults = null; + this.batchedGeneratedKeys = null; + this.cancelTimeoutMutex = null; + this.pingTarget = null; + } + + /** + * setCursorName defines the SQL cursor name that will be used by subsequent + * execute methods. This name can then be used in SQL positioned + * update/delete statements to identify the current row in the ResultSet + * generated by this statement. If a database doesn't support positioned + * update/delete, this method is a no-op. + * + *

+ * Note: This MySQL driver does not support cursors. + *

+ * + * @param name + * the new cursor name + * + * @exception SQLException + * if a database access error occurs + */ + public void setCursorName(String name) throws SQLException { + // No-op + } + + /** + * If escape scanning is on (the default), the driver will do escape + * substitution before sending the SQL to the database. + * + * @param enable + * true to enable; false to disable + * + * @exception SQLException + * if a database access error occurs + */ + public void setEscapeProcessing(boolean enable) + throws SQLException { + this.doEscapeProcessing = enable; + } + + /** + * JDBC 2.0 Give a hint as to the direction in which the rows in a result + * set will be processed. The hint applies only to result sets created using + * this Statement object. The default value is ResultSet.FETCH_FORWARD. + * + * @param direction + * the initial direction for processing rows + * + * @exception SQLException + * if a database-access error occurs or direction is not one + * of ResultSet.FETCH_FORWARD, ResultSet.FETCH_REVERSE, or + * ResultSet.FETCH_UNKNOWN + */ + public void setFetchDirection(int direction) throws SQLException { + switch (direction) { + case java.sql.ResultSet.FETCH_FORWARD: + case java.sql.ResultSet.FETCH_REVERSE: + case java.sql.ResultSet.FETCH_UNKNOWN: + break; + + default: + throw SQLError.createSQLException( + Messages.getString("Statement.5"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * JDBC 2.0 Give the JDBC driver a hint as to the number of rows that should + * be fetched from the database when more rows are needed. The number of + * rows specified only affects result sets created using this statement. If + * the value specified is zero, then the hint is ignored. The default value + * is zero. + * + * @param rows + * the number of rows to fetch + * + * @exception SQLException + * if a database-access error occurs, or the condition 0 + * <= rows <= this.getMaxRows() is not satisfied. + */ + public void setFetchSize(int rows) throws SQLException { + if (((rows < 0) && (rows != Integer.MIN_VALUE)) + || ((this.maxRows != 0) && (this.maxRows != -1) && (rows > this + .getMaxRows()))) { + throw SQLError.createSQLException( + Messages.getString("Statement.7"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$ + } + + this.fetchSize = rows; + } + + protected void setHoldResultsOpenOverClose(boolean holdResultsOpenOverClose) { + this.holdResultsOpenOverClose = holdResultsOpenOverClose; + } + + /** + * Sets the maxFieldSize + * + * @param max + * the new max column size limit; zero means unlimited + * + * @exception SQLException + * if size exceeds buffer size + */ + public void setMaxFieldSize(int max) throws SQLException { + if (max < 0) { + throw SQLError.createSQLException(Messages + .getString("Statement.11"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + int maxBuf = (this.connection != null) ? this.connection + .getMaxAllowedPacket() : MysqlIO.getMaxBuf(); + + if (max > maxBuf) { + throw SQLError.createSQLException(Messages.getString( + "Statement.13", //$NON-NLS-1$ + new Object[] { new Long(maxBuf) }), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + this.maxFieldSize = max; + } + + /** + * Set the maximum number of rows + * + * @param max + * the new max rows limit; zero means unlimited + * + * @exception SQLException + * if a database access error occurs + * + * @see getMaxRows + */ + public void setMaxRows(int max) throws SQLException { + if ((max > MysqlDefs.MAX_ROWS) || (max < 0)) { + throw SQLError + .createSQLException( + Messages.getString("Statement.15") + max //$NON-NLS-1$ + + " > " //$NON-NLS-1$ //$NON-NLS-2$ + + MysqlDefs.MAX_ROWS + ".", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (max == 0) { + max = -1; + } + + this.maxRows = max; + this.maxRowsChanged = true; + + if (this.maxRows == -1) { + this.connection.unsetMaxRows(this); + this.maxRowsChanged = false; + } else { + // Most people don't use setMaxRows() + // so don't penalize them + // with the extra query it takes + // to do it efficiently unless we need + // to. + this.connection.maxRowsChanged(this); + } + } + + /** + * Sets the queryTimeout limit + * + * @param seconds - + * the new query timeout limit in seconds + * + * @exception SQLException + * if a database access error occurs + */ + public void setQueryTimeout(int seconds) throws SQLException { + if (seconds < 0) { + throw SQLError.createSQLException(Messages + .getString("Statement.21"), //$NON-NLS-1$ + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + + this.timeoutInMillis = seconds * 1000; + } + + /** + * Sets the concurrency for result sets generated by this statement + * + * @param concurrencyFlag + * DOCUMENT ME! + */ + void setResultSetConcurrency(int concurrencyFlag) { + this.resultSetConcurrency = concurrencyFlag; + } + + /** + * Sets the result set type for result sets generated by this statement + * + * @param typeFlag + * DOCUMENT ME! + */ + void setResultSetType(int typeFlag) { + this.resultSetType = typeFlag; + } + + protected void getBatchedGeneratedKeys(java.sql.Statement batchedStatement) throws SQLException { + if (this.retrieveGeneratedKeys) { + java.sql.ResultSet rs = null; + + try { + rs = batchedStatement.getGeneratedKeys(); + + while (rs.next()) { + this.batchedGeneratedKeys + .add(new byte[][] { rs.getBytes(1) }); + } + } finally { + if (rs != null) { + rs.close(); + } + } + } + } + + protected void getBatchedGeneratedKeys() throws SQLException { + if (this.retrieveGeneratedKeys) { + java.sql.ResultSet rs = null; + + try { + rs = getGeneratedKeysInternal(); + + while (rs.next()) { + this.batchedGeneratedKeys + .add(new byte[][] { rs.getBytes(1) }); + } + } finally { + if (rs != null) { + rs.close(); + } + } + } + } + + /** + * @return + */ + private boolean useServerFetch() throws SQLException { + + return this.connection.isCursorFetchEnabled() && this.fetchSize > 0 + && this.resultSetConcurrency == ResultSet.CONCUR_READ_ONLY + && this.resultSetType == ResultSet.TYPE_FORWARD_ONLY; + } + + protected int findStartOfStatement(String sql) { + int statementStartPos = 0; + + if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) { + statementStartPos = sql.indexOf("*/"); + + if (statementStartPos == -1) { + statementStartPos = 0; + } else { + statementStartPos += 2; + } + } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--") + || StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) { + statementStartPos = sql.indexOf('\n'); + + if (statementStartPos == -1) { + statementStartPos = sql.indexOf('\r'); + + if (statementStartPos == -1) { + statementStartPos = 0; + } + } + } + + return statementStartPos; + } + + protected synchronized void setPingTarget(PingTarget pingTarget) { + this.pingTarget = pingTarget; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/StringUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/StringUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/StringUtils.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,1621 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigDecimal; + +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +/** + * Various utility methods for converting to/from byte arrays in the platform + * encoding + * + * @author Mark Matthews + */ +public class StringUtils { + + private static final int BYTE_RANGE = (1 + Byte.MAX_VALUE) - Byte.MIN_VALUE; + + private static byte[] allBytes = new byte[BYTE_RANGE]; + + private static char[] byteToChars = new char[BYTE_RANGE]; + + private static Method toPlainStringMethod; + + static final int WILD_COMPARE_MATCH_NO_WILD = 0; + + static final int WILD_COMPARE_MATCH_WITH_WILD = 1; + + static final int WILD_COMPARE_NO_MATCH = -1; + + static { + for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) { + allBytes[i - Byte.MIN_VALUE] = (byte) i; + } + + String allBytesString = new String(allBytes, 0, Byte.MAX_VALUE + - Byte.MIN_VALUE); + + int allBytesStringLen = allBytesString.length(); + + for (int i = 0; (i < (Byte.MAX_VALUE - Byte.MIN_VALUE)) + && (i < allBytesStringLen); i++) { + byteToChars[i] = allBytesString.charAt(i); + } + + try { + toPlainStringMethod = BigDecimal.class.getMethod("toPlainString", + new Class[0]); + } catch (NoSuchMethodException nsme) { + // that's okay, we fallback to .toString() + } + } + + /** + * Takes care of the fact that Sun changed the output of + * BigDecimal.toString() between JDK-1.4 and JDK 5 + * + * @param decimal + * the big decimal to stringify + * + * @return a string representation of 'decimal' + */ + public static String consistentToString(BigDecimal decimal) { + if (decimal == null) { + return null; + } + + if (toPlainStringMethod != null) { + try { + return (String) toPlainStringMethod.invoke(decimal, null); + } catch (InvocationTargetException invokeEx) { + // that's okay, we fall-through to decimal.toString() + } catch (IllegalAccessException accessEx) { + // that's okay, we fall-through to decimal.toString() + } + } + + return decimal.toString(); + } + + /** + * Dumps the given bytes to STDOUT as a hex dump (up to length bytes). + * + * @param byteBuffer + * the data to print as hex + * @param length + * the number of bytes to print + * + * @return ... + */ + public static final String dumpAsHex(byte[] byteBuffer, int length) { + StringBuffer outputBuf = new StringBuffer(length * 4); + + int p = 0; + int rows = length / 8; + + for (int i = 0; (i < rows) && (p < length); i++) { + int ptemp = p; + + for (int j = 0; j < 8; j++) { + String hexVal = Integer.toHexString(byteBuffer[ptemp] & 0xff); + + if (hexVal.length() == 1) { + hexVal = "0" + hexVal; //$NON-NLS-1$ + } + + outputBuf.append(hexVal + " "); //$NON-NLS-1$ + ptemp++; + } + + outputBuf.append(" "); //$NON-NLS-1$ + + for (int j = 0; j < 8; j++) { + if ((byteBuffer[p] > 32) && (byteBuffer[p] < 127)) { + outputBuf.append((char) byteBuffer[p] + " "); //$NON-NLS-1$ + } else { + outputBuf.append(". "); //$NON-NLS-1$ + } + + p++; + } + + outputBuf.append("\n"); //$NON-NLS-1$ + } + + int n = 0; + + for (int i = p; i < length; i++) { + String hexVal = Integer.toHexString(byteBuffer[i] & 0xff); + + if (hexVal.length() == 1) { + hexVal = "0" + hexVal; //$NON-NLS-1$ + } + + outputBuf.append(hexVal + " "); //$NON-NLS-1$ + n++; + } + + for (int i = n; i < 8; i++) { + outputBuf.append(" "); //$NON-NLS-1$ + } + + outputBuf.append(" "); //$NON-NLS-1$ + + for (int i = p; i < length; i++) { + if ((byteBuffer[i] > 32) && (byteBuffer[i] < 127)) { + outputBuf.append((char) byteBuffer[i] + " "); //$NON-NLS-1$ + } else { + outputBuf.append(". "); //$NON-NLS-1$ + } + } + + outputBuf.append("\n"); //$NON-NLS-1$ + + return outputBuf.toString(); + } + + private static boolean endsWith(byte[] dataFrom, String suffix) { + for (int i = 1; i <= suffix.length(); i++) { + int dfOffset = dataFrom.length - i; + int suffixOffset = suffix.length() - i; + if (dataFrom[dfOffset] != suffix.charAt(suffixOffset)) { + return false; + } + } + return true; + } + + /** + * Unfortunately, SJIS has 0x5c as a high byte in some of its double-byte + * characters, so we need to escape it. + * + * @param origBytes + * the original bytes in SJIS format + * @param origString + * the string that had .getBytes() called on it + * @param offset + * where to start converting from + * @param length + * how many characters to convert. + * + * @return byte[] with 0x5c escaped + */ + public static byte[] escapeEasternUnicodeByteStream(byte[] origBytes, + String origString, int offset, int length) { + if ((origBytes == null) || (origBytes.length == 0)) { + return origBytes; + } + + int bytesLen = origBytes.length; + int bufIndex = 0; + int strIndex = 0; + + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(bytesLen); + + while (true) { + if (origString.charAt(strIndex) == '\\') { + // write it out as-is + bytesOut.write(origBytes[bufIndex++]); + + // bytesOut.write(origBytes[bufIndex++]); + } else { + // Grab the first byte + int loByte = origBytes[bufIndex]; + + if (loByte < 0) { + loByte += 256; // adjust for signedness/wrap-around + } + + // We always write the first byte + bytesOut.write(loByte); + + // + // The codepage characters in question exist between + // 0x81-0x9F and 0xE0-0xFC... + // + // See: + // + // http://www.microsoft.com/GLOBALDEV/Reference/dbcs/932.htm + // + // Problematic characters in GBK + // + // U+905C : CJK UNIFIED IDEOGRAPH + // + // Problematic characters in Big5 + // + // B9F0 = U+5C62 : CJK UNIFIED IDEOGRAPH + // + if (loByte >= 0x80) { + if (bufIndex < (bytesLen - 1)) { + int hiByte = origBytes[bufIndex + 1]; + + if (hiByte < 0) { + hiByte += 256; // adjust for signedness/wrap-around + } + + // write the high byte here, and increment the index + // for the high byte + bytesOut.write(hiByte); + bufIndex++; + + // escape 0x5c if necessary + if (hiByte == 0x5C) { + bytesOut.write(hiByte); + } + } + } else if (loByte == 0x5c) { + if (bufIndex < (bytesLen - 1)) { + int hiByte = origBytes[bufIndex + 1]; + + if (hiByte < 0) { + hiByte += 256; // adjust for signedness/wrap-around + } + + if (hiByte == 0x62) { + // we need to escape the 0x5c + bytesOut.write(0x5c); + bytesOut.write(0x62); + bufIndex++; + } + } + } + + bufIndex++; + } + + if (bufIndex >= bytesLen) { + // we're done + break; + } + + strIndex++; + } + + return bytesOut.toByteArray(); + } + + /** + * Returns the first non whitespace char, converted to upper case + * + * @param searchIn + * the string to search in + * + * @return the first non-whitespace character, upper cased. + */ + public static char firstNonWsCharUc(String searchIn) { + return firstNonWsCharUc(searchIn, 0); + } + + public static char firstNonWsCharUc(String searchIn, int startAt) { + if (searchIn == null) { + return 0; + } + + int length = searchIn.length(); + + for (int i = startAt; i < length; i++) { + char c = searchIn.charAt(i); + + if (!Character.isWhitespace(c)) { + return Character.toUpperCase(c); + } + } + + return 0; + } + + /** + * Adds '+' to decimal numbers that are positive (MySQL doesn't understand + * them otherwise + * + * @param dString + * The value as a string + * + * @return String the string with a '+' added (if needed) + */ + public static final String fixDecimalExponent(String dString) { + int ePos = dString.indexOf("E"); //$NON-NLS-1$ + + if (ePos == -1) { + ePos = dString.indexOf("e"); //$NON-NLS-1$ + } + + if (ePos != -1) { + if (dString.length() > (ePos + 1)) { + char maybeMinusChar = dString.charAt(ePos + 1); + + if (maybeMinusChar != '-' && maybeMinusChar != '+') { + StringBuffer buf = new StringBuffer(dString.length() + 1); + buf.append(dString.substring(0, ePos + 1)); + buf.append('+'); + buf.append(dString.substring(ePos + 1, dString.length())); + dString = buf.toString(); + } + } + } + + return dString; + } + + public static final byte[] getBytes(char[] c, + SingleByteCharsetConverter converter, String encoding, + String serverEncoding, boolean parserKnowsUnicode) + throws SQLException { + try { + byte[] b = null; + + if (converter != null) { + b = converter.toBytes(c); + } else if (encoding == null) { + b = new String(c).getBytes(); + } else { + String s = new String(c); + + b = s.getBytes(encoding); + + if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$ + + if (!encoding.equalsIgnoreCase(serverEncoding)) { + b = escapeEasternUnicodeByteStream(b, s, 0, s.length()); + } + } + } + + return b; + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException(Messages.getString("StringUtils.5") //$NON-NLS-1$ + + encoding + Messages.getString("StringUtils.6"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + public static final byte[] getBytes(char[] c, + SingleByteCharsetConverter converter, String encoding, + String serverEncoding, int offset, int length, + boolean parserKnowsUnicode) throws SQLException { + try { + byte[] b = null; + + if (converter != null) { + b = converter.toBytes(c, offset, length); + } else if (encoding == null) { + byte[] temp = new String(c, offset, length).getBytes(); + + length = temp.length; + + b = new byte[length]; + System.arraycopy(temp, 0, b, 0, length); + } else { + String s = new String(c, offset, length); + + byte[] temp = s.getBytes(encoding); + + length = temp.length; + + b = new byte[length]; + System.arraycopy(temp, 0, b, 0, length); + + if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$ + + if (!encoding.equalsIgnoreCase(serverEncoding)) { + b = escapeEasternUnicodeByteStream(b, s, offset, length); + } + } + } + + return b; + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException(Messages.getString("StringUtils.10") //$NON-NLS-1$ + + encoding + Messages.getString("StringUtils.11"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + public static final byte[] getBytes(char[] c, String encoding, + String serverEncoding, boolean parserKnowsUnicode, Connection conn) + throws SQLException { + try { + + SingleByteCharsetConverter converter = null; + + if (conn != null) { + converter = conn.getCharsetConverter(encoding); + } else { + converter = SingleByteCharsetConverter.getInstance(encoding, null); + } + + return getBytes(c, converter, encoding, serverEncoding, + parserKnowsUnicode); + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException(Messages.getString("StringUtils.0") //$NON-NLS-1$ + + encoding + Messages.getString("StringUtils.1"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * Returns the byte[] representation of the given string (re)using the given + * charset converter, and the given encoding. + * + * @param s + * the string to convert + * @param converter + * the converter to reuse + * @param encoding + * the character encoding to use + * @param serverEncoding + * DOCUMENT ME! + * @param parserKnowsUnicode + * DOCUMENT ME! + * + * @return byte[] representation of the string + * + * @throws SQLException + * if an encoding unsupported by the JVM is supplied. + */ + public static final byte[] getBytes(String s, + SingleByteCharsetConverter converter, String encoding, + String serverEncoding, boolean parserKnowsUnicode) + throws SQLException { + try { + byte[] b = null; + + if (converter != null) { + b = converter.toBytes(s); + } else if (encoding == null) { + b = s.getBytes(); + } else { + b = s.getBytes(encoding); + + if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$ + + if (!encoding.equalsIgnoreCase(serverEncoding)) { + b = escapeEasternUnicodeByteStream(b, s, 0, s.length()); + } + } + } + + return b; + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException(Messages.getString("StringUtils.5") //$NON-NLS-1$ + + encoding + Messages.getString("StringUtils.6"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * DOCUMENT ME! + * + * @param s + * DOCUMENT ME! + * @param converter + * DOCUMENT ME! + * @param encoding + * DOCUMENT ME! + * @param serverEncoding + * DOCUMENT ME! + * @param offset + * DOCUMENT ME! + * @param length + * DOCUMENT ME! + * @param parserKnowsUnicode + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public static final byte[] getBytes(String s, + SingleByteCharsetConverter converter, String encoding, + String serverEncoding, int offset, int length, + boolean parserKnowsUnicode) throws SQLException { + try { + byte[] b = null; + + if (converter != null) { + b = converter.toBytes(s, offset, length); + } else if (encoding == null) { + byte[] temp = s.substring(offset, offset + length).getBytes(); + + length = temp.length; + + b = new byte[length]; + System.arraycopy(temp, 0, b, 0, length); + } else { + + byte[] temp = s.substring(offset, offset + length) + .getBytes(encoding); + + length = temp.length; + + b = new byte[length]; + System.arraycopy(temp, 0, b, 0, length); + + if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$ + || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$ + + if (!encoding.equalsIgnoreCase(serverEncoding)) { + b = escapeEasternUnicodeByteStream(b, s, offset, length); + } + } + } + + return b; + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException(Messages.getString("StringUtils.10") //$NON-NLS-1$ + + encoding + Messages.getString("StringUtils.11"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + /** + * Returns the byte[] representation of the given string using given + * encoding. + * + * @param s + * the string to convert + * @param encoding + * the character encoding to use + * @param parserKnowsUnicode + * DOCUMENT ME! + * + * @return byte[] representation of the string + * + * @throws SQLException + * if an encoding unsupported by the JVM is supplied. + */ + public static final byte[] getBytes(String s, String encoding, + String serverEncoding, boolean parserKnowsUnicode, Connection conn) + throws SQLException { + try { + SingleByteCharsetConverter converter = null; + + if (conn != null) { + converter = conn.getCharsetConverter(encoding); + } else { + converter = SingleByteCharsetConverter.getInstance(encoding, null); + } + + return getBytes(s, converter, encoding, serverEncoding, + parserKnowsUnicode); + } catch (UnsupportedEncodingException uee) { + throw SQLError.createSQLException(Messages.getString("StringUtils.0") //$NON-NLS-1$ + + encoding + Messages.getString("StringUtils.1"), + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ + } + } + + public static int getInt(byte[] buf, int offset, int endPos) throws NumberFormatException { + int base = 10; + + int s = offset; + + /* Skip white space. */ + while (Character.isWhitespace((char) buf[s]) && (s < endPos)) { + ++s; + } + + if (s == endPos) { + throw new NumberFormatException(new String(buf)); + } + + /* Check for a sign. */ + boolean negative = false; + + if ((char) buf[s] == '-') { + negative = true; + ++s; + } else if ((char) buf[s] == '+') { + ++s; + } + + /* Save the pointer so we can check later if anything happened. */ + int save = s; + + int cutoff = Integer.MAX_VALUE / base; + int cutlim = (Integer.MAX_VALUE % base); + + if (negative) { + cutlim++; + } + + boolean overflow = false; + + int i = 0; + + for (; s < endPos; s++) { + char c = (char) buf[s]; + + if (Character.isDigit(c)) { + c -= '0'; + } else if (Character.isLetter(c)) { + c = (char) (Character.toUpperCase(c) - 'A' + 10); + } else { + break; + } + + if (c >= base) { + break; + } + + /* Check for overflow. */ + if ((i > cutoff) || ((i == cutoff) && (c > cutlim))) { + overflow = true; + } else { + i *= base; + i += c; + } + } + + if (s == save) { + throw new NumberFormatException(new String(buf)); + } + + if (overflow) { + throw new NumberFormatException(new String(buf)); + } + + /* Return the result of the appropriate sign. */ + return (negative ? (-i) : i); + } + + public static int getInt(byte[] buf) throws NumberFormatException { + return getInt(buf, 0, buf.length); + } + + public static long getLong(byte[] buf) throws NumberFormatException { + int base = 10; + + int s = 0; + + /* Skip white space. */ + while (Character.isWhitespace((char) buf[s]) && (s < buf.length)) { + ++s; + } + + if (s == buf.length) { + throw new NumberFormatException(new String(buf)); + } + + /* Check for a sign. */ + boolean negative = false; + + if ((char) buf[s] == '-') { + negative = true; + ++s; + } else if ((char) buf[s] == '+') { + ++s; + } + + /* Save the pointer so we can check later if anything happened. */ + int save = s; + + long cutoff = Long.MAX_VALUE / base; + long cutlim = (int) (Long.MAX_VALUE % base); + + if (negative) { + cutlim++; + } + + boolean overflow = false; + long i = 0; + + for (; s < buf.length; s++) { + char c = (char) buf[s]; + + if (Character.isDigit(c)) { + c -= '0'; + } else if (Character.isLetter(c)) { + c = (char) (Character.toUpperCase(c) - 'A' + 10); + } else { + break; + } + + if (c >= base) { + break; + } + + /* Check for overflow. */ + if ((i > cutoff) || ((i == cutoff) && (c > cutlim))) { + overflow = true; + } else { + i *= base; + i += c; + } + } + + if (s == save) { + throw new NumberFormatException(new String(buf)); + } + + if (overflow) { + throw new NumberFormatException(new String(buf)); + } + + /* Return the result of the appropriate sign. */ + return (negative ? (-i) : i); + } + + public static short getShort(byte[] buf) throws NumberFormatException { + short base = 10; + + int s = 0; + + /* Skip white space. */ + while (Character.isWhitespace((char) buf[s]) && (s < buf.length)) { + ++s; + } + + if (s == buf.length) { + throw new NumberFormatException(new String(buf)); + } + + /* Check for a sign. */ + boolean negative = false; + + if ((char) buf[s] == '-') { + negative = true; + ++s; + } else if ((char) buf[s] == '+') { + ++s; + } + + /* Save the pointer so we can check later if anything happened. */ + int save = s; + + short cutoff = (short) (Short.MAX_VALUE / base); + short cutlim = (short) (Short.MAX_VALUE % base); + + if (negative) { + cutlim++; + } + + boolean overflow = false; + short i = 0; + + for (; s < buf.length; s++) { + char c = (char) buf[s]; + + if (Character.isDigit(c)) { + c -= '0'; + } else if (Character.isLetter(c)) { + c = (char) (Character.toUpperCase(c) - 'A' + 10); + } else { + break; + } + + if (c >= base) { + break; + } + + /* Check for overflow. */ + if ((i > cutoff) || ((i == cutoff) && (c > cutlim))) { + overflow = true; + } else { + i *= base; + i += c; + } + } + + if (s == save) { + throw new NumberFormatException(new String(buf)); + } + + if (overflow) { + throw new NumberFormatException(new String(buf)); + } + + /* Return the result of the appropriate sign. */ + return (negative ? (short) -i : (short) i); + } + + public final static int indexOfIgnoreCase(int startingPosition, + String searchIn, String searchFor) { + if ((searchIn == null) || (searchFor == null) + || startingPosition > searchIn.length()) { + return -1; + } + + int patternLength = searchFor.length(); + int stringLength = searchIn.length(); + int stopSearchingAt = stringLength - patternLength; + + int i = startingPosition; + + if (patternLength == 0) { + return -1; + } + + // Brute force string pattern matching + // Some locales don't follow upper-case rule, so need to check both + char firstCharOfPatternUc = Character.toUpperCase(searchFor.charAt(0)); + char firstCharOfPatternLc = Character.toLowerCase(searchFor.charAt(0)); + + lookForFirstChar: while (true) { + while ((i < stopSearchingAt) + && (Character.toUpperCase(searchIn.charAt(i)) != firstCharOfPatternUc) + && Character.toLowerCase(searchIn.charAt(i)) != firstCharOfPatternLc) { + i++; + } + + if (i > stopSearchingAt) { + return -1; + } + + int j = i + 1; + int end = (j + patternLength) - 1; + + int k = 1; // start at second char of pattern + + while (j < end) { + int searchInPos = j++; + int searchForPos = k++; + + if (Character.toUpperCase(searchIn.charAt(searchInPos)) != Character + .toUpperCase(searchFor.charAt(searchForPos))) { + i++; + + // start over + continue lookForFirstChar; + } + + // Georgian and Turkish locales don't have same convention, so + // need to check lowercase + // too! + if (Character.toLowerCase(searchIn.charAt(searchInPos)) != Character + .toLowerCase(searchFor.charAt(searchForPos))) { + i++; + + // start over + continue lookForFirstChar; + } + } + + return i; // found entire pattern + } + } + + /** + * DOCUMENT ME! + * + * @param searchIn + * DOCUMENT ME! + * @param searchFor + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public final static int indexOfIgnoreCase(String searchIn, String searchFor) { + return indexOfIgnoreCase(0, searchIn, searchFor); + } + + public static int indexOfIgnoreCaseRespectMarker(int startAt, String src, + String target, String marker, String markerCloses, + boolean allowBackslashEscapes) { + char contextMarker = Character.MIN_VALUE; + boolean escaped = false; + int markerTypeFound = -1; + int srcLength = src.length(); + int ind = 0; + + for (int i = startAt; i < srcLength; i++) { + char c = src.charAt(i); + + if (allowBackslashEscapes && c == '\\') { + escaped = !escaped; + } else if (markerTypeFound != -1 && c == markerCloses.charAt(markerTypeFound) && !escaped) { + contextMarker = Character.MIN_VALUE; + markerTypeFound = -1; + } else if ((ind = marker.indexOf(c)) != -1 && !escaped + && contextMarker == Character.MIN_VALUE) { + markerTypeFound = ind; + contextMarker = c; + } else if (c == target.charAt(0) && !escaped + && contextMarker == Character.MIN_VALUE) { + if (indexOfIgnoreCase(i, src, target) != -1) + return i; + } + } + + return -1; + + } + + public static int indexOfIgnoreCaseRespectQuotes(int startAt, String src, + String target, char quoteChar, boolean allowBackslashEscapes) { + char contextMarker = Character.MIN_VALUE; + boolean escaped = false; + + int srcLength = src.length(); + + for (int i = startAt; i < srcLength; i++) { + char c = src.charAt(i); + + if (allowBackslashEscapes && c == '\\') { + escaped = !escaped; + } else if (c == contextMarker && !escaped) { + contextMarker = Character.MIN_VALUE; + } else if (c == quoteChar && !escaped + && contextMarker == Character.MIN_VALUE) { + contextMarker = c; + // This test looks complex, but remember that in certain locales, upper case + // of two different codepoints coverts to same codepoint, and vice-versa. + } else if ((Character.toUpperCase(c) == Character.toUpperCase(target.charAt(0)) || + Character.toLowerCase(c) == Character.toLowerCase(target.charAt(0))) && !escaped + && contextMarker == Character.MIN_VALUE) { + if (startsWithIgnoreCase(src, i, target)) + return i; + } + } + + return -1; + + } + + /** + * Splits stringToSplit into a list, using the given delimitter + * + * @param stringToSplit + * the string to split + * @param delimitter + * the string to split on + * @param trim + * should the split strings be whitespace trimmed? + * + * @return the list of strings, split by delimitter + * + * @throws IllegalArgumentException + * DOCUMENT ME! + */ + public static final List split(String stringToSplit, String delimitter, + boolean trim) { + if (stringToSplit == null) { + return new ArrayList(); + } + + if (delimitter == null) { + throw new IllegalArgumentException(); + } + + StringTokenizer tokenizer = new StringTokenizer(stringToSplit, + delimitter, false); + + List splitTokens = new ArrayList(tokenizer.countTokens()); + + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken(); + + if (trim) { + token = token.trim(); + } + + splitTokens.add(token); + } + + return splitTokens; + } + + /** + * Splits stringToSplit into a list, using the given delimitter + * + * @param stringToSplit + * the string to split + * @param delimitter + * the string to split on + * @param trim + * should the split strings be whitespace trimmed? + * + * @return the list of strings, split by delimiter + * + * @throws IllegalArgumentException + * DOCUMENT ME! + */ + public static final List split(String stringToSplit, String delimiter, + String markers, String markerCloses, boolean trim) { + if (stringToSplit == null) { + return new ArrayList(); + } + + if (delimiter == null) { + throw new IllegalArgumentException(); + } + + int delimPos = 0; + int currentPos = 0; + + List splitTokens = new ArrayList(); + + while ((delimPos = indexOfIgnoreCaseRespectMarker(currentPos, + stringToSplit, delimiter, markers, markerCloses, false)) != -1) { + String token = stringToSplit.substring(currentPos, delimPos); + + if (trim) { + token = token.trim(); + } + + splitTokens.add(token); + currentPos = delimPos + 1; + } + + if (currentPos < stringToSplit.length()) { + String token = stringToSplit.substring(currentPos); + + if (trim) { + token = token.trim(); + } + + splitTokens.add(token); + } + + return splitTokens; + } + + private static boolean startsWith(byte[] dataFrom, String chars) { + for (int i = 0; i < chars.length(); i++) { + if (dataFrom[i] != chars.charAt(i)) { + return false; + } + } + return true; + } + + /** + * Determines whether or not the string 'searchIn' contains the string + * 'searchFor', dis-regarding case starting at 'startAt' Shorthand for a + * String.regionMatch(...) + * + * @param searchIn + * the string to search in + * @param startAt + * the position to start at + * @param searchFor + * the string to search for + * + * @return whether searchIn starts with searchFor, ignoring case + */ + public static boolean startsWithIgnoreCase(String searchIn, int startAt, + String searchFor) { + return searchIn.regionMatches(true, startAt, searchFor, 0, searchFor + .length()); + } + + /** + * Determines whether or not the string 'searchIn' contains the string + * 'searchFor', dis-regarding case. Shorthand for a String.regionMatch(...) + * + * @param searchIn + * the string to search in + * @param searchFor + * the string to search for + * + * @return whether searchIn starts with searchFor, ignoring case + */ + public static boolean startsWithIgnoreCase(String searchIn, String searchFor) { + return startsWithIgnoreCase(searchIn, 0, searchFor); + } + + /** + * Determines whether or not the sting 'searchIn' contains the string + * 'searchFor', disregarding case,leading whitespace and non-alphanumeric + * characters. + * + * @param searchIn + * the string to search in + * @param searchFor + * the string to search for + * + * @return true if the string starts with 'searchFor' ignoring whitespace + */ + public static boolean startsWithIgnoreCaseAndNonAlphaNumeric( + String searchIn, String searchFor) { + if (searchIn == null) { + return searchFor == null; + } + + int beginPos = 0; + + int inLength = searchIn.length(); + + for (beginPos = 0; beginPos < inLength; beginPos++) { + char c = searchIn.charAt(beginPos); + + if (Character.isLetterOrDigit(c)) { + break; + } + } + + return startsWithIgnoreCase(searchIn, beginPos, searchFor); + } + + /** + * Determines whether or not the sting 'searchIn' contains the string + * 'searchFor', disregarding case and leading whitespace + * + * @param searchIn + * the string to search in + * @param searchFor + * the string to search for + * + * @return true if the string starts with 'searchFor' ignoring whitespace + */ + public static boolean startsWithIgnoreCaseAndWs(String searchIn, + String searchFor) { + return startsWithIgnoreCaseAndWs(searchIn, searchFor, 0); + } + + /** + * Determines whether or not the sting 'searchIn' contains the string + * 'searchFor', disregarding case and leading whitespace + * + * @param searchIn + * the string to search in + * @param searchFor + * the string to search for + * @param beginPos + * where to start searching + * + * @return true if the string starts with 'searchFor' ignoring whitespace + */ + + public static boolean startsWithIgnoreCaseAndWs(String searchIn, + String searchFor, int beginPos) { + if (searchIn == null) { + return searchFor == null; + } + + int inLength = searchIn.length(); + + for (; beginPos < inLength; beginPos++) { + if (!Character.isWhitespace(searchIn.charAt(beginPos))) { + break; + } + } + + return startsWithIgnoreCase(searchIn, beginPos, searchFor); + } + + /** + * @param bytesToStrip + * @param prefix + * @param suffix + * @return + */ + public static byte[] stripEnclosure(byte[] source, String prefix, + String suffix) { + if (source.length >= prefix.length() + suffix.length() + && startsWith(source, prefix) && endsWith(source, suffix)) { + + int totalToStrip = prefix.length() + suffix.length(); + int enclosedLength = source.length - totalToStrip; + byte[] enclosed = new byte[enclosedLength]; + + int startPos = prefix.length(); + int numToCopy = enclosed.length; + System.arraycopy(source, startPos, enclosed, 0, numToCopy); + + return enclosed; + } + return source; + } + + /** + * Returns the bytes as an ASCII String. + * + * @param buffer + * the bytes representing the string + * + * @return The ASCII String. + */ + public static final String toAsciiString(byte[] buffer) { + return toAsciiString(buffer, 0, buffer.length); + } + + /** + * Returns the bytes as an ASCII String. + * + * @param buffer + * the bytes to convert + * @param startPos + * the position to start converting + * @param length + * the length of the string to convert + * + * @return the ASCII string + */ + public static final String toAsciiString(byte[] buffer, int startPos, + int length) { + char[] charArray = new char[length]; + int readpoint = startPos; + + for (int i = 0; i < length; i++) { + charArray[i] = (char) buffer[readpoint]; + readpoint++; + } + + return new String(charArray); + } + + /** + * Compares searchIn against searchForWildcard with wildcards (heavily + * borrowed from strings/ctype-simple.c in the server sources) + * + * @param searchIn + * the string to search in + * @param searchForWildcard + * the string to search for, using the 'standard' SQL wildcard + * chars of '%' and '_' + * + * @return WILD_COMPARE_MATCH_NO_WILD if matched, WILD_COMPARE_NO_MATCH if + * not matched with wildcard, WILD_COMPARE_MATCH_WITH_WILD if + * matched with wildcard + */ + public static int wildCompare(String searchIn, String searchForWildcard) { + if ((searchIn == null) || (searchForWildcard == null)) { + return WILD_COMPARE_NO_MATCH; + } + + if (searchForWildcard.equals("%")) { //$NON-NLS-1$ + + return WILD_COMPARE_MATCH_WITH_WILD; + } + + int result = WILD_COMPARE_NO_MATCH; /* Not found, using wildcards */ + + char wildcardMany = '%'; + char wildcardOne = '_'; + char wildcardEscape = '\\'; + + int searchForPos = 0; + int searchForEnd = searchForWildcard.length(); + + int searchInPos = 0; + int searchInEnd = searchIn.length(); + + while (searchForPos != searchForEnd) { + char wildstrChar = searchForWildcard.charAt(searchForPos); + + while ((searchForWildcard.charAt(searchForPos) != wildcardMany) + && (wildstrChar != wildcardOne)) { + if ((searchForWildcard.charAt(searchForPos) == wildcardEscape) + && ((searchForPos + 1) != searchForEnd)) { + searchForPos++; + } + + if ((searchInPos == searchInEnd) + || (Character.toUpperCase(searchForWildcard + .charAt(searchForPos++)) != Character + .toUpperCase(searchIn.charAt(searchInPos++)))) { + return WILD_COMPARE_MATCH_WITH_WILD; /* No match */ + } + + if (searchForPos == searchForEnd) { + return ((searchInPos != searchInEnd) ? WILD_COMPARE_MATCH_WITH_WILD + : WILD_COMPARE_MATCH_NO_WILD); /* + * Match if both are + * at end + */ + } + + result = WILD_COMPARE_MATCH_WITH_WILD; /* Found an anchor char */ + } + + if (searchForWildcard.charAt(searchForPos) == wildcardOne) { + do { + if (searchInPos == searchInEnd) { /* + * Skip one char if + * possible + */ + + return (result); + } + + searchInPos++; + } while ((++searchForPos < searchForEnd) + && (searchForWildcard.charAt(searchForPos) == wildcardOne)); + + if (searchForPos == searchForEnd) { + break; + } + } + + if (searchForWildcard.charAt(searchForPos) == wildcardMany) { /* + * Found + * w_many + */ + + char cmp; + + searchForPos++; + + /* Remove any '%' and '_' from the wild search string */ + for (; searchForPos != searchForEnd; searchForPos++) { + if (searchForWildcard.charAt(searchForPos) == wildcardMany) { + continue; + } + + if (searchForWildcard.charAt(searchForPos) == wildcardOne) { + if (searchInPos == searchInEnd) { + return (WILD_COMPARE_NO_MATCH); + } + + searchInPos++; + + continue; + } + + break; /* Not a wild character */ + } + + if (searchForPos == searchForEnd) { + return WILD_COMPARE_MATCH_NO_WILD; /* Ok if w_many is last */ + } + + if (searchInPos == searchInEnd) { + return WILD_COMPARE_NO_MATCH; + } + + if (((cmp = searchForWildcard.charAt(searchForPos)) == wildcardEscape) + && ((searchForPos + 1) != searchForEnd)) { + cmp = searchForWildcard.charAt(++searchForPos); + } + + searchForPos++; + + do { + while ((searchInPos != searchInEnd) + && (Character.toUpperCase(searchIn + .charAt(searchInPos)) != Character + .toUpperCase(cmp))) + searchInPos++; + + if (searchInPos++ == searchInEnd) { + return WILD_COMPARE_NO_MATCH; + } + + { + int tmp = wildCompare(searchIn, searchForWildcard); + + if (tmp <= 0) { + return (tmp); + } + } + } while ((searchInPos != searchInEnd) + && (searchForWildcard.charAt(0) != wildcardMany)); + + return WILD_COMPARE_NO_MATCH; + } + } + + return ((searchInPos != searchInEnd) ? WILD_COMPARE_MATCH_WITH_WILD + : WILD_COMPARE_MATCH_NO_WILD); + } + + static byte[] s2b(String s, Connection conn) throws SQLException { + if (s == null) { + return null; + } + + if ((conn != null) && conn.getUseUnicode()) { + try { + String encoding = conn.getEncoding(); + + if (encoding == null) { + return s.getBytes(); + } + + SingleByteCharsetConverter converter = conn + .getCharsetConverter(encoding); + + if (converter != null) { + return converter.toBytes(s); + } + + return s.getBytes(encoding); + } catch (java.io.UnsupportedEncodingException E) { + return s.getBytes(); + } + } + + return s.getBytes(); + } + + public static int lastIndexOf(byte[] s, char c) { + if (s == null) { + return -1; + } + + for (int i = s.length - 1; i >= 0; i--) { + if (s[i] == c) { + return i; + } + } + + return -1; + } + + public static int indexOf(byte[] s, char c) { + if (s == null) { + return -1; + } + + int length = s.length; + + for (int i = 0; i < length; i++) { + if (s[i] == c) { + return i; + } + } + + return -1; + } + + /** + * Returns the given string, with comments removed + * + * @param src + * the source string + * @param stringOpens + * characters which delimit the "open" of a string + * @param stringCloses + * characters which delimit the "close" of a string, in + * counterpart order to stringOpens + * @param slashStarComments + * strip slash-star type "C" style comments + * @param slashSlashComments + * strip slash-slash C++ style comments to end-of-line + * @param hashComments + * strip #-style comments to end-of-line + * @param dashDashComments + * strip "--" style comments to end-of-line + * @return the input string with all comment-delimited data removed + */ + public static String stripComments(String src, String stringOpens, + String stringCloses, boolean slashStarComments, + boolean slashSlashComments, boolean hashComments, + boolean dashDashComments) { + if (src == null) { + return null; + } + + StringBuffer buf = new StringBuffer(src.length()); + + // It's just more natural to deal with this as a stream + // when parsing..This code is currently only called when + // parsing the kind of metadata that developers are strongly + // recommended to cache anyways, so we're not worried + // about the _1_ extra object allocation if it cleans + // up the code + + StringReader sourceReader = new StringReader(src); + + int contextMarker = Character.MIN_VALUE; + boolean escaped = false; + int markerTypeFound = -1; + + int ind = 0; + + int currentChar = 0; + + try { + while ((currentChar = sourceReader.read()) != -1) { + + if (false && currentChar == '\\') { + escaped = !escaped; + } else if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound) + && !escaped) { + contextMarker = Character.MIN_VALUE; + markerTypeFound = -1; + } else if ((ind = stringOpens.indexOf(currentChar)) != -1 + && !escaped && contextMarker == Character.MIN_VALUE) { + markerTypeFound = ind; + contextMarker = currentChar; + } + + if (contextMarker == Character.MIN_VALUE && currentChar == '/' + && (slashSlashComments || slashStarComments)) { + currentChar = sourceReader.read(); + if (currentChar == '*' && slashStarComments) { + int prevChar = 0; + while ((currentChar = sourceReader.read()) != '/' + || prevChar != '*') { + if (currentChar == '\r') { + + currentChar = sourceReader.read(); + if (currentChar == '\n') { + currentChar = sourceReader.read(); + } + } else { + if (currentChar == '\n') { + + currentChar = sourceReader.read(); + } + } + if (currentChar < 0) + break; + prevChar = currentChar; + } + continue; + } else if (currentChar == '/' && slashSlashComments) { + while ((currentChar = sourceReader.read()) != '\n' + && currentChar != '\r' && currentChar >= 0) + ; + } + } else if (contextMarker == Character.MIN_VALUE + && currentChar == '#' && hashComments) { + // Slurp up everything until the newline + while ((currentChar = sourceReader.read()) != '\n' + && currentChar != '\r' && currentChar >= 0) + ; + } else if (contextMarker == Character.MIN_VALUE + && currentChar == '-' && dashDashComments) { + currentChar = sourceReader.read(); + + if (currentChar == -1 || currentChar != '-') { + buf.append('-'); + + if (currentChar != -1) { + buf.append(currentChar); + } + + continue; + } + + // Slurp up everything until the newline + + while ((currentChar = sourceReader.read()) != '\n' + && currentChar != '\r' && currentChar >= 0) + ; + } + + if (currentChar != -1) { + buf.append((char) currentChar); + } + } + } catch (IOException ioEx) { + // we'll never see this from a StringReader + } + + return buf.toString(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/TimeUtil.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/TimeUtil.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/TimeUtil.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,1179 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.sql.Date; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; + +import java.util.Calendar; +import java.util.Collections; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.TimeZone; + +/** + * Timezone conversion routines + * + * @author Mark Matthews + */ +public class TimeUtil { + static final Map ABBREVIATED_TIMEZONES; + + static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT"); + + static final Map TIMEZONE_MAPPINGS; + + static { + HashMap tempMap = new HashMap(); + + // + // Windows Mappings + // + tempMap.put("Romance", "Europe/Paris"); + tempMap.put("Romance Standard Time", "Europe/Paris"); + tempMap.put("Warsaw", "Europe/Warsaw"); + tempMap.put("Central Europe", "Europe/Prague"); + tempMap.put("Central Europe Standard Time", "Europe/Prague"); + tempMap.put("Prague Bratislava", "Europe/Prague"); + tempMap.put("W. Central Africa Standard Time", "Africa/Luanda"); + tempMap.put("FLE", "Europe/Helsinki"); + tempMap.put("FLE Standard Time", "Europe/Helsinki"); + tempMap.put("GFT", "Europe/Athens"); + tempMap.put("GFT Standard Time", "Europe/Athens"); + tempMap.put("GTB", "Europe/Athens"); + tempMap.put("GTB Standard Time", "Europe/Athens"); + tempMap.put("Israel", "Asia/Jerusalem"); + tempMap.put("Israel Standard Time", "Asia/Jerusalem"); + tempMap.put("Arab", "Asia/Riyadh"); + tempMap.put("Arab Standard Time", "Asia/Riyadh"); + tempMap.put("Arabic Standard Time", "Asia/Baghdad"); + tempMap.put("E. Africa", "Africa/Nairobi"); + tempMap.put("E. Africa Standard Time", "Africa/Nairobi"); + tempMap.put("Saudi Arabia", "Asia/Riyadh"); + tempMap.put("Saudi Arabia Standard Time", "Asia/Riyadh"); + tempMap.put("Iran", "Asia/Tehran"); + tempMap.put("Iran Standard Time", "Asia/Tehran"); + tempMap.put("Afghanistan", "Asia/Kabul"); + tempMap.put("Afghanistan Standard Time", "Asia/Kabul"); + tempMap.put("India", "Asia/Calcutta"); + tempMap.put("India Standard Time", "Asia/Calcutta"); + tempMap.put("Myanmar Standard Time", "Asia/Rangoon"); + tempMap.put("Nepal Standard Time", "Asia/Katmandu"); + tempMap.put("Sri Lanka", "Asia/Colombo"); + tempMap.put("Sri Lanka Standard Time", "Asia/Colombo"); + tempMap.put("Beijing", "Asia/Shanghai"); + tempMap.put("China", "Asia/Shanghai"); + tempMap.put("China Standard Time", "Asia/Shanghai"); + tempMap.put("AUS Central", "Australia/Darwin"); + tempMap.put("AUS Central Standard Time", "Australia/Darwin"); + tempMap.put("Cen. Australia", "Australia/Adelaide"); + tempMap.put("Cen. Australia Standard Time", "Australia/Adelaide"); + tempMap.put("Vladivostok", "Asia/Vladivostok"); + tempMap.put("Vladivostok Standard Time", "Asia/Vladivostok"); + tempMap.put("West Pacific", "Pacific/Guam"); + tempMap.put("West Pacific Standard Time", "Pacific/Guam"); + tempMap.put("E. South America", "America/Sao_Paulo"); + tempMap.put("E. South America Standard Time", "America/Sao_Paulo"); + tempMap.put("Greenland Standard Time", "America/Godthab"); + tempMap.put("Newfoundland", "America/St_Johns"); + tempMap.put("Newfoundland Standard Time", "America/St_Johns"); + tempMap.put("Pacific SA", "America/Caracas"); + tempMap.put("Pacific SA Standard Time", "America/Caracas"); + tempMap.put("SA Western", "America/Caracas"); + tempMap.put("SA Western Standard Time", "America/Caracas"); + tempMap.put("SA Pacific", "America/Bogota"); + tempMap.put("SA Pacific Standard Time", "America/Bogota"); + tempMap.put("US Eastern", "America/Indianapolis"); + tempMap.put("US Eastern Standard Time", "America/Indianapolis"); + tempMap.put("Central America Standard Time", "America/Regina"); + tempMap.put("Mexico", "America/Mexico_City"); + tempMap.put("Mexico Standard Time", "America/Mexico_City"); + tempMap.put("Canada Central", "America/Regina"); + tempMap.put("Canada Central Standard Time", "America/Regina"); + tempMap.put("US Mountain", "America/Phoenix"); + tempMap.put("US Mountain Standard Time", "America/Phoenix"); + tempMap.put("GMT", "Europe/London"); + tempMap.put("GMT Standard Time", "Europe/London"); + tempMap.put("Ekaterinburg", "Asia/Yekaterinburg"); + tempMap.put("Ekaterinburg Standard Time", "Asia/Yekaterinburg"); + tempMap.put("West Asia", "Asia/Karachi"); + tempMap.put("West Asia Standard Time", "Asia/Karachi"); + tempMap.put("Central Asia", "Asia/Dhaka"); + tempMap.put("Central Asia Standard Time", "Asia/Dhaka"); + tempMap.put("N. Central Asia Standard Time", "Asia/Novosibirsk"); + tempMap.put("Bangkok", "Asia/Bangkok"); + tempMap.put("Bangkok Standard Time", "Asia/Bangkok"); + tempMap.put("North Asia Standard Time", "Asia/Krasnoyarsk"); + tempMap.put("SE Asia", "Asia/Bangkok"); + tempMap.put("SE Asia Standard Time", "Asia/Bangkok"); + tempMap.put("North Asia East Standard Time", "Asia/Ulaanbaatar"); + tempMap.put("Singapore", "Asia/Singapore"); + tempMap.put("Singapore Standard Time", "Asia/Singapore"); + tempMap.put("Taipei", "Asia/Taipei"); + tempMap.put("Taipei Standard Time", "Asia/Taipei"); + tempMap.put("W. Australia", "Australia/Perth"); + tempMap.put("W. Australia Standard Time", "Australia/Perth"); + tempMap.put("Korea", "Asia/Seoul"); + tempMap.put("Korea Standard Time", "Asia/Seoul"); + tempMap.put("Tokyo", "Asia/Tokyo"); + tempMap.put("Tokyo Standard Time", "Asia/Tokyo"); + tempMap.put("Yakutsk", "Asia/Yakutsk"); + tempMap.put("Yakutsk Standard Time", "Asia/Yakutsk"); + tempMap.put("Central European", "Europe/Belgrade"); + tempMap.put("Central European Standard Time", "Europe/Belgrade"); + tempMap.put("W. Europe", "Europe/Berlin"); + tempMap.put("W. Europe Standard Time", "Europe/Berlin"); + tempMap.put("Tasmania", "Australia/Hobart"); + tempMap.put("Tasmania Standard Time", "Australia/Hobart"); + tempMap.put("AUS Eastern", "Australia/Sydney"); + tempMap.put("AUS Eastern Standard Time", "Australia/Sydney"); + tempMap.put("E. Australia", "Australia/Brisbane"); + tempMap.put("E. Australia Standard Time", "Australia/Brisbane"); + tempMap.put("Sydney Standard Time", "Australia/Sydney"); + tempMap.put("Central Pacific", "Pacific/Guadalcanal"); + tempMap.put("Central Pacific Standard Time", "Pacific/Guadalcanal"); + tempMap.put("Dateline", "Pacific/Majuro"); + tempMap.put("Dateline Standard Time", "Pacific/Majuro"); + tempMap.put("Fiji", "Pacific/Fiji"); + tempMap.put("Fiji Standard Time", "Pacific/Fiji"); + tempMap.put("Samoa", "Pacific/Apia"); + tempMap.put("Samoa Standard Time", "Pacific/Apia"); + tempMap.put("Hawaiian", "Pacific/Honolulu"); + tempMap.put("Hawaiian Standard Time", "Pacific/Honolulu"); + tempMap.put("Alaskan", "America/Anchorage"); + tempMap.put("Alaskan Standard Time", "America/Anchorage"); + tempMap.put("Pacific", "America/Los_Angeles"); + tempMap.put("Pacific Standard Time", "America/Los_Angeles"); + tempMap.put("Mexico Standard Time 2", "America/Chihuahua"); + tempMap.put("Mountain", "America/Denver"); + tempMap.put("Mountain Standard Time", "America/Denver"); + tempMap.put("Central", "America/Chicago"); + tempMap.put("Central Standard Time", "America/Chicago"); + tempMap.put("Eastern", "America/New_York"); + tempMap.put("Eastern Standard Time", "America/New_York"); + tempMap.put("E. Europe", "Europe/Bucharest"); + tempMap.put("E. Europe Standard Time", "Europe/Bucharest"); + tempMap.put("Egypt", "Africa/Cairo"); + tempMap.put("Egypt Standard Time", "Africa/Cairo"); + tempMap.put("South Africa", "Africa/Harare"); + tempMap.put("South Africa Standard Time", "Africa/Harare"); + tempMap.put("Atlantic", "America/Halifax"); + tempMap.put("Atlantic Standard Time", "America/Halifax"); + tempMap.put("SA Eastern", "America/Buenos_Aires"); + tempMap.put("SA Eastern Standard Time", "America/Buenos_Aires"); + tempMap.put("Mid-Atlantic", "Atlantic/South_Georgia"); + tempMap.put("Mid-Atlantic Standard Time", "Atlantic/South_Georgia"); + tempMap.put("Azores", "Atlantic/Azores"); + tempMap.put("Azores Standard Time", "Atlantic/Azores"); + tempMap.put("Cape Verde Standard Time", "Atlantic/Cape_Verde"); + tempMap.put("Russian", "Europe/Moscow"); + tempMap.put("Russian Standard Time", "Europe/Moscow"); + tempMap.put("New Zealand", "Pacific/Auckland"); + tempMap.put("New Zealand Standard Time", "Pacific/Auckland"); + tempMap.put("Tonga Standard Time", "Pacific/Tongatapu"); + tempMap.put("Arabian", "Asia/Muscat"); + tempMap.put("Arabian Standard Time", "Asia/Muscat"); + tempMap.put("Caucasus", "Asia/Tbilisi"); + tempMap.put("Caucasus Standard Time", "Asia/Tbilisi"); + tempMap.put("GMT Standard Time", "GMT"); + tempMap.put("Greenwich", "GMT"); + tempMap.put("Greenwich Standard Time", "GMT"); + tempMap.put("UTC", "GMT"); + + TIMEZONE_MAPPINGS = Collections.unmodifiableMap(tempMap); + + // + // Handle abbreviated mappings + // + tempMap = new HashMap(); + + tempMap.put("ACST", new String[] { "America/Porto_Acre" }); + tempMap.put("ACT", new String[] { "America/Porto_Acre" }); + tempMap.put("ADDT", new String[] { "America/Pangnirtung" }); + tempMap.put("ADMT", new String[] { "Africa/Asmera", + "Africa/Addis_Ababa" }); + tempMap.put("ADT", new String[] { "Atlantic/Bermuda", "Asia/Baghdad", + "America/Thule", "America/Goose_Bay", "America/Halifax", + "America/Glace_Bay", "America/Pangnirtung", "America/Barbados", + "America/Martinique" }); + tempMap.put("AFT", new String[] { "Asia/Kabul" }); + tempMap.put("AHDT", new String[] { "America/Anchorage" }); + tempMap.put("AHST", new String[] { "America/Anchorage" }); + tempMap.put("AHWT", new String[] { "America/Anchorage" }); + tempMap.put("AKDT", new String[] { "America/Juneau", "America/Yakutat", + "America/Anchorage", "America/Nome" }); + tempMap.put("AKST", new String[] { "Asia/Aqtobe", "America/Juneau", + "America/Yakutat", "America/Anchorage", "America/Nome" }); + tempMap.put("AKT", new String[] { "Asia/Aqtobe" }); + tempMap.put("AKTST", new String[] { "Asia/Aqtobe" }); + tempMap.put("AKWT", new String[] { "America/Juneau", "America/Yakutat", + "America/Anchorage", "America/Nome" }); + tempMap.put("ALMST", new String[] { "Asia/Almaty" }); + tempMap.put("ALMT", new String[] { "Asia/Almaty" }); + tempMap.put("AMST", new String[] { "Asia/Yerevan", "America/Cuiaba", + "America/Porto_Velho", "America/Boa_Vista", "America/Manaus" }); + tempMap.put("AMT", new String[] { "Europe/Athens", "Europe/Amsterdam", + "Asia/Yerevan", "Africa/Asmera", "America/Cuiaba", + "America/Porto_Velho", "America/Boa_Vista", "America/Manaus", + "America/Asuncion" }); + tempMap.put("ANAMT", new String[] { "Asia/Anadyr" }); + tempMap.put("ANAST", new String[] { "Asia/Anadyr" }); + tempMap.put("ANAT", new String[] { "Asia/Anadyr" }); + tempMap.put("ANT", new String[] { "America/Aruba", "America/Curacao" }); + tempMap.put("AQTST", new String[] { "Asia/Aqtobe", "Asia/Aqtau" }); + tempMap.put("AQTT", new String[] { "Asia/Aqtobe", "Asia/Aqtau" }); + tempMap.put("ARST", new String[] { "Antarctica/Palmer", + "America/Buenos_Aires", "America/Rosario", "America/Cordoba", + "America/Jujuy", "America/Catamarca", "America/Mendoza" }); + tempMap.put("ART", new String[] { "Antarctica/Palmer", + "America/Buenos_Aires", "America/Rosario", "America/Cordoba", + "America/Jujuy", "America/Catamarca", "America/Mendoza" }); + tempMap.put("ASHST", new String[] { "Asia/Ashkhabad" }); + tempMap.put("ASHT", new String[] { "Asia/Ashkhabad" }); + tempMap.put("AST", new String[] { "Atlantic/Bermuda", "Asia/Bahrain", + "Asia/Baghdad", "Asia/Kuwait", "Asia/Qatar", "Asia/Riyadh", + "Asia/Aden", "America/Thule", "America/Goose_Bay", + "America/Halifax", "America/Glace_Bay", "America/Pangnirtung", + "America/Anguilla", "America/Antigua", "America/Barbados", + "America/Dominica", "America/Santo_Domingo", "America/Grenada", + "America/Guadeloupe", "America/Martinique", + "America/Montserrat", "America/Puerto_Rico", + "America/St_Kitts", "America/St_Lucia", "America/Miquelon", + "America/St_Vincent", "America/Tortola", "America/St_Thomas", + "America/Aruba", "America/Curacao", "America/Port_of_Spain" }); + tempMap.put("AWT", new String[] { "America/Puerto_Rico" }); + tempMap.put("AZOST", new String[] { "Atlantic/Azores" }); + tempMap.put("AZOT", new String[] { "Atlantic/Azores" }); + tempMap.put("AZST", new String[] { "Asia/Baku" }); + tempMap.put("AZT", new String[] { "Asia/Baku" }); + tempMap.put("BAKST", new String[] { "Asia/Baku" }); + tempMap.put("BAKT", new String[] { "Asia/Baku" }); + tempMap.put("BDT", new String[] { "Asia/Dacca", "America/Nome", + "America/Adak" }); + tempMap.put("BEAT", new String[] { "Africa/Nairobi", + "Africa/Mogadishu", "Africa/Kampala" }); + tempMap.put("BEAUT", new String[] { "Africa/Nairobi", + "Africa/Dar_es_Salaam", "Africa/Kampala" }); + tempMap.put("BMT", new String[] { "Europe/Brussels", "Europe/Chisinau", + "Europe/Tiraspol", "Europe/Bucharest", "Europe/Zurich", + "Asia/Baghdad", "Asia/Bangkok", "Africa/Banjul", + "America/Barbados", "America/Bogota" }); + tempMap.put("BNT", new String[] { "Asia/Brunei" }); + tempMap.put("BORT", + new String[] { "Asia/Ujung_Pandang", "Asia/Kuching" }); + tempMap.put("BOST", new String[] { "America/La_Paz" }); + tempMap.put("BOT", new String[] { "America/La_Paz" }); + tempMap.put("BRST", new String[] { "America/Belem", + "America/Fortaleza", "America/Araguaina", "America/Maceio", + "America/Sao_Paulo" }); + tempMap.put("BRT", new String[] { "America/Belem", "America/Fortaleza", + "America/Araguaina", "America/Maceio", "America/Sao_Paulo" }); + tempMap.put("BST", new String[] { "Europe/London", "Europe/Belfast", + "Europe/Dublin", "Europe/Gibraltar", "Pacific/Pago_Pago", + "Pacific/Midway", "America/Nome", "America/Adak" }); + tempMap.put("BTT", new String[] { "Asia/Thimbu" }); + tempMap.put("BURT", new String[] { "Asia/Dacca", "Asia/Rangoon", + "Asia/Calcutta" }); + tempMap.put("BWT", new String[] { "America/Nome", "America/Adak" }); + tempMap.put("CANT", new String[] { "Atlantic/Canary" }); + tempMap.put("CAST", + new String[] { "Africa/Gaborone", "Africa/Khartoum" }); + tempMap.put("CAT", new String[] { "Africa/Gaborone", + "Africa/Bujumbura", "Africa/Lubumbashi", "Africa/Blantyre", + "Africa/Maputo", "Africa/Windhoek", "Africa/Kigali", + "Africa/Khartoum", "Africa/Lusaka", "Africa/Harare", + "America/Anchorage" }); + tempMap.put("CCT", new String[] { "Indian/Cocos" }); + tempMap.put("CDDT", new String[] { "America/Rankin_Inlet" }); + tempMap.put("CDT", new String[] { "Asia/Harbin", "Asia/Shanghai", + "Asia/Chungking", "Asia/Urumqi", "Asia/Kashgar", "Asia/Taipei", + "Asia/Macao", "America/Chicago", "America/Indianapolis", + "America/Indiana/Marengo", "America/Indiana/Knox", + "America/Indiana/Vevay", "America/Louisville", + "America/Menominee", "America/Rainy_River", "America/Winnipeg", + "America/Pangnirtung", "America/Iqaluit", + "America/Rankin_Inlet", "America/Cambridge_Bay", + "America/Cancun", "America/Mexico_City", "America/Chihuahua", + "America/Belize", "America/Costa_Rica", "America/Havana", + "America/El_Salvador", "America/Guatemala", + "America/Tegucigalpa", "America/Managua" }); + tempMap.put("CEST", new String[] { "Europe/Tirane", "Europe/Andorra", + "Europe/Vienna", "Europe/Minsk", "Europe/Brussels", + "Europe/Sofia", "Europe/Prague", "Europe/Copenhagen", + "Europe/Tallinn", "Europe/Berlin", "Europe/Gibraltar", + "Europe/Athens", "Europe/Budapest", "Europe/Rome", + "Europe/Riga", "Europe/Vaduz", "Europe/Vilnius", + "Europe/Luxembourg", "Europe/Malta", "Europe/Chisinau", + "Europe/Tiraspol", "Europe/Monaco", "Europe/Amsterdam", + "Europe/Oslo", "Europe/Warsaw", "Europe/Lisbon", + "Europe/Kaliningrad", "Europe/Madrid", "Europe/Stockholm", + "Europe/Zurich", "Europe/Kiev", "Europe/Uzhgorod", + "Europe/Zaporozhye", "Europe/Simferopol", "Europe/Belgrade", + "Africa/Algiers", "Africa/Tripoli", "Africa/Tunis", + "Africa/Ceuta" }); + tempMap.put("CET", new String[] { "Europe/Tirane", "Europe/Andorra", + "Europe/Vienna", "Europe/Minsk", "Europe/Brussels", + "Europe/Sofia", "Europe/Prague", "Europe/Copenhagen", + "Europe/Tallinn", "Europe/Berlin", "Europe/Gibraltar", + "Europe/Athens", "Europe/Budapest", "Europe/Rome", + "Europe/Riga", "Europe/Vaduz", "Europe/Vilnius", + "Europe/Luxembourg", "Europe/Malta", "Europe/Chisinau", + "Europe/Tiraspol", "Europe/Monaco", "Europe/Amsterdam", + "Europe/Oslo", "Europe/Warsaw", "Europe/Lisbon", + "Europe/Kaliningrad", "Europe/Madrid", "Europe/Stockholm", + "Europe/Zurich", "Europe/Kiev", "Europe/Uzhgorod", + "Europe/Zaporozhye", "Europe/Simferopol", "Europe/Belgrade", + "Africa/Algiers", "Africa/Tripoli", "Africa/Casablanca", + "Africa/Tunis", "Africa/Ceuta" }); + tempMap.put("CGST", new String[] { "America/Scoresbysund" }); + tempMap.put("CGT", new String[] { "America/Scoresbysund" }); + tempMap.put("CHDT", new String[] { "America/Belize" }); + tempMap.put("CHUT", new String[] { "Asia/Chungking" }); + tempMap.put("CJT", new String[] { "Asia/Tokyo" }); + tempMap.put("CKHST", new String[] { "Pacific/Rarotonga" }); + tempMap.put("CKT", new String[] { "Pacific/Rarotonga" }); + tempMap.put("CLST", new String[] { "Antarctica/Palmer", + "America/Santiago" }); + tempMap.put("CLT", new String[] { "Antarctica/Palmer", + "America/Santiago" }); + tempMap.put("CMT", new String[] { "Europe/Copenhagen", + "Europe/Chisinau", "Europe/Tiraspol", "America/St_Lucia", + "America/Buenos_Aires", "America/Rosario", "America/Cordoba", + "America/Jujuy", "America/Catamarca", "America/Mendoza", + "America/Caracas" }); + tempMap.put("COST", new String[] { "America/Bogota" }); + tempMap.put("COT", new String[] { "America/Bogota" }); + tempMap + .put("CST", new String[] { "Asia/Harbin", "Asia/Shanghai", + "Asia/Chungking", "Asia/Urumqi", "Asia/Kashgar", + "Asia/Taipei", "Asia/Macao", "Asia/Jayapura", + "Australia/Darwin", "Australia/Adelaide", + "Australia/Broken_Hill", "America/Chicago", + "America/Indianapolis", "America/Indiana/Marengo", + "America/Indiana/Knox", "America/Indiana/Vevay", + "America/Louisville", "America/Detroit", + "America/Menominee", "America/Rainy_River", + "America/Winnipeg", "America/Regina", + "America/Swift_Current", "America/Pangnirtung", + "America/Iqaluit", "America/Rankin_Inlet", + "America/Cambridge_Bay", "America/Cancun", + "America/Mexico_City", "America/Chihuahua", + "America/Hermosillo", "America/Mazatlan", + "America/Belize", "America/Costa_Rica", + "America/Havana", "America/El_Salvador", + "America/Guatemala", "America/Tegucigalpa", + "America/Managua" }); + tempMap.put("CUT", new String[] { "Europe/Zaporozhye" }); + tempMap.put("CVST", new String[] { "Atlantic/Cape_Verde" }); + tempMap.put("CVT", new String[] { "Atlantic/Cape_Verde" }); + tempMap.put("CWT", new String[] { "America/Chicago", + "America/Indianapolis", "America/Indiana/Marengo", + "America/Indiana/Knox", "America/Indiana/Vevay", + "America/Louisville", "America/Menominee" }); + tempMap.put("CXT", new String[] { "Indian/Christmas" }); + tempMap.put("DACT", new String[] { "Asia/Dacca" }); + tempMap.put("DAVT", new String[] { "Antarctica/Davis" }); + tempMap.put("DDUT", new String[] { "Antarctica/DumontDUrville" }); + tempMap.put("DFT", new String[] { "Europe/Oslo", "Europe/Paris" }); + tempMap.put("DMT", new String[] { "Europe/Belfast", "Europe/Dublin" }); + tempMap.put("DUSST", new String[] { "Asia/Dushanbe" }); + tempMap.put("DUST", new String[] { "Asia/Dushanbe" }); + tempMap.put("EASST", new String[] { "Pacific/Easter" }); + tempMap.put("EAST", new String[] { "Indian/Antananarivo", + "Pacific/Easter" }); + tempMap.put("EAT", new String[] { "Indian/Comoro", + "Indian/Antananarivo", "Indian/Mayotte", "Africa/Djibouti", + "Africa/Asmera", "Africa/Addis_Ababa", "Africa/Nairobi", + "Africa/Mogadishu", "Africa/Khartoum", "Africa/Dar_es_Salaam", + "Africa/Kampala" }); + tempMap.put("ECT", new String[] { "Pacific/Galapagos", + "America/Guayaquil" }); + tempMap.put("EDDT", new String[] { "America/Iqaluit" }); + tempMap.put("EDT", new String[] { "America/New_York", + "America/Indianapolis", "America/Indiana/Marengo", + "America/Indiana/Vevay", "America/Louisville", + "America/Detroit", "America/Montreal", "America/Thunder_Bay", + "America/Nipigon", "America/Pangnirtung", "America/Iqaluit", + "America/Cancun", "America/Nassau", "America/Santo_Domingo", + "America/Port-au-Prince", "America/Jamaica", + "America/Grand_Turk" }); + tempMap.put("EEMT", new String[] { "Europe/Minsk", "Europe/Chisinau", + "Europe/Tiraspol", "Europe/Kaliningrad", "Europe/Moscow" }); + tempMap.put("EEST", new String[] { "Europe/Minsk", "Europe/Sofia", + "Europe/Tallinn", "Europe/Helsinki", "Europe/Athens", + "Europe/Riga", "Europe/Vilnius", "Europe/Chisinau", + "Europe/Tiraspol", "Europe/Warsaw", "Europe/Bucharest", + "Europe/Kaliningrad", "Europe/Moscow", "Europe/Istanbul", + "Europe/Kiev", "Europe/Uzhgorod", "Europe/Zaporozhye", + "Asia/Nicosia", "Asia/Amman", "Asia/Beirut", "Asia/Gaza", + "Asia/Damascus", "Africa/Cairo" }); + tempMap.put("EET", new String[] { "Europe/Minsk", "Europe/Sofia", + "Europe/Tallinn", "Europe/Helsinki", "Europe/Athens", + "Europe/Riga", "Europe/Vilnius", "Europe/Chisinau", + "Europe/Tiraspol", "Europe/Warsaw", "Europe/Bucharest", + "Europe/Kaliningrad", "Europe/Moscow", "Europe/Istanbul", + "Europe/Kiev", "Europe/Uzhgorod", "Europe/Zaporozhye", + "Europe/Simferopol", "Asia/Nicosia", "Asia/Amman", + "Asia/Beirut", "Asia/Gaza", "Asia/Damascus", "Africa/Cairo", + "Africa/Tripoli" }); + tempMap.put("EGST", new String[] { "America/Scoresbysund" }); + tempMap.put("EGT", new String[] { "Atlantic/Jan_Mayen", + "America/Scoresbysund" }); + tempMap.put("EHDT", new String[] { "America/Santo_Domingo" }); + tempMap.put("EST", new String[] { "Australia/Brisbane", + "Australia/Lindeman", "Australia/Hobart", + "Australia/Melbourne", "Australia/Sydney", + "Australia/Broken_Hill", "Australia/Lord_Howe", + "America/New_York", "America/Chicago", "America/Indianapolis", + "America/Indiana/Marengo", "America/Indiana/Knox", + "America/Indiana/Vevay", "America/Louisville", + "America/Detroit", "America/Menominee", "America/Montreal", + "America/Thunder_Bay", "America/Nipigon", + "America/Pangnirtung", "America/Iqaluit", "America/Cancun", + "America/Antigua", "America/Nassau", "America/Cayman", + "America/Santo_Domingo", "America/Port-au-Prince", + "America/Jamaica", "America/Managua", "America/Panama", + "America/Grand_Turk" }); + tempMap.put("EWT", new String[] { "America/New_York", + "America/Indianapolis", "America/Indiana/Marengo", + "America/Indiana/Vevay", "America/Louisville", + "America/Detroit", "America/Jamaica" }); + tempMap.put("FFMT", new String[] { "America/Martinique" }); + tempMap.put("FJST", new String[] { "Pacific/Fiji" }); + tempMap.put("FJT", new String[] { "Pacific/Fiji" }); + tempMap.put("FKST", new String[] { "Atlantic/Stanley" }); + tempMap.put("FKT", new String[] { "Atlantic/Stanley" }); + tempMap.put("FMT", + new String[] { "Atlantic/Madeira", "Africa/Freetown" }); + tempMap.put("FNST", new String[] { "America/Noronha" }); + tempMap.put("FNT", new String[] { "America/Noronha" }); + tempMap.put("FRUST", new String[] { "Asia/Bishkek" }); + tempMap.put("FRUT", new String[] { "Asia/Bishkek" }); + tempMap.put("GALT", new String[] { "Pacific/Galapagos" }); + tempMap.put("GAMT", new String[] { "Pacific/Gambier" }); + tempMap.put("GBGT", new String[] { "America/Guyana" }); + tempMap.put("GEST", new String[] { "Asia/Tbilisi" }); + tempMap.put("GET", new String[] { "Asia/Tbilisi" }); + tempMap.put("GFT", new String[] { "America/Cayenne" }); + tempMap.put("GHST", new String[] { "Africa/Accra" }); + tempMap.put("GILT", new String[] { "Pacific/Tarawa" }); + tempMap.put("GMT", new String[] { "Atlantic/St_Helena", + "Atlantic/Reykjavik", "Europe/London", "Europe/Belfast", + "Europe/Dublin", "Europe/Gibraltar", "Africa/Porto-Novo", + "Africa/Ouagadougou", "Africa/Abidjan", "Africa/Malabo", + "Africa/Banjul", "Africa/Accra", "Africa/Conakry", + "Africa/Bissau", "Africa/Monrovia", "Africa/Bamako", + "Africa/Timbuktu", "Africa/Nouakchott", "Africa/Niamey", + "Africa/Sao_Tome", "Africa/Dakar", "Africa/Freetown", + "Africa/Lome" }); + tempMap.put("GST", new String[] { "Atlantic/South_Georgia", + "Asia/Bahrain", "Asia/Muscat", "Asia/Qatar", "Asia/Dubai", + "Pacific/Guam" }); + tempMap.put("GYT", new String[] { "America/Guyana" }); + tempMap.put("HADT", new String[] { "America/Adak" }); + tempMap.put("HART", new String[] { "Asia/Harbin" }); + tempMap.put("HAST", new String[] { "America/Adak" }); + tempMap.put("HAWT", new String[] { "America/Adak" }); + tempMap.put("HDT", new String[] { "Pacific/Honolulu" }); + tempMap.put("HKST", new String[] { "Asia/Hong_Kong" }); + tempMap.put("HKT", new String[] { "Asia/Hong_Kong" }); + tempMap.put("HMT", new String[] { "Atlantic/Azores", "Europe/Helsinki", + "Asia/Dacca", "Asia/Calcutta", "America/Havana" }); + tempMap.put("HOVST", new String[] { "Asia/Hovd" }); + tempMap.put("HOVT", new String[] { "Asia/Hovd" }); + tempMap.put("HST", new String[] { "Pacific/Johnston", + "Pacific/Honolulu" }); + tempMap.put("HWT", new String[] { "Pacific/Honolulu" }); + tempMap.put("ICT", new String[] { "Asia/Phnom_Penh", "Asia/Vientiane", + "Asia/Bangkok", "Asia/Saigon" }); + tempMap.put("IDDT", new String[] { "Asia/Jerusalem", "Asia/Gaza" }); + tempMap.put("IDT", new String[] { "Asia/Jerusalem", "Asia/Gaza" }); + tempMap.put("IHST", new String[] { "Asia/Colombo" }); + tempMap.put("IMT", new String[] { "Europe/Sofia", "Europe/Istanbul", + "Asia/Irkutsk" }); + tempMap.put("IOT", new String[] { "Indian/Chagos" }); + tempMap.put("IRKMT", new String[] { "Asia/Irkutsk" }); + tempMap.put("IRKST", new String[] { "Asia/Irkutsk" }); + tempMap.put("IRKT", new String[] { "Asia/Irkutsk" }); + tempMap.put("IRST", new String[] { "Asia/Tehran" }); + tempMap.put("IRT", new String[] { "Asia/Tehran" }); + tempMap.put("ISST", new String[] { "Atlantic/Reykjavik" }); + tempMap.put("IST", new String[] { "Atlantic/Reykjavik", + "Europe/Belfast", "Europe/Dublin", "Asia/Dacca", "Asia/Thimbu", + "Asia/Calcutta", "Asia/Jerusalem", "Asia/Katmandu", + "Asia/Karachi", "Asia/Gaza", "Asia/Colombo" }); + tempMap.put("JAYT", new String[] { "Asia/Jayapura" }); + tempMap.put("JMT", new String[] { "Atlantic/St_Helena", + "Asia/Jerusalem" }); + tempMap.put("JST", new String[] { "Asia/Rangoon", "Asia/Dili", + "Asia/Ujung_Pandang", "Asia/Tokyo", "Asia/Kuala_Lumpur", + "Asia/Kuching", "Asia/Manila", "Asia/Singapore", + "Pacific/Nauru" }); + tempMap.put("KART", new String[] { "Asia/Karachi" }); + tempMap.put("KAST", new String[] { "Asia/Kashgar" }); + tempMap.put("KDT", new String[] { "Asia/Seoul" }); + tempMap.put("KGST", new String[] { "Asia/Bishkek" }); + tempMap.put("KGT", new String[] { "Asia/Bishkek" }); + tempMap.put("KMT", new String[] { "Europe/Vilnius", "Europe/Kiev", + "America/Cayman", "America/Jamaica", "America/St_Vincent", + "America/Grand_Turk" }); + tempMap.put("KOST", new String[] { "Pacific/Kosrae" }); + tempMap.put("KRAMT", new String[] { "Asia/Krasnoyarsk" }); + tempMap.put("KRAST", new String[] { "Asia/Krasnoyarsk" }); + tempMap.put("KRAT", new String[] { "Asia/Krasnoyarsk" }); + tempMap.put("KST", new String[] { "Asia/Seoul", "Asia/Pyongyang" }); + tempMap.put("KUYMT", new String[] { "Europe/Samara" }); + tempMap.put("KUYST", new String[] { "Europe/Samara" }); + tempMap.put("KUYT", new String[] { "Europe/Samara" }); + tempMap.put("KWAT", new String[] { "Pacific/Kwajalein" }); + tempMap.put("LHST", new String[] { "Australia/Lord_Howe" }); + tempMap.put("LINT", new String[] { "Pacific/Kiritimati" }); + tempMap.put("LKT", new String[] { "Asia/Colombo" }); + tempMap.put("LPMT", new String[] { "America/La_Paz" }); + tempMap.put("LRT", new String[] { "Africa/Monrovia" }); + tempMap.put("LST", new String[] { "Europe/Riga" }); + tempMap.put("M", new String[] { "Europe/Moscow" }); + tempMap.put("MADST", new String[] { "Atlantic/Madeira" }); + tempMap.put("MAGMT", new String[] { "Asia/Magadan" }); + tempMap.put("MAGST", new String[] { "Asia/Magadan" }); + tempMap.put("MAGT", new String[] { "Asia/Magadan" }); + tempMap.put("MALT", new String[] { "Asia/Kuala_Lumpur", + "Asia/Singapore" }); + tempMap.put("MART", new String[] { "Pacific/Marquesas" }); + tempMap.put("MAWT", new String[] { "Antarctica/Mawson" }); + tempMap.put("MDDT", new String[] { "America/Cambridge_Bay", + "America/Yellowknife", "America/Inuvik" }); + tempMap.put("MDST", new String[] { "Europe/Moscow" }); + tempMap.put("MDT", new String[] { "America/Denver", "America/Phoenix", + "America/Boise", "America/Regina", "America/Swift_Current", + "America/Edmonton", "America/Cambridge_Bay", + "America/Yellowknife", "America/Inuvik", "America/Chihuahua", + "America/Hermosillo", "America/Mazatlan" }); + tempMap.put("MET", new String[] { "Europe/Tirane", "Europe/Andorra", + "Europe/Vienna", "Europe/Minsk", "Europe/Brussels", + "Europe/Sofia", "Europe/Prague", "Europe/Copenhagen", + "Europe/Tallinn", "Europe/Berlin", "Europe/Gibraltar", + "Europe/Athens", "Europe/Budapest", "Europe/Rome", + "Europe/Riga", "Europe/Vaduz", "Europe/Vilnius", + "Europe/Luxembourg", "Europe/Malta", "Europe/Chisinau", + "Europe/Tiraspol", "Europe/Monaco", "Europe/Amsterdam", + "Europe/Oslo", "Europe/Warsaw", "Europe/Lisbon", + "Europe/Kaliningrad", "Europe/Madrid", "Europe/Stockholm", + "Europe/Zurich", "Europe/Kiev", "Europe/Uzhgorod", + "Europe/Zaporozhye", "Europe/Simferopol", "Europe/Belgrade", + "Africa/Algiers", "Africa/Tripoli", "Africa/Casablanca", + "Africa/Tunis", "Africa/Ceuta" }); + tempMap.put("MHT", + new String[] { "Pacific/Majuro", "Pacific/Kwajalein" }); + tempMap.put("MMT", new String[] { "Indian/Maldives", "Europe/Minsk", + "Europe/Moscow", "Asia/Rangoon", "Asia/Ujung_Pandang", + "Asia/Colombo", "Pacific/Easter", "Africa/Monrovia", + "America/Managua", "America/Montevideo" }); + tempMap.put("MOST", new String[] { "Asia/Macao" }); + tempMap.put("MOT", new String[] { "Asia/Macao" }); + tempMap.put("MPT", new String[] { "Pacific/Saipan" }); + tempMap.put("MSK", new String[] { "Europe/Minsk", "Europe/Tallinn", + "Europe/Riga", "Europe/Vilnius", "Europe/Chisinau", + "Europe/Kiev", "Europe/Uzhgorod", "Europe/Zaporozhye", + "Europe/Simferopol" }); + tempMap.put("MST", new String[] { "Europe/Moscow", "America/Denver", + "America/Phoenix", "America/Boise", "America/Regina", + "America/Swift_Current", "America/Edmonton", + "America/Dawson_Creek", "America/Cambridge_Bay", + "America/Yellowknife", "America/Inuvik", "America/Mexico_City", + "America/Chihuahua", "America/Hermosillo", "America/Mazatlan", + "America/Tijuana" }); + tempMap.put("MUT", new String[] { "Indian/Mauritius" }); + tempMap.put("MVT", new String[] { "Indian/Maldives" }); + tempMap.put("MWT", new String[] { "America/Denver", "America/Phoenix", + "America/Boise" }); + tempMap + .put("MYT", + new String[] { "Asia/Kuala_Lumpur", "Asia/Kuching" }); + tempMap.put("NCST", new String[] { "Pacific/Noumea" }); + tempMap.put("NCT", new String[] { "Pacific/Noumea" }); + tempMap.put("NDT", new String[] { "America/Nome", "America/Adak", + "America/St_Johns", "America/Goose_Bay" }); + tempMap.put("NEGT", new String[] { "America/Paramaribo" }); + tempMap.put("NFT", new String[] { "Europe/Paris", "Europe/Oslo", + "Pacific/Norfolk" }); + tempMap.put("NMT", new String[] { "Pacific/Norfolk" }); + tempMap.put("NOVMT", new String[] { "Asia/Novosibirsk" }); + tempMap.put("NOVST", new String[] { "Asia/Novosibirsk" }); + tempMap.put("NOVT", new String[] { "Asia/Novosibirsk" }); + tempMap.put("NPT", new String[] { "Asia/Katmandu" }); + tempMap.put("NRT", new String[] { "Pacific/Nauru" }); + tempMap.put("NST", new String[] { "Europe/Amsterdam", + "Pacific/Pago_Pago", "Pacific/Midway", "America/Nome", + "America/Adak", "America/St_Johns", "America/Goose_Bay" }); + tempMap.put("NUT", new String[] { "Pacific/Niue" }); + tempMap.put("NWT", new String[] { "America/Nome", "America/Adak" }); + tempMap.put("NZDT", new String[] { "Antarctica/McMurdo" }); + tempMap.put("NZHDT", new String[] { "Pacific/Auckland" }); + tempMap.put("NZST", new String[] { "Antarctica/McMurdo", + "Pacific/Auckland" }); + tempMap.put("OMSMT", new String[] { "Asia/Omsk" }); + tempMap.put("OMSST", new String[] { "Asia/Omsk" }); + tempMap.put("OMST", new String[] { "Asia/Omsk" }); + tempMap.put("PDDT", new String[] { "America/Inuvik", + "America/Whitehorse", "America/Dawson" }); + tempMap.put("PDT", new String[] { "America/Los_Angeles", + "America/Juneau", "America/Boise", "America/Vancouver", + "America/Dawson_Creek", "America/Inuvik", "America/Whitehorse", + "America/Dawson", "America/Tijuana" }); + tempMap.put("PEST", new String[] { "America/Lima" }); + tempMap.put("PET", new String[] { "America/Lima" }); + tempMap.put("PETMT", new String[] { "Asia/Kamchatka" }); + tempMap.put("PETST", new String[] { "Asia/Kamchatka" }); + tempMap.put("PETT", new String[] { "Asia/Kamchatka" }); + tempMap.put("PGT", new String[] { "Pacific/Port_Moresby" }); + tempMap.put("PHOT", new String[] { "Pacific/Enderbury" }); + tempMap.put("PHST", new String[] { "Asia/Manila" }); + tempMap.put("PHT", new String[] { "Asia/Manila" }); + tempMap.put("PKT", new String[] { "Asia/Karachi" }); + tempMap.put("PMDT", new String[] { "America/Miquelon" }); + tempMap.put("PMMT", new String[] { "Pacific/Port_Moresby" }); + tempMap.put("PMST", new String[] { "America/Miquelon" }); + tempMap.put("PMT", new String[] { "Antarctica/DumontDUrville", + "Europe/Prague", "Europe/Paris", "Europe/Monaco", + "Africa/Algiers", "Africa/Tunis", "America/Panama", + "America/Paramaribo" }); + tempMap.put("PNT", new String[] { "Pacific/Pitcairn" }); + tempMap.put("PONT", new String[] { "Pacific/Ponape" }); + tempMap.put("PPMT", new String[] { "America/Port-au-Prince" }); + tempMap.put("PST", new String[] { "Pacific/Pitcairn", + "America/Los_Angeles", "America/Juneau", "America/Boise", + "America/Vancouver", "America/Dawson_Creek", "America/Inuvik", + "America/Whitehorse", "America/Dawson", "America/Hermosillo", + "America/Mazatlan", "America/Tijuana" }); + tempMap.put("PWT", new String[] { "Pacific/Palau", + "America/Los_Angeles", "America/Juneau", "America/Boise", + "America/Tijuana" }); + tempMap.put("PYST", new String[] { "America/Asuncion" }); + tempMap.put("PYT", new String[] { "America/Asuncion" }); + tempMap.put("QMT", new String[] { "America/Guayaquil" }); + tempMap.put("RET", new String[] { "Indian/Reunion" }); + tempMap.put("RMT", new String[] { "Atlantic/Reykjavik", "Europe/Rome", + "Europe/Riga", "Asia/Rangoon" }); + tempMap.put("S", new String[] { "Europe/Moscow" }); + tempMap.put("SAMMT", new String[] { "Europe/Samara" }); + tempMap + .put("SAMST", + new String[] { "Europe/Samara", "Asia/Samarkand" }); + tempMap.put("SAMT", new String[] { "Europe/Samara", "Asia/Samarkand", + "Pacific/Pago_Pago", "Pacific/Apia" }); + tempMap.put("SAST", new String[] { "Africa/Maseru", "Africa/Windhoek", + "Africa/Johannesburg", "Africa/Mbabane" }); + tempMap.put("SBT", new String[] { "Pacific/Guadalcanal" }); + tempMap.put("SCT", new String[] { "Indian/Mahe" }); + tempMap.put("SDMT", new String[] { "America/Santo_Domingo" }); + tempMap.put("SGT", new String[] { "Asia/Singapore" }); + tempMap.put("SHEST", new String[] { "Asia/Aqtau" }); + tempMap.put("SHET", new String[] { "Asia/Aqtau" }); + tempMap.put("SJMT", new String[] { "America/Costa_Rica" }); + tempMap.put("SLST", new String[] { "Africa/Freetown" }); + tempMap.put("SMT", new String[] { "Atlantic/Stanley", + "Europe/Stockholm", "Europe/Simferopol", "Asia/Phnom_Penh", + "Asia/Vientiane", "Asia/Kuala_Lumpur", "Asia/Singapore", + "Asia/Saigon", "America/Santiago" }); + tempMap.put("SRT", new String[] { "America/Paramaribo" }); + tempMap.put("SST", + new String[] { "Pacific/Pago_Pago", "Pacific/Midway" }); + tempMap.put("SVEMT", new String[] { "Asia/Yekaterinburg" }); + tempMap.put("SVEST", new String[] { "Asia/Yekaterinburg" }); + tempMap.put("SVET", new String[] { "Asia/Yekaterinburg" }); + tempMap.put("SWAT", new String[] { "Africa/Windhoek" }); + tempMap.put("SYOT", new String[] { "Antarctica/Syowa" }); + tempMap.put("TAHT", new String[] { "Pacific/Tahiti" }); + tempMap + .put("TASST", + new String[] { "Asia/Samarkand", "Asia/Tashkent" }); + tempMap.put("TAST", new String[] { "Asia/Samarkand", "Asia/Tashkent" }); + tempMap.put("TBIST", new String[] { "Asia/Tbilisi" }); + tempMap.put("TBIT", new String[] { "Asia/Tbilisi" }); + tempMap.put("TBMT", new String[] { "Asia/Tbilisi" }); + tempMap.put("TFT", new String[] { "Indian/Kerguelen" }); + tempMap.put("TJT", new String[] { "Asia/Dushanbe" }); + tempMap.put("TKT", new String[] { "Pacific/Fakaofo" }); + tempMap.put("TMST", new String[] { "Asia/Ashkhabad" }); + tempMap.put("TMT", new String[] { "Europe/Tallinn", "Asia/Tehran", + "Asia/Ashkhabad" }); + tempMap.put("TOST", new String[] { "Pacific/Tongatapu" }); + tempMap.put("TOT", new String[] { "Pacific/Tongatapu" }); + tempMap.put("TPT", new String[] { "Asia/Dili" }); + tempMap.put("TRST", new String[] { "Europe/Istanbul" }); + tempMap.put("TRT", new String[] { "Europe/Istanbul" }); + tempMap.put("TRUT", new String[] { "Pacific/Truk" }); + tempMap.put("TVT", new String[] { "Pacific/Funafuti" }); + tempMap.put("ULAST", new String[] { "Asia/Ulaanbaatar" }); + tempMap.put("ULAT", new String[] { "Asia/Ulaanbaatar" }); + tempMap.put("URUT", new String[] { "Asia/Urumqi" }); + tempMap.put("UYHST", new String[] { "America/Montevideo" }); + tempMap.put("UYT", new String[] { "America/Montevideo" }); + tempMap.put("UZST", new String[] { "Asia/Samarkand", "Asia/Tashkent" }); + tempMap.put("UZT", new String[] { "Asia/Samarkand", "Asia/Tashkent" }); + tempMap.put("VET", new String[] { "America/Caracas" }); + tempMap.put("VLAMT", new String[] { "Asia/Vladivostok" }); + tempMap.put("VLAST", new String[] { "Asia/Vladivostok" }); + tempMap.put("VLAT", new String[] { "Asia/Vladivostok" }); + tempMap.put("VUST", new String[] { "Pacific/Efate" }); + tempMap.put("VUT", new String[] { "Pacific/Efate" }); + tempMap.put("WAKT", new String[] { "Pacific/Wake" }); + tempMap.put("WARST", + new String[] { "America/Jujuy", "America/Mendoza" }); + tempMap + .put("WART", + new String[] { "America/Jujuy", "America/Mendoza" }); + tempMap.put("WAST", + new String[] { "Africa/Ndjamena", "Africa/Windhoek" }); + tempMap.put("WAT", new String[] { "Africa/Luanda", "Africa/Porto-Novo", + "Africa/Douala", "Africa/Bangui", "Africa/Ndjamena", + "Africa/Kinshasa", "Africa/Brazzaville", "Africa/Malabo", + "Africa/Libreville", "Africa/Banjul", "Africa/Conakry", + "Africa/Bissau", "Africa/Bamako", "Africa/Nouakchott", + "Africa/El_Aaiun", "Africa/Windhoek", "Africa/Niamey", + "Africa/Lagos", "Africa/Dakar", "Africa/Freetown" }); + tempMap.put("WEST", new String[] { "Atlantic/Faeroe", + "Atlantic/Azores", "Atlantic/Madeira", "Atlantic/Canary", + "Europe/Brussels", "Europe/Luxembourg", "Europe/Monaco", + "Europe/Lisbon", "Europe/Madrid", "Africa/Algiers", + "Africa/Casablanca", "Africa/Ceuta" }); + tempMap.put("WET", new String[] { "Atlantic/Faeroe", "Atlantic/Azores", + "Atlantic/Madeira", "Atlantic/Canary", "Europe/Andorra", + "Europe/Brussels", "Europe/Luxembourg", "Europe/Monaco", + "Europe/Lisbon", "Europe/Madrid", "Africa/Algiers", + "Africa/Casablanca", "Africa/El_Aaiun", "Africa/Ceuta" }); + tempMap.put("WFT", new String[] { "Pacific/Wallis" }); + tempMap.put("WGST", new String[] { "America/Godthab" }); + tempMap.put("WGT", new String[] { "America/Godthab" }); + tempMap.put("WMT", new String[] { "Europe/Vilnius", "Europe/Warsaw" }); + tempMap.put("WST", new String[] { "Antarctica/Casey", "Pacific/Apia", + "Australia/Perth" }); + tempMap.put("YAKMT", new String[] { "Asia/Yakutsk" }); + tempMap.put("YAKST", new String[] { "Asia/Yakutsk" }); + tempMap.put("YAKT", new String[] { "Asia/Yakutsk" }); + tempMap.put("YAPT", new String[] { "Pacific/Yap" }); + tempMap.put("YDDT", new String[] { "America/Whitehorse", + "America/Dawson" }); + tempMap.put("YDT", new String[] { "America/Yakutat", + "America/Whitehorse", "America/Dawson" }); + tempMap.put("YEKMT", new String[] { "Asia/Yekaterinburg" }); + tempMap.put("YEKST", new String[] { "Asia/Yekaterinburg" }); + tempMap.put("YEKT", new String[] { "Asia/Yekaterinburg" }); + tempMap.put("YERST", new String[] { "Asia/Yerevan" }); + tempMap.put("YERT", new String[] { "Asia/Yerevan" }); + tempMap.put("YST", new String[] { "America/Yakutat", + "America/Whitehorse", "America/Dawson" }); + tempMap.put("YWT", new String[] { "America/Yakutat" }); + + ABBREVIATED_TIMEZONES = Collections.unmodifiableMap(tempMap); + } + + /** + * Change the given times from one timezone to another + * + * @param conn + * the current connection to the MySQL server + * @param t + * the times to change + * @param fromTz + * the timezone to change from + * @param toTz + * the timezone to change to + * + * @return the times changed to the timezone 'toTz' + */ + public static Time changeTimezone(Connection conn, + Calendar sessionCalendar, + Calendar targetCalendar, + Time t, + TimeZone fromTz, + TimeZone toTz, + boolean rollForward) { + if ((conn != null)) { + if (conn.getUseTimezone() && + !conn.getNoTimezoneConversionForTimeType()) { + // Convert the timestamp from GMT to the server's timezone + Calendar fromCal = Calendar.getInstance(fromTz); + fromCal.setTime(t); + + int fromOffset = fromCal.get(Calendar.ZONE_OFFSET) + + fromCal.get(Calendar.DST_OFFSET); + Calendar toCal = Calendar.getInstance(toTz); + toCal.setTime(t); + + int toOffset = toCal.get(Calendar.ZONE_OFFSET) + + toCal.get(Calendar.DST_OFFSET); + int offsetDiff = fromOffset - toOffset; + long toTime = toCal.getTime().getTime(); + + if (rollForward || (conn.isServerTzUTC() && !conn.isClientTzUTC())) { + toTime += offsetDiff; + } else { + toTime -= offsetDiff; + } + + Time changedTime = new Time(toTime); + + return changedTime; + } else if (conn.getUseJDBCCompliantTimezoneShift()) { + if (targetCalendar != null) { + + Time adjustedTime = new Time( + jdbcCompliantZoneShift(sessionCalendar, + targetCalendar, t)); + + return adjustedTime; + } + } + } + + return t; + } + + /** + * Change the given timestamp from one timezone to another + * + * @param conn + * the current connection to the MySQL server + * @param tstamp + * the timestamp to change + * @param fromTz + * the timezone to change from + * @param toTz + * the timezone to change to + * + * @return the timestamp changed to the timezone 'toTz' + */ + public static Timestamp changeTimezone(Connection conn, + Calendar sessionCalendar, + Calendar targetCalendar, + Timestamp tstamp, + TimeZone fromTz, + TimeZone toTz, + boolean rollForward) { + if ((conn != null)) { + if (conn.getUseTimezone()) { + // Convert the timestamp from GMT to the server's timezone + Calendar fromCal = Calendar.getInstance(fromTz); + fromCal.setTime(tstamp); + + int fromOffset = fromCal.get(Calendar.ZONE_OFFSET) + + fromCal.get(Calendar.DST_OFFSET); + Calendar toCal = Calendar.getInstance(toTz); + toCal.setTime(tstamp); + + int toOffset = toCal.get(Calendar.ZONE_OFFSET) + + toCal.get(Calendar.DST_OFFSET); + int offsetDiff = fromOffset - toOffset; + long toTime = toCal.getTime().getTime(); + + if (rollForward || (conn.isServerTzUTC() && !conn.isClientTzUTC())) { + toTime += offsetDiff; + } else { + toTime -= offsetDiff; + } + + Timestamp changedTimestamp = new Timestamp(toTime); + + return changedTimestamp; + } else if (conn.getUseJDBCCompliantTimezoneShift()) { + if (targetCalendar != null) { + + Timestamp adjustedTimestamp = new Timestamp( + jdbcCompliantZoneShift(sessionCalendar, + targetCalendar, tstamp)); + + adjustedTimestamp.setNanos(tstamp.getNanos()); + + return adjustedTimestamp; + } + } + } + + return tstamp; + } + + private static long jdbcCompliantZoneShift(Calendar sessionCalendar, + Calendar targetCalendar, + java.util.Date dt) { + if (sessionCalendar == null) { + sessionCalendar = new GregorianCalendar(); + } + + // JDBC spec is not clear whether or not this + // calendar should be immutable, so let's treat + // it like it is, for safety + + java.util.Date origCalDate = targetCalendar.getTime(); + java.util.Date origSessionDate = sessionCalendar.getTime(); + + try { + sessionCalendar.setTime(dt); + + targetCalendar.set(Calendar.YEAR, sessionCalendar.get(Calendar.YEAR)); + targetCalendar.set(Calendar.MONTH, sessionCalendar.get(Calendar.MONTH)); + targetCalendar.set(Calendar.DAY_OF_MONTH, sessionCalendar.get(Calendar.DAY_OF_MONTH)); + + targetCalendar.set(Calendar.HOUR_OF_DAY, sessionCalendar.get(Calendar.HOUR_OF_DAY)); + targetCalendar.set(Calendar.MINUTE, sessionCalendar.get(Calendar.MINUTE)); + targetCalendar.set(Calendar.SECOND, sessionCalendar.get(Calendar.SECOND)); + targetCalendar.set(Calendar.MILLISECOND, sessionCalendar.get(Calendar.MILLISECOND)); + + return targetCalendar.getTime().getTime(); + + } finally { + sessionCalendar.setTime(origSessionDate); + targetCalendar.setTime(origCalDate); + } + } + + // + // WARN! You must externally synchronize these calendar instances + // See ResultSet.fastDateCreate() for an example + // + final static Date fastDateCreate(boolean useGmtConversion, + Calendar gmtCalIfNeeded, + Calendar cal, int year, int month, int day) { + + Calendar dateCal = cal; + + if (useGmtConversion) { + + if (gmtCalIfNeeded == null) { + gmtCalIfNeeded = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + } + gmtCalIfNeeded.clear(); + + dateCal = gmtCalIfNeeded; + } + + dateCal.clear(); + + // why-oh-why is this different than java.util.date, + // in the year part, but it still keeps the silly '0' + // for the start month???? + dateCal.set(year, month - 1, day, 0, 0, 0); + + long dateAsMillis = 0; + + try { + dateAsMillis = dateCal.getTimeInMillis(); + } catch (IllegalAccessError iae) { + // Must be on JDK-1.3.1 or older.... + dateAsMillis = dateCal.getTime().getTime(); + } + + return new Date(dateAsMillis); + } + + final static Time fastTimeCreate(Calendar cal, int hour, int minute, + int second) throws SQLException { + if (hour < 0 || hour > 23) { + throw SQLError.createSQLException("Illegal hour value '" + hour + "' for java.sql.Time type in value '" + + timeFormattedString(hour, minute, second) + ".", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (minute < 0 || minute > 59) { + throw SQLError.createSQLException("Illegal minute value '" + minute + "'" + "' for java.sql.Time type in value '" + + timeFormattedString(hour, minute, second) + ".", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (second < 0 || second > 59) { + throw SQLError.createSQLException("Illegal minute value '" + second + "'" + "' for java.sql.Time type in value '" + + timeFormattedString(hour, minute, second) + ".", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + cal.clear(); + + // Set 'date' to epoch of Jan 1, 1970 + cal.set(1970, 0, 1, hour, minute, second); + + long timeAsMillis = 0; + + try { + timeAsMillis = cal.getTimeInMillis(); + } catch (IllegalAccessError iae) { + // Must be on JDK-1.3.1 or older.... + timeAsMillis = cal.getTime().getTime(); + } + + return new Time(timeAsMillis); + } + + final static Timestamp fastTimestampCreate(boolean useGmtConversion, + Calendar gmtCalIfNeeded, + Calendar cal, int year, + int month, int day, int hour, int minute, int seconds, + int secondsPart) { + cal.clear(); + + // why-oh-why is this different than java.util.date, + // in the year part, but it still keeps the silly '0' + // for the start month???? + cal.set(year, month - 1, day, hour, minute, seconds); + + int offsetDiff = 0; + + if (useGmtConversion) { + int fromOffset = cal.get(Calendar.ZONE_OFFSET) + + cal.get(Calendar.DST_OFFSET); + + if (gmtCalIfNeeded == null) { + gmtCalIfNeeded = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + } + gmtCalIfNeeded.clear(); + + gmtCalIfNeeded.setTimeInMillis(cal.getTimeInMillis()); + + int toOffset = gmtCalIfNeeded.get(Calendar.ZONE_OFFSET) + + gmtCalIfNeeded.get(Calendar.DST_OFFSET); + offsetDiff = fromOffset - toOffset; + } + + long tsAsMillis = 0; + + try { + tsAsMillis = cal.getTimeInMillis(); + } catch (IllegalAccessError iae) { + // Must be on JDK-1.3.1 or older.... + tsAsMillis = cal.getTime().getTime(); + } + + Timestamp ts = new Timestamp(tsAsMillis + offsetDiff); + ts.setNanos(secondsPart); + + return ts; + } + + /** + * Returns the 'official' Java timezone name for the given timezone + * + * @param timezoneStr + * the 'common' timezone name + * + * @return the Java timezone name for the given timezone + * + * @throws IllegalArgumentException + * DOCUMENT ME! + */ + public static String getCanoncialTimezone(String timezoneStr) { + if (timezoneStr == null) { + return null; + } + + timezoneStr = timezoneStr.trim(); + + // Fix windows Daylight/Standard shift JDK doesn't map these (doh) + + int daylightIndex = StringUtils.indexOfIgnoreCase(timezoneStr, + "DAYLIGHT"); + + if (daylightIndex != -1) { + StringBuffer timezoneBuf = new StringBuffer(); + timezoneBuf.append(timezoneStr.substring(0, daylightIndex)); + timezoneBuf.append("Standard"); + timezoneBuf.append(timezoneStr.substring(daylightIndex + + "DAYLIGHT".length(), timezoneStr.length())); + timezoneStr = timezoneBuf.toString(); + } + + String canonicalTz = (String) TIMEZONE_MAPPINGS.get(timezoneStr); + + // if we didn't find it, try abbreviated timezones + if (canonicalTz == null) { + String[] abbreviatedTimezone = (String[]) ABBREVIATED_TIMEZONES + .get(timezoneStr); + + if (abbreviatedTimezone != null) { + // If there's only one mapping use that + if (abbreviatedTimezone.length == 1) { + canonicalTz = abbreviatedTimezone[0]; + } else { + StringBuffer errorMsg = new StringBuffer( + "The server timezone value '"); + errorMsg.append(timezoneStr); + errorMsg + .append("' represents more than one timezone. You must "); + errorMsg + .append("configure either the server or client to use a "); + errorMsg + .append("more specifc timezone value if you want to enable "); + errorMsg.append("timezone support. The timezones that '"); + errorMsg.append(timezoneStr); + errorMsg.append("' maps to are: "); + errorMsg.append(abbreviatedTimezone[0]); + + for (int i = 1; i < abbreviatedTimezone.length; i++) { + errorMsg.append(", "); + errorMsg.append(abbreviatedTimezone[i]); + } + + throw new IllegalArgumentException(errorMsg.toString()); + } + } + } + + return canonicalTz; + } + + // we could use SimpleDateFormat, but it won't work when the time values + // are out-of-bounds, and we're using this for error messages for exactly + // that case + // + + private static String timeFormattedString(int hours, int minutes, int seconds) { + StringBuffer buf = new StringBuffer(8); + + if (hours < 10) { + buf.append("0"); + } + + buf.append(hours); + buf.append(":"); + + if (minutes < 10) { + buf.append("0"); + } + + buf.append(minutes); + buf.append(":"); + + if (seconds < 10) { + buf.append("0"); + } + + buf.append(seconds); + + return buf.toString(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/UpdatableResultSet.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/UpdatableResultSet.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/UpdatableResultSet.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,2506 @@ +/* + Copyright (C) 2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import com.mysql.jdbc.profiler.ProfileEventSink; +import com.mysql.jdbc.profiler.ProfilerEvent; + +import java.math.BigDecimal; + +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * A result set that is updatable. + * + * @author Mark Matthews + */ +public class UpdatableResultSet extends ResultSet { + /** Marker for 'stream' data when doing INSERT rows */ + private final static byte[] STREAM_DATA_MARKER = "** STREAM DATA **" //$NON-NLS-1$ + .getBytes(); + + private SingleByteCharsetConverter charConverter; + + private String charEncoding; + + /** What is the default value for the column? */ + private byte[][] defaultColumnValue; + + /** PreparedStatement used to delete data */ + private com.mysql.jdbc.PreparedStatement deleter = null; + + private String deleteSQL = null; + + private boolean initializedCharConverter = false; + + /** PreparedStatement used to insert data */ + private com.mysql.jdbc.PreparedStatement inserter = null; + + private String insertSQL = null; + + /** Is this result set updateable? */ + private boolean isUpdatable = false; + + /** Reason the result set is not updatable */ + private String notUpdatableReason = null; + + /** List of primary keys */ + private List primaryKeyIndicies = null; + + private String qualifiedAndQuotedTableName; + + private String quotedIdChar = null; + + /** PreparedStatement used to refresh data */ + private com.mysql.jdbc.PreparedStatement refresher; + + private String refreshSQL = null; + + /** The binary data for the 'current' row */ + private Object[] savedCurrentRow; + + private String tableOnlyName; + + /** PreparedStatement used to delete data */ + private com.mysql.jdbc.PreparedStatement updater = null; + + /** SQL for in-place modifcation */ + private String updateSQL = null; + + private boolean populateInserterWithDefaultValues = false; + + /** + * Create a result set for an executeUpdate statement. + * + * @param updateCount + * the number of rows affected by the update + * @param updateID + * the autoincrement value (if any) + * @param conn + * DOCUMENT ME! + * @param creatorStmt + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public UpdatableResultSet(long updateCount, long updateID, Connection conn, + Statement creatorStmt) throws SQLException { + super(updateCount, updateID, conn, creatorStmt); + checkUpdatability(); + } + + /** + * Creates a new ResultSet object. + * + * @param catalog + * the database in use when we were created + * @param fields + * an array of Field objects (basically, the ResultSet MetaData) + * @param tuples + * actual row data + * @param conn + * the Connection that created us. + * @param creatorStmt + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public UpdatableResultSet(String catalog, Field[] fields, RowData tuples, + Connection conn, Statement creatorStmt) throws SQLException { + super(catalog, fields, tuples, conn, creatorStmt); + checkUpdatability(); + this.populateInserterWithDefaultValues = + this.connection.getPopulateInsertRowWithDefaultValues(); + } + + /** + * JDBC 2.0 + * + *

+ * Move to an absolute row number in the result set. + *

+ * + *

+ * If row is positive, moves to an absolute row with respect to the + * beginning of the result set. The first row is row 1, the second is row 2, + * etc. + *

+ * + *

+ * If row is negative, moves to an absolute row position with respect to the + * end of result set. For example, calling absolute(-1) positions the cursor + * on the last row, absolute(-2) indicates the next-to-last row, etc. + *

+ * + *

+ * An attempt to position the cursor beyond the first/last row in the result + * set, leaves the cursor before/after the first/last row, respectively. + *

+ * + *

+ * Note: Calling absolute(1) is the same as calling first(). Calling + * absolute(-1) is the same as calling last(). + *

+ * + * @param row + * DOCUMENT ME! + * + * @return true if on the result set, false if off. + * + * @exception SQLException + * if a database-access error occurs, or row is 0, or result + * set type is TYPE_FORWARD_ONLY. + */ + public synchronized boolean absolute(int row) throws SQLException { + return super.absolute(row); + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the end of the result set, just after the last row. Has no + * effect if the result set contains no rows. + *

+ * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY. + */ + public synchronized void afterLast() throws SQLException { + super.afterLast(); + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the front of the result set, just before the first row. Has no + * effect if the result set contains no rows. + *

+ * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY + */ + public synchronized void beforeFirst() throws SQLException { + super.beforeFirst(); + } + + /** + * JDBC 2.0 The cancelRowUpdates() method may be called after calling an + * updateXXX() method(s) and before calling updateRow() to rollback the + * updates made to a row. If no updates have been made or updateRow() has + * already been called, then this method has no effect. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row. + */ + public synchronized void cancelRowUpdates() throws SQLException { + checkClosed(); + + if (this.doingUpdates) { + this.doingUpdates = false; + this.updater.clearParameters(); + } + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.ResultSet#checkRowPos() + */ + protected void checkRowPos() throws SQLException { + checkClosed(); + + if (!this.onInsertRow) { + super.checkRowPos(); + } + } + + /** + * Is this ResultSet updateable? + * + * @throws SQLException + * DOCUMENT ME! + */ + protected void checkUpdatability() throws SQLException { + if (this.fields == null) { + // we've been created to be populated with cached + // metadata, and we don't have the metadata yet, + // we'll be called again by + // Connection.initializeResultsMetadataFromCache() + // when the metadata has been made available + + return; + } + + String singleTableName = null; + String catalogName = null; + + int primaryKeyCount = 0; + + // We can only do this if we know that there is a currently + // selected database, or if we're talking to a > 4.1 version + // of MySQL server (as it returns database names in field + // info) + // + if ((this.catalog == null) || (this.catalog.length() == 0)) { + this.catalog = this.fields[0].getDatabaseName(); + + if ((this.catalog == null) || (this.catalog.length() == 0)) { + throw SQLError.createSQLException(Messages + .getString("UpdatableResultSet.43") //$NON-NLS-1$ + , SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + if (this.fields.length > 0) { + singleTableName = this.fields[0].getOriginalTableName(); + catalogName = this.fields[0].getDatabaseName(); + + if (singleTableName == null) { + singleTableName = this.fields[0].getTableName(); + catalogName = this.catalog; + } + + if (singleTableName != null && singleTableName.length() == 0) { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.3"); + + return; + } + + if (this.fields[0].isPrimaryKey()) { + primaryKeyCount++; + } + + // + // References only one table? + // + for (int i = 1; i < this.fields.length; i++) { + String otherTableName = this.fields[i].getOriginalTableName(); + String otherCatalogName = this.fields[i].getDatabaseName(); + + if (otherTableName == null) { + otherTableName = this.fields[i].getTableName(); + otherCatalogName = this.catalog; + } + + if (otherTableName != null && otherTableName.length() == 0) { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.3"); + + return; + } + + if ((singleTableName == null) + || !otherTableName.equals(singleTableName)) { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.0"); + + return; + } + + // Can't reference more than one database + if ((catalogName == null) + || !otherCatalogName.equals(catalogName)) { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.1"); + + return; + } + + if (this.fields[i].isPrimaryKey()) { + primaryKeyCount++; + } + } + + if ((singleTableName == null) || (singleTableName.length() == 0)) { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.2"); + + return; + } + } else { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.3"); + + return; + } + + if (this.connection.getStrictUpdates()) { + java.sql.DatabaseMetaData dbmd = this.connection.getMetaData(); + + java.sql.ResultSet rs = null; + HashMap primaryKeyNames = new HashMap(); + + try { + rs = dbmd.getPrimaryKeys(catalogName, null, singleTableName); + + while (rs.next()) { + String keyName = rs.getString(4); + keyName = keyName.toUpperCase(); + primaryKeyNames.put(keyName, keyName); + } + } finally { + if (rs != null) { + try { + rs.close(); + } catch (Exception ex) { + AssertionFailedException.shouldNotHappen(ex); + } + + rs = null; + } + } + + int existingPrimaryKeysCount = primaryKeyNames.size(); + + if (existingPrimaryKeysCount == 0) { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.5"); + + return; // we can't update tables w/o keys + } + + // + // Contains all primary keys? + // + for (int i = 0; i < this.fields.length; i++) { + if (this.fields[i].isPrimaryKey()) { + String columnNameUC = this.fields[i].getName() + .toUpperCase(); + + if (primaryKeyNames.remove(columnNameUC) == null) { + // try original name + String originalName = this.fields[i].getOriginalName(); + + if (originalName != null) { + if (primaryKeyNames.remove(originalName + .toUpperCase()) == null) { + // we don't know about this key, so give up :( + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.6", + new Object[] {originalName}); + + return; + } + } + } + } + } + + this.isUpdatable = primaryKeyNames.isEmpty(); + + if (!this.isUpdatable) { + if (existingPrimaryKeysCount > 1) { + this.notUpdatableReason = Messages.getString("NotUpdatableReason.7"); + } else { + this.notUpdatableReason = Messages.getString("NotUpdatableReason.4"); + } + + return; + } + } + + // + // Must have at least one primary key + // + if (primaryKeyCount == 0) { + this.isUpdatable = false; + this.notUpdatableReason = Messages.getString("NotUpdatableReason.4"); + + return; + } + + this.isUpdatable = true; + this.notUpdatableReason = null; + + return; + } + + /** + * JDBC 2.0 Delete the current row from the result set and the underlying + * database. Cannot be called when on the insert row. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row. + * @throws SQLException + * if the ResultSet is not updatable or some other error occurs + */ + public synchronized void deleteRow() throws SQLException { + checkClosed(); + + if (!this.isUpdatable) { + throw new NotUpdatable(this.notUpdatableReason); + } + + if (this.onInsertRow) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.1")); //$NON-NLS-1$ + } else if (this.rowData.size() == 0) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.2")); //$NON-NLS-1$ + } else if (isBeforeFirst()) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.3")); //$NON-NLS-1$ + } else if (isAfterLast()) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.4")); //$NON-NLS-1$ + } + + if (this.deleter == null) { + if (this.deleteSQL == null) { + generateStatements(); + } + + this.deleter = this.connection + .clientPrepareStatement(this.deleteSQL); + } + + this.deleter.clearParameters(); + + String characterEncoding = null; + + if (this.connection.getUseUnicode()) { + characterEncoding = this.connection.getEncoding(); + } + + // + // FIXME: Use internal routines where possible for character + // conversion! + try { + int numKeys = this.primaryKeyIndicies.size(); + + if (numKeys == 1) { + int index = ((Integer) this.primaryKeyIndicies.get(0)) + .intValue(); + String currentVal = ((characterEncoding == null) ? new String( + (byte[]) this.thisRow[index]) : new String( + (byte[]) this.thisRow[index], characterEncoding)); + this.deleter.setString(1, currentVal); + } else { + for (int i = 0; i < numKeys; i++) { + int index = ((Integer) this.primaryKeyIndicies.get(i)) + .intValue(); + String currentVal = ((characterEncoding == null) ? new String( + (byte[]) this.thisRow[index]) + : new String((byte[]) this.thisRow[index], + characterEncoding)); + this.deleter.setString(i + 1, currentVal); + } + } + + this.deleter.executeUpdate(); + this.rowData.removeRow(this.rowData.getCurrentRowNumber()); + } catch (java.io.UnsupportedEncodingException encodingEx) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.39", //$NON-NLS-1$ + new Object[] { this.charEncoding }) //$NON-NLS-1$ + , SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + private synchronized void extractDefaultValues() throws SQLException { + java.sql.DatabaseMetaData dbmd = this.connection.getMetaData(); + + java.sql.ResultSet columnsResultSet = null; + + try { + columnsResultSet = dbmd.getColumns(this.catalog, null, + this.tableOnlyName, "%"); //$NON-NLS-1$ + + HashMap columnNameToDefaultValueMap = new HashMap( + this.fields.length /* at least this big... */); + + while (columnsResultSet.next()) { + String columnName = columnsResultSet.getString("COLUMN_NAME"); //$NON-NLS-1$ + byte[] defaultValue = columnsResultSet.getBytes("COLUMN_DEF"); //$NON-NLS-1$ + + columnNameToDefaultValueMap.put(columnName, defaultValue); + } + + int numFields = this.fields.length; + + this.defaultColumnValue = new byte[numFields][]; + + for (int i = 0; i < numFields; i++) { + String defValTableName = this.fields[i].getOriginalName(); + + if ((defValTableName == null) + || (defValTableName.length() == 0)) { + defValTableName = this.fields[i].getName(); + } + + if (defValTableName != null) { + byte[] defaultVal = (byte[]) columnNameToDefaultValueMap + .get(defValTableName); + + this.defaultColumnValue[i] = defaultVal; + } + } + } finally { + if (columnsResultSet != null) { + columnsResultSet.close(); + + columnsResultSet = null; + } + } + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the first row in the result set. + *

+ * + * @return true if on a valid row, false if no rows in the result set. + * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY. + */ + public synchronized boolean first() throws SQLException { + return super.first(); + } + + /** + * Figure out whether or not this ResultSet is updateable, and if so, + * generate the PreparedStatements to support updates. + * + * @throws SQLException + * DOCUMENT ME! + * @throws NotUpdatable + * DOCUMENT ME! + */ + protected synchronized void generateStatements() throws SQLException { + if (!this.isUpdatable) { + this.doingUpdates = false; + this.onInsertRow = false; + + throw new NotUpdatable(this.notUpdatableReason); + } + + String quotedId = getQuotedIdChar(); + + if (this.fields[0].getOriginalTableName() != null) { + StringBuffer tableNameBuffer = new StringBuffer(); + + String databaseName = this.fields[0].getDatabaseName(); + + if ((databaseName != null) && (databaseName.length() > 0)) { + tableNameBuffer.append(quotedId); + tableNameBuffer.append(databaseName); + tableNameBuffer.append(quotedId); + tableNameBuffer.append('.'); + } + + this.tableOnlyName = this.fields[0].getOriginalTableName(); + + tableNameBuffer.append(quotedId); + tableNameBuffer.append(this.tableOnlyName); + tableNameBuffer.append(quotedId); + + this.qualifiedAndQuotedTableName = tableNameBuffer.toString(); + } else { + StringBuffer tableNameBuffer = new StringBuffer(); + + this.tableOnlyName = this.fields[0].getTableName(); + + tableNameBuffer.append(quotedId); + tableNameBuffer.append(this.tableOnlyName); + tableNameBuffer.append(quotedId); + + this.qualifiedAndQuotedTableName = tableNameBuffer.toString(); + } + + this.primaryKeyIndicies = new ArrayList(); + + StringBuffer fieldValues = new StringBuffer(); + StringBuffer keyValues = new StringBuffer(); + StringBuffer columnNames = new StringBuffer(); + StringBuffer insertPlaceHolders = new StringBuffer(); + boolean firstTime = true; + boolean keysFirstTime = true; + + String equalsStr = this.connection.versionMeetsMinimum(3, 23, 0) ? "<=>" + : "="; + + for (int i = 0; i < this.fields.length; i++) { + String originalColumnName = this.fields[i].getOriginalName(); + String columnName = null; + + if (this.connection.getIO().hasLongColumnInfo() + && (originalColumnName != null) + && (originalColumnName.length() > 0)) { + columnName = originalColumnName; + } else { + columnName = this.fields[i].getName(); + } + + if (this.fields[i].isPrimaryKey()) { + this.primaryKeyIndicies.add(new Integer(i)); + + if (!keysFirstTime) { + keyValues.append(" AND "); //$NON-NLS-1$ + } else { + keysFirstTime = false; + } + + keyValues.append(quotedId); + keyValues.append(columnName); + keyValues.append(quotedId); + keyValues.append(equalsStr); + keyValues.append("?"); //$NON-NLS-1$ + } + + if (firstTime) { + firstTime = false; + fieldValues.append("SET "); //$NON-NLS-1$ + } else { + fieldValues.append(","); //$NON-NLS-1$ + columnNames.append(","); //$NON-NLS-1$ + insertPlaceHolders.append(","); //$NON-NLS-1$ + } + + insertPlaceHolders.append("?"); //$NON-NLS-1$ + + columnNames.append(quotedId); + columnNames.append(columnName); + columnNames.append(quotedId); + + fieldValues.append(quotedId); + fieldValues.append(columnName); + fieldValues.append(quotedId); + fieldValues.append("=?"); //$NON-NLS-1$ + } + + this.updateSQL = "UPDATE " + this.qualifiedAndQuotedTableName + " " //$NON-NLS-1$ //$NON-NLS-2$ + + fieldValues.toString() //$NON-NLS-1$ //$NON-NLS-2$ + + " WHERE " + keyValues.toString(); //$NON-NLS-1$ + this.insertSQL = "INSERT INTO " + this.qualifiedAndQuotedTableName //$NON-NLS-1$ + + " (" + columnNames.toString() //$NON-NLS-1$ //$NON-NLS-2$ + + ") VALUES (" + insertPlaceHolders.toString() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + this.refreshSQL = "SELECT " + columnNames.toString() + " FROM " //$NON-NLS-1$ //$NON-NLS-2$ + + this.qualifiedAndQuotedTableName //$NON-NLS-1$ //$NON-NLS-2$ + + " WHERE " + keyValues.toString(); //$NON-NLS-1$ + this.deleteSQL = "DELETE FROM " + this.qualifiedAndQuotedTableName //$NON-NLS-1$ + + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ + + keyValues.toString(); + } + + private synchronized SingleByteCharsetConverter getCharConverter() + throws SQLException { + if (!this.initializedCharConverter) { + this.initializedCharConverter = true; + + if (this.connection.getUseUnicode()) { + this.charEncoding = connection.getEncoding(); + this.charConverter = this.connection + .getCharsetConverter(this.charEncoding); + } + } + + return this.charConverter; + } + + /** + * JDBC 2.0 Return the concurrency of this result set. The concurrency used + * is determined by the statement that created the result set. + * + * @return the concurrency type, CONCUR_READ_ONLY, etc. + * + * @exception SQLException + * if a database-access error occurs + */ + public int getConcurrency() throws SQLException { + return (this.isUpdatable ? CONCUR_UPDATABLE : CONCUR_READ_ONLY); + } + + private synchronized String getQuotedIdChar() throws SQLException { + if (this.quotedIdChar == null) { + boolean useQuotedIdentifiers = this.connection + .supportsQuotedIdentifiers(); + + if (useQuotedIdentifiers) { + java.sql.DatabaseMetaData dbmd = this.connection.getMetaData(); + this.quotedIdChar = dbmd.getIdentifierQuoteString(); + } else { + this.quotedIdChar = ""; //$NON-NLS-1$ + } + } + + return this.quotedIdChar; + } + + /** + * JDBC 2.0 Insert the contents of the insert row into the result set and + * the database. Must be on the insert row when this method is called. + * + * @exception SQLException + * if a database-access error occurs, if called when not on + * the insert row, or if all non-nullable columns in the + * insert row have not been given a value + */ + public synchronized void insertRow() throws SQLException { + checkClosed(); + + if (!this.onInsertRow) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.7")); //$NON-NLS-1$ + } + + this.inserter.executeUpdate(); + + long autoIncrementId = this.inserter.getLastInsertID(); + int numFields = this.fields.length; + byte[][] newRow = new byte[numFields][]; + + for (int i = 0; i < numFields; i++) { + if (this.inserter.isNull(i)) { + newRow[i] = null; + } else { + newRow[i] = this.inserter.getBytesRepresentation(i); + } + + // + // WARN: This non-variant only holds if MySQL never allows more + // than one auto-increment key (which is the way it is _today_) + // + if (this.fields[i].isAutoIncrement() && autoIncrementId > 0) { + newRow[i] = String.valueOf(autoIncrementId).getBytes(); + this.inserter.setBytesNoEscapeNoQuotes(i + 1, newRow[i]); + } + } + + refreshRow(this.inserter, newRow); + + this.rowData.addRow(newRow); + resetInserter(); + } + + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is after the last row in the result set. + *

+ * + * @return true if after the last row, false otherwise. Returns false when + * the result set contains no rows. + * + * @exception SQLException + * if a database-access error occurs. + */ + public synchronized boolean isAfterLast() throws SQLException { + return super.isAfterLast(); + } + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is before the first row in the result set. + *

+ * + * @return true if before the first row, false otherwise. Returns false when + * the result set contains no rows. + * + * @exception SQLException + * if a database-access error occurs. + */ + public synchronized boolean isBeforeFirst() throws SQLException { + return super.isBeforeFirst(); + } + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is on the first row of the result set. + *

+ * + * @return true if on the first row, false otherwise. + * + * @exception SQLException + * if a database-access error occurs. + */ + public synchronized boolean isFirst() throws SQLException { + return super.isFirst(); + } + + /** + * JDBC 2.0 + * + *

+ * Determine if the cursor is on the last row of the result set. Note: + * Calling isLast() may be expensive since the JDBC driver might need to + * fetch ahead one row in order to determine whether the current row is the + * last row in the result set. + *

+ * + * @return true if on the last row, false otherwise. + * + * @exception SQLException + * if a database-access error occurs. + */ + public synchronized boolean isLast() throws SQLException { + return super.isLast(); + } + + boolean isUpdatable() { + return this.isUpdatable; + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the last row in the result set. + *

+ * + * @return true if on a valid row, false if no rows in the result set. + * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWARD_ONLY. + */ + public synchronized boolean last() throws SQLException { + return super.last(); + } + + /** + * JDBC 2.0 Move the cursor to the remembered cursor position, usually the + * current row. Has no effect unless the cursor is on the insert row. + * + * @exception SQLException + * if a database-access error occurs, or the result set is + * not updatable + * @throws SQLException + * if the ResultSet is not updatable or some other error occurs + */ + public synchronized void moveToCurrentRow() throws SQLException { + checkClosed(); + + if (!this.isUpdatable) { + throw new NotUpdatable(this.notUpdatableReason); + } + + if (this.onInsertRow) { + this.onInsertRow = false; + this.thisRow = this.savedCurrentRow; + } + } + + /** + * JDBC 2.0 Move to the insert row. The current cursor position is + * remembered while the cursor is positioned on the insert row. The insert + * row is a special row associated with an updatable result set. It is + * essentially a buffer where a new row may be constructed by calling the + * updateXXX() methods prior to inserting the row into the result set. Only + * the updateXXX(), getXXX(), and insertRow() methods may be called when the + * cursor is on the insert row. All of the columns in a result set must be + * given a value each time this method is called before calling insertRow(). + * UpdateXXX()must be called before getXXX() on a column. + * + * @exception SQLException + * if a database-access error occurs, or the result set is + * not updatable + * @throws NotUpdatable + * DOCUMENT ME! + */ + public synchronized void moveToInsertRow() throws SQLException { + checkClosed(); + + if (!this.isUpdatable) { + throw new NotUpdatable(this.notUpdatableReason); + } + + if (this.inserter == null) { + if (this.insertSQL == null) { + generateStatements(); + } + + this.inserter = this.connection + .clientPrepareStatement(this.insertSQL); + if (this.populateInserterWithDefaultValues) { + extractDefaultValues(); + } + + resetInserter(); + } else { + resetInserter(); + } + + int numFields = this.fields.length; + + this.onInsertRow = true; + this.doingUpdates = false; + this.savedCurrentRow = this.thisRow; + this.thisRow = new byte[numFields][]; + + for (int i = 0; i < numFields; i++) { + if (!this.populateInserterWithDefaultValues) { + this.inserter.setBytesNoEscapeNoQuotes(i + 1, + "DEFAULT".getBytes()); + this.thisRow[i] = null; + } else { + if (this.defaultColumnValue[i] != null) { + Field f = this.fields[i]; + + switch (f.getMysqlType()) { + case MysqlDefs.FIELD_TYPE_DATE: + case MysqlDefs.FIELD_TYPE_DATETIME: + case MysqlDefs.FIELD_TYPE_NEWDATE: + case MysqlDefs.FIELD_TYPE_TIME: + case MysqlDefs.FIELD_TYPE_TIMESTAMP: + + if (this.defaultColumnValue[i].length > 7 + && this.defaultColumnValue[i][0] == (byte) 'C' + && this.defaultColumnValue[i][1] == (byte) 'U' + && this.defaultColumnValue[i][2] == (byte) 'R' + && this.defaultColumnValue[i][3] == (byte) 'R' + && this.defaultColumnValue[i][4] == (byte) 'E' + && this.defaultColumnValue[i][5] == (byte) 'N' + && this.defaultColumnValue[i][6] == (byte) 'T' + && this.defaultColumnValue[i][7] == (byte) '_') { + this.inserter.setBytesNoEscapeNoQuotes(i + 1, + this.defaultColumnValue[i]); + + break; + } + default: + this.inserter.setBytes(i + 1, this.defaultColumnValue[i], + false, false); + } + + // This value _could_ be changed from a getBytes(), so we + // need a copy.... + byte[] defaultValueCopy = new byte[this.defaultColumnValue[i].length]; + System.arraycopy(defaultColumnValue[i], 0, defaultValueCopy, 0, + defaultValueCopy.length); + this.thisRow[i] = defaultValueCopy; + } else { + this.inserter.setNull(i + 1, java.sql.Types.NULL); + this.thisRow[i] = null; + } + } + } + } + + /** + * A ResultSet is initially positioned before its first row, the first call + * to next makes the first row the current row; the second call makes the + * second row the current row, etc. + * + *

+ * If an input stream from the previous row is open, it is implicitly + * closed. The ResultSet's warning chain is cleared when a new row is read + *

+ * + * @return true if the new current is valid; false if there are no more rows + * + * @exception SQLException + * if a database access error occurs + */ + public synchronized boolean next() throws SQLException { + return super.next(); + } + + /** + * The prev method is not part of JDBC, but because of the architecture of + * this driver it is possible to move both forward and backward within the + * result set. + * + *

+ * If an input stream from the previous row is open, it is implicitly + * closed. The ResultSet's warning chain is cleared when a new row is read + *

+ * + * @return true if the new current is valid; false if there are no more rows + * + * @exception SQLException + * if a database access error occurs + */ + public synchronized boolean prev() throws SQLException { + return super.prev(); + } + + /** + * JDBC 2.0 + * + *

+ * Moves to the previous row in the result set. + *

+ * + *

+ * Note: previous() is not the same as relative(-1) since it makes sense to + * call previous() when there is no current row. + *

+ * + * @return true if on a valid row, false if off the result set. + * + * @exception SQLException + * if a database-access error occurs, or result set type is + * TYPE_FORWAR_DONLY. + */ + public synchronized boolean previous() throws SQLException { + return super.previous(); + } + + /** + * Closes this ResultSet, releasing all resources. + * + * @param calledExplicitly + * was this called from close()? + * + * @throws SQLException + * if an error occurs. + */ + protected void realClose(boolean calledExplicitly) throws SQLException { + if (this.isClosed) { + return; + } + + SQLException sqlEx = null; + + if (this.useUsageAdvisor) { + if ((this.deleter == null) && (this.inserter == null) + && (this.refresher == null) && (this.updater == null)) { + this.eventSink = ProfileEventSink.getInstance(this.connection); + + String message = Messages.getString("UpdatableResultSet.34"); //$NON-NLS-1$ + + this.eventSink.consumeEvent(new ProfilerEvent( + ProfilerEvent.TYPE_WARN, + "", //$NON-NLS-1$ + (this.owningStatement == null) ? "N/A" //$NON-NLS-1$ + : this.owningStatement.currentCatalog, //$NON-NLS-1$ + this.connectionId, + (this.owningStatement == null) ? (-1) + : this.owningStatement.getId(), this.resultId, + System.currentTimeMillis(), 0, Constants.MILLIS_I18N, + null, this.pointOfOrigin, message)); + } + } + + try { + if (this.deleter != null) { + this.deleter.close(); + } + } catch (SQLException ex) { + sqlEx = ex; + } + + try { + if (this.inserter != null) { + this.inserter.close(); + } + } catch (SQLException ex) { + sqlEx = ex; + } + + try { + if (this.refresher != null) { + this.refresher.close(); + } + } catch (SQLException ex) { + sqlEx = ex; + } + + try { + if (this.updater != null) { + this.updater.close(); + } + } catch (SQLException ex) { + sqlEx = ex; + } + + super.realClose(calledExplicitly); + + if (sqlEx != null) { + throw sqlEx; + } + } + + /** + * JDBC 2.0 Refresh the value of the current row with its current value in + * the database. Cannot be called when on the insert row. The refreshRow() + * method provides a way for an application to explicitly tell the JDBC + * driver to refetch a row(s) from the database. An application may want to + * call refreshRow() when caching or prefetching is being done by the JDBC + * driver to fetch the latest value of a row from the database. The JDBC + * driver may actually refresh multiple rows at once if the fetch size is + * greater than one. All values are refetched subject to the transaction + * isolation level and cursor sensitivity. If refreshRow() is called after + * calling updateXXX(), but before calling updateRow() then the updates made + * to the row are lost. Calling refreshRow() frequently will likely slow + * performance. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row. + * @throws NotUpdatable + * DOCUMENT ME! + */ + public synchronized void refreshRow() throws SQLException { + checkClosed(); + + if (!this.isUpdatable) { + throw new NotUpdatable(); + } + + if (this.onInsertRow) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.8")); //$NON-NLS-1$ + } else if (this.rowData.size() == 0) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.9")); //$NON-NLS-1$ + } else if (isBeforeFirst()) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.10")); //$NON-NLS-1$ + } else if (isAfterLast()) { + throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.11")); //$NON-NLS-1$ + } + + refreshRow(this.updater, this.thisRow); + } + + private synchronized void refreshRow(PreparedStatement updateInsertStmt, + Object[] rowToRefresh) throws SQLException { + if (this.refresher == null) { + if (this.refreshSQL == null) { + generateStatements(); + } + + this.refresher = this.connection + .clientPrepareStatement(this.refreshSQL); + } + + this.refresher.clearParameters(); + + int numKeys = this.primaryKeyIndicies.size(); + + if (numKeys == 1) { + byte[] dataFrom = null; + int index = ((Integer) this.primaryKeyIndicies.get(0)).intValue(); + + if (!this.doingUpdates && !this.onInsertRow) { + dataFrom = (byte[]) rowToRefresh[index]; + } else { + dataFrom = updateInsertStmt.getBytesRepresentation(index); + + // Primary keys not set? + if (updateInsertStmt.isNull(index) || (dataFrom.length == 0)) { + dataFrom = (byte[]) rowToRefresh[index]; + } else { + dataFrom = stripBinaryPrefix(dataFrom); + } + } + + this.refresher.setBytesNoEscape(1, dataFrom); + } else { + for (int i = 0; i < numKeys; i++) { + byte[] dataFrom = null; + int index = ((Integer) this.primaryKeyIndicies.get(i)) + .intValue(); + + if (!this.doingUpdates && !this.onInsertRow) { + dataFrom = (byte[]) rowToRefresh[index]; + } else { + dataFrom = updateInsertStmt.getBytesRepresentation(index); + + // Primary keys not set? + if (updateInsertStmt.isNull(index) || (dataFrom.length == 0)) { + dataFrom = (byte[]) this.thisRow[index]; + } else { + dataFrom = stripBinaryPrefix(dataFrom); + } + } + + this.refresher.setBytesNoEscape(i + 1, dataFrom); + } + } + + java.sql.ResultSet rs = null; + + try { + rs = this.refresher.executeQuery(); + + int numCols = rs.getMetaData().getColumnCount(); + + if (rs.next()) { + for (int i = 0; i < numCols; i++) { + byte[] val = rs.getBytes(i + 1); + + if ((val == null) || rs.wasNull()) { + rowToRefresh[i] = null; + } else { + rowToRefresh[i] = rs.getBytes(i + 1); + } + } + } else { + throw SQLError.createSQLException(Messages + .getString("UpdatableResultSet.12"), //$NON-NLS-1$ + SQLError.SQL_STATE_GENERAL_ERROR); //$NON-NLS-1$ + } + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ex) { + ; // ignore + } + } + } + } + + /** + * JDBC 2.0 + * + *

+ * Moves a relative number of rows, either positive or negative. Attempting + * to move beyond the first/last row in the result set positions the cursor + * before/after the the first/last row. Calling relative(0) is valid, but + * does not change the cursor position. + *

+ * + *

+ * Note: Calling relative(1) is different than calling next() since is makes + * sense to call next() when there is no current row, for example, when the + * cursor is positioned before the first row or after the last row of the + * result set. + *

+ * + * @param rows + * DOCUMENT ME! + * + * @return true if on a row, false otherwise. + * + * @exception SQLException + * if a database-access error occurs, or there is no current + * row, or result set type is TYPE_FORWARD_ONLY. + */ + public synchronized boolean relative(int rows) throws SQLException { + return super.relative(rows); + } + + private void resetInserter() throws SQLException { + this.inserter.clearParameters(); + + for (int i = 0; i < this.fields.length; i++) { + this.inserter.setNull(i + 1, 0); + } + } + + /** + * JDBC 2.0 Determine if this row has been deleted. A deleted row may leave + * a visible "hole" in a result set. This method can be used to detect holes + * in a result set. The value returned depends on whether or not the result + * set can detect deletions. + * + * @return true if deleted and deletes are detected + * + * @exception SQLException + * if a database-access error occurs + * @throws NotImplemented + * DOCUMENT ME! + * + * @see DatabaseMetaData#deletesAreDetected + */ + public synchronized boolean rowDeleted() throws SQLException { + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Determine if the current row has been inserted. The value + * returned depends on whether or not the result set can detect visible + * inserts. + * + * @return true if inserted and inserts are detected + * + * @exception SQLException + * if a database-access error occurs + * @throws NotImplemented + * DOCUMENT ME! + * + * @see DatabaseMetaData#insertsAreDetected + */ + public synchronized boolean rowInserted() throws SQLException { + throw new NotImplemented(); + } + + /** + * JDBC 2.0 Determine if the current row has been updated. The value + * returned depends on whether or not the result set can detect updates. + * + * @return true if the row has been visibly updated by the owner or another, + * and updates are detected + * + * @exception SQLException + * if a database-access error occurs + * @throws NotImplemented + * DOCUMENT ME! + * + * @see DatabaseMetaData#updatesAreDetected + */ + public synchronized boolean rowUpdated() throws SQLException { + throw new NotImplemented(); + } + + /** + * Sets the concurrency type of this result set + * + * @param concurrencyFlag + * the type of concurrency that this ResultSet should support. + */ + protected void setResultSetConcurrency(int concurrencyFlag) { + super.setResultSetConcurrency(concurrencyFlag); + + // + // FIXME: Issue warning when asked for updateable result set, but result + // set is not + // updatable + // + // if ((concurrencyFlag == CONCUR_UPDATABLE) && !isUpdatable()) { + // java.sql.SQLWarning warning = new java.sql.SQLWarning( + // NotUpdatable.NOT_UPDATEABLE_MESSAGE); + // } + } + + private byte[] stripBinaryPrefix(byte[] dataFrom) { + return StringUtils.stripEnclosure(dataFrom, "_binary'", "'"); + } + + /** + * Reset UPDATE prepared statement to value in current row. This_Row MUST + * point to current, valid row. + * + * @throws SQLException + * DOCUMENT ME! + */ + synchronized void syncUpdate() throws SQLException { + if (this.updater == null) { + if (this.updateSQL == null) { + generateStatements(); + } + + this.updater = this.connection + .clientPrepareStatement(this.updateSQL); + } + + int numFields = this.fields.length; + this.updater.clearParameters(); + + for (int i = 0; i < numFields; i++) { + if (this.thisRow[i] != null) { + this.updater.setBytes(i + 1, (byte[]) this.thisRow[i], + this.fields[i].isBinary(), false); + } else { + this.updater.setNull(i + 1, 0); + } + } + + int numKeys = this.primaryKeyIndicies.size(); + + if (numKeys == 1) { + int index = ((Integer) this.primaryKeyIndicies.get(0)).intValue(); + byte[] keyData = (byte[]) this.thisRow[index]; + this.updater.setBytes(numFields + 1, keyData, false, false); + } else { + for (int i = 0; i < numKeys; i++) { + byte[] currentVal = (byte[]) this.thisRow[((Integer) this.primaryKeyIndicies + .get(i)).intValue()]; + + if (currentVal != null) { + this.updater.setBytes(numFields + i + 1, currentVal, false, + false); + } else { + this.updater.setNull(numFields + i + 1, 0); + } + } + } + } + + /** + * JDBC 2.0 Update a column with an ascii stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param length + * the length of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateAsciiStream(int columnIndex, + java.io.InputStream x, int length) throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setAsciiStream(columnIndex, x, length); + } else { + this.inserter.setAsciiStream(columnIndex, x, length); + this.thisRow[columnIndex - 1] = STREAM_DATA_MARKER; + } + } + + /** + * JDBC 2.0 Update a column with an ascii stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * @param length + * of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateAsciiStream(String columnName, + java.io.InputStream x, int length) throws SQLException { + updateAsciiStream(findColumn(columnName), x, length); + } + + /** + * JDBC 2.0 Update a column with a BigDecimal value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBigDecimal(int columnIndex, BigDecimal x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setBigDecimal(columnIndex, x); + } else { + this.inserter.setBigDecimal(columnIndex, x); + + if (x == null) { + this.thisRow[columnIndex - 1] = null; + } else { + this.thisRow[columnIndex - 1] = x.toString().getBytes(); + } + } + } + + /** + * JDBC 2.0 Update a column with a BigDecimal value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBigDecimal(String columnName, BigDecimal x) + throws SQLException { + updateBigDecimal(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a binary stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param length + * the length of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBinaryStream(int columnIndex, + java.io.InputStream x, int length) throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setBinaryStream(columnIndex, x, length); + } else { + this.inserter.setBinaryStream(columnIndex, x, length); + + if (x == null) { + this.thisRow[columnIndex - 1] = null; + } else { + this.thisRow[columnIndex - 1] = STREAM_DATA_MARKER; + } + } + } + + /** + * JDBC 2.0 Update a column with a binary stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * @param length + * of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBinaryStream(String columnName, + java.io.InputStream x, int length) throws SQLException { + updateBinaryStream(findColumn(columnName), x, length); + } + + /** + * @see ResultSet#updateBlob(int, Blob) + */ + public synchronized void updateBlob(int columnIndex, java.sql.Blob blob) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setBlob(columnIndex, blob); + } else { + this.inserter.setBlob(columnIndex, blob); + + if (blob == null) { + this.thisRow[columnIndex - 1] = null; + } else { + this.thisRow[columnIndex - 1] = STREAM_DATA_MARKER; + } + } + } + + /** + * @see ResultSet#updateBlob(String, Blob) + */ + public synchronized void updateBlob(String columnName, java.sql.Blob blob) + throws SQLException { + updateBlob(findColumn(columnName), blob); + } + + /** + * JDBC 2.0 Update a column with a boolean value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBoolean(int columnIndex, boolean x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setBoolean(columnIndex, x); + } else { + this.inserter.setBoolean(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a boolean value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBoolean(String columnName, boolean x) + throws SQLException { + updateBoolean(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a byte value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateByte(int columnIndex, byte x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setByte(columnIndex, x); + } else { + this.inserter.setByte(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a byte value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateByte(String columnName, byte x) + throws SQLException { + updateByte(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a byte array value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBytes(int columnIndex, byte[] x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setBytes(columnIndex, x); + } else { + this.inserter.setBytes(columnIndex, x); + + this.thisRow[columnIndex - 1] = x; + } + } + + /** + * JDBC 2.0 Update a column with a byte array value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateBytes(String columnName, byte[] x) + throws SQLException { + updateBytes(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a character stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param length + * the length of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateCharacterStream(int columnIndex, + java.io.Reader x, int length) throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setCharacterStream(columnIndex, x, length); + } else { + this.inserter.setCharacterStream(columnIndex, x, length); + + if (x == null) { + this.thisRow[columnIndex - 1] = null; + } else { + this.thisRow[columnIndex - 1] = STREAM_DATA_MARKER; + } + } + } + + /** + * JDBC 2.0 Update a column with a character stream value. The updateXXX() + * methods are used to update column values in the current row, or the + * insert row. The updateXXX() methods do not update the underlying + * database, instead the updateRow() or insertRow() methods are called to + * update the database. + * + * @param columnName + * the name of the column + * @param reader + * the new column value + * @param length + * of the stream + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateCharacterStream(String columnName, + java.io.Reader reader, int length) throws SQLException { + updateCharacterStream(findColumn(columnName), reader, length); + } + + /** + * @see ResultSet#updateClob(int, Clob) + */ + public void updateClob(int columnIndex, java.sql.Clob clob) + throws SQLException { + if (clob == null) { + updateNull(columnIndex); + } else { + updateCharacterStream(columnIndex, clob.getCharacterStream(), + (int) clob.length()); + } + } + + /** + * JDBC 2.0 Update a column with a Date value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateDate(int columnIndex, java.sql.Date x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setDate(columnIndex, x); + } else { + this.inserter.setDate(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a Date value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateDate(String columnName, java.sql.Date x) + throws SQLException { + updateDate(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a Double value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateDouble(int columnIndex, double x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setDouble(columnIndex, x); + } else { + this.inserter.setDouble(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a double value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateDouble(String columnName, double x) + throws SQLException { + updateDouble(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a float value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateFloat(int columnIndex, float x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setFloat(columnIndex, x); + } else { + this.inserter.setFloat(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a float value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateFloat(String columnName, float x) + throws SQLException { + updateFloat(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with an integer value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateInt(int columnIndex, int x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setInt(columnIndex, x); + } else { + this.inserter.setInt(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with an integer value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateInt(String columnName, int x) + throws SQLException { + updateInt(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a long value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateLong(int columnIndex, long x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setLong(columnIndex, x); + } else { + this.inserter.setLong(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a long value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateLong(String columnName, long x) + throws SQLException { + updateLong(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Give a nullable column a null value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateNull(int columnIndex) throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setNull(columnIndex, 0); + } else { + this.inserter.setNull(columnIndex, 0); + + this.thisRow[columnIndex - 1] = null; + } + } + + /** + * JDBC 2.0 Update a column with a null value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateNull(String columnName) throws SQLException { + updateNull(findColumn(columnName)); + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateObject(int columnIndex, Object x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setObject(columnIndex, x); + } else { + this.inserter.setObject(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * @param scale + * For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types + * this is the number of digits after the decimal. For all other + * types this value will be ignored. + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateObject(int columnIndex, Object x, int scale) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setObject(columnIndex, x); + } else { + this.inserter.setObject(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateObject(String columnName, Object x) + throws SQLException { + updateObject(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with an Object value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * @param scale + * For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types + * this is the number of digits after the decimal. For all other + * types this value will be ignored. + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateObject(String columnName, Object x, int scale) + throws SQLException { + updateObject(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update the underlying database with the new contents of the + * current row. Cannot be called when on the insert row. + * + * @exception SQLException + * if a database-access error occurs, or if called when on + * the insert row + * @throws NotUpdatable + * DOCUMENT ME! + */ + public synchronized void updateRow() throws SQLException { + if (!this.isUpdatable) { + throw new NotUpdatable(this.notUpdatableReason); + } + + if (this.doingUpdates) { + this.updater.executeUpdate(); + refreshRow(); + this.doingUpdates = false; + } + + // + // fixes calling updateRow() and then doing more + // updates on same row... + syncUpdate(); + } + + /** + * JDBC 2.0 Update a column with a short value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateShort(int columnIndex, short x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setShort(columnIndex, x); + } else { + this.inserter.setShort(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a short value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateShort(String columnName, short x) + throws SQLException { + updateShort(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a String value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateString(int columnIndex, String x) + throws SQLException { + checkClosed(); + + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setString(columnIndex, x); + } else { + this.inserter.setString(columnIndex, x); + + if (x == null) { + this.thisRow[columnIndex - 1] = null; + } else { + if (getCharConverter() != null) { + this.thisRow[columnIndex - 1] = StringUtils.getBytes(x, + this.charConverter, this.charEncoding, + this.connection.getServerCharacterEncoding(), + this.connection.parserKnowsUnicode()); + } else { + this.thisRow[columnIndex - 1] = x.getBytes(); + } + } + } + } + + /** + * JDBC 2.0 Update a column with a String value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateString(String columnName, String x) + throws SQLException { + updateString(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a Time value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateTime(int columnIndex, java.sql.Time x) + throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setTime(columnIndex, x); + } else { + this.inserter.setTime(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a Time value. The updateXXX() methods are + * used to update column values in the current row, or the insert row. The + * updateXXX() methods do not update the underlying database, instead the + * updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateTime(String columnName, java.sql.Time x) + throws SQLException { + updateTime(findColumn(columnName), x); + } + + /** + * JDBC 2.0 Update a column with a Timestamp value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnIndex + * the first column is 1, the second is 2, ... + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateTimestamp(int columnIndex, + java.sql.Timestamp x) throws SQLException { + if (!this.onInsertRow) { + if (!this.doingUpdates) { + this.doingUpdates = true; + syncUpdate(); + } + + this.updater.setTimestamp(columnIndex, x); + } else { + this.inserter.setTimestamp(columnIndex, x); + + this.thisRow[columnIndex - 1] = this.inserter + .getBytesRepresentation(columnIndex - 1); + } + } + + /** + * JDBC 2.0 Update a column with a Timestamp value. The updateXXX() methods + * are used to update column values in the current row, or the insert row. + * The updateXXX() methods do not update the underlying database, instead + * the updateRow() or insertRow() methods are called to update the database. + * + * @param columnName + * the name of the column + * @param x + * the new column value + * + * @exception SQLException + * if a database-access error occurs + */ + public synchronized void updateTimestamp(String columnName, + java.sql.Timestamp x) throws SQLException { + updateTimestamp(findColumn(columnName), x); + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/Util.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/Util.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/Util.java 17 Aug 2012 14:57:08 -0000 1.1 @@ -0,0 +1,372 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.ObjectInputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.TimeZone; + +/** + * Various utility methods for the driver. + * + * @author Mark Matthews + */ +public class Util { + + protected static Method systemNanoTimeMethod; + + private static boolean isColdFusion = false; + + static { + try { + systemNanoTimeMethod = System.class.getMethod("nanoTime", null); + } catch (SecurityException e) { + systemNanoTimeMethod = null; + } catch (NoSuchMethodException e) { + systemNanoTimeMethod = null; + } + + // + // Detect the ColdFusion MX environment + // + // Unfortunately, no easy-to-discern classes are available + // to our classloader to check... + // + + String loadedFrom = stackTraceToString(new Throwable()); + + if (loadedFrom != null) { + isColdFusion = loadedFrom.indexOf("coldfusion") != -1; + } else { + isColdFusion = false; + } + } + + public static boolean isColdFusion() { + return isColdFusion; + } + + protected static boolean nanoTimeAvailable() { + return systemNanoTimeMethod != null; + } + + // cache this ourselves, as the method call is statically-synchronized in all but JDK6! + + private static final TimeZone DEFAULT_TIMEZONE = TimeZone.getDefault(); + + static final TimeZone getDefaultTimeZone() { + return (TimeZone)DEFAULT_TIMEZONE.clone(); + } + + class RandStructcture { + long maxValue; + + double maxValueDbl; + + long seed1; + + long seed2; + } + + + private static Util enclosingInstance = new Util(); + + // Right from Monty's code + static String newCrypt(String password, String seed) { + byte b; + double d; + + if ((password == null) || (password.length() == 0)) { + return password; + } + + long[] pw = newHash(seed); + long[] msg = newHash(password); + long max = 0x3fffffffL; + long seed1 = (pw[0] ^ msg[0]) % max; + long seed2 = (pw[1] ^ msg[1]) % max; + char[] chars = new char[seed.length()]; + + for (int i = 0; i < seed.length(); i++) { + seed1 = ((seed1 * 3) + seed2) % max; + seed2 = (seed1 + seed2 + 33) % max; + d = (double) seed1 / (double) max; + b = (byte) java.lang.Math.floor((d * 31) + 64); + chars[i] = (char) b; + } + + seed1 = ((seed1 * 3) + seed2) % max; + seed2 = (seed1 + seed2 + 33) % max; + d = (double) seed1 / (double) max; + b = (byte) java.lang.Math.floor(d * 31); + + for (int i = 0; i < seed.length(); i++) { + chars[i] ^= (char) b; + } + + return new String(chars); + } + + static long[] newHash(String password) { + long nr = 1345345333L; + long add = 7; + long nr2 = 0x12345671L; + long tmp; + + for (int i = 0; i < password.length(); ++i) { + if ((password.charAt(i) == ' ') || (password.charAt(i) == '\t')) { + continue; // skip spaces + } + + tmp = (0xff & password.charAt(i)); + nr ^= ((((nr & 63) + add) * tmp) + (nr << 8)); + nr2 += ((nr2 << 8) ^ nr); + add += tmp; + } + + long[] result = new long[2]; + result[0] = nr & 0x7fffffffL; + result[1] = nr2 & 0x7fffffffL; + + return result; + } + + static String oldCrypt(String password, String seed) { + long hp; + long hm; + long s1; + long s2; + long max = 0x01FFFFFF; + double d; + byte b; + + if ((password == null) || (password.length() == 0)) { + return password; + } + + hp = oldHash(seed); + hm = oldHash(password); + + long nr = hp ^ hm; + nr %= max; + s1 = nr; + s2 = nr / 2; + + char[] chars = new char[seed.length()]; + + for (int i = 0; i < seed.length(); i++) { + s1 = ((s1 * 3) + s2) % max; + s2 = (s1 + s2 + 33) % max; + d = (double) s1 / max; + b = (byte) java.lang.Math.floor((d * 31) + 64); + chars[i] = (char) b; + } + + return new String(chars); + } + + static long oldHash(String password) { + long nr = 1345345333; + long nr2 = 7; + long tmp; + + for (int i = 0; i < password.length(); i++) { + if ((password.charAt(i) == ' ') || (password.charAt(i) == '\t')) { + continue; + } + + tmp = password.charAt(i); + nr ^= ((((nr & 63) + nr2) * tmp) + (nr << 8)); + nr2 += tmp; + } + + return nr & ((1L << 31) - 1L); + } + + private static RandStructcture randomInit(long seed1, long seed2) { + RandStructcture randStruct = enclosingInstance.new RandStructcture(); + + randStruct.maxValue = 0x3FFFFFFFL; + randStruct.maxValueDbl = randStruct.maxValue; + randStruct.seed1 = seed1 % randStruct.maxValue; + randStruct.seed2 = seed2 % randStruct.maxValue; + + return randStruct; + } + + /** + * Given a ResultSet and an index into the columns of that ResultSet, read + * binary data from the column which represents a serialized object, and + * re-create the object. + * + * @param resultSet + * the ResultSet to use. + * @param index + * an index into the ResultSet. + * @return the object if it can be de-serialized + * @throws Exception + * if an error occurs + */ + public static Object readObject(java.sql.ResultSet resultSet, int index) + throws Exception { + ObjectInputStream objIn = new ObjectInputStream(resultSet + .getBinaryStream(index)); + Object obj = objIn.readObject(); + objIn.close(); + + return obj; + } + + private static double rnd(RandStructcture randStruct) { + randStruct.seed1 = ((randStruct.seed1 * 3) + randStruct.seed2) + % randStruct.maxValue; + randStruct.seed2 = (randStruct.seed1 + randStruct.seed2 + 33) + % randStruct.maxValue; + + return ((randStruct.seed1) / randStruct.maxValueDbl); + } + + /** + * DOCUMENT ME! + * + * @param message + * DOCUMENT ME! + * @param password + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public static String scramble(String message, String password) { + long[] hashPass; + long[] hashMessage; + byte[] to = new byte[8]; + String val = ""; //$NON-NLS-1$ + + message = message.substring(0, 8); + + if ((password != null) && (password.length() > 0)) { + hashPass = newHash(password); + hashMessage = newHash(message); + + RandStructcture randStruct = randomInit(hashPass[0] + ^ hashMessage[0], hashPass[1] ^ hashMessage[1]); + + int msgPos = 0; + int msgLength = message.length(); + int toPos = 0; + + while (msgPos++ < msgLength) { + to[toPos++] = (byte) (Math.floor(rnd(randStruct) * 31) + 64); + } + + /* Make it harder to break */ + byte extra = (byte) (Math.floor(rnd(randStruct) * 31)); + + for (int i = 0; i < to.length; i++) { + to[i] ^= extra; + } + + val = new String(to); + } + + return val; + } + + // ~ Inner Classes + // ---------------------------------------------------------- + + /** + * Converts a nested exception into a nicer message + * + * @param ex + * the exception to expand into a message. + * + * @return a message containing the exception, the message (if any), and a + * stacktrace. + */ + public static String stackTraceToString(Throwable ex) { + StringBuffer traceBuf = new StringBuffer(); + traceBuf.append(Messages.getString("Util.1")); //$NON-NLS-1$ + + if (ex != null) { + traceBuf.append(ex.getClass().getName()); + + String message = ex.getMessage(); + + if (message != null) { + traceBuf.append(Messages.getString("Util.2")); //$NON-NLS-1$ + traceBuf.append(message); + } + + StringWriter out = new StringWriter(); + + PrintWriter printOut = new PrintWriter(out); + + ex.printStackTrace(printOut); + + traceBuf.append(Messages.getString("Util.3")); //$NON-NLS-1$ + traceBuf.append(out.toString()); + } + + traceBuf.append(Messages.getString("Util.4")); //$NON-NLS-1$ + + return traceBuf.toString(); + } + + /** + * Does a network interface exist locally with the given hostname? + * + * @param hostname the hostname (or IP address in string form) to check + * @return true if it exists, false if no, or unable to determine due to VM version support + * of java.net.NetworkInterface + */ + public static boolean interfaceExists(String hostname) { + try { + Class networkInterfaceClass = Class.forName("java.net.NetworkInterface"); + return networkInterfaceClass.getMethod("getByName", null).invoke(networkInterfaceClass, new Object[] { hostname }) != null; + } catch (Throwable t) { + return false; + } + } + + public static long getCurrentTimeNanosOrMillis() { + if (systemNanoTimeMethod != null) { + try { + return ((Long)systemNanoTimeMethod.invoke(null, null)).longValue(); + } catch (IllegalArgumentException e) { + // ignore - fall through to currentTimeMillis() + } catch (IllegalAccessException e) { + // ignore - fall through to currentTimeMillis() + } catch (InvocationTargetException e) { + // ignore - fall through to currentTimeMillis() + } + } + + return System.currentTimeMillis(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/WatchableOutputStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/WatchableOutputStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/WatchableOutputStream.java 17 Aug 2012 14:57:10 -0000 1.1 @@ -0,0 +1,64 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/** + * A java.io.OutputStream used to write ASCII data into Blobs and Clobs + * + * @author Mark Matthews + */ +class WatchableOutputStream extends ByteArrayOutputStream { + // ~ Instance fields + // -------------------------------------------------------- + + private OutputStreamWatcher watcher; + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * @see java.io.OutputStream#close() + */ + public void close() throws IOException { + super.close(); + + if (this.watcher != null) { + this.watcher.streamClosed(this); + } + } + + /** + * DOCUMENT ME! + * + * @param watcher + * DOCUMENT ME! + */ + public void setWatcher(OutputStreamWatcher watcher) { + this.watcher = watcher; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/WatchableWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/WatchableWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/WatchableWriter.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,64 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +import java.io.CharArrayWriter; + +/** + * A java.io.Writer used to write unicode data into Blobs and Clobs + * + * @author Mark Matthews + */ +class WatchableWriter extends CharArrayWriter { + // ~ Instance fields + // -------------------------------------------------------- + + private WriterWatcher watcher; + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * @see java.io.Writer#close() + */ + public void close() { + super.close(); + + // Send data to watcher + if (this.watcher != null) { + this.watcher.writerClosed(this); + } + } + + /** + * DOCUMENT ME! + * + * @param watcher + * DOCUMENT ME! + */ + public void setWatcher(WriterWatcher watcher) { + this.watcher = watcher; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/WriterWatcher.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/WriterWatcher.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/WriterWatcher.java 17 Aug 2012 14:57:09 -0000 1.1 @@ -0,0 +1,42 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc; + +/** + * Objects that want to be notified of lifecycle events on a WatchableWriter + * should implement this interface, and register themselves with setWatcher() on + * the WatchableWriter instance. + * + * @author Mark Matthews + */ +interface WriterWatcher { + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Called when the Writer being watched has .close() called + */ + void writerClosed(WatchableWriter out); +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/3-0-Compat.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/3-0-Compat.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/3-0-Compat.properties 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,18 @@ +# +# Settings to maintain Connector/J 3.0.x compatibility +# (as much as it can be) +# + +emptyStringsConvertToZero=true +jdbcCompliantTruncation=false +noDatetimeStringSync=true +nullCatalogMeansCurrent=true +nullNamePatternMatchesAll=true +transformedBitIsBoolean=false +dontTrackOpenResources=true +zeroDateTimeBehavior=convertToNull +useServerPrepStmts=false +autoClosePStmtStreams=true +processEscapeCodesForPrepStmts=false +useFastDateParsing=false +populateInsertRowWithDefaultValues=false \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/clusterBase.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/clusterBase.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/clusterBase.properties 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,4 @@ +# Basic properties for clusters +autoReconnect=true +failOverReadOnly=false +roundRobinLoadBalance=true \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/coldFusion.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/coldFusion.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/coldFusion.properties 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,25 @@ +# +# Properties for optimal usage in ColdFusion +# +# Automagically pulled in if "autoConfigureForColdFusion" is "true" +# which is the default configuration of the driver +# + +# +# CF uses a _lot_ of RSMD.isCaseSensitive() - this optimizes it +# + +useDynamicCharsetInfo=false + +# +# CF's pool tends to be "chatty" like DBCP +# + +alwaysSendSetIsolation=false +useLocalSessionState=true + +# +# CF's pool seems to loose connectivity on page restart +# + +autoReconnect=true Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/fullDebug.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/fullDebug.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/fullDebug.properties 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,6 @@ +# Settings for 'max-debug' style situations +profileSQL=true +gatherPerMetrics=true +useUsageAdvisor=true +logSlowQueries=true +explainSlowQueries=true \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/maxPerformance.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/maxPerformance.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/maxPerformance.properties 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,29 @@ +# +# A configuration that maximizes performance, while +# still staying JDBC-compliant and not doing anything that +# would be "dangerous" to run-of-the-mill J2EE applications +# +# Note that because we're caching things like callable statements +# and the server configuration, this bundle isn't appropriate +# for use with servers that get config'd dynamically without +# restarting the application using this configuration bundle. + +cachePrepStmts=true +cacheCallableStatements=true + +cacheServerConfiguration=true + +# +# Reduces amount of calls to database to set +# session state. "Safe" as long as application uses +# Connection methods to set current database, autocommit +# and transaction isolation +# + +useLocalSessionState=true +elideSetAutoCommits=true +alwaysSendSetIsolation=false + +# Can cause high-GC pressure if timeouts are used on every +# query +enableQueryTimeouts=false \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/solarisMaxPerformance.properties =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/solarisMaxPerformance.properties,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/configs/solarisMaxPerformance.properties 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,13 @@ +# +# Solaris has pretty high syscall overhead, so these configs +# remove as many syscalls as possible. +# + +# Reduce recv() syscalls + +useUnbufferedInput=false +useReadAheadInput=false + +# Reduce number of calls to getTimeOfDay() + +maintainTimeStats=false \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLDataException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLDataException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLDataException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,43 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLDataException extends MySQLNonTransientException { + + public MySQLDataException() { + super(); + } + + public MySQLDataException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLDataException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLDataException(String reason) { + super(reason); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLIntegrityConstraintViolationException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLIntegrityConstraintViolationException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLIntegrityConstraintViolationException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,44 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLIntegrityConstraintViolationException extends + MySQLNonTransientException { + + public MySQLIntegrityConstraintViolationException() { + super(); + } + + public MySQLIntegrityConstraintViolationException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLIntegrityConstraintViolationException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLIntegrityConstraintViolationException(String reason) { + super(reason); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLInvalidAuthorizationSpecException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLInvalidAuthorizationSpecException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLInvalidAuthorizationSpecException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,44 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLInvalidAuthorizationSpecException extends + MySQLNonTransientException { + + public MySQLInvalidAuthorizationSpecException() { + super(); + } + + public MySQLInvalidAuthorizationSpecException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLInvalidAuthorizationSpecException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLInvalidAuthorizationSpecException(String reason) { + super(reason); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLNonTransientConnectionException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLNonTransientConnectionException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLNonTransientConnectionException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,44 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLNonTransientConnectionException extends + MySQLNonTransientException { + + public MySQLNonTransientConnectionException() { + super(); + } + + public MySQLNonTransientConnectionException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLNonTransientConnectionException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLNonTransientConnectionException(String reason) { + super(reason); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLNonTransientException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLNonTransientException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLNonTransientException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,45 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +import java.sql.SQLException; + +public class MySQLNonTransientException extends SQLException { + + public MySQLNonTransientException() { + super(); + } + + public MySQLNonTransientException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLNonTransientException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLNonTransientException(String reason) { + super(reason); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLSyntaxErrorException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLSyntaxErrorException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLSyntaxErrorException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,43 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLSyntaxErrorException extends MySQLNonTransientException { + + public MySQLSyntaxErrorException() { + super(); + } + + public MySQLSyntaxErrorException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLSyntaxErrorException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLSyntaxErrorException(String reason) { + super(reason); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTimeoutException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTimeoutException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTimeoutException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,48 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLTimeoutException extends MySQLTransientException { + + public MySQLTimeoutException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLTimeoutException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLTimeoutException(String reason) { + super(reason); + } + + public MySQLTimeoutException() { + super("Statement cancelled due to timeout or client request"); + } + + public int getErrorCode() { + // TODO Auto-generated method stub + return super.getErrorCode(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransactionRollbackException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransactionRollbackException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransactionRollbackException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,44 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLTransactionRollbackException extends MySQLTransientException { + + public MySQLTransactionRollbackException(String reason, String SQLState, + int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLTransactionRollbackException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLTransactionRollbackException(String reason) { + super(reason); + } + + public MySQLTransactionRollbackException() { + super(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransientConnectionException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransientConnectionException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransientConnectionException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,44 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +public class MySQLTransientConnectionException extends MySQLTransientException { + + public MySQLTransientConnectionException(String reason, String SQLState, + int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLTransientConnectionException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLTransientConnectionException(String reason) { + super(reason); + } + + public MySQLTransientConnectionException() { + super(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransientException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransientException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/exceptions/MySQLTransientException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,45 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.exceptions; + +import java.sql.SQLException; + +public class MySQLTransientException extends SQLException { + + public MySQLTransientException(String reason, String SQLState, int vendorCode) { + super(reason, SQLState, vendorCode); + } + + public MySQLTransientException(String reason, String SQLState) { + super(reason, SQLState); + } + + public MySQLTransientException(String reason) { + super(reason); + } + + public MySQLTransientException() { + super(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/c3p0/MysqlConnectionTester.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/c3p0/MysqlConnectionTester.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/c3p0/MysqlConnectionTester.java 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,134 @@ +/* + Copyright (C) 2002-2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ +package com.mysql.jdbc.integration.c3p0; + +import java.lang.reflect.Method; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import com.mchange.v2.c3p0.C3P0ProxyConnection; +import com.mchange.v2.c3p0.QueryConnectionTester; +import com.mysql.jdbc.CommunicationsException; + +/** + * ConnectionTester for C3P0 connection pool that uses the more efficient + * COM_PING method of testing connection 'liveness' for MySQL, and 'sorts' + * exceptions based on SQLState or class of 'CommunicationsException' for + * handling exceptions. + * + * @version $Id: MysqlConnectionTester.java,v 1.1.2.1 2005/05/13 18:58:39 + * mmatthews Exp $ + */ +public final class MysqlConnectionTester implements QueryConnectionTester { + + private static final long serialVersionUID = 3256444690067896368L; + + private static final Object[] NO_ARGS_ARRAY = new Object[0]; + + private Method pingMethod; + + public MysqlConnectionTester() { + try { + pingMethod = com.mysql.jdbc.Connection.class + .getMethod("ping", null); + } catch (Exception ex) { + // punt, we have no way to recover, other than we now use 'SELECT 1' + // for + // handling the connection testing. + } + } + + /* + * (non-Javadoc) + * + * @see com.mchange.v2.c3p0.ConnectionTester#activeCheckConnection(java.sql.Connection) + */ + public int activeCheckConnection(Connection con) { + try { + if (pingMethod != null) { + if (con instanceof com.mysql.jdbc.Connection) { + // We've been passed an instance of a MySQL connection -- + // no need for reflection + ((com.mysql.jdbc.Connection) con).ping(); + } else { + // Assume the connection is a C3P0 proxy + C3P0ProxyConnection castCon = (C3P0ProxyConnection) con; + castCon.rawConnectionOperation(pingMethod, + C3P0ProxyConnection.RAW_CONNECTION, NO_ARGS_ARRAY); + } + } else { + Statement pingStatement = null; + + try { + pingStatement = con.createStatement(); + pingStatement.executeQuery("SELECT 1").close(); + } finally { + if (pingStatement != null) { + pingStatement.close(); + } + } + } + + return CONNECTION_IS_OKAY; + } catch (Exception ex) { + return CONNECTION_IS_INVALID; + } + } + + /* + * (non-Javadoc) + * + * @see com.mchange.v2.c3p0.ConnectionTester#statusOnException(java.sql.Connection, + * java.lang.Throwable) + */ + public int statusOnException(Connection arg0, Throwable throwable) { + if (throwable instanceof CommunicationsException) { + return CONNECTION_IS_INVALID; + } + + if (throwable instanceof SQLException) { + String sqlState = ((SQLException) throwable).getSQLState(); + + if (sqlState != null && sqlState.startsWith("08")) { + return CONNECTION_IS_INVALID; + } + + return CONNECTION_IS_OKAY; + } + + // Runtime/Unchecked? + + return CONNECTION_IS_INVALID; + } + + /* + * (non-Javadoc) + * + * @see com.mchange.v2.c3p0.QueryConnectionTester#activeCheckConnection(java.sql.Connection, + * java.lang.String) + */ + public int activeCheckConnection(Connection arg0, String arg1) { + return CONNECTION_IS_OKAY; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/jboss/ExtendedMysqlExceptionSorter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/jboss/ExtendedMysqlExceptionSorter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/jboss/ExtendedMysqlExceptionSorter.java 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,54 @@ +/* + Copyright (C) 2002-2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ +package com.mysql.jdbc.integration.jboss; + +import java.sql.SQLException; + +import org.jboss.resource.adapter.jdbc.ExceptionSorter; +import org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter; + +/** + * Exception sorter used for JBoss to make recovery of downed/stale connections + * work more consistently. + * + * @version $Id: ExtendedMysqlExceptionSorter.java,v 1.1.2.1 2005/05/13 18:58:42 + * mmatthews Exp $ + */ +public final class ExtendedMysqlExceptionSorter extends MySQLExceptionSorter { + + /* + * (non-Javadoc) + * + * @see org.jboss.resource.adapter.jdbc.ExceptionSorter#isExceptionFatal(java.sql.SQLException) + */ + public boolean isExceptionFatal(SQLException ex) { + String sqlState = ex.getSQLState(); + + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + + return super.isExceptionFatal(ex); + } + +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/jboss/MysqlValidConnectionChecker.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/jboss/MysqlValidConnectionChecker.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/integration/jboss/MysqlValidConnectionChecker.java 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,129 @@ +/* + Copyright (C) 2002-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +package com.mysql.jdbc.integration.jboss; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import org.jboss.resource.adapter.jdbc.ValidConnectionChecker; + +import com.mysql.jdbc.SQLError; + +/** + * A more efficient connection checker for JBoss. + * + * @version $Id: MysqlValidConnectionChecker.java,v 1.1.2.1 2005/05/13 18:58:42 + * mmatthews Exp $ + */ +public final class MysqlValidConnectionChecker implements + ValidConnectionChecker, Serializable { + + private static final long serialVersionUID = 3258689922776119348L; + + private Method pingMethod; + + private Method pingMethodWrapped; + + private final static Object[] NO_ARGS_OBJECT_ARRAY = new Object[0]; + + public MysqlValidConnectionChecker() { + try { + // Avoid classloader goofiness + Class mysqlConnection = Thread.currentThread() + .getContextClassLoader().loadClass( + "com.mysql.jdbc.Connection"); + + pingMethod = mysqlConnection.getMethod("ping", null); + + Class mysqlConnectionWrapper = Thread.currentThread() + .getContextClassLoader().loadClass( + "com.mysql.jdbc.jdbc2.optional.ConnectionWrapper"); + + pingMethodWrapped = mysqlConnectionWrapper.getMethod("ping", null); + } catch (Exception ex) { + // Punt, we'll use 'SELECT 1' to do the check + } + } + + /* + * (non-Javadoc) + * + * @see org.jboss.resource.adapter.jdbc.ValidConnectionChecker#isValidConnection(java.sql.Connection) + */ + public SQLException isValidConnection(Connection conn) { + if (conn instanceof com.mysql.jdbc.Connection) { + if (pingMethod != null) { + try { + this.pingMethod.invoke(conn, null); + + return null; + } catch (Exception ex) { + if (ex instanceof SQLException) { + return (SQLException) ex; + } + + return SQLError.createSQLException("Ping failed: " + ex.toString()); + } + } + } else if (conn instanceof com.mysql.jdbc.jdbc2.optional.ConnectionWrapper) { + if (pingMethodWrapped != null) { + try { + this.pingMethodWrapped.invoke(conn, null); + + return null; + } catch (Exception ex) { + if (ex instanceof SQLException) { + return (SQLException) ex; + } + + return SQLError.createSQLException("Ping failed: " + ex.toString()); + } + } + } + + // Punt and use 'SELECT 1' + + Statement pingStatement = null; + + try { + pingStatement = conn.createStatement(); + + pingStatement.executeQuery("SELECT 1").close(); + + return null; + } catch (SQLException sqlEx) { + return sqlEx; + } finally { + if (pingStatement != null) { + try { + pingStatement.close(); + } catch (SQLException sqlEx) { + // can't do anything about it here + } + } + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/CallableStatementWrapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/CallableStatementWrapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/CallableStatementWrapper.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,1765 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + */ + +package com.mysql.jdbc.jdbc2.optional; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.Ref; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Map; + +import com.mysql.jdbc.SQLError; + +/** + * Wraps callable statements created by pooled connections. + * + * @version $Id: CallableStatementWrapper.java,v 1.1.2.1 2005/05/13 18:58:38 + * mmatthews Exp $ + */ +public class CallableStatementWrapper extends PreparedStatementWrapper + implements CallableStatement { + + /** + * @param c + * @param conn + * @param toWrap + */ + public CallableStatementWrapper(ConnectionWrapper c, + MysqlPooledConnection conn, CallableStatement toWrap) { + super(c, conn, toWrap); + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#registerOutParameter(int, int) + */ + public void registerOutParameter(int parameterIndex, int sqlType) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).registerOutParameter( + parameterIndex, sqlType); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#registerOutParameter(int, int, int) + */ + public void registerOutParameter(int parameterIndex, int sqlType, int scale) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).registerOutParameter( + parameterIndex, sqlType, scale); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#wasNull() + */ + public boolean wasNull() throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).wasNull(); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getString(int) + */ + public String getString(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getString(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBoolean(int) + */ + public boolean getBoolean(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBoolean(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getByte(int) + */ + public byte getByte(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getByte(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getShort(int) + */ + public short getShort(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getShort(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getInt(int) + */ + public int getInt(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getInt(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getLong(int) + */ + public long getLong(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getLong(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getFloat(int) + */ + public float getFloat(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getFloat(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getDouble(int) + */ + public double getDouble(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getDouble(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBigDecimal(int, int) + */ + public BigDecimal getBigDecimal(int parameterIndex, int scale) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getBigDecimal( + parameterIndex, scale); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBytes(int) + */ + public byte[] getBytes(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBytes(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getDate(int) + */ + public Date getDate(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getDate(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTime(int) + */ + public Time getTime(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getTime(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTimestamp(int) + */ + public Timestamp getTimestamp(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getTimestamp(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getObject(int) + */ + public Object getObject(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getObject(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBigDecimal(int) + */ + public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBigDecimal(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getObject(int, java.util.Map) + */ + public Object getObject(int parameterIndex, Map typeMap) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getObject( + parameterIndex, typeMap); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getRef(int) + */ + public Ref getRef(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getRef(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBlob(int) + */ + public Blob getBlob(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBlob(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getClob(int) + */ + public Clob getClob(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getClob(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getArray(int) + */ + public Array getArray(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getArray(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getDate(int, java.util.Calendar) + */ + public Date getDate(int parameterIndex, Calendar cal) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getDate( + parameterIndex, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTime(int, java.util.Calendar) + */ + public Time getTime(int parameterIndex, Calendar cal) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getTime( + parameterIndex, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTimestamp(int, java.util.Calendar) + */ + public Timestamp getTimestamp(int parameterIndex, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getTimestamp( + parameterIndex, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#registerOutParameter(int, int, + * java.lang.String) + */ + public void registerOutParameter(int paramIndex, int sqlType, + String typeName) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).registerOutParameter( + paramIndex, sqlType, typeName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, + * int) + */ + public void registerOutParameter(String parameterName, int sqlType) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).registerOutParameter( + parameterName, sqlType); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, + * int, int) + */ + public void registerOutParameter(String parameterName, int sqlType, + int scale) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).registerOutParameter( + parameterName, sqlType, scale); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, + * int, java.lang.String) + */ + public void registerOutParameter(String parameterName, int sqlType, + String typeName) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).registerOutParameter( + parameterName, sqlType, typeName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getURL(int) + */ + public URL getURL(int parameterIndex) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getURL(parameterIndex); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setURL(java.lang.String, java.net.URL) + */ + public void setURL(String parameterName, URL val) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setURL(parameterName, + val); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setNull(java.lang.String, int) + */ + public void setNull(String parameterName, int sqlType) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setNull(parameterName, + sqlType); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setBoolean(java.lang.String, boolean) + */ + public void setBoolean(String parameterName, boolean x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setBoolean( + parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setByte(java.lang.String, byte) + */ + public void setByte(String parameterName, byte x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt) + .setByte(parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setShort(java.lang.String, short) + */ + public void setShort(String parameterName, short x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setShort(parameterName, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setInt(java.lang.String, int) + */ + public void setInt(String parameterName, int x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setInt(parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setLong(java.lang.String, long) + */ + public void setLong(String parameterName, long x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt) + .setLong(parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setFloat(java.lang.String, float) + */ + public void setFloat(String parameterName, float x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setFloat(parameterName, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setDouble(java.lang.String, double) + */ + public void setDouble(String parameterName, double x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setDouble(parameterName, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setBigDecimal(java.lang.String, + * java.math.BigDecimal) + */ + public void setBigDecimal(String parameterName, BigDecimal x) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setBigDecimal( + parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setString(java.lang.String, + * java.lang.String) + */ + public void setString(String parameterName, String x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setString(parameterName, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setBytes(java.lang.String, byte[]) + */ + public void setBytes(String parameterName, byte[] x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setBytes(parameterName, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date) + */ + public void setDate(String parameterName, Date x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt) + .setDate(parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time) + */ + public void setTime(String parameterName, Time x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt) + .setTime(parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setTimestamp(java.lang.String, + * java.sql.Timestamp) + */ + public void setTimestamp(String parameterName, Timestamp x) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setTimestamp( + parameterName, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setAsciiStream(java.lang.String, + * java.io.InputStream, int) + */ + public void setAsciiStream(String parameterName, InputStream x, int length) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setAsciiStream( + parameterName, x, length); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setBinaryStream(java.lang.String, + * java.io.InputStream, int) + */ + public void setBinaryStream(String parameterName, InputStream x, int length) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setBinaryStream( + parameterName, x, length); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setObject(java.lang.String, + * java.lang.Object, int, int) + */ + public void setObject(String parameterName, Object x, int targetSqlType, + int scale) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setObject(parameterName, + x, targetSqlType, scale); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setObject(java.lang.String, + * java.lang.Object, int) + */ + public void setObject(String parameterName, Object x, int targetSqlType) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setObject(parameterName, + x, targetSqlType); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setObject(java.lang.String, + * java.lang.Object) + */ + public void setObject(String parameterName, Object x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setObject(parameterName, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setCharacterStream(java.lang.String, + * java.io.Reader, int) + */ + public void setCharacterStream(String parameterName, Reader reader, + int length) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setCharacterStream( + parameterName, reader, length); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date, + * java.util.Calendar) + */ + public void setDate(String parameterName, Date x, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setDate(parameterName, + x, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time, + * java.util.Calendar) + */ + public void setTime(String parameterName, Time x, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setTime(parameterName, + x, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setTimestamp(java.lang.String, + * java.sql.Timestamp, java.util.Calendar) + */ + public void setTimestamp(String parameterName, Timestamp x, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setTimestamp( + parameterName, x, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#setNull(java.lang.String, int, + * java.lang.String) + */ + public void setNull(String parameterName, int sqlType, String typeName) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((CallableStatement) this.wrappedStmt).setNull(parameterName, + sqlType, typeName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getString(int) + */ + public String getString(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getString(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBoolean(int) + */ + public boolean getBoolean(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBoolean(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getByte(int) + */ + public byte getByte(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getByte(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getShort(int) + */ + public short getShort(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getShort(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getInt(int) + */ + public int getInt(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getInt(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getLong(int) + */ + public long getLong(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getLong(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getFloat(int) + */ + public float getFloat(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getFloat(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getDouble(int) + */ + public double getDouble(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getDouble(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBytes(int) + */ + public byte[] getBytes(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBytes(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getDate(int) + */ + public Date getDate(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getDate(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTime(int) + */ + public Time getTime(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getTime(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTimestamp(int) + */ + public Timestamp getTimestamp(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getTimestamp(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getObject(int) + */ + public Object getObject(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getObject(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBigDecimal(int) + */ + public BigDecimal getBigDecimal(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBigDecimal(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getObject(int, java.util.Map) + */ + public Object getObject(String parameterName, Map typeMap) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getObject( + parameterName, typeMap); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getRef(int) + */ + public Ref getRef(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getRef(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getBlob(int) + */ + public Blob getBlob(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getBlob(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getClob(int) + */ + public Clob getClob(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getClob(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getArray(int) + */ + public Array getArray(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getArray(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getDate(int, java.util.Calendar) + */ + public Date getDate(String parameterName, Calendar cal) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getDate( + parameterName, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTime(int, java.util.Calendar) + */ + public Time getTime(String parameterName, Calendar cal) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getTime( + parameterName, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getTimestamp(int, java.util.Calendar) + */ + public Timestamp getTimestamp(String parameterName, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt).getTimestamp( + parameterName, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.CallableStatement#getURL(java.lang.String) + */ + public URL getURL(String parameterName) throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((CallableStatement) this.wrappedStmt) + .getURL(parameterName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/ConnectionWrapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/ConnectionWrapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/ConnectionWrapper.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,839 @@ +/* + Copyright (C) 2002-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Savepoint; +import java.sql.Statement; + +import com.mysql.jdbc.MysqlErrorNumbers; +import com.mysql.jdbc.SQLError; + +/** + * This class serves as a wrapper for the org.gjt.mm.mysql.jdbc2.Connection + * class. It is returned to the application server which may wrap it again and + * then return it to the application client in response to + * dataSource.getConnection(). + * + *

+ * All method invocations are forwarded to org.gjt.mm.mysql.jdbc2.Connection + * unless the close method was previously called, in which case a sqlException + * is thrown. The close method performs a 'logical close' on the connection. + *

+ * + *

+ * All sqlExceptions thrown by the physical connection are intercepted and sent + * to connectionEvent listeners before being thrown to client. + *

+ * + * @author Todd Wolff todd.wolff_at_prodigy.net + * + * @see org.gjt.mm.mysql.jdbc2.Connection + * @see org.gjt.mm.mysql.jdbc2.optional.MysqlPooledConnection + */ +public class ConnectionWrapper extends WrapperBase implements Connection { + private com.mysql.jdbc.Connection mc = null; + + private MysqlPooledConnection mpc = null; + + private String invalidHandleStr = "Logical handle no longer valid"; + + private boolean closed; + private boolean isForXa; + + /** + * Construct a new LogicalHandle and set instance variables + * + * @param mysqlPooledConnection + * reference to object that instantiated this object + * @param mysqlConnection + * physical connection to db + * + * @throws SQLException + * if an error occurs. + */ + public ConnectionWrapper(MysqlPooledConnection mysqlPooledConnection, + com.mysql.jdbc.Connection mysqlConnection, + boolean forXa) throws SQLException { + this.mpc = mysqlPooledConnection; + this.mc = mysqlConnection; + this.closed = false; + this.pooledConnection = this.mpc; + this.isForXa = forXa; + + if (this.isForXa) { + setInGlobalTx(false); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#setAutoCommit + */ + public void setAutoCommit(boolean autoCommit) throws SQLException { + checkClosed(); + + if (autoCommit && isInGlobalTx()) { + throw SQLError.createSQLException("Can't set autocommit to 'true' on an XAConnection", + SQLError.SQL_STATE_INVALID_TRANSACTION_TERMINATION, + MysqlErrorNumbers.ER_XA_RMERR); + } + + try { + this.mc.setAutoCommit(autoCommit); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#getAutoCommit() + */ + public boolean getAutoCommit() throws SQLException { + checkClosed(); + + try { + return this.mc.getAutoCommit(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return false; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#setCatalog() + */ + public void setCatalog(String catalog) throws SQLException { + checkClosed(); + + try { + this.mc.setCatalog(catalog); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @return the current catalog + * + * @throws SQLException + * if an error occurs + */ + public String getCatalog() throws SQLException { + checkClosed(); + + try { + return this.mc.getCatalog(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#isClosed() + */ + public boolean isClosed() throws SQLException { + return (this.closed || this.mc.isClosed()); + } + + public boolean isMasterConnection() throws SQLException { + return this.mc.isMasterConnection(); + } + + /** + * @see Connection#setHoldability(int) + */ + public void setHoldability(int arg0) throws SQLException { + checkClosed(); + + try { + this.mc.setHoldability(arg0); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * @see Connection#getHoldability() + */ + public int getHoldability() throws SQLException { + checkClosed(); + + try { + return this.mc.getHoldability(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return Statement.CLOSE_CURRENT_RESULT; // we don't reach this code, + // compiler can't tell + } + + /** + * Allows clients to determine how long this connection has been idle. + * + * @return how long the connection has been idle. + */ + public long getIdleFor() { + return this.mc.getIdleFor(); + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @return a metadata instance + * + * @throws SQLException + * if an error occurs + */ + public java.sql.DatabaseMetaData getMetaData() throws SQLException { + checkClosed(); + + try { + return this.mc.getMetaData(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#setReadOnly() + */ + public void setReadOnly(boolean readOnly) throws SQLException { + checkClosed(); + + try { + this.mc.setReadOnly(readOnly); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#isReadOnly() + */ + public boolean isReadOnly() throws SQLException { + checkClosed(); + + try { + return this.mc.isReadOnly(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return false; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#setSavepoint() + */ + public java.sql.Savepoint setSavepoint() throws SQLException { + checkClosed(); + + if (isInGlobalTx()) { + throw SQLError.createSQLException("Can't set autocommit to 'true' on an XAConnection", + SQLError.SQL_STATE_INVALID_TRANSACTION_TERMINATION, + MysqlErrorNumbers.ER_XA_RMERR); + } + + try { + return this.mc.setSavepoint(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#setSavepoint(String) + */ + public java.sql.Savepoint setSavepoint(String arg0) throws SQLException { + checkClosed(); + + if (isInGlobalTx()) { + throw SQLError.createSQLException("Can't set autocommit to 'true' on an XAConnection", + SQLError.SQL_STATE_INVALID_TRANSACTION_TERMINATION, + MysqlErrorNumbers.ER_XA_RMERR); + } + + try { + return this.mc.setSavepoint(arg0); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#setTransactionIsolation() + */ + public void setTransactionIsolation(int level) throws SQLException { + checkClosed(); + + try { + this.mc.setTransactionIsolation(level); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#getTransactionIsolation() + */ + public int getTransactionIsolation() throws SQLException { + checkClosed(); + + try { + return this.mc.getTransactionIsolation(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return TRANSACTION_REPEATABLE_READ; // we don't reach this code, + // compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#setTypeMap() + */ + public void setTypeMap(java.util.Map map) throws SQLException { + checkClosed(); + + try { + this.mc.setTypeMap(map); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#getTypeMap() + */ + public java.util.Map getTypeMap() throws SQLException { + checkClosed(); + + try { + return this.mc.getTypeMap(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#getWarnings + */ + public java.sql.SQLWarning getWarnings() throws SQLException { + checkClosed(); + + try { + return this.mc.getWarnings(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @throws SQLException + * if an error occurs + */ + public void clearWarnings() throws SQLException { + checkClosed(); + + try { + this.mc.clearWarnings(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * The physical connection is not actually closed. the physical connection + * is closed when the application server calls + * mysqlPooledConnection.close(). this object is de-referenced by the pooled + * connection each time mysqlPooledConnection.getConnection() is called by + * app server. + * + * @throws SQLException + * if an error occurs + */ + public void close() throws SQLException { + close(true); + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @throws SQLException + * if an error occurs + */ + public void commit() throws SQLException { + checkClosed(); + + if (isInGlobalTx()) { + throw SQLError.createSQLException( + "Can't call commit() on an XAConnection associated with a global transaction", + SQLError.SQL_STATE_INVALID_TRANSACTION_TERMINATION, + MysqlErrorNumbers.ER_XA_RMERR); + } + + try { + this.mc.commit(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#createStatement() + */ + public java.sql.Statement createStatement() throws SQLException { + checkClosed(); + + try { + return new StatementWrapper(this, this.mpc, this.mc + .createStatement()); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#createStatement() + */ + public java.sql.Statement createStatement(int resultSetType, + int resultSetConcurrency) throws SQLException { + checkClosed(); + + try { + return new StatementWrapper(this, this.mpc, this.mc + .createStatement(resultSetType, resultSetConcurrency)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#createStatement(int, int, int) + */ + public java.sql.Statement createStatement(int arg0, int arg1, int arg2) + throws SQLException { + checkClosed(); + + try { + return new StatementWrapper(this, this.mpc, this.mc + .createStatement(arg0, arg1, arg2)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#nativeSQL() + */ + public String nativeSQL(String sql) throws SQLException { + checkClosed(); + + try { + return this.mc.nativeSQL(sql); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#prepareCall() + */ + public java.sql.CallableStatement prepareCall(String sql) + throws SQLException { + checkClosed(); + + try { + return new CallableStatementWrapper(this, this.mpc, this.mc + .prepareCall(sql)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#prepareCall() + */ + public java.sql.CallableStatement prepareCall(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException { + checkClosed(); + + try { + return new CallableStatementWrapper(this, this.mpc, this.mc + .prepareCall(sql, resultSetType, resultSetConcurrency)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#prepareCall(String, int, int, int) + */ + public java.sql.CallableStatement prepareCall(String arg0, int arg1, + int arg2, int arg3) throws SQLException { + checkClosed(); + + try { + return new CallableStatementWrapper(this, this.mpc, this.mc + .prepareCall(arg0, arg1, arg2, arg3)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + public java.sql.PreparedStatement clientPrepare(String sql) throws SQLException + { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, + this.mc.clientPrepareStatement(sql)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; + } + + public java.sql.PreparedStatement clientPrepare(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException + { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, + this.mc.clientPrepareStatement(sql, + resultSetType, resultSetConcurrency)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#prepareStatement() + */ + public java.sql.PreparedStatement prepareStatement(String sql) + throws SQLException { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, this.mc + .prepareStatement(sql)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#prepareStatement() + */ + public java.sql.PreparedStatement prepareStatement(String sql, + int resultSetType, int resultSetConcurrency) throws SQLException { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, this.mc + .prepareStatement(sql, resultSetType, resultSetConcurrency)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#prepareStatement(String, int, int, int) + */ + public java.sql.PreparedStatement prepareStatement(String arg0, int arg1, + int arg2, int arg3) throws SQLException { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, this.mc + .prepareStatement(arg0, arg1, arg2, arg3)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#prepareStatement(String, int) + */ + public java.sql.PreparedStatement prepareStatement(String arg0, int arg1) + throws SQLException { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, this.mc + .prepareStatement(arg0, arg1)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#prepareStatement(String, int[]) + */ + public java.sql.PreparedStatement prepareStatement(String arg0, int[] arg1) + throws SQLException { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, this.mc + .prepareStatement(arg0, arg1)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#prepareStatement(String, String[]) + */ + public java.sql.PreparedStatement prepareStatement(String arg0, + String[] arg1) throws SQLException { + checkClosed(); + + try { + return new PreparedStatementWrapper(this, this.mpc, this.mc + .prepareStatement(arg0, arg1)); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + + return null; // we don't reach this code, compiler can't tell + } + + /** + * @see Connection#releaseSavepoint(Savepoint) + */ + public void releaseSavepoint(Savepoint arg0) throws SQLException { + checkClosed(); + + try { + this.mc.releaseSavepoint(arg0); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * Passes call to method on physical connection instance. Notifies listeners + * of any caught exceptions before re-throwing to client. + * + * @see java.sql.Connection#rollback() + */ + public void rollback() throws SQLException { + checkClosed(); + + + if (isInGlobalTx()) { + throw SQLError.createSQLException("Can't call rollback() on an XAConnection associated with a global transaction", + SQLError.SQL_STATE_INVALID_TRANSACTION_TERMINATION, + MysqlErrorNumbers.ER_XA_RMERR); + } + + try { + this.mc.rollback(); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + /** + * @see Connection#rollback(Savepoint) + */ + public void rollback(Savepoint arg0) throws SQLException { + checkClosed(); + + if (isInGlobalTx()) { + throw SQLError.createSQLException("Can't call rollback() on an XAConnection associated with a global transaction", + SQLError.SQL_STATE_INVALID_TRANSACTION_TERMINATION, + MysqlErrorNumbers.ER_XA_RMERR); + } + + try { + this.mc.rollback(arg0); + } catch (SQLException sqlException) { + checkAndFireConnectionError(sqlException); + } + } + + public boolean isSameResource(Connection c) { + if (c instanceof ConnectionWrapper) { + return this.mc.isSameResource(((ConnectionWrapper)c).mc); + } else if (c instanceof com.mysql.jdbc.Connection) { + return this.mc.isSameResource((com.mysql.jdbc.Connection)c); + } + + return false; + } + + protected void close(boolean fireClosedEvent) throws SQLException { + synchronized (this.mpc) { + if (this.closed) { + return; + } + + if (!isInGlobalTx() + && this.mc.getRollbackOnPooledClose() + && !this.getAutoCommit()) { + rollback(); + } + + if (fireClosedEvent) { + this.mpc.callListener( + MysqlPooledConnection.CONNECTION_CLOSED_EVENT, null); + } + + // set closed status to true so that if application client tries to + // make additional + // calls a sqlException will be thrown. The physical connection is + // re-used by the pooled connection each time getConnection is + // called. + this.closed = true; + } + } + + private void checkClosed() throws SQLException { + if (this.closed) { + throw SQLError.createSQLException(this.invalidHandleStr); + } + } + + protected boolean isInGlobalTx() { + return this.mc.isInGlobalTx(); + } + + protected void setInGlobalTx(boolean flag) { + this.mc.setInGlobalTx(flag); + } + + public void ping() throws SQLException { + if (this.mc != null) { + this.mc.ping(); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlConnectionPoolDataSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlConnectionPoolDataSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlConnectionPoolDataSource.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,85 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.ConnectionPoolDataSource; +import javax.sql.PooledConnection; + +/** + * This class is used to obtain a physical connection and instantiate and return + * a MysqlPooledConnection. J2EE application servers map client calls to + * dataSource.getConnection to this class based upon mapping set within + * deployment descriptor. This class extends MysqlDataSource. + * + * @see javax.sql.PooledConnection + * @see javax.sql.ConnectionPoolDataSource + * @see org.gjt.mm.mysql.MysqlDataSource + * @author Todd Wolff + */ +public class MysqlConnectionPoolDataSource extends MysqlDataSource implements + ConnectionPoolDataSource { + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Returns a pooled connection. + * + * @exception SQLException + * if an error occurs + * @return a PooledConnection + */ + public synchronized PooledConnection getPooledConnection() + throws SQLException { + Connection connection = getConnection(); + MysqlPooledConnection mysqlPooledConnection = new MysqlPooledConnection( + (com.mysql.jdbc.Connection)connection); + + return mysqlPooledConnection; + } + + /** + * This method is invoked by the container. Obtains physical connection + * using mySql.Driver class and returns a mysqlPooledConnection object. + * + * @param s + * user name + * @param s1 + * password + * @exception SQLException + * if an error occurs + * @return a PooledConnection + */ + public synchronized PooledConnection getPooledConnection(String s, String s1) + throws SQLException { + Connection connection = getConnection(s, s1); + MysqlPooledConnection mysqlPooledConnection = new MysqlPooledConnection( + (com.mysql.jdbc.Connection)connection); + + return mysqlPooledConnection; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlDataSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlDataSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlDataSource.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,427 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import com.mysql.jdbc.ConnectionProperties; +import com.mysql.jdbc.NonRegisteringDriver; + +import java.io.PrintWriter; +import java.io.Serializable; + +import java.sql.SQLException; + +import java.util.Properties; + +import javax.naming.NamingException; +import javax.naming.Reference; +import javax.naming.Referenceable; +import javax.naming.StringRefAddr; + +import javax.sql.DataSource; + +/** + * A JNDI DataSource for a Mysql JDBC connection + * + * @author Mark Matthews + */ +public class MysqlDataSource extends ConnectionProperties implements + DataSource, Referenceable, Serializable { + /** The driver to create connections with */ + protected static com.mysql.jdbc.Driver mysqlDriver = null; + + static { + try { + mysqlDriver = (com.mysql.jdbc.Driver) Class.forName( + "com.mysql.jdbc.Driver").newInstance(); + } catch (Exception E) { + throw new RuntimeException( + "Can not load Driver class com.mysql.jdbc.Driver"); + } + } + + /** Log stream */ + protected PrintWriter logWriter = null; + + /** Database Name */ + protected String databaseName = null; + + /** Character Encoding */ + protected String encoding = null; + + /** Hostname */ + protected String hostName = null; + + /** Password */ + protected String password = null; + + /** The profileSql property */ + protected String profileSql = "false"; + + /** The JDBC URL */ + protected String url = null; + + /** User name */ + protected String user = null; + + /** Should we construct the URL, or has it been set explicitly */ + protected boolean explicitUrl = false; + + /** Port number */ + protected int port = 3306; + + /** + * Default no-arg constructor for Serialization + */ + public MysqlDataSource() { + } + + /** + * Creates a new connection using the already configured username and + * password. + * + * @return a connection to the database + * + * @throws SQLException + * if an error occurs + */ + public java.sql.Connection getConnection() throws SQLException { + return getConnection(this.user, this.password); + } + + /** + * Creates a new connection with the given username and password + * + * @param userID + * the user id to connect with + * @param password + * the password to connect with + * + * @return a connection to the database + * + * @throws SQLException + * if an error occurs + */ + public java.sql.Connection getConnection(String userID, String pass) + throws SQLException { + Properties props = new Properties(); + + if (userID != null) { + props.setProperty(NonRegisteringDriver.USER_PROPERTY_KEY, userID); + } + + if (pass != null) { + props.setProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY, pass); + } + + exposeAsProperties(props); + + return getConnection(props); + } + + /** + * Sets the database name. + * + * @param dbName + * the name of the database + */ + public void setDatabaseName(String dbName) { + this.databaseName = dbName; + } + + /** + * Gets the name of the database + * + * @return the name of the database for this data source + */ + public String getDatabaseName() { + return (this.databaseName != null) ? this.databaseName : ""; + } + + /** + * Sets the log writer for this data source. + * + * @see javax.sql.DataSource#setLogWriter(PrintWriter) + */ + public void setLogWriter(PrintWriter output) throws SQLException { + this.logWriter = output; + } + + /** + * Returns the log writer for this data source + * + * @return the log writer for this data source + */ + public java.io.PrintWriter getLogWriter() { + return this.logWriter; + } + + /** + * DOCUMENT ME! + * + * @param seconds + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public void setLoginTimeout(int seconds) throws SQLException { + } + + /** + * Returns the login timeout + * + * @return the login timeout + */ + public int getLoginTimeout() { + return 0; + } + + /** + * Sets the password + * + * @param pass + * the password + */ + public void setPassword(String pass) { + this.password = pass; + } + + /** + * Sets the database port. + * + * @param p + * the port + */ + public void setPort(int p) { + this.port = p; + } + + /** + * Returns the port number + * + * @return the port number + */ + public int getPort() { + return this.port; + } + + /** + * Sets the port number + * + * @param p + * the port + * + * @see #setPort + */ + public void setPortNumber(int p) { + setPort(p); + } + + /** + * Returns the port number + * + * @return the port number + */ + public int getPortNumber() { + return getPort(); + } + + /** + * DOCUMENT ME! + * + * @param ref + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + */ + public void setPropertiesViaRef(Reference ref) throws SQLException { + super.initializeFromRef(ref); + } + + /** + * Required method to support this class as a Referenceable. + * + * @return a Reference to this data source + * + * @throws NamingException + * if a JNDI error occurs + */ + public Reference getReference() throws NamingException { + String factoryName = "com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory"; + Reference ref = new Reference(getClass().getName(), factoryName, null); + ref.add(new StringRefAddr(NonRegisteringDriver.USER_PROPERTY_KEY, + getUser())); + ref.add(new StringRefAddr(NonRegisteringDriver.PASSWORD_PROPERTY_KEY, + this.password)); + ref.add(new StringRefAddr("serverName", getServerName())); + ref.add(new StringRefAddr("port", "" + getPort())); + ref.add(new StringRefAddr("databaseName", getDatabaseName())); + ref.add(new StringRefAddr("url", getUrl())); + ref.add(new StringRefAddr("explicitUrl", String + .valueOf(this.explicitUrl))); + + // + // Now store all of the 'non-standard' properties... + // + try { + storeToRef(ref); + } catch (SQLException sqlEx) { + throw new NamingException(sqlEx.getMessage()); + } + + return ref; + } + + /** + * Sets the server name. + * + * @param serverName + * the server name + */ + public void setServerName(String serverName) { + this.hostName = serverName; + } + + /** + * Returns the name of the database server + * + * @return the name of the database server + */ + public String getServerName() { + return (this.hostName != null) ? this.hostName : ""; + } + + // + // I've seen application servers use both formats + // URL or url (doh) + // + + /** + * Sets the URL for this connection + * + * @param url + * the URL for this connection + */ + public void setURL(String url) { + setUrl(url); + } + + /** + * Returns the URL for this connection + * + * @return the URL for this connection + */ + public String getURL() { + return getUrl(); + } + + /** + * This method is used by the app server to set the url string specified + * within the datasource deployment descriptor. It is discovered using + * introspection and matches if property name in descriptor is "url". + * + * @param url + * url to be used within driver.connect + */ + public void setUrl(String url) { + this.url = url; + this.explicitUrl = true; + } + + /** + * Returns the JDBC URL that will be used to create the database connection. + * + * @return the URL for this connection + */ + public String getUrl() { + if (!this.explicitUrl) { + String builtUrl = "jdbc:mysql://"; + builtUrl = builtUrl + getServerName() + ":" + getPort() + "/" + + getDatabaseName(); + + return builtUrl; + } + + return this.url; + } + + /** + * Sets the user ID. + * + * @param userID + * the User ID + */ + public void setUser(String userID) { + this.user = userID; + } + + /** + * Returns the configured user for this connection + * + * @return the user for this connection + */ + public String getUser() { + return this.user; + } + + /** + * Creates a connection using the specified properties. + * + * @param props + * the properties to connect with + * + * @return a connection to the database + * + * @throws SQLException + * if an error occurs + */ + protected java.sql.Connection getConnection(Properties props) + throws SQLException { + String jdbcUrlToUse = null; + + if (!this.explicitUrl) { + StringBuffer jdbcUrl = new StringBuffer("jdbc:mysql://"); + + if (this.hostName != null) { + jdbcUrl.append(this.hostName); + } + + jdbcUrl.append(":"); + jdbcUrl.append(this.port); + jdbcUrl.append("/"); + + if (this.databaseName != null) { + jdbcUrl.append(this.databaseName); + } + + jdbcUrlToUse = jdbcUrl.toString(); + } else { + jdbcUrlToUse = this.url; + } + + return mysqlDriver.connect(jdbcUrlToUse, props); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlDataSourceFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlDataSourceFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlDataSourceFactory.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,151 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import java.util.Hashtable; + +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.RefAddr; +import javax.naming.Reference; +import javax.naming.spi.ObjectFactory; + +import com.mysql.jdbc.NonRegisteringDriver; + +/** + * Factory class for MysqlDataSource objects + * + * @author Mark Matthews + */ +public class MysqlDataSourceFactory implements ObjectFactory { + /** + * The class name for a standard MySQL DataSource. + */ + protected final static String DATA_SOURCE_CLASS_NAME = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource"; + + /** + * The class name for a poolable MySQL DataSource. + */ + protected final static String POOL_DATA_SOURCE_CLASS_NAME = "com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"; + + /** + * The class name for a MysqlXADataSource + */ + + protected final static String XA_DATA_SOURCE_CLASS_NAME = "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"; + + /** + * DOCUMENT ME! + * + * @param refObj + * DOCUMENT ME! + * @param nm + * DOCUMENT ME! + * @param ctx + * DOCUMENT ME! + * @param env + * DOCUMENT ME! + * @return DOCUMENT ME! + * @throws Exception + * DOCUMENT ME! + */ + public Object getObjectInstance(Object refObj, Name nm, Context ctx, + Hashtable env) throws Exception { + Reference ref = (Reference) refObj; + String className = ref.getClassName(); + + if ((className != null) + && (className.equals(DATA_SOURCE_CLASS_NAME) || className + .equals(POOL_DATA_SOURCE_CLASS_NAME) || + className.equals(XA_DATA_SOURCE_CLASS_NAME))) { + MysqlDataSource dataSource = null; + + try { + dataSource = (MysqlDataSource) Class.forName(className) + .newInstance(); + } catch (Exception ex) { + throw new RuntimeException("Unable to create DataSource of " + + "class '" + className + "', reason: " + ex.toString()); + } + + int portNumber = 3306; + + String portNumberAsString = nullSafeRefAddrStringGet("port", ref); + + if (portNumberAsString != null) { + portNumber = Integer.parseInt(portNumberAsString); + } + + dataSource.setPort(portNumber); + + String user = nullSafeRefAddrStringGet(NonRegisteringDriver.USER_PROPERTY_KEY, ref); + + if (user != null) { + dataSource.setUser(user); + } + + String password = nullSafeRefAddrStringGet(NonRegisteringDriver.PASSWORD_PROPERTY_KEY, ref); + + if (password != null) { + dataSource.setPassword(password); + } + + String serverName = nullSafeRefAddrStringGet("serverName", ref); + + if (serverName != null) { + dataSource.setServerName(serverName); + } + + String databaseName = nullSafeRefAddrStringGet("databaseName", ref); + + if (databaseName != null) { + dataSource.setDatabaseName(databaseName); + } + + String explicitUrlAsString = nullSafeRefAddrStringGet("explicitUrl", ref); + + if (explicitUrlAsString != null) { + if (Boolean.valueOf(explicitUrlAsString).booleanValue()) { + dataSource.setUrl(nullSafeRefAddrStringGet("url", ref)); + } + } + + dataSource.setPropertiesViaRef(ref); + + return dataSource; + } + + // We can't create an instance of the reference + return null; + } + + private String nullSafeRefAddrStringGet(String referenceName, Reference ref) { + RefAddr refAddr = ref.get(referenceName); + + String asString = refAddr != null ? (String)refAddr.getContent() : null; + + return asString; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlPooledConnection.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlPooledConnection.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlPooledConnection.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,212 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Enumeration; +import java.util.Hashtable; + +import javax.sql.ConnectionEvent; +import javax.sql.ConnectionEventListener; +import javax.sql.PooledConnection; + +import com.mysql.jdbc.SQLError; + +/** + * This class is used to wrap and return a physical connection within a logical + * handle. It also registers and notifies ConnectionEventListeners of any + * ConnectionEvents + * + * @see javax.sql.PooledConnection + * @see org.gjt.mm.mysql.jdbc2.optional.LogicalHandle + * @author Todd Wolff + */ +public class MysqlPooledConnection implements PooledConnection { + + /** + * The flag for an exception being thrown. + */ + public static final int CONNECTION_ERROR_EVENT = 1; + + /** + * The flag for a connection being closed. + */ + public static final int CONNECTION_CLOSED_EVENT = 2; + + // ~ Instance/static variables ............................................. + + private Hashtable eventListeners; + + private Connection logicalHandle; + + private com.mysql.jdbc.Connection physicalConn; + + // ~ Constructors .......................................................... + + /** + * Construct a new MysqlPooledConnection and set instance variables + * + * @param connection + * physical connection to db + */ + public MysqlPooledConnection(com.mysql.jdbc.Connection connection) { + this.logicalHandle = null; + this.physicalConn = connection; + this.eventListeners = new Hashtable(10); + } + + // ~ Methods ............................................................... + + /** + * Adds ConnectionEventListeners to a hash table to be used for notification + * of ConnectionEvents + * + * @param connectioneventlistener + * listener to be notified with ConnectionEvents + */ + public synchronized void addConnectionEventListener( + ConnectionEventListener connectioneventlistener) { + + if (this.eventListeners != null) { + this.eventListeners.put(connectioneventlistener, + connectioneventlistener); + } + } + + /** + * Removes ConnectionEventListeners from hash table used for notification of + * ConnectionEvents + * + * @param connectioneventlistener + * listener to be removed + */ + public synchronized void removeConnectionEventListener( + ConnectionEventListener connectioneventlistener) { + + if (this.eventListeners != null) { + this.eventListeners.remove(connectioneventlistener); + } + } + + /** + * Invoked by the container. Return a logicalHandle object that wraps a + * physical connection. + * + * @see java.sql.DataSource#getConnection() + */ + public synchronized Connection getConnection() throws SQLException { + return getConnection(true, false); + + } + + protected synchronized Connection getConnection(boolean resetServerState, + boolean forXa) + throws SQLException { + if (this.physicalConn == null) { + + SQLException sqlException = SQLError.createSQLException( + "Physical Connection doesn't exist"); + callListener(CONNECTION_ERROR_EVENT, sqlException); + + throw sqlException; + } + + try { + + if (this.logicalHandle != null) { + ((ConnectionWrapper) this.logicalHandle).close(false); + } + + if (resetServerState) { + ((com.mysql.jdbc.Connection) this.physicalConn).resetServerState(); + } + + this.logicalHandle = new ConnectionWrapper(this, this.physicalConn, forXa); + } catch (SQLException sqlException) { + callListener(CONNECTION_ERROR_EVENT, sqlException); + + throw sqlException; + } + + return this.logicalHandle; + } + + /** + * Invoked by the container (not the client), and should close the physical + * connection. This will be called if the pool is destroyed or the + * connectionEventListener receives a connectionErrorOccurred event. + * + * @see java.sql.DataSource#close() + */ + public synchronized void close() throws SQLException { + if (this.physicalConn != null) { + this.physicalConn.close(); + } + + this.physicalConn = null; + } + + /** + * Notifies all registered ConnectionEventListeners of ConnectionEvents. + * Instantiates a new ConnectionEvent which wraps sqlException and invokes + * either connectionClose or connectionErrorOccurred on listener as + * appropriate. + * + * @param eventType + * value indicating whether connectionClosed or + * connectionErrorOccurred called + * @param sqlException + * the exception being thrown + */ + protected synchronized void callListener(int eventType, + SQLException sqlException) { + + if (this.eventListeners == null) { + + return; + } + + Enumeration enumeration = this.eventListeners.keys(); + ConnectionEvent connectionevent = new ConnectionEvent(this, + sqlException); + + while (enumeration.hasMoreElements()) { + + ConnectionEventListener connectioneventlistener = (ConnectionEventListener) enumeration + .nextElement(); + ConnectionEventListener connectioneventlistener1 = (ConnectionEventListener) this.eventListeners + .get(connectioneventlistener); + + if (eventType == CONNECTION_CLOSED_EVENT) { + connectioneventlistener1.connectionClosed(connectionevent); + } else if (eventType == CONNECTION_ERROR_EVENT) { + connectioneventlistener1 + .connectionErrorOccurred(connectionevent); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXAConnection.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXAConnection.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXAConnection.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,639 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ +package com.mysql.jdbc.jdbc2.optional; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.sql.XAConnection; +import javax.transaction.xa.XAException; +import javax.transaction.xa.XAResource; +import javax.transaction.xa.Xid; + +import com.mysql.jdbc.log.Log; + +/* + * XA BEGIN [JOIN | RESUME] XA START TRANSACTION [JOIN | RESUME] XA + * COMMIT [ONE PHASE] XA END [SUSPEND [FOR MIGRATE]] XA PREPARE + * XA RECOVER XA ROLLBACK + */ + +/** + * An object that provides support for distributed transactions. An + * XAConnection object may be enlisted in a distributed + * transaction by means of an XAResource object. A transaction + * manager, usually part of a middle tier server, manages an + * XAConnection object through the XAResource + * object. + *

+ * An application programmer does not use this interface directly; rather, it is + * used by a transaction manager working in the middle tier server. + * + * @since 1.4 + */ +public class MysqlXAConnection extends MysqlPooledConnection implements + XAConnection, XAResource { + + private com.mysql.jdbc.Connection underlyingConnection; + + private final static Map MYSQL_ERROR_CODES_TO_XA_ERROR_CODES; + + private Log log; + + protected boolean logXaCommands; + + static { + HashMap temp = new HashMap(); + + temp.put(new Integer(1397), new Integer(XAException.XAER_NOTA)); + temp.put(new Integer(1398), new Integer(XAException.XAER_INVAL)); + temp.put(new Integer(1399), new Integer(XAException.XAER_RMFAIL)); + temp.put(new Integer(1400), new Integer(XAException.XAER_OUTSIDE)); + temp.put(new Integer(1401), new Integer(XAException.XAER_RMERR)); + temp.put(new Integer(1402), new Integer(XAException.XA_RBROLLBACK)); + + MYSQL_ERROR_CODES_TO_XA_ERROR_CODES = Collections.unmodifiableMap(temp); + } + + /** + * @param connection + */ + public MysqlXAConnection(com.mysql.jdbc.Connection connection, boolean logXaCommands) + throws SQLException { + super(connection); + this.underlyingConnection = connection; + this.log = connection.getLog(); + this.logXaCommands = logXaCommands; + } + + /** + * Retrieves an XAResource object that the transaction + * manager will use to manage this XAConnection object's + * participation in a distributed transaction. + * + * @return the XAResource object + * @exception SQLException + * if a database access error occurs + */ + public XAResource getXAResource() throws SQLException { + return this; + } + + /** + * Obtains the current transaction timeout value set for this XAResource + * instance. If XAResource.setTransactionTimeout was not used prior to + * invoking this method, the return value is the default timeout set for the + * resource manager; otherwise, the value used in the previous + * setTransactionTimeout call is returned. + * + * @return the transaction timeout value in seconds. + * + * @throws XAException + * An error has occurred. Possible exception values are + * XAER_RMERR and XAER_RMFAIL. + */ + public int getTransactionTimeout() throws XAException { + // TODO Auto-generated method stub + return 0; + } + + /** + * Sets the current transaction timeout value for this XAResource instance. + * Once set, this timeout value is effective until setTransactionTimeout is + * invoked again with a different value. + * + * To reset the timeout value to the default value used by the resource + * manager, set the value to zero. If the timeout operation is performed + * successfully, the method returns true; otherwise false. + * + * If a resource manager does not support explicitly setting the transaction + * timeout value, this method returns false. + * + * @parameter seconds The transaction timeout value in seconds. + * + * @return true if the transaction timeout value is set successfully; + * otherwise false. + * + * @throws XAException + * An error has occurred. Possible exception values are + * XAER_RMERR, XAER_RMFAIL, or XAER_INVAL. + */ + public boolean setTransactionTimeout(int arg0) throws XAException { + // TODO Auto-generated method stub + return false; + } + + /** + * This method is called to determine if the resource manager instance + * represented by the target object is the same as the resouce manager + * instance represented by the parameter xares. + * + * @parameter xares An XAResource object whose resource manager instance is + * to be compared with the resource manager instance of the + * target object. + * + * @return true if it's the same RM instance; otherwise false. + * + * @throws XAException + * An error has occurred. Possible exception values are + * XAER_RMERR and XAER_RMFAIL. + */ + public boolean isSameRM(XAResource xares) throws XAException { + + if (xares instanceof MysqlXAConnection) { + return this.underlyingConnection + .isSameResource(((MysqlXAConnection) xares).underlyingConnection); + } + + return false; + } + + /** + * This method is called to obtain a list of prepared transaction branches + * from a resource manager. The transaction manager calls this method during + * recovery to obtain the list of transaction branches that are currently in + * prepared or heuristically completed states. + * + * The flag parameter indicates where the recover scan should start or end, + * or start and end. This method may be invoked one or more times during a + * recovery scan. The resource manager maintains a cursor which marks the + * current position of the prepared or heuristically completed transaction list. + * Each invocation of the recover method moves the cursor passed the set of Xids + * that are returned. + * + * Two consecutive invocation of this method that starts from the + * beginning of the list must return the same list of transaction branches + * unless one of the following takes place: + * + * - the transaction manager invokes the commit, forget, prepare, or rollback method for that resource + * manager, between the two consecutive invocation of the recovery scan. + * + * - the resource manager heuristically completes some transaction branches + * between the two invocation of the recovery scan. + * + * @param flag + * One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS. TMNOFLAGS must be + * used when no other flags are set in the parameter. + * + * @returns The resource manager returns zero or more XIDs of the + * transaction branches that are currently in a prepared or + * heuristically completed state. If an error occurs during the + * operation, the resource manager should throw the appropriate + * XAException. + * + * @throws XAException + * An error has occurred. Possible values are XAER_RMERR, + * XAER_RMFAIL, XAER_INVAL, and XAER_PROTO. + */ + public Xid[] recover(int flag) throws XAException { + return recover(this.underlyingConnection, flag); + } + + protected static Xid[] recover(Connection c, int flag) throws XAException { + /* + The XA RECOVER statement returns information for those XA transactions on the MySQL server that are in the PREPARED state. (See Section 13.4.7.2, �XA Transaction States�.) The output includes a row for each such XA transaction on the server, regardless of which client started it. + + XA RECOVER output rows look like this (for an example xid value consisting of the parts 'abc', 'def', and 7): + + mysql> XA RECOVER; + +----------+--------------+--------------+--------+ + | formatID | gtrid_length | bqual_length | data | + +----------+--------------+--------------+--------+ + | 7 | 3 | 3 | abcdef | + +----------+--------------+--------------+--------+ + + The output columns have the following meanings: + + formatID is the formatID part of the transaction xid + gtrid_length is the length in bytes of the gtrid part of the xid + bqual_length is the length in bytes of the bqual part of the xid + data is the concatenation of the gtrid and bqual parts of the xid + */ + + boolean startRscan = ((flag & TMSTARTRSCAN) > 0); + boolean endRscan = ((flag & TMENDRSCAN) > 0); + + if (!startRscan && !endRscan && flag != TMNOFLAGS) { + throw new MysqlXAException(XAException.XAER_INVAL, + "Invalid flag, must use TMNOFLAGS, or any combination of TMSTARTRSCAN and TMENDRSCAN", + null); + } + + // + // We return all recovered XIDs at once, so if not + // TMSTARTRSCAN, return no new XIDs + // + // We don't attempt to maintain state to check for TMNOFLAGS + // "outside" of a scan + // + + if (!startRscan) { + return new Xid[0]; + } + + ResultSet rs = null; + Statement stmt = null; + + List recoveredXidList = new ArrayList(); + + try { + // TODO: Cache this for lifetime of XAConnection + stmt = c.createStatement(); + + rs = stmt.executeQuery("XA RECOVER"); + + while (rs.next()) { + final int formatId = rs.getInt(1); + int gtridLength = rs.getInt(2); + int bqualLength = rs.getInt(3); + byte[] gtridAndBqual = rs.getBytes(4); + + final byte[] gtrid = new byte[gtridLength]; + final byte[] bqual = new byte[bqualLength]; + + if (gtridAndBqual.length != (gtridLength + bqualLength)) { + throw new MysqlXAException(XAException.XA_RBPROTO, + "Error while recovering XIDs from RM. GTRID and BQUAL are wrong sizes", + null); + } + + System.arraycopy(gtridAndBqual, 0, gtrid, 0, + gtridLength); + System.arraycopy(gtridAndBqual, gtridLength, bqual, 0, + bqualLength); + + recoveredXidList.add(new MysqlXid(gtrid, bqual, + formatId)); + } + } catch (SQLException sqlEx) { + throw mapXAExceptionFromSQLException(sqlEx); + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException sqlEx) { + throw mapXAExceptionFromSQLException(sqlEx); + } + } + + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { + throw mapXAExceptionFromSQLException(sqlEx); + } + } + } + + int numXids = recoveredXidList.size(); + + Xid[] asXids = new Xid[numXids]; + Object[] asObjects = recoveredXidList.toArray(); + + for (int i = 0; i < numXids; i++) { + asXids[i] = (Xid) asObjects[i]; + } + + return asXids; + } + + /** + * Asks the resource manager to prepare for a transaction commit of the + * transaction specified in xid. + * + * @parameter xid A global transaction identifier. + * + * @returns A value indicating the resource manager's vote on the outcome of + * the transaction. + * + * The possible values are: XA_RDONLY or XA_OK. If the resource manager + * wants to roll back the transaction, it should do so by raising an + * appropriate XAException in the prepare method. + * + * @throws XAException + * An error has occurred. Possible exception values are: XA_RB*, + * XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or + * XAER_PROTO. + */ + public int prepare(Xid xid) throws XAException { + StringBuffer commandBuf = new StringBuffer(); + commandBuf.append("XA PREPARE "); + commandBuf.append(xidToString(xid)); + + dispatchCommand(commandBuf.toString()); + + return XA_OK; // TODO: Check for read-only + } + + /** + * Tells the resource manager to forget about a heuristically completed + * transaction branch. + * + * @parameter xid A global transaction identifier. + * + * @throws XAException + * An error has occurred. Possible exception values are + * XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or + * XAER_PROTO. + */ + public void forget(Xid xid) throws XAException { + // TODO Auto-generated method stub + } + + /** + * Informs the resource manager to roll back work done on behalf of a + * transaction branch. + * + * @parameter xid A global transaction identifier. + * + * @throws XAException + * An error has occurred. Possible XAExceptions are XA_HEURHAZ, + * XA_HEURCOM, XA_HEURRB, XA_HEURMIX, XAER_RMERR, XAER_RMFAIL, + * XAER_NOTA, XAER_INVAL, or XAER_PROTO. + * + * If the transaction branch is already marked rollback-only the resource + * manager may throw one of the XA_RB* exceptions. + * + * Upon return, the resource manager has rolled back the branch's work and + * has released all held resources. + */ + public void rollback(Xid xid) throws XAException { + StringBuffer commandBuf = new StringBuffer(); + commandBuf.append("XA ROLLBACK "); + commandBuf.append(xidToString(xid)); + + try { + dispatchCommand(commandBuf.toString()); + } finally { + this.underlyingConnection.setInGlobalTx(false); + } + } + + /** + * Ends the work performed on behalf of a transaction branch. + * + * The resource manager disassociates the XA resource from the transaction + * branch specified and lets the transaction complete. + * + * If TMSUSPEND is specified in the flags, the transaction branch is + * temporarily suspended in an incomplete state. The transaction context is + * in a suspended state and must be resumed via the start method with + * TMRESUME specified. + * + * If TMFAIL is specified, the portion of work has failed. The resource + * manager may mark the transaction as rollback-only + * + * If TMSUCCESS is specified, the portion of work has completed + * successfully. + * + * @parameter xid A global transaction identifier that is the same as the + * identifier used previously in the start method. + * + * @parameter flags One of TMSUCCESS, TMFAIL, or TMSUSPEND. + * + * @throws XAException - + * An error has occurred. Possible XAException values are + * XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, XAER_PROTO, + * or XA_RB*. + */ + public void end(Xid xid, int flags) throws XAException { + StringBuffer commandBuf = new StringBuffer(); + commandBuf.append("XA END "); + commandBuf.append(xidToString(xid)); + + switch (flags) { + case TMSUCCESS: + break; // no-op + case TMSUSPEND: + commandBuf.append(" SUSPEND"); + break; + case TMFAIL: + break; // no-op + default: + throw new XAException(XAException.XAER_INVAL); + } + + dispatchCommand(commandBuf.toString()); + } + + /** + * Starts work on behalf of a transaction branch specified in xid. + * + * If TMJOIN is specified, the start applies to joining a transaction + * previously seen by the resource manager. + * + * If TMRESUME is specified, the start applies to resuming a suspended + * transaction specified in the parameter xid. + * + * If neither TMJOIN nor TMRESUME is specified and the transaction specified + * by xid has previously been seen by the resource manager, the resource + * manager throws the XAException exception with XAER_DUPID error code. + * + * @parameter xid A global transaction identifier to be associated with the + * resource. + * + * @parameter flags One of TMNOFLAGS, TMJOIN, or TMRESUME. + * + * @throws XAException + * An error has occurred. Possible exceptions are XA_RB*, + * XAER_RMERR, XAER_RMFAIL, XAER_DUPID, XAER_OUTSIDE, XAER_NOTA, + * XAER_INVAL, or XAER_PROTO. + */ + public void start(Xid xid, int flags) throws XAException { + StringBuffer commandBuf = new StringBuffer(); + commandBuf.append("XA START "); + commandBuf.append(xidToString(xid)); + + switch (flags) { + case TMJOIN: + commandBuf.append(" JOIN"); + break; + case TMRESUME: + commandBuf.append(" RESUME"); + break; + case TMNOFLAGS: + // no-op + break; + default: + throw new XAException(XAException.XAER_INVAL); + } + + dispatchCommand(commandBuf.toString()); + + this.underlyingConnection.setInGlobalTx(true); + } + + /** + * Commits the global transaction specified by xid. + * + * @parameter xid A global transaction identifier + * @parameter onePhase - If true, the resource manager should use a + * one-phase commit protocol to commit the work done on behalf of + * xid. + * + * @throws XAException + * An error has occurred. Possible XAExceptions are XA_HEURHAZ, + * XA_HEURCOM, XA_HEURRB, XA_HEURMIX, XAER_RMERR, XAER_RMFAIL, + * XAER_NOTA, XAER_INVAL, or XAER_PROTO. + * + * If the resource manager did not commit the transaction and the parameter + * onePhase is set to true, the resource manager may throw one of the XA_RB* + * exceptions. + * + * Upon return, the resource manager has rolled back the branch's work and + * has released all held resources. + */ + + public void commit(Xid xid, boolean onePhase) throws XAException { + StringBuffer commandBuf = new StringBuffer(); + commandBuf.append("XA COMMIT "); + commandBuf.append(xidToString(xid)); + + if (onePhase) { + commandBuf.append(" ONE PHASE"); + } + + try { + dispatchCommand(commandBuf.toString()); + } finally { + this.underlyingConnection.setInGlobalTx(false); + } + } + + private ResultSet dispatchCommand(String command) throws XAException { + Statement stmt = null; + + try { + if (this.logXaCommands) { + this.log.logDebug("Executing XA statement: " + command); + } + + // TODO: Cache this for lifetime of XAConnection + stmt = this.underlyingConnection.createStatement(); + + stmt.execute(command); + + ResultSet rs = stmt.getResultSet(); + + return rs; + } catch (SQLException sqlEx) { + throw mapXAExceptionFromSQLException(sqlEx); + } finally { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException sqlEx) { + } + } + } + } + + protected static XAException mapXAExceptionFromSQLException(SQLException sqlEx) { + + Integer xaCode = (Integer) MYSQL_ERROR_CODES_TO_XA_ERROR_CODES + .get(new Integer(sqlEx.getErrorCode())); + + if (xaCode != null) { + return new MysqlXAException(xaCode.intValue(), sqlEx.getMessage(), null); + } + + // Punt? We don't know what the error code is here + return new MysqlXAException(sqlEx.getMessage(), null); + } + + private static String xidToString(Xid xid) { + byte[] gtrid = xid.getGlobalTransactionId(); + + byte[] btrid = xid.getBranchQualifier(); + + int lengthAsString = 6; // for (0x and ,) * 2 + + if (gtrid != null) { + lengthAsString += (2 * gtrid.length); + } + + if (btrid != null) { + lengthAsString += (2 * btrid.length); + } + + String formatIdInHex = Integer.toHexString(xid.getFormatId()); + + lengthAsString += formatIdInHex.length(); + lengthAsString += 3; // for the '.' after formatId + + StringBuffer asString = new StringBuffer(lengthAsString); + + asString.append("0x"); + + if (gtrid != null) { + for (int i = 0; i < gtrid.length; i++) { + String asHex = Integer.toHexString(gtrid[i] & 0xff); + + if (asHex.length() == 1) { + asString.append("0"); + } + + asString.append(asHex); + } + } + + asString.append(","); + + if (btrid != null) { + asString.append("0x"); + + for (int i = 0; i < btrid.length; i++) { + String asHex = Integer.toHexString(btrid[i] & 0xff); + + if (asHex.length() == 1) { + asString.append("0"); + } + + asString.append(asHex); + } + } + + asString.append(",0x"); + asString.append(formatIdInHex); + + return asString.toString(); + } + + /* + * (non-Javadoc) + * + * @see javax.sql.PooledConnection#getConnection() + */ + public synchronized Connection getConnection() throws SQLException { + Connection connToWrap = getConnection(false, true); + + return connToWrap; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXADataSource.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXADataSource.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXADataSource.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,75 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.XAConnection; + +/** + * @author mmatthew + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. To enable and disable the creation of type + * comments go to Window>Preferences>Java>Code Generation. + */ +public class MysqlXADataSource extends MysqlDataSource implements + javax.sql.XADataSource { + + /** + * @see javax.sql.XADataSource#getXAConnection() + */ + public XAConnection getXAConnection() throws SQLException { + + Connection conn = getConnection(); + + return wrapConnection(conn); + } + + /** + * @see javax.sql.XADataSource#getXAConnection(String, String) + */ + public XAConnection getXAConnection(String user, String password) + throws SQLException { + + Connection conn = getConnection(user, password); + + return wrapConnection(conn); + } + + /** + * Wraps a connection as a 'fake' XAConnection + */ + + private XAConnection wrapConnection(Connection conn) throws SQLException { + if (getPinGlobalTxToPhysicalConnection() || + ((com.mysql.jdbc.Connection)conn).getPinGlobalTxToPhysicalConnection()) { + return new SuspendableXAConnection((com.mysql.jdbc.Connection) conn); + } + + return new MysqlXAConnection((com.mysql.jdbc.Connection) conn, getLogXaCommands()); + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXAException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXAException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXAException.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,66 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + +package com.mysql.jdbc.jdbc2.optional; + +import javax.transaction.xa.XAException; + +/** + * The stock XAException class isn't too friendly (i.e. no + * error messages), so we extend it a bit. + */ +class MysqlXAException extends XAException { + private static final long serialVersionUID = -9075817535836563004L; + + private String message; + private String xidAsString; + + public MysqlXAException(int errorCode, String message, String xidAsString) { + super(errorCode); + this.message = message; + this.xidAsString = xidAsString; + } + + public MysqlXAException(String message, String xidAsString) { + super(); + + this.message = message; + this.xidAsString = xidAsString; + } + + public String getMessage() { + String superMessage = super.getMessage(); + StringBuffer returnedMessage = new StringBuffer(); + + if (superMessage != null) { + returnedMessage.append(superMessage); + returnedMessage.append(":"); + } + + if (this.message != null) { + returnedMessage.append(this.message); + } + + return returnedMessage.toString(); + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXid.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXid.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/MysqlXid.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,112 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +package com.mysql.jdbc.jdbc2.optional; + +import javax.transaction.xa.Xid; + +/** + * Implementation of the XID interface for MySQL XA + * + * @version $Id: MysqlXid.java,v 1.1 2012/08/17 14:57:11 marcin Exp $ + */ +public class MysqlXid implements Xid { + + int hash = 0; + + byte[] myBqual; + + int myFormatId; + + byte[] myGtrid; + + public MysqlXid(byte[] gtrid, byte[] bqual, int formatId) { + this.myGtrid = gtrid; + this.myBqual = bqual; + this.myFormatId = formatId; + } + + public boolean equals(Object another) { + + if (another instanceof Xid) { + Xid anotherAsXid = (Xid) another; + + if (this.myFormatId != anotherAsXid.getFormatId()) { + return false; + } + + byte[] otherBqual = anotherAsXid.getBranchQualifier(); + byte[] otherGtrid = anotherAsXid.getGlobalTransactionId(); + + if (otherGtrid != null && otherGtrid.length == this.myGtrid.length) { + int length = otherGtrid.length; + + for (int i = 0; i < length; i++) { + if (otherGtrid[i] != this.myGtrid[i]) { + return false; + } + } + + if (otherBqual != null && otherBqual.length == myBqual.length) { + length = otherBqual.length; + + for (int i = 0; i < length; i++) { + if (otherBqual[i] != this.myBqual[i]) { + return false; + } + } + } else { + return false; + } + + return true; + } else { + return false; + } + } else { + return false; + } + } + + public byte[] getBranchQualifier() { + return this.myBqual; + } + + public int getFormatId() { + return this.myFormatId; + }; + + public byte[] getGlobalTransactionId() { + return this.myGtrid; + } + + public synchronized int hashCode() { + if (this.hash == 0) { + for (int i = 0; i < this.myGtrid.length; i++) { + this.hash = 33 * this.hash + this.myGtrid[i]; + } + } + + return this.hash; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/PreparedStatementWrapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/PreparedStatementWrapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/PreparedStatementWrapper.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,854 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import com.mysql.jdbc.SQLError; + +import java.io.InputStream; +import java.io.Reader; + +import java.math.BigDecimal; + +import java.net.URL; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Date; +import java.sql.ParameterMetaData; +import java.sql.PreparedStatement; +import java.sql.Ref; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; + +import java.util.Calendar; + +/** + * Wraps prepared statements so that errors can be reported correctly to + * ConnectionEventListeners. + * + * @author Mark Matthews + * + * @version $Id: PreparedStatementWrapper.java,v 1.1.2.1 2005/05/13 18:58:38 + * mmatthews Exp $ + */ +public class PreparedStatementWrapper extends StatementWrapper implements + PreparedStatement { + PreparedStatementWrapper(ConnectionWrapper c, MysqlPooledConnection conn, + PreparedStatement toWrap) { + super(c, conn, toWrap); + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setArray(int, java.sql.Array) + */ + public void setArray(int parameterIndex, Array x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setArray(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, + * int) + */ + public void setAsciiStream(int parameterIndex, InputStream x, int length) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setAsciiStream( + parameterIndex, x, length); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setBigDecimal(int, java.math.BigDecimal) + */ + public void setBigDecimal(int parameterIndex, BigDecimal x) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setBigDecimal( + parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, + * int) + */ + public void setBinaryStream(int parameterIndex, InputStream x, int length) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setBinaryStream( + parameterIndex, x, length); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setBlob(int, java.sql.Blob) + */ + public void setBlob(int parameterIndex, Blob x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setBlob(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setBoolean(int, boolean) + */ + public void setBoolean(int parameterIndex, boolean x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setBoolean( + parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setByte(int, byte) + */ + public void setByte(int parameterIndex, byte x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setByte(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setBytes(int, byte[]) + */ + public void setBytes(int parameterIndex, byte[] x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setBytes(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, + * int) + */ + public void setCharacterStream(int parameterIndex, Reader reader, int length) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setCharacterStream( + parameterIndex, reader, length); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setClob(int, java.sql.Clob) + */ + public void setClob(int parameterIndex, Clob x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setClob(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setDate(int, java.sql.Date) + */ + public void setDate(int parameterIndex, Date x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setDate(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setDate(int, java.sql.Date, + * java.util.Calendar) + */ + public void setDate(int parameterIndex, Date x, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setDate(parameterIndex, + x, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setDouble(int, double) + */ + public void setDouble(int parameterIndex, double x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setDouble( + parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setFloat(int, float) + */ + public void setFloat(int parameterIndex, float x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setFloat(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setInt(int, int) + */ + public void setInt(int parameterIndex, int x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt) + .setInt(parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setLong(int, long) + */ + public void setLong(int parameterIndex, long x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setLong(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#getMetaData() + */ + public ResultSetMetaData getMetaData() throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((PreparedStatement) this.wrappedStmt).getMetaData(); + } + + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setNull(int, int) + */ + public void setNull(int parameterIndex, int sqlType) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setNull(parameterIndex, + sqlType); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setNull(int, int, java.lang.String) + */ + public void setNull(int parameterIndex, int sqlType, String typeName) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setNull(parameterIndex, + sqlType, typeName); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setObject(int, java.lang.Object) + */ + public void setObject(int parameterIndex, Object x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setObject( + parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int) + */ + public void setObject(int parameterIndex, Object x, int targetSqlType) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setObject( + parameterIndex, x, targetSqlType); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int, + * int) + */ + public void setObject(int parameterIndex, Object x, int targetSqlType, + int scale) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setObject( + parameterIndex, x, targetSqlType, scale); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#getParameterMetaData() + */ + public ParameterMetaData getParameterMetaData() throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((PreparedStatement) this.wrappedStmt) + .getParameterMetaData(); + } + + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setRef(int, java.sql.Ref) + */ + public void setRef(int parameterIndex, Ref x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt) + .setRef(parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setShort(int, short) + */ + public void setShort(int parameterIndex, short x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setShort(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setString(int, java.lang.String) + */ + public void setString(int parameterIndex, String x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setString( + parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setTime(int, java.sql.Time) + */ + public void setTime(int parameterIndex, Time x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setTime(parameterIndex, + x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setTime(int, java.sql.Time, + * java.util.Calendar) + */ + public void setTime(int parameterIndex, Time x, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setTime(parameterIndex, + x, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp) + */ + public void setTimestamp(int parameterIndex, Timestamp x) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setTimestamp( + parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp, + * java.util.Calendar) + */ + public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setTimestamp( + parameterIndex, x, cal); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#setURL(int, java.net.URL) + */ + public void setURL(int parameterIndex, URL x) throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt) + .setURL(parameterIndex, x); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /** + * DOCUMENT ME! + * + * @param parameterIndex + * DOCUMENT ME! + * @param x + * DOCUMENT ME! + * @param length + * DOCUMENT ME! + * + * @throws SQLException + * DOCUMENT ME! + * + * @see java.sql.PreparedStatement#setUnicodeStream(int, + * java.io.InputStream, int) + * @deprecated + */ + public void setUnicodeStream(int parameterIndex, InputStream x, int length) + throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).setUnicodeStream( + parameterIndex, x, length); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#addBatch() + */ + public void addBatch() throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).addBatch(); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#clearParameters() + */ + public void clearParameters() throws SQLException { + try { + if (this.wrappedStmt != null) { + ((PreparedStatement) this.wrappedStmt).clearParameters(); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#execute() + */ + public boolean execute() throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((PreparedStatement) this.wrappedStmt).execute(); + } + + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#executeQuery() + */ + public ResultSet executeQuery() throws SQLException { + try { + if (this.wrappedStmt != null) { + ResultSet rs = ((PreparedStatement) this.wrappedStmt) + .executeQuery(); + + ((com.mysql.jdbc.ResultSet) rs).setWrapperStatement(this); + + return rs; + } + + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.PreparedStatement#executeUpdate() + */ + public int executeUpdate() throws SQLException { + try { + if (this.wrappedStmt != null) { + return ((PreparedStatement) this.wrappedStmt).executeUpdate(); + } + + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return -1; // we actually never get here, but the compiler can't figure + + // that out + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/StatementWrapper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/StatementWrapper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/StatementWrapper.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,829 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import com.mysql.jdbc.SQLError; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Statement; + +/** + * Wraps statements so that errors can be reported correctly to + * ConnectionEventListeners. + * + * @author Mark Matthews + * + * @version $Id: StatementWrapper.java,v 1.1.2.1 2005/05/13 18:58:38 mmatthews + * Exp $ + */ +public class StatementWrapper extends WrapperBase implements Statement { + protected Statement wrappedStmt; + + protected ConnectionWrapper wrappedConn; + + protected StatementWrapper(ConnectionWrapper c, MysqlPooledConnection conn, + Statement toWrap) { + this.pooledConnection = conn; + this.wrappedStmt = toWrap; + this.wrappedConn = c; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getConnection() + */ + public Connection getConnection() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedConn; + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#setCursorName(java.lang.String) + */ + public void setCursorName(String name) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.setCursorName(name); + } else { + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#setEscapeProcessing(boolean) + */ + public void setEscapeProcessing(boolean enable) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.setEscapeProcessing(enable); + } else { + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#setFetchDirection(int) + */ + public void setFetchDirection(int direction) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.setFetchDirection(direction); + } else { + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getFetchDirection() + */ + public int getFetchDirection() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getFetchDirection(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return ResultSet.FETCH_FORWARD; // we actually never get here, but the + // compiler can't figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#setFetchSize(int) + */ + public void setFetchSize(int rows) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.setFetchSize(rows); + } else { + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getFetchSize() + */ + public int getFetchSize() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getFetchSize(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; // we actually never get here, but the compiler can't figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getGeneratedKeys() + */ + public ResultSet getGeneratedKeys() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getGeneratedKeys(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#setMaxFieldSize(int) + */ + public void setMaxFieldSize(int max) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.setMaxFieldSize(max); + } else { + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getMaxFieldSize() + */ + public int getMaxFieldSize() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getMaxFieldSize(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; // we actually never get here, but the compiler can't figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#setMaxRows(int) + */ + public void setMaxRows(int max) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.setMaxRows(max); + } else { + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getMaxRows() + */ + public int getMaxRows() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getMaxRows(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; // we actually never get here, but the compiler can't figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getMoreResults() + */ + public boolean getMoreResults() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getMoreResults(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getMoreResults(int) + */ + public boolean getMoreResults(int current) throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getMoreResults(current); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#setQueryTimeout(int) + */ + public void setQueryTimeout(int seconds) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.setQueryTimeout(seconds); + } else { + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getQueryTimeout() + */ + public int getQueryTimeout() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getQueryTimeout(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getResultSet() + */ + public ResultSet getResultSet() throws SQLException { + try { + if (this.wrappedStmt != null) { + ResultSet rs = this.wrappedStmt.getResultSet(); + + ((com.mysql.jdbc.ResultSet) rs).setWrapperStatement(this); + + return rs; + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getResultSetConcurrency() + */ + public int getResultSetConcurrency() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getResultSetConcurrency(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getResultSetHoldability() + */ + public int getResultSetHoldability() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getResultSetHoldability(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return Statement.CLOSE_CURRENT_RESULT; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getResultSetType() + */ + public int getResultSetType() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getResultSetType(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return ResultSet.TYPE_FORWARD_ONLY; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getUpdateCount() + */ + public int getUpdateCount() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getUpdateCount(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return -1; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#getWarnings() + */ + public SQLWarning getWarnings() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.getWarnings(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#addBatch(java.lang.String) + */ + public void addBatch(String sql) throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.addBatch(sql); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#cancel() + */ + public void cancel() throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.cancel(); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#clearBatch() + */ + public void clearBatch() throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.clearBatch(); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#clearWarnings() + */ + public void clearWarnings() throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.clearWarnings(); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#close() + */ + public void close() throws SQLException { + try { + if (this.wrappedStmt != null) { + this.wrappedStmt.close(); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } finally { + this.wrappedStmt = null; + this.pooledConnection = null; + } + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#execute(java.lang.String, int) + */ + public boolean execute(String sql, int autoGeneratedKeys) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.execute(sql, autoGeneratedKeys); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#execute(java.lang.String, int[]) + */ + public boolean execute(String sql, int[] columnIndexes) throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.execute(sql, columnIndexes); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#execute(java.lang.String, java.lang.String[]) + */ + public boolean execute(String sql, String[] columnNames) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.execute(sql, columnNames); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#execute(java.lang.String) + */ + public boolean execute(String sql) throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.execute(sql); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return false; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#executeBatch() + */ + public int[] executeBatch() throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.executeBatch(); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#executeQuery(java.lang.String) + */ + public ResultSet executeQuery(String sql) throws SQLException { + try { + if (this.wrappedStmt != null) { + + ResultSet rs = this.wrappedStmt.executeQuery(sql); + ((com.mysql.jdbc.ResultSet) rs).setWrapperStatement(this); + + return rs; + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return null; // we actually never get here, but the compiler can't + // figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#executeUpdate(java.lang.String, int) + */ + public int executeUpdate(String sql, int autoGeneratedKeys) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.executeUpdate(sql, autoGeneratedKeys); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return -1; // we actually never get here, but the compiler can't figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#executeUpdate(java.lang.String, int[]) + */ + public int executeUpdate(String sql, int[] columnIndexes) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.executeUpdate(sql, columnIndexes); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return -1; // we actually never get here, but the compiler can't figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#executeUpdate(java.lang.String, + * java.lang.String[]) + */ + public int executeUpdate(String sql, String[] columnNames) + throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.executeUpdate(sql, columnNames); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return -1; // we actually never get here, but the compiler can't figure + + // that out + } + + /* + * (non-Javadoc) + * + * @see java.sql.Statement#executeUpdate(java.lang.String) + */ + public int executeUpdate(String sql) throws SQLException { + try { + if (this.wrappedStmt != null) { + return this.wrappedStmt.executeUpdate(sql); + } + + throw SQLError.createSQLException("Statement already closed", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + + return -1; // we actually never get here, but the compiler can't figure + + // that out + } + + public void enableStreamingResults() throws SQLException { + try { + if (this.wrappedStmt != null) { + ((com.mysql.jdbc.Statement) this.wrappedStmt) + .enableStreamingResults(); + } else { + throw SQLError.createSQLException( + "No operations allowed after statement closed", + SQLError.SQL_STATE_GENERAL_ERROR); + } + } catch (SQLException sqlEx) { + checkAndFireConnectionError(sqlEx); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/SuspendableXAConnection.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/SuspendableXAConnection.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/SuspendableXAConnection.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,154 @@ +package com.mysql.jdbc.jdbc2.optional; + + +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +import javax.sql.XAConnection; +import javax.transaction.xa.XAException; +import javax.transaction.xa.XAResource; +import javax.transaction.xa.Xid; + +import com.mysql.jdbc.Connection; + +public class SuspendableXAConnection extends MysqlPooledConnection implements +XAConnection, XAResource { + + public SuspendableXAConnection(Connection connection) { + super(connection); + this.underlyingConnection = connection; + } + + private static final Map XIDS_TO_PHYSICAL_CONNECTIONS = + new HashMap(); + + private Xid currentXid; + + private XAConnection currentXAConnection; + private XAResource currentXAResource; + + private Connection underlyingConnection; + + private static synchronized XAConnection findConnectionForXid(Connection connectionToWrap, Xid xid) + throws SQLException { + // TODO: check for same GTRID, but different BQUALs...MySQL doesn't allow this yet + + // Note, we don't need to check for XIDs here, because MySQL itself will complain + // with a XAER_NOTA if need be. + + XAConnection conn = (XAConnection)XIDS_TO_PHYSICAL_CONNECTIONS.get(xid); + + if (conn == null) { + conn = new MysqlXAConnection(connectionToWrap, + connectionToWrap.getLogXaCommands()); + } + + return conn; + } + + private static synchronized void removeXAConnectionMapping(Xid xid) { + XIDS_TO_PHYSICAL_CONNECTIONS.remove(xid); + } + + private synchronized void switchToXid(Xid xid) throws XAException { + if (xid == null) { + throw new XAException(); + } + + try { + if (!xid.equals(this.currentXid)) { + XAConnection toSwitchTo = findConnectionForXid(this.underlyingConnection, xid); + this.currentXAConnection = toSwitchTo; + this.currentXid = xid; + this.currentXAResource = toSwitchTo.getXAResource(); + } + } catch (SQLException sqlEx) { + throw new XAException(); + } + } + + public XAResource getXAResource() throws SQLException { + return this; + } + + public void commit(Xid xid, boolean arg1) throws XAException { + switchToXid(xid); + this.currentXAResource.commit(xid, arg1); + removeXAConnectionMapping(xid); + } + + public void end(Xid xid, int arg1) throws XAException { + switchToXid(xid); + this.currentXAResource.end(xid, arg1); + } + + public void forget(Xid xid) throws XAException { + switchToXid(xid); + this.currentXAResource.forget(xid); + // remove? + removeXAConnectionMapping(xid); + } + + public int getTransactionTimeout() throws XAException { + // TODO Auto-generated method stub + return 0; + } + + public boolean isSameRM(XAResource xaRes) throws XAException { + return xaRes == this; + } + + public int prepare(Xid xid) throws XAException { + switchToXid(xid); + return this.currentXAResource.prepare(xid); + } + + public Xid[] recover(int flag) throws XAException { + return MysqlXAConnection.recover(this.underlyingConnection, flag); + } + + public void rollback(Xid xid) throws XAException { + switchToXid(xid); + this.currentXAResource.rollback(xid); + removeXAConnectionMapping(xid); + } + + public boolean setTransactionTimeout(int arg0) throws XAException { + // TODO Auto-generated method stub + return false; + } + + public void start(Xid xid, int arg1) throws XAException { + switchToXid(xid); + + if (arg1 != XAResource.TMJOIN) { + this.currentXAResource.start(xid, arg1); + + return; + } + + // + // Emulate join, by using resume on the same physical connection + // + + this.currentXAResource.start(xid, XAResource.TMRESUME); + } + + public synchronized java.sql.Connection getConnection() throws SQLException { + if (this.currentXAConnection == null) { + return getConnection(false, true); + } + + return this.currentXAConnection.getConnection(); + } + + public void close() throws SQLException { + if (this.currentXAConnection == null) { + super.close(); + } else { + removeXAConnectionMapping(this.currentXid); + this.currentXAConnection.close(); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/WrapperBase.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/WrapperBase.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/jdbc2/optional/WrapperBase.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,61 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.jdbc2.optional; + +import java.sql.SQLException; + +import com.mysql.jdbc.SQLError; + +/** + * Base class for all wrapped instances created by LogicalHandle + * + * @author Mark matthews + * + * @version $Id: WrapperBase.java,v 1.1 2012/08/17 14:57:11 marcin Exp $ + */ +abstract class WrapperBase { + protected MysqlPooledConnection pooledConnection; + + /** + * Fires connection error event if required, before re-throwing exception + * + * @param sqlEx + * the SQLException that has ocurred + * @throws SQLException + * (rethrown) + */ + protected void checkAndFireConnectionError(SQLException sqlEx) + throws SQLException { + if (this.pooledConnection != null) { + if (SQLError.SQL_STATE_COMMUNICATION_LINK_FAILURE.equals(sqlEx + .getSQLState())) { + this.pooledConnection.callListener( + MysqlPooledConnection.CONNECTION_ERROR_EVENT, sqlEx); + } + } + + throw sqlEx; + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/CommonsLogger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Attic/CommonsLogger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/CommonsLogger.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,108 @@ +/* + Copyright (C) 2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + +package com.mysql.jdbc.log; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class CommonsLogger implements com.mysql.jdbc.log.Log { + private Log logger; + + public CommonsLogger(String instanceName) { + logger = LogFactory.getLog(instanceName); + } + + public boolean isDebugEnabled() { + return this.logger.isInfoEnabled(); + } + + public boolean isErrorEnabled() { + return this.logger.isErrorEnabled(); + } + + public boolean isFatalEnabled() { + return this.logger.isFatalEnabled(); + } + + public boolean isInfoEnabled() { + return this.logger.isInfoEnabled(); + } + + public boolean isTraceEnabled() { + return this.logger.isTraceEnabled(); + } + + public boolean isWarnEnabled() { + return this.logger.isWarnEnabled(); + } + + public void logDebug(Object msg) { + this.logger.debug(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + public void logDebug(Object msg, Throwable thrown) { + this.logger.debug(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + public void logError(Object msg) { + this.logger.error(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + public void logError(Object msg, Throwable thrown) { + this.logger.fatal(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + public void logFatal(Object msg) { + this.logger.fatal(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + public void logFatal(Object msg, Throwable thrown) { + this.logger.fatal(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + public void logInfo(Object msg) { + this.logger.info(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + public void logInfo(Object msg, Throwable thrown) { + this.logger.info(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + public void logTrace(Object msg) { + this.logger.trace(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + public void logTrace(Object msg, Throwable thrown) { + this.logger.trace(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + public void logWarn(Object msg) { + this.logger.warn(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + public void logWarn(Object msg, Throwable thrown) { + this.logger.warn(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Jdk14Logger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Jdk14Logger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Jdk14Logger.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,298 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.log; + +import com.mysql.jdbc.profiler.ProfilerEvent; + +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Logging functionality for JDK1.4 + * + * @author Mark Matthews + * + * @version $Id: Jdk14Logger.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public class Jdk14Logger implements Log { + private static final Level DEBUG = Level.FINE; + + private static final Level ERROR = Level.SEVERE; + + private static final Level FATAL = Level.SEVERE; + + private static final Level INFO = Level.INFO; + + private static final Level TRACE = Level.FINEST; + + private static final Level WARN = Level.WARNING; + + /** + * The underlying logger from JDK-1.4 + */ + protected Logger jdkLogger = null; + + /** + * Creates a new Jdk14Logger object. + * + * @param name + * DOCUMENT ME! + */ + public Jdk14Logger(String name) { + this.jdkLogger = Logger.getLogger(name); + } + + /** + * @see com.mysql.jdbc.log.Log#isDebugEnabled() + */ + public boolean isDebugEnabled() { + return this.jdkLogger.isLoggable(Level.FINE); + } + + /** + * @see com.mysql.jdbc.log.Log#isErrorEnabled() + */ + public boolean isErrorEnabled() { + return this.jdkLogger.isLoggable(Level.SEVERE); + } + + /** + * @see com.mysql.jdbc.log.Log#isFatalEnabled() + */ + public boolean isFatalEnabled() { + return this.jdkLogger.isLoggable(Level.SEVERE); + } + + /** + * @see com.mysql.jdbc.log.Log#isInfoEnabled() + */ + public boolean isInfoEnabled() { + return this.jdkLogger.isLoggable(Level.INFO); + } + + /** + * @see com.mysql.jdbc.log.Log#isTraceEnabled() + */ + public boolean isTraceEnabled() { + return this.jdkLogger.isLoggable(Level.FINEST); + } + + /** + * @see com.mysql.jdbc.log.Log#isWarnEnabled() + */ + public boolean isWarnEnabled() { + return this.jdkLogger.isLoggable(Level.WARNING); + } + + /** + * Logs the given message instance using the 'debug' level + * + * @param message + * the message to log + */ + public void logDebug(Object message) { + logInternal(DEBUG, message, null); + } + + /** + * Logs the given message and Throwable at the 'debug' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logDebug(Object message, Throwable exception) { + logInternal(DEBUG, message, exception); + } + + /** + * Logs the given message instance using the 'error' level + * + * @param message + * the message to log + */ + public void logError(Object message) { + logInternal(ERROR, message, null); + } + + /** + * Logs the given message and Throwable at the 'error' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logError(Object message, Throwable exception) { + logInternal(ERROR, message, exception); + } + + /** + * Logs the given message instance using the 'fatal' level + * + * @param message + * the message to log + */ + public void logFatal(Object message) { + logInternal(FATAL, message, null); + } + + /** + * Logs the given message and Throwable at the 'fatal' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logFatal(Object message, Throwable exception) { + logInternal(FATAL, message, exception); + } + + /** + * Logs the given message instance using the 'info' level + * + * @param message + * the message to log + */ + public void logInfo(Object message) { + logInternal(INFO, message, null); + } + + /** + * Logs the given message and Throwable at the 'info' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logInfo(Object message, Throwable exception) { + logInternal(INFO, message, exception); + } + + /** + * Logs the given message instance using the 'trace' level + * + * @param message + * the message to log + */ + public void logTrace(Object message) { + logInternal(TRACE, message, null); + } + + /** + * Logs the given message and Throwable at the 'trace' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logTrace(Object message, Throwable exception) { + logInternal(TRACE, message, exception); + } + + /** + * Logs the given message instance using the 'warn' level + * + * @param message + * the message to log + */ + public void logWarn(Object message) { + logInternal(WARN, message, null); + } + + /** + * Logs the given message and Throwable at the 'warn' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logWarn(Object message, Throwable exception) { + logInternal(WARN, message, exception); + } + + private static final int findCallerStackDepth(StackTraceElement[] stackTrace) { + int numFrames = stackTrace.length; + + for (int i = 0; i < numFrames; i++) { + String callerClassName = stackTrace[i].getClassName(); + + if (!callerClassName.startsWith("com.mysql.jdbc") + || callerClassName.startsWith("com.mysql.jdbc.compliance")) { + return i; + } + } + + return 0; + } + + private void logInternal(Level level, Object msg, Throwable exception) { + // + // only go through this exercise if the message will actually + // be logged. + // + + if (this.jdkLogger.isLoggable(level)) { + String messageAsString = null; + String callerMethodName = "N/A"; + String callerClassName = "N/A"; + int lineNumber = 0; + String fileName = "N/A"; + + if (msg instanceof ProfilerEvent) { + messageAsString = LogUtils.expandProfilerEventIfNecessary(msg) + .toString(); + } else { + Throwable locationException = new Throwable(); + StackTraceElement[] locations = locationException + .getStackTrace(); + + int frameIdx = findCallerStackDepth(locations); + + if (frameIdx != 0) { + callerClassName = locations[frameIdx].getClassName(); + callerMethodName = locations[frameIdx].getMethodName(); + lineNumber = locations[frameIdx].getLineNumber(); + fileName = locations[frameIdx].getFileName(); + } + + messageAsString = String.valueOf(msg); + } + + if (exception == null) { + this.jdkLogger.logp(level, callerClassName, callerMethodName, + messageAsString); + } else { + this.jdkLogger.logp(level, callerClassName, callerMethodName, + messageAsString, exception); + } + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Log.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Log.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Log.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,184 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.log; + +/** + * Unified interface to logging facilities on different platforms + * + * @author Mark Matthews + * + * @version $Id: Log.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public interface Log { + /** + * Is the 'debug' log level enabled? + * + * @return true if so. + */ + boolean isDebugEnabled(); + + /** + * Is the 'error' log level enabled? + * + * @return true if so. + */ + boolean isErrorEnabled(); + + /** + * Is the 'fatal' log level enabled? + * + * @return true if so. + */ + boolean isFatalEnabled(); + + /** + * Is the 'info' log level enabled? + * + * @return true if so. + */ + boolean isInfoEnabled(); + + /** + * Is the 'trace' log level enabled? + * + * @return true if so. + */ + boolean isTraceEnabled(); + + /** + * Is the 'warn' log level enabled? + * + * @return true if so. + */ + boolean isWarnEnabled(); + + /** + * Logs the given message instance using the 'debug' level + * + * @param msg + * the message to log + */ + void logDebug(Object msg); + + /** + * Logs the given message and Throwable at the 'debug' level. + * + * @param msg + * the message to log + * @param thrown + * the throwable to log (may be null) + */ + void logDebug(Object msg, Throwable thrown); + + /** + * Logs the given message instance using the 'error' level + * + * @param msg + * the message to log + */ + void logError(Object msg); + + /** + * Logs the given message and Throwable at the 'error' level. + * + * @param msg + * the message to log + * @param thrown + * the throwable to log (may be null) + */ + void logError(Object msg, Throwable thrown); + + /** + * Logs the given message instance using the 'fatal' level + * + * @param msg + * the message to log + */ + void logFatal(Object msg); + + /** + * Logs the given message and Throwable at the 'fatal' level. + * + * @param msg + * the message to log + * @param thrown + * the throwable to log (may be null) + */ + void logFatal(Object msg, Throwable thrown); + + /** + * Logs the given message instance using the 'info' level + * + * @param msg + * the message to log + */ + void logInfo(Object msg); + + /** + * Logs the given message and Throwable at the 'info' level. + * + * @param msg + * the message to log + * @param thrown + * the throwable to log (may be null) + */ + void logInfo(Object msg, Throwable thrown); + + /** + * Logs the given message instance using the 'trace' level + * + * @param msg + * the message to log + */ + void logTrace(Object msg); + + /** + * Logs the given message and Throwable at the 'trace' level. + * + * @param msg + * the message to log + * @param thrown + * the throwable to log (may be null) + */ + void logTrace(Object msg, Throwable thrown); + + /** + * Logs the given message instance using the 'warn' level + * + * @param msg + * the message to log + */ + void logWarn(Object msg); + + /** + * Logs the given message and Throwable at the 'warn' level. + * + * @param msg + * the message to log + * @param thrown + * the throwable to log (may be null) + */ + void logWarn(Object msg, Throwable thrown); +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Log4JLogger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Attic/Log4JLogger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/Log4JLogger.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,213 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.log; + +import org.apache.log4j.Level; +import org.apache.log4j.Logger; + +/** + * Implementation of log interface for Apache Log4j + * + * @author Mark Matthews + * + * @version $Id: Log4JLogger.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public class Log4JLogger implements Log { + + private Logger logger; + + public Log4JLogger(String instanceName) { + this.logger = Logger.getLogger(instanceName); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#isDebugEnabled() + */ + public boolean isDebugEnabled() { + return this.logger.isDebugEnabled(); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#isErrorEnabled() + */ + public boolean isErrorEnabled() { + return this.logger.isEnabledFor(Level.ERROR); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#isFatalEnabled() + */ + public boolean isFatalEnabled() { + return this.logger.isEnabledFor(Level.FATAL); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#isInfoEnabled() + */ + public boolean isInfoEnabled() { + return this.logger.isInfoEnabled(); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#isTraceEnabled() + */ + public boolean isTraceEnabled() { + return this.logger.isDebugEnabled(); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#isWarnEnabled() + */ + public boolean isWarnEnabled() { + return this.logger.isEnabledFor(Level.WARN); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logDebug(java.lang.Object) + */ + public void logDebug(Object msg) { + this.logger.debug(LogUtils.expandProfilerEventIfNecessary(LogUtils + .expandProfilerEventIfNecessary(msg))); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logDebug(java.lang.Object, + * java.lang.Throwable) + */ + public void logDebug(Object msg, Throwable thrown) { + this.logger.debug(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logError(java.lang.Object) + */ + public void logError(Object msg) { + this.logger.error(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logError(java.lang.Object, + * java.lang.Throwable) + */ + public void logError(Object msg, Throwable thrown) { + this.logger.error(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logFatal(java.lang.Object) + */ + public void logFatal(Object msg) { + this.logger.fatal(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logFatal(java.lang.Object, + * java.lang.Throwable) + */ + public void logFatal(Object msg, Throwable thrown) { + this.logger.fatal(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logInfo(java.lang.Object) + */ + public void logInfo(Object msg) { + this.logger.info(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logInfo(java.lang.Object, + * java.lang.Throwable) + */ + public void logInfo(Object msg, Throwable thrown) { + this.logger.info(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logTrace(java.lang.Object) + */ + public void logTrace(Object msg) { + this.logger.debug(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logTrace(java.lang.Object, + * java.lang.Throwable) + */ + public void logTrace(Object msg, Throwable thrown) { + this.logger.debug(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logWarn(java.lang.Object) + */ + public void logWarn(Object msg) { + this.logger.warn(LogUtils.expandProfilerEventIfNecessary(msg)); + } + + /* + * (non-Javadoc) + * + * @see com.mysql.jdbc.log.Log#logWarn(java.lang.Object, + * java.lang.Throwable) + */ + public void logWarn(Object msg, Throwable thrown) { + this.logger.warn(LogUtils.expandProfilerEventIfNecessary(msg), thrown); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/LogFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/LogFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/LogFactory.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,105 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.log; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.sql.SQLException; + +import com.mysql.jdbc.SQLError; + +/** + * Creates instances of loggers for the driver to use. + * + * @author Mark Matthews + * + * @version $Id: LogFactory.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public class LogFactory { + + /** + * Returns a logger instance of the given class, with the given instance + * name. + * + * @param className + * the class to instantiate + * @param instanceName + * the instance name + * @return a logger instance + * @throws SQLException + * if unable to create a logger instance + */ + public static Log getLogger(String className, String instanceName) + throws SQLException { + + if (className == null) { + throw SQLError.createSQLException("Logger class can not be NULL", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + if (instanceName == null) { + throw SQLError.createSQLException("Logger instance name can not be NULL", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + + try { + Class loggerClass = null; + + try { + loggerClass = Class.forName(className); + } catch (ClassNotFoundException nfe) { + loggerClass = Class.forName(Log.class.getPackage().getName() + "." + className); + } + + Constructor constructor = loggerClass + .getConstructor(new Class[] { String.class }); + + return (Log) constructor.newInstance(new Object[] { instanceName }); + } catch (ClassNotFoundException cnfe) { + throw SQLError.createSQLException("Unable to load class for logger '" + + className + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (NoSuchMethodException nsme) { + throw SQLError.createSQLException( + "Logger class does not have a single-arg constructor that takes an instance name", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (InstantiationException inse) { + throw SQLError.createSQLException("Unable to instantiate logger class '" + + className + "', exception in constructor?", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (InvocationTargetException ite) { + throw SQLError.createSQLException("Unable to instantiate logger class '" + + className + "', exception in constructor?", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (IllegalAccessException iae) { + throw SQLError.createSQLException("Unable to instantiate logger class '" + + className + "', constructor not public", + SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } catch (ClassCastException cce) { + throw SQLError.createSQLException("Logger class '" + className + + "' does not implement the '" + Log.class.getName() + + "' interface", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/LogUtils.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/LogUtils.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/LogUtils.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,171 @@ +/* + Copyright (C) 2005-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +package com.mysql.jdbc.log; + +import com.mysql.jdbc.Util; +import com.mysql.jdbc.profiler.ProfilerEvent; + +public class LogUtils { + + public static final String CALLER_INFORMATION_NOT_AVAILABLE = "Caller information not available"; + + private static final String LINE_SEPARATOR = System + .getProperty("line.separator"); + + private static final int LINE_SEPARATOR_LENGTH = LINE_SEPARATOR.length(); + + public static Object expandProfilerEventIfNecessary( + Object possibleProfilerEvent) { + + if (possibleProfilerEvent instanceof ProfilerEvent) { + StringBuffer msgBuf = new StringBuffer(); + + ProfilerEvent evt = (ProfilerEvent) possibleProfilerEvent; + + Throwable locationException = evt.getEventCreationPoint(); + + if (locationException == null) { + locationException = new Throwable(); + } + + msgBuf.append("Profiler Event: ["); + + boolean appendLocationInfo = false; + + switch (evt.getEventType()) { + case ProfilerEvent.TYPE_EXECUTE: + msgBuf.append("EXECUTE"); + + break; + + case ProfilerEvent.TYPE_FETCH: + msgBuf.append("FETCH"); + + break; + + case ProfilerEvent.TYPE_OBJECT_CREATION: + msgBuf.append("CONSTRUCT"); + + break; + + case ProfilerEvent.TYPE_PREPARE: + msgBuf.append("PREPARE"); + + break; + + case ProfilerEvent.TYPE_QUERY: + msgBuf.append("QUERY"); + + break; + + case ProfilerEvent.TYPE_WARN: + msgBuf.append("WARN"); + appendLocationInfo = true; + + break; + + case ProfilerEvent.TYPE_SLOW_QUERY: + msgBuf.append("SLOW QUERY"); + appendLocationInfo = false; + + break; + + default: + msgBuf.append("UNKNOWN"); + } + + msgBuf.append("] "); + msgBuf.append(findCallingClassAndMethod(locationException)); + msgBuf.append(" duration: "); + msgBuf.append(evt.getEventDuration()); + msgBuf.append(" "); + msgBuf.append(evt.getDurationUnits()); + msgBuf.append(", connection-id: "); + msgBuf.append(evt.getConnectionId()); + msgBuf.append(", statement-id: "); + msgBuf.append(evt.getStatementId()); + msgBuf.append(", resultset-id: "); + msgBuf.append(evt.getResultSetId()); + + String evtMessage = evt.getMessage(); + + if (evtMessage != null) { + msgBuf.append(", message: "); + msgBuf.append(evtMessage); + } + + if (appendLocationInfo) { + msgBuf + .append("\n\nFull stack trace of location where event occurred:\n\n"); + msgBuf.append(Util.stackTraceToString(locationException)); + msgBuf.append("\n"); + } + + return msgBuf; + } + + return possibleProfilerEvent; + } + + public static String findCallingClassAndMethod(Throwable t) { + String stackTraceAsString = Util.stackTraceToString(t); + + String callingClassAndMethod = CALLER_INFORMATION_NOT_AVAILABLE; + + int endInternalMethods = stackTraceAsString + .lastIndexOf("com.mysql.jdbc"); + + if (endInternalMethods != -1) { + int endOfLine = -1; + int compliancePackage = stackTraceAsString.indexOf( + "com.mysql.jdbc.compliance", endInternalMethods); + + if (compliancePackage != -1) { + endOfLine = compliancePackage - LINE_SEPARATOR_LENGTH; + } else { + endOfLine = stackTraceAsString.indexOf(LINE_SEPARATOR, + endInternalMethods); + } + + if (endOfLine != -1) { + int nextEndOfLine = stackTraceAsString.indexOf(LINE_SEPARATOR, + endOfLine + LINE_SEPARATOR_LENGTH); + + if (nextEndOfLine != -1) { + callingClassAndMethod = stackTraceAsString.substring( + endOfLine + LINE_SEPARATOR_LENGTH, nextEndOfLine); + } else { + callingClassAndMethod = stackTraceAsString + .substring(endOfLine + LINE_SEPARATOR_LENGTH); + } + } + } + + if (!callingClassAndMethod.startsWith("\tat ") && + !callingClassAndMethod.startsWith("at ")) { + return "at " + callingClassAndMethod; + } + + return callingClassAndMethod; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/NullLogger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/NullLogger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/NullLogger.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,196 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.log; + +/** + * A logger that does nothing. Used before the log is configured via the URL or + * properties. + * + * @author Mark Matthews + * + * @version $Id: NullLogger.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public class NullLogger implements Log { + + /** + * Creates a new NullLogger with the given name + * + * @param instanceName + * (ignored) + */ + public NullLogger(String instanceName) { + } + + /** + * @see com.mysql.jdbc.log.Log#isDebugEnabled() + */ + public boolean isDebugEnabled() { + // XXX Auto-generated method stub + return false; + } + + /** + * @see com.mysql.jdbc.log.Log#isErrorEnabled() + */ + public boolean isErrorEnabled() { + // XXX Auto-generated method stub + return false; + } + + /** + * @see com.mysql.jdbc.log.Log#isFatalEnabled() + */ + public boolean isFatalEnabled() { + // XXX Auto-generated method stub + return false; + } + + /** + * @see com.mysql.jdbc.log.Log#isInfoEnabled() + */ + public boolean isInfoEnabled() { + // XXX Auto-generated method stub + return false; + } + + /** + * @see com.mysql.jdbc.log.Log#isTraceEnabled() + */ + public boolean isTraceEnabled() { + // XXX Auto-generated method stub + return false; + } + + /** + * @see com.mysql.jdbc.log.Log#isWarnEnabled() + */ + public boolean isWarnEnabled() { + // XXX Auto-generated method stub + return false; + } + + /** + * @see com.mysql.jdbc.log.Log#logDebug(java.lang.Object) + */ + public void logDebug(Object msg) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logDebug(java.lang.Object, + * java.lang.Throwable) + */ + public void logDebug(Object msg, Throwable thrown) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logError(java.lang.Object) + */ + public void logError(Object msg) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logError(java.lang.Object, + * java.lang.Throwable) + */ + public void logError(Object msg, Throwable thrown) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logFatal(java.lang.Object) + */ + public void logFatal(Object msg) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logFatal(java.lang.Object, + * java.lang.Throwable) + */ + public void logFatal(Object msg, Throwable thrown) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logInfo(java.lang.Object) + */ + public void logInfo(Object msg) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logInfo(java.lang.Object, + * java.lang.Throwable) + */ + public void logInfo(Object msg, Throwable thrown) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logTrace(java.lang.Object) + */ + public void logTrace(Object msg) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logTrace(java.lang.Object, + * java.lang.Throwable) + */ + public void logTrace(Object msg, Throwable thrown) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logWarn(java.lang.Object) + */ + public void logWarn(Object msg) { + // XXX Auto-generated method stub + + } + + /** + * @see com.mysql.jdbc.log.Log#logWarn(java.lang.Object, + * java.lang.Throwable) + */ + public void logWarn(Object msg, Throwable thrown) { + // XXX Auto-generated method stub + + } + +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/StandardLogger.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/log/StandardLogger.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/log/StandardLogger.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,321 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.log; + +import com.mysql.jdbc.Util; +import com.mysql.jdbc.profiler.ProfilerEvent; + +import java.util.Date; + +/** + * Provides logging facilities for those platforms that don't have built-in + * facilities. Simply logs messages to STDERR. + * + * @author Mark Matthews + * + * @version $Id: StandardLogger.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public class StandardLogger implements Log { + private static final int FATAL = 0; + + private static final int ERROR = 1; + + private static final int WARN = 2; + + private static final int INFO = 3; + + private static final int DEBUG = 4; + + private static final int TRACE = 5; + + public static StringBuffer bufferedLog = null; + + private boolean logLocationInfo = true; + + /** + * Creates a new StandardLogger object. + * + * @param name + * the name of the configuration to use -- ignored + */ + public StandardLogger(String name) { + this(name, false); + } + + public StandardLogger(String name, boolean logLocationInfo) { + this.logLocationInfo = logLocationInfo; + } + + public static void saveLogsToBuffer() { + if (bufferedLog == null) { + bufferedLog = new StringBuffer(); + } + } + + /** + * @see com.mysql.jdbc.log.Log#isDebugEnabled() + */ + public boolean isDebugEnabled() { + return true; + } + + /** + * @see com.mysql.jdbc.log.Log#isErrorEnabled() + */ + public boolean isErrorEnabled() { + return true; + } + + /** + * @see com.mysql.jdbc.log.Log#isFatalEnabled() + */ + public boolean isFatalEnabled() { + return true; + } + + /** + * @see com.mysql.jdbc.log.Log#isInfoEnabled() + */ + public boolean isInfoEnabled() { + return true; + } + + /** + * @see com.mysql.jdbc.log.Log#isTraceEnabled() + */ + public boolean isTraceEnabled() { + return true; + } + + /** + * @see com.mysql.jdbc.log.Log#isWarnEnabled() + */ + public boolean isWarnEnabled() { + return true; + } + + /** + * Logs the given message instance using the 'debug' level + * + * @param message + * the message to log + */ + public void logDebug(Object message) { + logInternal(DEBUG, message, null); + } + + /** + * Logs the given message and Throwable at the 'debug' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logDebug(Object message, Throwable exception) { + logInternal(DEBUG, message, exception); + } + + /** + * Logs the given message instance using the 'error' level + * + * @param message + * the message to log + */ + public void logError(Object message) { + logInternal(ERROR, message, null); + } + + /** + * Logs the given message and Throwable at the 'error' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logError(Object message, Throwable exception) { + logInternal(ERROR, message, exception); + } + + /** + * Logs the given message instance using the 'fatal' level + * + * @param message + * the message to log + */ + public void logFatal(Object message) { + logInternal(FATAL, message, null); + } + + /** + * Logs the given message and Throwable at the 'fatal' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logFatal(Object message, Throwable exception) { + logInternal(FATAL, message, exception); + } + + /** + * Logs the given message instance using the 'info' level + * + * @param message + * the message to log + */ + public void logInfo(Object message) { + logInternal(INFO, message, null); + } + + /** + * Logs the given message and Throwable at the 'info' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logInfo(Object message, Throwable exception) { + logInternal(INFO, message, exception); + } + + /** + * Logs the given message instance using the 'trace' level + * + * @param message + * the message to log + */ + public void logTrace(Object message) { + logInternal(TRACE, message, null); + } + + /** + * Logs the given message and Throwable at the 'trace' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logTrace(Object message, Throwable exception) { + logInternal(TRACE, message, exception); + } + + /** + * Logs the given message instance using the 'warn' level + * + * @param message + * the message to log + */ + public void logWarn(Object message) { + logInternal(WARN, message, null); + } + + /** + * Logs the given message and Throwable at the 'warn' level. + * + * @param message + * the message to log + * @param exception + * the throwable to log (may be null) + */ + public void logWarn(Object message, Throwable exception) { + logInternal(WARN, message, exception); + } + + private void logInternal(int level, Object msg, Throwable exception) { + StringBuffer msgBuf = new StringBuffer(); + msgBuf.append(new Date().toString()); + msgBuf.append(" "); + + switch (level) { + case FATAL: + msgBuf.append("FATAL: "); + + break; + + case ERROR: + msgBuf.append("ERROR: "); + + break; + + case WARN: + msgBuf.append("WARN: "); + + break; + + case INFO: + msgBuf.append("INFO: "); + + break; + + case DEBUG: + msgBuf.append("DEBUG: "); + + break; + + case TRACE: + msgBuf.append("TRACE: "); + + break; + } + + if (msg instanceof ProfilerEvent) { + msgBuf.append(LogUtils.expandProfilerEventIfNecessary(msg)); + + } else { + if (this.logLocationInfo && level != TRACE) { + Throwable locationException = new Throwable(); + msgBuf.append(LogUtils + .findCallingClassAndMethod(locationException)); + msgBuf.append(" "); + } + + if (msg != null) { + msgBuf.append(String.valueOf(msg)); + } + } + + if (exception != null) { + msgBuf.append("\n"); + msgBuf.append("\n"); + msgBuf.append("EXCEPTION STACK TRACE:"); + msgBuf.append("\n"); + msgBuf.append("\n"); + msgBuf.append(Util.stackTraceToString(exception)); + } + + String messageAsString = msgBuf.toString(); + + System.err.println(messageAsString); + + if (bufferedLog != null) { + bufferedLog.append(messageAsString); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/profiler/ProfileEventSink.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/profiler/Attic/ProfileEventSink.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/profiler/ProfileEventSink.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,91 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + +package com.mysql.jdbc.profiler; + +import com.mysql.jdbc.Connection; +import com.mysql.jdbc.log.Log; + +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +/** + * @author mmatthew + */ +public class ProfileEventSink { + + private static final Map CONNECTIONS_TO_SINKS = new HashMap(); + + private Connection ownerConnection = null; + + private Log log = null; + + /** + * Returns the ProfileEventSink that handles profiler events for the given + * connection. + * + * @param conn + * the connection to handle events for + * @return the ProfileEventSink that handles profiler events + */ + public static synchronized ProfileEventSink getInstance(Connection conn) { + ProfileEventSink sink = (ProfileEventSink) CONNECTIONS_TO_SINKS + .get(conn); + + if (sink == null) { + sink = new ProfileEventSink(conn); + CONNECTIONS_TO_SINKS.put(conn, sink); + } + + return sink; + } + + /** + * Process a profiler event + * + * @param evt + * the event to process + */ + public void consumeEvent(ProfilerEvent evt) { + if (evt.eventType == ProfilerEvent.TYPE_WARN) { + this.log.logWarn(evt); + } else { + this.log.logInfo(evt); + } + } + + public static synchronized void removeInstance(Connection conn) { + CONNECTIONS_TO_SINKS.remove(conn); + } + + private ProfileEventSink(Connection conn) { + this.ownerConnection = conn; + + try { + this.log = this.ownerConnection.getLog(); + } catch (SQLException sqlEx) { + throw new RuntimeException("Unable to get logger from connection"); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/profiler/ProfilerEvent.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/profiler/ProfilerEvent.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/profiler/ProfilerEvent.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,540 @@ +/* + Copyright (C) 2002-2007 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + +package com.mysql.jdbc.profiler; + +import java.util.Date; + +import com.mysql.jdbc.Util; + +/** + * @author mmatthew + */ +public class ProfilerEvent { + + /** + * A Profiler warning event + */ + public static final byte TYPE_WARN = 0; + + /** + * Profiler creating object type event + */ + public static final byte TYPE_OBJECT_CREATION = 1; + + /** + * Profiler event for prepared statements being prepared + */ + public static final byte TYPE_PREPARE = 2; + + /** + * Profiler event for a query being executed + */ + public static final byte TYPE_QUERY = 3; + + /** + * Profiler event for prepared statements being executed + */ + public static final byte TYPE_EXECUTE = 4; + + /** + * Profiler event for result sets being retrieved + */ + public static final byte TYPE_FETCH = 5; + + /** + * Profiler event for slow query + */ + public static final byte TYPE_SLOW_QUERY = 6; + + /** + * Type of event + */ + protected byte eventType; + + /** + * Associated connection (-1 for none) + */ + protected long connectionId; + + /** + * Associated statement (-1 for none) + */ + protected int statementId; + + /** + * Associated result set (-1 for none) + */ + protected int resultSetId; + + /** + * When was the event created? + */ + protected long eventCreationTime; + + /** + * How long did the event last? + */ + protected long eventDuration; + + /** + * What units was the duration measured in? + */ + protected String durationUnits; + + /** + * The hostname the event occurred on (as an index into a dictionary, used + * by 'remote' profilers for efficiency)? + */ + protected int hostNameIndex; + + /** + * The hostname the event occurred on + */ + protected String hostName; + + /** + * The catalog the event occurred on (as an index into a dictionary, used by + * 'remote' profilers for efficiency)? + */ + protected int catalogIndex; + + /** + * The catalog the event occurred on + */ + protected String catalog; + + /** + * Where was the event created (as an index into a dictionary, used by + * 'remote' profilers for efficiency)? + */ + protected int eventCreationPointIndex; + + /** + * Where was the event created (as a Throwable)? + */ + protected Throwable eventCreationPoint; + + /** + * Where was the event created (as a string description of the + * eventCreationPoint)? + */ + protected String eventCreationPointDesc; + + /** + * Optional event message + */ + protected String message; + + /** + * Creates a new profiler event + * + * @param eventType + * the event type (from the constants TYPE_????) + * @param hostName + * the hostname where the event occurs + * @param catalog + * the catalog in use + * @param connectionId + * the connection id (-1 if N/A) + * @param statementId + * the statement id (-1 if N/A) + * @param resultSetId + * the result set id (-1 if N/A) + * @param eventCreationTime + * when was the event created? + * @param eventDurationMillis + * how long did the event last? + * @param eventCreationPointDesc + * event creation point as a string + * @param eventCreationPoint + * event creation point as a Throwable + * @param message + * optional message + */ + public ProfilerEvent(byte eventType, String hostName, String catalog, + long connectionId, int statementId, int resultSetId, + long eventCreationTime, long eventDuration, String durationUnits, + String eventCreationPointDesc, Throwable eventCreationPoint, + String message) { + this.eventType = eventType; + this.connectionId = connectionId; + this.statementId = statementId; + this.resultSetId = resultSetId; + this.eventCreationTime = eventCreationTime; + this.eventDuration = eventDuration; + this.durationUnits = durationUnits; + this.eventCreationPoint = eventCreationPoint; + this.eventCreationPointDesc = eventCreationPointDesc; + this.message = message; + } + + /** + * Returns the description of when this event was created. + * + * @return a description of when this event was created. + */ + public String getEventCreationPointAsString() { + if (this.eventCreationPointDesc == null) { + this.eventCreationPointDesc = Util + .stackTraceToString(this.eventCreationPoint); + } + + return this.eventCreationPointDesc; + } + + /** + * Returns a representation of this event as a String. + * + * @return a String representation of this event. + */ + public String toString() { + StringBuffer buf = new StringBuffer(32); + + switch (this.eventType) { + case TYPE_EXECUTE: + buf.append("EXECUTE"); + break; + + case TYPE_FETCH: + buf.append("FETCH"); + break; + + case TYPE_OBJECT_CREATION: + buf.append("CONSTRUCT"); + break; + + case TYPE_PREPARE: + buf.append("PREPARE"); + break; + + case TYPE_QUERY: + buf.append("QUERY"); + break; + + case TYPE_WARN: + buf.append("WARN"); + break; + case TYPE_SLOW_QUERY: + buf.append("SLOW QUERY"); + break; + default: + buf.append("UNKNOWN"); + } + + buf.append(" created: "); + buf.append(new Date(this.eventCreationTime)); + buf.append(" duration: "); + buf.append(this.eventDuration); + buf.append(" connection: "); + buf.append(this.connectionId); + buf.append(" statement: "); + buf.append(this.statementId); + buf.append(" resultset: "); + buf.append(this.resultSetId); + + if (this.message != null) { + buf.append(" message: "); + buf.append(this.message); + + } + + if (this.eventCreationPointDesc != null) { + buf.append("\n\nEvent Created at:\n"); + buf.append(this.eventCreationPointDesc); + } + + return buf.toString(); + } + + /** + * Unpacks a binary representation of this event. + * + * @param buf + * the binary representation of this event + * @return the unpacked Event + * @throws Exception + * if an error occurs while unpacking the event + */ + public static ProfilerEvent unpack(byte[] buf) throws Exception { + int pos = 0; + + byte eventType = buf[pos++]; + long connectionId = readInt(buf, pos); + pos += 8; + int statementId = readInt(buf, pos); + pos += 4; + int resultSetId = readInt(buf, pos); + pos += 4; + long eventCreationTime = readLong(buf, pos); + pos += 8; + long eventDuration = readLong(buf, pos); + pos += 4; + + byte[] eventDurationUnits = readBytes(buf, pos); + pos += 4; + + if (eventDurationUnits != null) { + pos += eventDurationUnits.length; + } + + int eventCreationPointIndex = readInt(buf, pos); + pos += 4; + byte[] eventCreationAsBytes = readBytes(buf, pos); + pos += 4; + + if (eventCreationAsBytes != null) { + pos += eventCreationAsBytes.length; + } + + byte[] message = readBytes(buf, pos); + pos += 4; + + if (message != null) { + pos += message.length; + } + + return new ProfilerEvent(eventType, "", "", connectionId, statementId, + resultSetId, eventCreationTime, eventDuration, + new String(eventDurationUnits, "ISO8859_1"), + new String(eventCreationAsBytes, "ISO8859_1"), null, + new String(message, "ISO8859_1")); + } + + /** + * Creates a binary representation of this event. + * + * @return a binary representation of this event + * @throws Exception + * if an error occurs while packing this event. + */ + public byte[] pack() throws Exception { + + int len = 1 + 4 + 4 + 4 + 8 + 4 + 4; + + byte[] eventCreationAsBytes = null; + + getEventCreationPointAsString(); + + if (this.eventCreationPointDesc != null) { + eventCreationAsBytes = this.eventCreationPointDesc + .getBytes("ISO8859_1"); + len += (4 + eventCreationAsBytes.length); + } else { + len += 4; + } + + byte[] messageAsBytes = null; + + if (messageAsBytes != null) { + messageAsBytes = this.message.getBytes("ISO8859_1"); + len += (4 + messageAsBytes.length); + } else { + len += 4; + } + + byte[] durationUnitsAsBytes = null; + + if (durationUnits != null) { + durationUnitsAsBytes = this.durationUnits.getBytes("ISO8859_1"); + len += (4 + durationUnitsAsBytes.length); + } else { + len += 4; + } + + byte[] buf = new byte[len]; + + int pos = 0; + + buf[pos++] = this.eventType; + pos = writeLong(this.connectionId, buf, pos); + pos = writeInt(this.statementId, buf, pos); + pos = writeInt(this.resultSetId, buf, pos); + pos = writeLong(this.eventCreationTime, buf, pos); + pos = writeLong(this.eventDuration, buf, pos); + pos = writeBytes(durationUnitsAsBytes, buf, pos); + pos = writeInt(this.eventCreationPointIndex, buf, pos); + + if (eventCreationAsBytes != null) { + pos = writeBytes(eventCreationAsBytes, buf, pos); + } else { + pos = writeInt(0, buf, pos); + } + + if (messageAsBytes != null) { + pos = writeBytes(messageAsBytes, buf, pos); + } else { + pos = writeInt(0, buf, pos); + } + + return buf; + } + + private static int writeInt(int i, byte[] buf, int pos) { + + buf[pos++] = (byte) (i & 0xff); + buf[pos++] = (byte) (i >>> 8); + buf[pos++] = (byte) (i >>> 16); + buf[pos++] = (byte) (i >>> 24); + + return pos; + } + + private static int writeLong(long l, byte[] buf, int pos) { + buf[pos++] = (byte) (l & 0xff); + buf[pos++] = (byte) (l >>> 8); + buf[pos++] = (byte) (l >>> 16); + buf[pos++] = (byte) (l >>> 24); + buf[pos++] = (byte) (l >>> 32); + buf[pos++] = (byte) (l >>> 40); + buf[pos++] = (byte) (l >>> 48); + buf[pos++] = (byte) (l >>> 56); + + return pos; + } + + private static int writeBytes(byte[] msg, byte[] buf, int pos) { + pos = writeInt(msg.length, buf, pos); + + System.arraycopy(msg, 0, buf, pos, msg.length); + + return pos + msg.length; + } + + private static int readInt(byte[] buf, int pos) { + return (buf[pos++] & 0xff) | ((buf[pos++] & 0xff) << 8) + | ((buf[pos++] & 0xff) << 16) | ((buf[pos++] & 0xff) << 24); + + } + + private static long readLong(byte[] buf, int pos) { + return (long) (buf[pos++] & 0xff) | ((long) (buf[pos++] & 0xff) << 8) + | ((long) (buf[pos++] & 0xff) << 16) + | ((long) (buf[pos++] & 0xff) << 24) + | ((long) (buf[pos++] & 0xff) << 32) + | ((long) (buf[pos++] & 0xff) << 40) + | ((long) (buf[pos++] & 0xff) << 48) + | ((long) (buf[pos++] & 0xff) << 56); + } + + private static byte[] readBytes(byte[] buf, int pos) { + int length = readInt(buf, pos); + + pos += 4; + + byte[] msg = new byte[length]; + System.arraycopy(buf, pos, msg, 0, length); + + return msg; + } + + /** + * Returns the catalog in use + * + * @return the catalog in use + */ + public String getCatalog() { + return this.catalog; + } + + /** + * Returns the id of the connection in use when this event was created. + * + * @return the connection in use + */ + public long getConnectionId() { + return this.connectionId; + } + + /** + * Returns the point (as a Throwable stacktrace) where this event was + * created. + * + * @return the point where this event was created + */ + public Throwable getEventCreationPoint() { + return this.eventCreationPoint; + } + + /** + * Returns the time (in System.currentTimeMillis() form) when this event was + * created + * + * @return the time this event was created + */ + public long getEventCreationTime() { + return this.eventCreationTime; + } + + /** + * Returns the duration of the event in milliseconds + * + * @return the duration of the event in milliseconds + */ + public long getEventDuration() { + return this.eventDuration; + } + + /** + * Returns the units for getEventDuration() + */ + public String getDurationUnits() { + return this.durationUnits; + } + + /** + * Returns the event type flag + * + * @return the event type flag + */ + public byte getEventType() { + return this.eventType; + } + + /** + * Returns the id of the result set in use when this event was created. + * + * @return the result set in use + */ + public int getResultSetId() { + return this.resultSetId; + } + + /** + * Returns the id of the statement in use when this event was created. + * + * @return the statement in use + */ + public int getStatementId() { + return this.statementId; + } + + /** + * Returns the optional message for this event + * + * @return the message stored in this event + */ + public String getMessage() { + return this.message; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/trace/Tracer.aj =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/trace/Attic/Tracer.aj,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/trace/Tracer.aj 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,259 @@ +/* + Copyright (C) 2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package com.mysql.jdbc.trace; + +import java.io.PrintStream; +import java.sql.SQLException; + +import com.mysql.jdbc.log.Log; +import com.mysql.jdbc.log.StandardLogger; +import com.mysql.jdbc.Connection; + +import org.aspectj.lang.JoinPoint; + +public aspect Tracer { + + pointcut constructors(): execution(* *(..)) && within(com.mysql.jdbc.* ) + && within (!com.mysql.jdbc.trace.*) && within(!com.mysql.jdbc.log.*) + && within (!com.mysql.jdbc.Util); + + pointcut methods(): execution(* *(..)) && within(com.mysql.jdbc.* ) + && within(!com.mysql.jdbc.trace.*) && within(!com.mysql.jdbc.log.*) + && within (!com.mysql.jdbc.Util); + + before(): constructors() && methods() { + entry(thisJoinPoint, false); + } + + after() returning (Object o): constructors() && methods() { + exit(thisJoinPoint, false, o); + } + + private Log standardLogger = new StandardLogger("MySQL", false); + + private ThreadLocal stream = new ThreadLocal() { + protected Object initialValue() { + return System.err; + } + }; + + private ThreadLocal log = new ThreadLocal() { + protected Object initialValue() { + return standardLogger; + } + }; + + private ThreadLocal callDepth = new ThreadLocal() { + protected Object initialValue() { + return new Integer(0); + } + }; + + private PrintStream getStream() { + return (PrintStream)stream.get(); + } + + private void setStream(PrintStream s) { + stream.set(s); + } + + private int getCallDepth() { + return ((Integer)(callDepth.get())).intValue(); + } + + private void setCallDepth(int n) { + callDepth.set(new Integer(n)); + } + + private Log getLog() { + return (Log)log.get(); + } + + private void setLog(Log l) { + log.set(l); + } + + private void entry(JoinPoint jp, boolean isConstructor) { + + if (jp.getTarget() instanceof com.mysql.jdbc.Connection) { + if ("getLog".equals(jp.getSignature().getName())) { + return; + } + + try { + Log connectionLog = ((com.mysql.jdbc.Connection)jp.getTarget()).getLog(); + + if (getLog() != connectionLog) { + setLog(connectionLog); + } + } catch (SQLException ex) { + // swallow it, can't do anything here + } + } + + if ("com.mysql.jdbc.Buffer".equals(jp.getSignature().getDeclaringTypeName()) + && ("toString".equals(jp.getSignature().getName()) + || "dumpClampedBytes".equals(jp.getSignature().getName()))) { + return; + } + + if ("com.mysql.jdbc.StringUtils".equals(jp.getSignature().getDeclaringTypeName()) + && "dumpAsHex".equals(jp.getSignature().getName())) { + return; + } + + setCallDepth(getCallDepth() + 1); + printEntering(jp, isConstructor); + } + + private void exit(JoinPoint jp, boolean isConstructor, Object returnValue) { + if (jp.getTarget() instanceof com.mysql.jdbc.Connection) { + if ("getLog".equals(jp.getSignature().getName())) { + return; + } + } + + if ("com.mysql.jdbc.Buffer".equals(jp.getSignature().getDeclaringTypeName()) + && ("toString".equals(jp.getSignature().getName()) + || "dumpClampedBytes".equals(jp.getSignature().getName()))) { + return; + } + + if ("com.mysql.jdbc.StringUtils".equals(jp.getSignature().getDeclaringTypeName()) + && "dumpAsHex".equals(jp.getSignature().getName())) { + return; + } + + printExiting(jp, isConstructor, returnValue); + setCallDepth(getCallDepth() - 1); + } + + private void printEntering (JoinPoint jp, boolean isConstructor) { + + + if (getLog().isTraceEnabled()) { + + StringBuffer buf = new StringBuffer(80); + printIndent(buf); + buf.append("--> "); + + buf.append(jp.getSourceLocation().getFileName()); + buf.append(":"); + buf.append(jp.getSourceLocation().getLine()); + buf.append(" "); + buf.append(jp.getSignature().getDeclaringTypeName()); + buf.append("."); + buf.append(jp.getSignature().getName()); + printParameters(jp, buf); + + getLog().logTrace(buf); + } + } + + private void printExiting (JoinPoint jp, boolean isConstructor, Object returnValue) { + if (getLog().isTraceEnabled()) { + StringBuffer buf = new StringBuffer(80); + printIndent(buf); + + buf.append("<-- "); + buf.append(jp.getSourceLocation().getFileName()); + buf.append(":"); + buf.append(jp.getSourceLocation().getLine()); + buf.append(" "); + buf.append(jp.getSignature().getDeclaringTypeName()); + buf.append("."); + buf.append(jp.getSignature().getName()); + buf.append("(..) returning "); + + boolean isString = returnValue instanceof String; + + if (isString) { + buf.append("\""); + } + + buf.append(returnValue); + + if (isString) { + buf.append("\""); + } + + getLog().logTrace(buf); + } + } + + + + private void printIndent(StringBuffer buf) { + for (int i = 0; i < getCallDepth(); i++) { + buf.append(" "); + } + } + + private void printParameters(JoinPoint jp, StringBuffer buf) { + Object[] params = jp.getArgs(); + + buf.append("("); + + for (int i = 0; i < params.length; i++) { + boolean isString = params[i] instanceof String; + + if (isString) { + buf.append("\""); + } + + if (params[i] != null) { + Class paramClass = params[i].getClass(); + String paramClassName = null; + + if (paramClass != null) { + paramClassName = paramClass.getName(); + } + + if (paramClassName!= null && + "com.mysql.jdbc.Buffer".equals(paramClassName) + || "com.mysql.jdbc.ByteArrayBuffer".equals(paramClassName) + || "com.mysql.jdbc.ChannelBuffer".equals(paramClassName)) { + buf.append("Network packet, data follows:\n\n"); + buf.append(params[i]); + buf.append("\n\n"); + } else { + buf.append(params[i]); + } + } else { + buf.append("null"); + } + + if (isString) { + buf.append("\""); + } + + if (i < params.length - 1) { + buf.append(", "); + } + } + + buf.append(")"); + } + +} + Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/BaseBugReport.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/BaseBugReport.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/BaseBugReport.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,263 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.util; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; + +import com.mysql.jdbc.Driver; + +/** + * Base class to help file bug reports for Connector/J. + * + *

+ * MySQL AB + *

    + * really + *
+ * appreciates repeatable testcases when reporting bugs, so we're giving you + * this class to make that job a bit easier (and standarized). + * + *

+ * To create a testcase, create a class that inherits from this class + * (com.mysql.jdbc.util.BaseBugReport), and override the methods 'setUp', + * 'tearDown' and 'runTest'. + * + *

+ * In the 'setUp' method, create code that creates your tables, and populates + * them with any data needed to demonstrate the bug. + * + *

+ * In the 'runTest' method, create code that demonstrates the bug using the + * tables and data you created in the 'setUp' method. + * + *

+ * In the 'tearDown' method, drop any tables you created in the 'setUp' method. + * + *

+ * In any of the above three methods, you should use one of the variants of the + * 'getConnection' method to create a JDBC connection to MySQL, which will use + * the default JDBC URL of 'jdbc:mysql:///test'. + * + *

+ * If you need to use a JDBC URL that is different than 'jdbc:mysql:///test', + * then override the method 'getUrl' as well. + * + *

+ * Use the 'assertTrue' methods to create conditions that must be met in your + * testcase demonstrating the behavior you are expecting (vs. the behavior you + * are observing, which is why you are most likely filing a bug report). + * + *

+ * Finally, create a 'main' method that creates a new instance of your testcase, + * and calls the 'run' method: + * + *

+ * + *

+ * public static void main(String[] args) throws Exception {
+ * 	new MyBugReport().run();
+ * }
+ * 
+ * + *

+ * When filing a potential bug with MySQL Connector/J at http://bugs.mysql.com/ + * or on the bugs mailing list, please include the code that you have just + * written using this class. + * + * @author Mark Matthews + * @version $Id: BaseBugReport.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public abstract class BaseBugReport { + + private Connection conn; + + private Driver driver; + + /** + * Constructor for this BugReport, sets up JDBC driver used to create + * connections. + */ + public BaseBugReport() { + try { + this.driver = new Driver(); + } catch (SQLException ex) { + throw new RuntimeException(ex.toString()); + } + } + + /** + * Override this method with code that sets up the testcase for + * demonstrating your bug (creating tables, populating data, etc). + * + * @throws Exception + * if an error occurs during the 'setUp' phase. + */ + public abstract void setUp() throws Exception; + + /** + * Override this method with code that cleans up anything created in the + * setUp() method. + * + * @throws Exception + * if an error occurs during the 'tearDown' phase. + */ + public abstract void tearDown() throws Exception; + + /** + * Override this method with code that demonstrates the bug. This method + * will be called after setUp(), and before tearDown(). + * + * @throws Exception + * if an error occurs during your test run. + */ + public abstract void runTest() throws Exception; + + /** + * Runs the testcase by calling the setUp(), runTest() and tearDown() + * methods. The tearDown() method is run regardless of any errors occuring + * in the other methods. + * + * @throws Exception + * if an error occurs in any of the aforementioned methods. + */ + public final void run() throws Exception { + try { + setUp(); + runTest(); + + } finally { + tearDown(); + } + } + + /** + * Throws an exception with the given message if condition evalutates to + * 'false'. + * + * @param message + * the message to use in the exception + * @param condition + * the condition to test for + * @throws Exception + * if !condition + */ + protected final void assertTrue(String message, boolean condition) + throws Exception { + if (!condition) { + throw new Exception("Assertion failed: " + message); + } + } + + /** + * Throws an exception if condition evalutates to 'false'. + * + * @param condition + * the condition to test for + * @throws Exception + * if !condition + */ + protected final void assertTrue(boolean condition) throws Exception { + assertTrue("(no message given)", condition); + } + + /** + * Provides the JDBC URL to use to demonstrate the bug. The + * java.sql.Connection that you use to demonstrate this bug will be provided + * by the getConnection() method using this URL. + * + * The default value is 'jdbc:mysql:///test' + */ + public String getUrl() { + return "jdbc:mysql:///test"; + } + + /** + * Provides a connection to the JDBC URL specified in getUrl(). + * + * If a connection already exists, that connection is returned. Otherwise a + * new connection is created. + * + * @return a connection to the JDBC URL specified in getUrl(). + * + * @throws SQLException + * if an error is caused while creating the connection. + */ + public final synchronized Connection getConnection() throws SQLException { + if (this.conn == null || this.conn.isClosed()) { + this.conn = getNewConnection(); + } + + return this.conn; + } + + /** + * Use this if you need to get a new connection for your bug report (i.e. + * there's more than one connection involved). + * + * @return a new connection to the JDBC URL specified in getUrl(). + * + * @throws SQLException + * if an error is caused while creating the connection. + */ + public final synchronized Connection getNewConnection() throws SQLException { + return getConnection(getUrl()); + } + + /** + * Returns a connection using the given URL. + * + * @param url + * the JDBC URL to use + * @return a new java.sql.Connection to the JDBC URL. + * @throws SQLException + * if an error occurs getting the connection. + */ + public final synchronized Connection getConnection(String url) + throws SQLException { + return getConnection(url, null); + } + + /** + * Returns a connection using the given URL and properties. + * + * @param url + * the JDBC URL to use + * @param props + * the JDBC properties to use + * @return a new java.sql.Connection to the JDBC URL. + * @throws SQLException + * if an error occurs getting the connection. + */ + public final synchronized Connection getConnection(String url, + Properties props) throws SQLException { + + // Don't follow this example in your own code + // This is to bypass the java.sql.DriverManager + + return this.driver.connect(url, props); + } +} \ No newline at end of file Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ErrorMappingsDocGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ErrorMappingsDocGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ErrorMappingsDocGenerator.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,43 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.util; + +import com.mysql.jdbc.SQLError; + +/** + * Creates XML file describing mapping of MySQL error #'s to SQL92 and X/Open + * states. + * + * @author Mark Matthews + * + * @version $Id: ErrorMappingsDocGenerator.java,v 1.1.2.1 2005/05/13 18:58:39 + * mmatthews Exp $ + */ +public class ErrorMappingsDocGenerator { + + public static void main(String[] args) throws Exception { + SQLError.dumpSqlStatesMappingsAsXml(); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/LRUCache.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/LRUCache.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/LRUCache.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,51 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.util; + +import java.util.LinkedHashMap; +import java.util.Map.Entry; + +/** + * @author Mark Matthews + * @version $Id: LRUCache.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public class LRUCache extends LinkedHashMap { + private static final long serialVersionUID = 1L; + protected int maxElements; + + public LRUCache(int maxSize) { + super(maxSize); + this.maxElements = maxSize; + } + + /* + * (non-Javadoc) + * + * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry) + */ + protected boolean removeEldestEntry(Entry eldest) { + return (size() > this.maxElements); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/PropertiesDocGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/PropertiesDocGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/PropertiesDocGenerator.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,40 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.util; + +import java.sql.SQLException; + +import com.mysql.jdbc.ConnectionProperties; + +/** + * Creates docbook table of connection properties from ConnectionProperties + * class. + */ +public class PropertiesDocGenerator extends ConnectionProperties { + + public static void main(String[] args) throws SQLException { + System.out.println(new PropertiesDocGenerator().exposeAsXml()); + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ReadAheadInputStream.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ReadAheadInputStream.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ReadAheadInputStream.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,309 @@ +/* + Copyright (C) 2002-2005 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + */ + +package com.mysql.jdbc.util; + +import java.io.IOException; +import java.io.InputStream; + +import com.mysql.jdbc.log.Log; + +/** + * A non-blocking buffered input stream. Reads more if it can, won't block to + * fill the buffer, only blocks to satisfy a request of read(byte[]) + * + * @author Mark Matthews + * + * @version $Id: ReadAheadInputStream.java,v 1.1.2.1 2005/05/13 18:58:39 + * mmatthews Exp $ + */ +public class ReadAheadInputStream extends InputStream { + + private final static int DEFAULT_BUFFER_SIZE = 4096; + + private InputStream underlyingStream; + + private byte buf[]; + + protected int endOfCurrentData; + + protected int currentPosition; + + protected boolean doDebug = false; + + protected Log log; + + private void fill(int readAtLeastTheseManyBytes) throws IOException { + checkClosed(); + + this.currentPosition = 0; /* no mark: throw away the buffer */ + + this.endOfCurrentData = currentPosition; + + // Read at least as many bytes as the caller wants, but don't + // block to fill the whole buffer (like java.io.BufferdInputStream + // does) + + int bytesToRead = Math.min(this.buf.length - currentPosition, + readAtLeastTheseManyBytes); + + int bytesAvailable = this.underlyingStream.available(); + + if (bytesAvailable > bytesToRead) { + + // Great, there's more available, let's grab those + // bytes too! (read-ahead) + + bytesToRead = Math.min(this.buf.length - currentPosition, + bytesAvailable); + } + + if (this.doDebug) { + StringBuffer debugBuf = new StringBuffer(); + debugBuf.append(" ReadAheadInputStream.fill("); + debugBuf.append(readAtLeastTheseManyBytes); + debugBuf.append("), buffer_size="); + debugBuf.append(this.buf.length); + debugBuf.append(", current_position="); + debugBuf.append(currentPosition); + debugBuf.append(", need to read "); + debugBuf.append(Math.min(this.buf.length - currentPosition, + readAtLeastTheseManyBytes)); + debugBuf.append(" bytes to fill request,"); + + if (bytesAvailable > 0) { + debugBuf.append(" underlying InputStream reports "); + debugBuf.append(bytesAvailable); + + debugBuf.append(" total bytes available,"); + } + + debugBuf.append(" attempting to read "); + debugBuf.append(bytesToRead); + debugBuf.append(" bytes."); + + if (this.log != null) { + this.log.logTrace(debugBuf.toString()); + } else { + System.err.println(debugBuf.toString()); + } + } + + int n = this.underlyingStream.read(this.buf, currentPosition, + bytesToRead); + + if (n > 0) { + endOfCurrentData = n + currentPosition; + } + } + + private int readFromUnderlyingStreamIfNecessary(byte[] b, int off, int len) + throws IOException { + checkClosed(); + + int avail = endOfCurrentData - currentPosition; + + if (this.doDebug) { + StringBuffer debugBuf = new StringBuffer(); + debugBuf.append("ReadAheadInputStream.readIfNecessary("); + debugBuf.append(b); + debugBuf.append(","); + debugBuf.append(off); + debugBuf.append(","); + debugBuf.append(len); + debugBuf.append(")"); + + if (avail <= 0) { + debugBuf + .append(" not all data available in buffer, must read from stream"); + + if (len >= this.buf.length) { + debugBuf + .append(", amount requested > buffer, returning direct read() from stream"); + } + } + + if (this.log != null) { + this.log.logTrace(debugBuf.toString()); + } else { + System.err.println(debugBuf.toString()); + } + } + + if (avail <= 0) { + + if (len >= this.buf.length) { + return this.underlyingStream.read(b, off, len); + } + + fill(len); + + avail = endOfCurrentData - currentPosition; + + if (avail <= 0) + return -1; + } + + int bytesActuallyRead = (avail < len) ? avail : len; + + System.arraycopy(this.buf, currentPosition, b, off, bytesActuallyRead); + + this.currentPosition += bytesActuallyRead; + + return bytesActuallyRead; + } + + public synchronized int read(byte b[], int off, int len) throws IOException { + checkClosed(); // Check for closed stream + if ((off | len | (off + len) | (b.length - (off + len))) < 0) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return 0; + } + + int totalBytesRead = 0; + + while (true) { + int bytesReadThisRound = readFromUnderlyingStreamIfNecessary(b, off + + totalBytesRead, len - totalBytesRead); + + // end-of-stream? + if (bytesReadThisRound <= 0) { + if (totalBytesRead == 0) { + totalBytesRead = bytesReadThisRound; + } + + break; + } + + totalBytesRead += bytesReadThisRound; + + // Read _at_least_ enough bytes + if (totalBytesRead >= len) { + break; + } + + // Nothing to read? + if (this.underlyingStream.available() <= 0) { + break; + } + } + + return totalBytesRead; + } + + public int read() throws IOException { + checkClosed(); + + if (currentPosition >= endOfCurrentData) { + fill(1); + if (currentPosition >= endOfCurrentData) + return -1; + } + + return this.buf[currentPosition++] & 0xff; + } + + public int available() throws IOException { + checkClosed(); + + return this.underlyingStream.available() + + (this.endOfCurrentData - this.currentPosition); + } + + private void checkClosed() throws IOException { + + if (this.buf == null) { + throw new IOException("Stream closed"); + } + } + + /** + * + */ + public ReadAheadInputStream(InputStream toBuffer, boolean debug, Log logTo) { + this(toBuffer, DEFAULT_BUFFER_SIZE, debug, logTo); + } + + public ReadAheadInputStream(InputStream toBuffer, int bufferSize, + boolean debug, + Log logTo) { + this.underlyingStream = toBuffer; + this.buf = new byte[bufferSize]; + this.doDebug = debug; + this.log = logTo; + } + + /* + * (non-Javadoc) + * + * @see java.io.Closeable#close() + */ + public void close() throws IOException { + if (this.underlyingStream != null) { + try { + this.underlyingStream.close(); + } finally { + this.underlyingStream = null; + this.buf = null; + this.log = null; + } + } + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#markSupported() + */ + public boolean markSupported() { + return false; + } + + /* + * (non-Javadoc) + * + * @see java.io.InputStream#skip(long) + */ + public long skip(long n) throws IOException { + checkClosed(); + if (n <= 0) { + return 0; + } + + long bytesAvailInBuffer = this.endOfCurrentData - this.currentPosition; + + if (bytesAvailInBuffer <= 0) { + + fill((int) n); + bytesAvailInBuffer = this.endOfCurrentData - this.currentPosition; + if (bytesAvailInBuffer <= 0) + return 0; + } + + long bytesSkipped = (bytesAvailInBuffer < n) ? bytesAvailInBuffer : n; + this.currentPosition += bytesSkipped; + return bytesSkipped; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ResultSetUtil.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ResultSetUtil.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ResultSetUtil.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,90 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.util; + +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; + +/** + * Utilities for dealing with result sets (used in testcases and profiler). + * + * @author Mark Matthews + * + * @version $Id: ResultSetUtil.java,v 1.1 2012/08/17 14:57:12 marcin Exp $ + */ +public class ResultSetUtil { + + public static StringBuffer appendResultSetSlashGStyle( + StringBuffer appendTo, ResultSet rs) throws SQLException { + ResultSetMetaData rsmd = rs.getMetaData(); + + int numFields = rsmd.getColumnCount(); + int maxWidth = 0; + + String[] fieldNames = new String[numFields]; + + for (int i = 0; i < numFields; i++) { + fieldNames[i] = rsmd.getColumnLabel(i + 1); + + if (fieldNames[i].length() > maxWidth) { + maxWidth = fieldNames[i].length(); + } + } + + int rowCount = 1; + + while (rs.next()) { + appendTo.append("*************************** "); + appendTo.append(rowCount++); + appendTo.append(". row ***************************\n"); + + for (int i = 0; i < numFields; i++) { + int leftPad = maxWidth - fieldNames[i].length(); + + for (int j = 0; j < leftPad; j++) { + appendTo.append(" "); + } + + appendTo.append(fieldNames[i]); + appendTo.append(": "); + + String stringVal = rs.getString(i + 1); + + if (stringVal != null) { + appendTo.append(stringVal); + } else { + appendTo.append("NULL"); + } + + appendTo.append("\n"); + } + + appendTo.append("\n"); + } + + return appendTo; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ServerController.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ServerController.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/ServerController.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,351 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.util; + +import java.io.File; +import java.io.IOException; + +import java.util.Iterator; +import java.util.Locale; +import java.util.Properties; + +import com.mysql.jdbc.StringUtils; + +/** + * Controls a MySQL server using Java RunTime methods + * + * @version $Id: ServerController.java,v 1.1.2.1 2005/05/13 18:58:39 mmatthews + * Exp $ + * @author Mark Matthews + */ +public class ServerController { + + /** + * Where is the server installed? + */ + public static final String BASEDIR_KEY = "basedir"; + + /** + * Where are the databases installed? + */ + public static final String DATADIR_KEY = "datadir"; + + /** + * Where is the config file located? + */ + + public static final String DEFAULTS_FILE_KEY = "defaults-file"; + + /** + * What is the name of the executable to run? + */ + + public static final String EXECUTABLE_NAME_KEY = "executable"; + + /** + * What is the path to the mysql server executable (if not standard?) + */ + + public static final String EXECUTABLE_PATH_KEY = "executablePath"; + + /** + * The default executable to run + */ + + /** + * The process representing the MySQL server + */ + private Process serverProcess = null; + + /** + * The list of properties for this server + */ + private Properties serverProps = null; + + /** + * The system properties + */ + private Properties systemProps = null; + + /** + * Creates a ServerController with the directory for the MySQL server. + * + * The 'datadir' is set to the same directory. + * + * @param baseDir + * the base directory for the MySQL server. + */ + public ServerController(String baseDir) { + setBaseDir(baseDir); + } + + /** + * Creates a server controller for the MySQL server with the given basedir + * and datadir. + * + * @param basedir + * the basedir to use when starting MySQL. + * @param datadir + * the datadir to use when starting MySQL. + */ + public ServerController(String basedir, String datadir) { + } + + /** + * Sets the basedir to use when starting MySQL. + * + * @param baseDir + * the basedir to use when starting MySQL. + */ + public void setBaseDir(String baseDir) { + getServerProps().setProperty(BASEDIR_KEY, baseDir); + } + + /** + * Sets the data to use when starting MySQL. + * + * @param dataDir + * the basedir to use when starting MySQL. + */ + public void setDataDir(String dataDir) { + getServerProps().setProperty(DATADIR_KEY, dataDir); + } + + /** + * Starts the server, returning a java.lang.Process instance that represents + * the mysql server. + * + * @return Process a java.lang.Process instance representing the mysql + * server process. + * @throws IOException + * if an error occurs while starting the mysql server. + */ + public Process start() throws IOException { + if (this.serverProcess != null) { + throw new IllegalArgumentException("Server already started"); + } else { + this.serverProcess = Runtime.getRuntime().exec(getCommandLine()); + + return this.serverProcess; + } + } + + /** + * Stops the server (if started) + * + * @param forceIfNecessary + * use forceStop if mysqladmin doesn't shut the server down + * + * @throws IOException + * if an error occurs while stopping the server + */ + public void stop(boolean forceIfNecessary) throws IOException { + if (this.serverProcess != null) { + + String basedir = getServerProps().getProperty(BASEDIR_KEY); + + StringBuffer pathBuf = new StringBuffer(basedir); + + if (!basedir.endsWith(File.separator)) { + pathBuf.append(File.separator); + } + + String defaultsFilePath = getServerProps().getProperty( + DEFAULTS_FILE_KEY); + + pathBuf.append("bin"); + pathBuf.append(File.separator); + pathBuf.append("mysqladmin shutdown"); + + System.out.println(pathBuf.toString()); + + Process mysqladmin = Runtime.getRuntime().exec(pathBuf.toString()); + + int exitStatus = -1; + + try { + exitStatus = mysqladmin.waitFor(); + } catch (InterruptedException ie) { + ; // ignore + } + + // + // Terminate the process if mysqladmin couldn't + // do it, and the user requested a force stop. + // + if (exitStatus != 0 && forceIfNecessary) { + forceStop(); + } + } + } + + /** + * Forcefully terminates the server process (if started). + */ + public void forceStop() { + if (this.serverProcess != null) { + this.serverProcess.destroy(); + this.serverProcess = null; + } + } + + /** + * Returns the list of properties that will be used to start/control the + * server. + * + * @return Properties the list of properties. + */ + public synchronized Properties getServerProps() { + if (this.serverProps == null) { + this.serverProps = new Properties(); + } + + return this.serverProps; + } + + /** + * Returns the full commandline used to start the mysql server, including + * and arguments to be passed to the server process. + * + * @return String the commandline used to start the mysql server. + */ + private String getCommandLine() { + StringBuffer commandLine = new StringBuffer(getFullExecutablePath()); + commandLine.append(buildOptionalCommandLine()); + + return commandLine.toString(); + } + + /** + * Returns the fully-qualifed path to the 'mysqld' executable + * + * @return String the path to the server executable. + */ + private String getFullExecutablePath() { + StringBuffer pathBuf = new StringBuffer(); + + String optionalExecutablePath = getServerProps().getProperty( + EXECUTABLE_PATH_KEY); + + if (optionalExecutablePath == null) { + // build the path using the defaults + String basedir = getServerProps().getProperty(BASEDIR_KEY); + pathBuf.append(basedir); + + if (!basedir.endsWith(File.separator)) { + pathBuf.append(File.separatorChar); + } + + if (runningOnWindows()) { + pathBuf.append("bin"); + } else { + pathBuf.append("libexec"); + } + + pathBuf.append(File.separatorChar); + } else { + pathBuf.append(optionalExecutablePath); + + if (!optionalExecutablePath.endsWith(File.separator)) { + pathBuf.append(File.separatorChar); + } + } + + String executableName = getServerProps().getProperty( + EXECUTABLE_NAME_KEY, "mysqld"); + + pathBuf.append(executableName); + + return pathBuf.toString(); + } + + /** + * Builds the list of command-line arguments that will be passed to the + * mysql server to be started. + * + * @return String the list of command-line arguments. + */ + private String buildOptionalCommandLine() { + StringBuffer commandLineBuf = new StringBuffer(); + + if (this.serverProps != null) { + + for (Iterator iter = this.serverProps.keySet().iterator(); iter + .hasNext();) { + String key = (String) iter.next(); + String value = this.serverProps.getProperty(key); + + if (!isNonCommandLineArgument(key)) { + if (value != null && value.length() > 0) { + commandLineBuf.append(" \""); + commandLineBuf.append("--"); + commandLineBuf.append(key); + commandLineBuf.append("="); + commandLineBuf.append(value); + commandLineBuf.append("\""); + } else { + commandLineBuf.append(" --"); + commandLineBuf.append(key); + } + } + } + } + + return commandLineBuf.toString(); + } + + /** + * Returns true if the property does not belong as a command-line argument + * + * @return boolean if the property should not be a command-line argument. + */ + private boolean isNonCommandLineArgument(String propName) { + return propName.equals(EXECUTABLE_NAME_KEY) + || propName.equals(EXECUTABLE_PATH_KEY); + } + + /** + * Lazily creates a list of system properties. + * + * @return Properties the properties from System.getProperties() + */ + private synchronized Properties getSystemProperties() { + if (this.systemProps == null) { + this.systemProps = System.getProperties(); + } + + return this.systemProps; + } + + /** + * Is this ServerController running on a Windows operating system? + * + * @return boolean if this ServerController is running on Windows + */ + private boolean runningOnWindows() { + return StringUtils.indexOfIgnoreCase(getSystemProperties().getProperty( + "os.name"), "WINDOWS") != -1; + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/TimezoneDump.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/TimezoneDump.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/TimezoneDump.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,86 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package com.mysql.jdbc.util; + +import com.mysql.jdbc.TimeUtil; + +import java.sql.DriverManager; +import java.sql.ResultSet; + +/** + * Dumps the timezone of the MySQL server represented by the JDBC url given on + * the commandline (or localhost/test if none provided). + * + * @author Mark Matthews + */ +public class TimezoneDump { + // ~ Static fields/initializers + // --------------------------------------------- + + private static final String DEFAULT_URL = "jdbc:mysql:///test"; + + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Constructor for TimezoneDump. + */ + public TimezoneDump() { + super(); + } + + // ~ Methods + // ---------------------------------------------------------------- + + /** + * Entry point for program when called from the command line. + * + * @param args + * command-line args. Arg 1 is JDBC URL. + * @throws Exception + * if any errors occur + */ + public static void main(String[] args) throws Exception { + String jdbcUrl = DEFAULT_URL; + + if ((args.length == 1) && (args[0] != null)) { + jdbcUrl = args[0]; + } + + Class.forName("com.mysql.jdbc.Driver").newInstance(); + + ResultSet rs = DriverManager.getConnection(jdbcUrl).createStatement() + .executeQuery("SHOW VARIABLES LIKE 'timezone'"); + + while (rs.next()) { + String timezoneFromServer = rs.getString(2); + System.out.println("MySQL timezone name: " + timezoneFromServer); + + String canonicalTimezone = TimeUtil + .getCanoncialTimezone(timezoneFromServer); + System.out.println("Java timezone name: " + canonicalTimezone); + } + } +} Index: 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/VersionFSHierarchyMaker.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/com/mysql/jdbc/util/VersionFSHierarchyMaker.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/com/mysql/jdbc/util/VersionFSHierarchyMaker.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,133 @@ +/* + Copyright (C) 2005-2006 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package com.mysql.jdbc.util; + +import java.io.File; +import java.io.FileOutputStream; +import java.sql.Connection; +import java.sql.ResultSet; +import java.util.Properties; + +import com.mysql.jdbc.NonRegisteringDriver; + +/** + * Creates output directory structure for multi-jvm, multi-url + * unit, regression and compliance tests. + */ +public class VersionFSHierarchyMaker { + + /** + * @param args + */ + public static void main(String[] args) throws Exception { + if (args.length < 3) { + usage(); + System.exit(1); + } + + String jdbcUrl = null; + + String jvmVersion = removeWhitespaceChars(System.getProperty("java.version")); + String jvmVendor = removeWhitespaceChars(System.getProperty("java.vendor")); + String osName = removeWhitespaceChars(System.getProperty("os.name")); + String osArch = removeWhitespaceChars(System.getProperty("os.arch")); + String osVersion = removeWhitespaceChars(System.getProperty("os.version")); + + jdbcUrl = System.getProperty("com.mysql.jdbc.testsuite.url"); + + String mysqlVersion = "not-available"; + + try { + Connection conn = new NonRegisteringDriver().connect(jdbcUrl, null); + + ResultSet rs = conn.createStatement().executeQuery("SELECT VERSION()"); + rs.next(); + mysqlVersion = removeWhitespaceChars(rs.getString(1)); + } catch (Throwable t) { + mysqlVersion = "no-server-running-on-" + removeWhitespaceChars(jdbcUrl); + } + + String jvmSubdirName = jvmVendor + "-" + jvmVersion; + String osSubdirName = osName + "-" + osArch + "-" + osVersion; + + File baseDir = new File(args[1]); + File mysqlVersionDir = new File(baseDir, mysqlVersion); + File osVersionDir = new File(mysqlVersionDir, osSubdirName); + File jvmVersionDir = new File(osVersionDir, jvmSubdirName); + + jvmVersionDir.mkdirs(); + + + FileOutputStream pathOut = null; + + try { + String propsOutputPath = args[2]; + pathOut = new FileOutputStream(propsOutputPath); + String baseDirStr = baseDir.getAbsolutePath(); + String jvmVersionDirStr = jvmVersionDir.getAbsolutePath(); + + if (jvmVersionDirStr.startsWith(baseDirStr)) { + jvmVersionDirStr = jvmVersionDirStr.substring(baseDirStr.length() + 1); + } + + pathOut.write(jvmVersionDirStr.getBytes()); + } finally { + if (pathOut != null) { + pathOut.flush(); + pathOut.close(); + } + } + } + + public static String removeWhitespaceChars(String input) { + if (input == null) { + return input; + } + + int strLen = input.length(); + + StringBuffer output = new StringBuffer(strLen); + + for (int i = 0; i < strLen; i++) { + char c = input.charAt(i); + if (!Character.isDigit(c) && !Character.isLetter(c)) { + if (Character.isWhitespace(c)) { + output.append("_"); + } else { + output.append("."); + } + } else { + output.append(c); + } + } + + return output.toString(); + } + + private static void usage() { + System.err.println("Creates a fs hierarchy representing MySQL version, OS version and JVM version."); + System.err.println("Stores the full path as 'outputDirectory' property in file 'directoryPropPath'"); + System.err.println(); + System.err.println("Usage: java VersionFSHierarchyMaker unit|compliance baseDirectory directoryPropPath"); + } +} Index: 3rdParty_sources/mysql-connector/org/gjt/mm/mysql/Driver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/mysql-connector/org/gjt/mm/mysql/Driver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/mysql-connector/org/gjt/mm/mysql/Driver.java 17 Aug 2012 14:57:13 -0000 1.1 @@ -0,0 +1,47 @@ +/* + Copyright (C) 2002-2004 MySQL AB + + This program is free software; you can redistribute it and/or modify + it under the terms of version 2 of the GNU General Public License as + published by the Free Software Foundation. + + There are special exceptions to the terms and conditions of the GPL + as it is applied to this software. View the full text of the + exception in file EXCEPTIONS-CONNECTOR-J in the directory of this + software distribution. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + + */ +package org.gjt.mm.mysql; + +import java.sql.SQLException; + +/** + * Here for backwards compatibility with MM.MySQL + * + * @author Mark Matthews + */ +public class Driver extends com.mysql.jdbc.Driver { + // ~ Constructors + // ----------------------------------------------------------- + + /** + * Creates a new instance of Driver + * + * @throws SQLException + * if a database error occurs. + */ + public Driver() throws SQLException { + super(); + } +} Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/CSVReader.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/Attic/CSVReader.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/CSVReader.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,245 @@ +package au.com.bytecode.opencsv; + +/** + Copyright 2005 Bytecode Pty Ltd. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; + +/** + * A very simple CSV reader released under a commercial-friendly license. + * + * @author Glen Smith + * + */ +public class CSVReader { + + private BufferedReader br; + + private boolean hasNext = true; + + private char separator; + + private char quotechar; + + private int skipLines; + + private boolean linesSkiped; + + /** The default separator to use if none is supplied to the constructor. */ + public static final char DEFAULT_SEPARATOR = ','; + + /** + * The default quote character to use if none is supplied to the + * constructor. + */ + public static final char DEFAULT_QUOTE_CHARACTER = '"'; + + /** + * The default line to start reading. + */ + public static final int DEFAULT_SKIP_LINES = 0; + + /** + * Constructs CSVReader using a comma for the separator. + * + * @param reader + * the reader to an underlying CSV source. + */ + public CSVReader(Reader reader) { + this(reader, DEFAULT_SEPARATOR); + } + + /** + * Constructs CSVReader with supplied separator. + * + * @param reader + * the reader to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries. + */ + public CSVReader(Reader reader, char separator) { + this(reader, separator, DEFAULT_QUOTE_CHARACTER); + } + + + + /** + * Constructs CSVReader with supplied separator and quote char. + * + * @param reader + * the reader to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries + * @param quotechar + * the character to use for quoted elements + */ + public CSVReader(Reader reader, char separator, char quotechar) { + this(reader, separator, quotechar, DEFAULT_SKIP_LINES); + } + + /** + * Constructs CSVReader with supplied separator and quote char. + * + * @param reader + * the reader to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries + * @param quotechar + * the character to use for quoted elements + * @param line + * the line number to skip for start reading + */ + public CSVReader(Reader reader, char separator, char quotechar, int line) { + this.br = new BufferedReader(reader); + this.separator = separator; + this.quotechar = quotechar; + this.skipLines = line; + } + + /** + * Reads the entire file into a List with each element being a String[] of + * tokens. + * + * @return a List of String[], with each String[] representing a line of the + * file. + * + * @throws IOException + * if bad things happen during the read + */ + public List readAll() throws IOException { + + List allElements = new ArrayList(); + while (hasNext) { + String[] nextLineAsTokens = readNext(); + if (nextLineAsTokens != null) + allElements.add(nextLineAsTokens); + } + return allElements; + + } + + /** + * Reads the next line from the buffer and converts to a string array. + * + * @return a string array with each comma-separated element as a separate + * entry. + * + * @throws IOException + * if bad things happen during the read + */ + public String[] readNext() throws IOException { + + String nextLine = getNextLine(); + return hasNext ? parseLine(nextLine) : null; + } + + /** + * Reads the next line from the file. + * + * @return the next line from the file without trailing newline + * @throws IOException + * if bad things happen during the read + */ + private String getNextLine() throws IOException { + if (!this.linesSkiped) { + for (int i = 0; i < skipLines; i++) { + br.readLine(); + } + this.linesSkiped = true; + } + String nextLine = br.readLine(); + if (nextLine == null) { + hasNext = false; + } + return hasNext ? nextLine : null; + } + + /** + * Parses an incoming String and returns an array of elements. + * + * @param nextLine + * the string to parse + * @return the comma-tokenized list of elements, or null if nextLine is null + * @throws IOException if bad things happen during the read + */ + private String[] parseLine(String nextLine) throws IOException { + + if (nextLine == null) { + return null; + } + + List tokensOnThisLine = new ArrayList(); + StringBuffer sb = new StringBuffer(); + boolean inQuotes = false; + do { + if (inQuotes) { + // continuing a quoted section, reappend newline + sb.append("\n"); + nextLine = getNextLine(); + if (nextLine == null) + break; + } + for (int i = 0; i < nextLine.length(); i++) { + + char c = nextLine.charAt(i); + if (c == quotechar) { + // this gets complex... the quote may end a quoted block, or escape another quote. + // do a 1-char lookahead: + if( inQuotes // we are in quotes, therefore there can be escaped quotes in here. + && nextLine.length() > (i+1) // there is indeed another character to check. + && nextLine.charAt(i+1) == quotechar ){ // ..and that char. is a quote also. + // we have two quote chars in a row == one quote char, so consume them both and + // put one on the token. we do *not* exit the quoted text. + sb.append(nextLine.charAt(i+1)); + i++; + }else{ + inQuotes = !inQuotes; + // the tricky case of an embedded quote in the middle: a,bc"d"ef,g + if(i>2 //not on the begining of the line + && nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence + && nextLine.length()>(i+1) && + nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence + ){ + sb.append(c); + } + } + } else if (c == separator && !inQuotes) { + tokensOnThisLine.add(sb.toString()); + sb = new StringBuffer(); // start work on next token + } else { + sb.append(c); + } + } + } while (inQuotes); + tokensOnThisLine.add(sb.toString()); + return (String[]) tokensOnThisLine.toArray(new String[0]); + + } + + /** + * Closes the underlying reader. + * + * @throws IOException if the close fails + */ + public void close() throws IOException{ + br.close(); + } + +} Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/CSVWriter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/Attic/CSVWriter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/CSVWriter.java 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,406 @@ +package au.com.bytecode.opencsv; + +/** + Copyright 2005 Bytecode Pty Ltd. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.Writer; +import java.math.BigDecimal; +import java.sql.Clob; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.text.SimpleDateFormat; +import java.util.Iterator; +import java.util.List; + +/** + * A very simple CSV writer released under a commercial-friendly license. + * + * @author Glen Smith + * + */ +public class CSVWriter { + + private Writer rawWriter; + + private PrintWriter pw; + + private char separator; + + private char quotechar; + + private char escapechar; + + private String lineEnd; + + /** The character used for escaping quotes. */ + public static final char DEFAULT_ESCAPE_CHARACTER = '"'; + + /** The default separator to use if none is supplied to the constructor. */ + public static final char DEFAULT_SEPARATOR = ','; + + /** + * The default quote character to use if none is supplied to the + * constructor. + */ + public static final char DEFAULT_QUOTE_CHARACTER = '"'; + + /** The quote constant to use when you wish to suppress all quoting. */ + public static final char NO_QUOTE_CHARACTER = '\u0000'; + + /** The escape constant to use when you wish to suppress all escaping. */ + public static final char NO_ESCAPE_CHARACTER = '\u0000'; + + /** Default line terminator uses platform encoding. */ + public static final String DEFAULT_LINE_END = "\n"; + + private static final SimpleDateFormat + TIMESTAMP_FORMATTER = + new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); + + private static final SimpleDateFormat + DATE_FORMATTER = + new SimpleDateFormat("dd-MMM-yyyy"); + + /** + * Constructs CSVWriter using a comma for the separator. + * + * @param writer + * the writer to an underlying CSV source. + */ + public CSVWriter(Writer writer) { + this(writer, DEFAULT_SEPARATOR); + } + + /** + * Constructs CSVWriter with supplied separator. + * + * @param writer + * the writer to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries. + */ + public CSVWriter(Writer writer, char separator) { + this(writer, separator, DEFAULT_QUOTE_CHARACTER); + } + + /** + * Constructs CSVWriter with supplied separator and quote char. + * + * @param writer + * the writer to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries + * @param quotechar + * the character to use for quoted elements + */ + public CSVWriter(Writer writer, char separator, char quotechar) { + this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER); + } + + /** + * Constructs CSVWriter with supplied separator and quote char. + * + * @param writer + * the writer to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries + * @param quotechar + * the character to use for quoted elements + * @param escapechar + * the character to use for escaping quotechars or escapechars + */ + public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) { + this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END); + } + + + /** + * Constructs CSVWriter with supplied separator and quote char. + * + * @param writer + * the writer to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries + * @param quotechar + * the character to use for quoted elements + * @param lineEnd + * the line feed terminator to use + */ + public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) { + this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); + } + + + + /** + * Constructs CSVWriter with supplied separator, quote char, escape char and line ending. + * + * @param writer + * the writer to an underlying CSV source. + * @param separator + * the delimiter to use for separating entries + * @param quotechar + * the character to use for quoted elements + * @param escapechar + * the character to use for escaping quotechars or escapechars + * @param lineEnd + * the line feed terminator to use + */ + public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) { + this.rawWriter = writer; + this.pw = new PrintWriter(writer); + this.separator = separator; + this.quotechar = quotechar; + this.escapechar = escapechar; + this.lineEnd = lineEnd; + } + + /** + * Writes the entire list to a CSV file. The list is assumed to be a + * String[] + * + * @param allLines + * a List of String[], with each String[] representing a line of + * the file. + */ + public void writeAll(List allLines) { + + for (Iterator iter = allLines.iterator(); iter.hasNext();) { + String[] nextLine = (String[]) iter.next(); + writeNext(nextLine); + } + + } + + protected void writeColumnNames(ResultSetMetaData metadata) + throws SQLException { + + int columnCount = metadata.getColumnCount(); + + String[] nextLine = new String[columnCount]; + for (int i = 0; i < columnCount; i++) { + nextLine[i] = metadata.getColumnName(i + 1); + } + writeNext(nextLine); + } + + /** + * Writes the entire ResultSet to a CSV file. + * + * The caller is responsible for closing the ResultSet. + * + * @param rs the recordset to write + * @param includeColumnNames true if you want column names in the output, false otherwise + * + */ + public void writeAll(java.sql.ResultSet rs, boolean includeColumnNames) throws SQLException, IOException { + + ResultSetMetaData metadata = rs.getMetaData(); + + + if (includeColumnNames) { + writeColumnNames(metadata); + } + + int columnCount = metadata.getColumnCount(); + + while (rs.next()) + { + String[] nextLine = new String[columnCount]; + + for (int i = 0; i < columnCount; i++) { + nextLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1); + } + + writeNext(nextLine); + } + } + + private static String getColumnValue(ResultSet rs, int colType, int colIndex) + throws SQLException, IOException { + + String value = ""; + + switch (colType) + { + case Types.BIT: + Object bit = rs.getObject(colIndex); + if (bit != null) { + value = String.valueOf(bit); + } + break; + case Types.BOOLEAN: + boolean b = rs.getBoolean(colIndex); + if (!rs.wasNull()) { + value = Boolean.valueOf(b).toString(); + } + break; + case Types.CLOB: + Clob c = rs.getClob(colIndex); + if (c != null) { + value = read(c); + } + break; + case Types.BIGINT: + case Types.DECIMAL: + case Types.DOUBLE: + case Types.FLOAT: + case Types.REAL: + case Types.NUMERIC: + BigDecimal bd = rs.getBigDecimal(colIndex); + if (bd != null) { + value = "" + bd.doubleValue(); + } + break; + case Types.INTEGER: + case Types.TINYINT: + case Types.SMALLINT: + int intValue = rs.getInt(colIndex); + if (!rs.wasNull()) { + value = "" + intValue; + } + break; + case Types.JAVA_OBJECT: + Object obj = rs.getObject(colIndex); + if (obj != null) { + value = String.valueOf(obj); + } + break; + case Types.DATE: + java.sql.Date date = rs.getDate(colIndex); + if (date != null) { + value = DATE_FORMATTER.format(date);; + } + break; + case Types.TIME: + Time t = rs.getTime(colIndex); + if (t != null) { + value = t.toString(); + } + break; + case Types.TIMESTAMP: + Timestamp tstamp = rs.getTimestamp(colIndex); + if (tstamp != null) { + value = TIMESTAMP_FORMATTER.format(tstamp); + } + break; + case Types.LONGVARCHAR: + case Types.VARCHAR: + case Types.CHAR: + value = rs.getString(colIndex); + break; + default: + value = ""; + } + + + if (value == null) + { + value = ""; + } + + return value; + + } + + private static String read(Clob c) throws SQLException, IOException + { + StringBuffer sb = new StringBuffer( (int) c.length()); + Reader r = c.getCharacterStream(); + char[] cbuf = new char[2048]; + int n = 0; + while ((n = r.read(cbuf, 0, cbuf.length)) != -1) { + if (n > 0) { + sb.append(cbuf, 0, n); + } + } + return sb.toString(); + } + + /** + * Writes the next line to the file. + * + * @param nextLine + * a string array with each comma-separated element as a separate + * entry. + */ + public void writeNext(String[] nextLine) { + + if (nextLine == null) + return; + + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < nextLine.length; i++) { + + if (i != 0) { + sb.append(separator); + } + + String nextElement = nextLine[i]; + if (nextElement == null) + continue; + if (quotechar != NO_QUOTE_CHARACTER) + sb.append(quotechar); + for (int j = 0; j < nextElement.length(); j++) { + char nextChar = nextElement.charAt(j); + if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) { + sb.append(escapechar).append(nextChar); + } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) { + sb.append(escapechar).append(nextChar); + } else { + sb.append(nextChar); + } + } + if (quotechar != NO_QUOTE_CHARACTER) + sb.append(quotechar); + } + + sb.append(lineEnd); + pw.write(sb.toString()); + + } + + /** + * Flush underlying stream to writer. + * + * @throws IOException if bad things happen + */ + public void flush() throws IOException { + + pw.flush(); + + } + + /** + * Close the underlying stream writer flushing any buffered content. + * + * @throws IOException if bad things happen + * + */ + public void close() throws IOException { + pw.flush(); + pw.close(); + rawWriter.close(); + } + +} Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/Attic/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/package.html 17 Aug 2012 14:57:11 -0000 1.1 @@ -0,0 +1,12 @@ + + + + + +

+A very simple CSV parser for Java released under a commercial-friendly license. +

+
+opencsv.sourceforge.net + + Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/ColumnPositionMappingStrategy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/Attic/ColumnPositionMappingStrategy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/ColumnPositionMappingStrategy.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,36 @@ +package au.com.bytecode.opencsv.bean; +import java.io.IOException; + +import au.com.bytecode.opencsv.CSVReader; + +/** + Copyright 2007 Kyle Miller. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +public class ColumnPositionMappingStrategy extends HeaderColumnNameMappingStrategy { + protected String[] columnMapping = new String[] {}; + public void captureHeader(CSVReader reader) throws IOException { + //do nothing, first line is not header + } + protected String getColumnName(int col) { + return (null != columnMapping && col < columnMapping.length) ? columnMapping[col] : null ; + } + public String[] getColumnMapping() { + return columnMapping; + } + public void setColumnMapping(String[] columnMapping) { + this.columnMapping = columnMapping; + } +} Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/CsvToBean.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/Attic/CsvToBean.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/CsvToBean.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,83 @@ +package au.com.bytecode.opencsv.bean; + +/** + Copyright 2007 Kyle Miller. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; +import java.beans.PropertyEditor; +import java.beans.PropertyEditorManager; +import java.io.Reader; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + +import au.com.bytecode.opencsv.CSVReader; + +public class CsvToBean { + + public CsvToBean() { + } + + public List parse(MappingStrategy mapper, Reader reader) { + try { + CSVReader csv = new CSVReader(reader); + mapper.captureHeader(csv); + String[] line; + List list = new ArrayList(); + while(null != (line = csv.readNext())) { + Object obj = processLine(mapper, line); + list.add(obj); // TODO: (Kyle) null check object + } + return list; + } catch (Exception e) { + throw new RuntimeException("Error parsing CSV!", e); + } + } + + protected Object processLine(MappingStrategy mapper, String[] line) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException { + Object bean = mapper.createBean(); + for(int col = 0; col < line.length; col++) { + String value = line[col]; + PropertyDescriptor prop = mapper.findDescriptor(col); + if (null != prop) { + Object obj = convertValue(value, prop); + prop.getWriteMethod().invoke(bean, new Object[] {obj}); + } + } + return bean; + } + + protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException, IllegalAccessException { + PropertyEditor editor = getPropertyEditor(prop); + Object obj = value; + if (null != editor) { + editor.setAsText(value); + obj = editor.getValue(); + } + return obj; + } + + /* + * Attempt to find custom property editor on descriptor first, else try the propery editor manager. + */ + protected PropertyEditor getPropertyEditor(PropertyDescriptor desc) throws InstantiationException, IllegalAccessException { + Class cls = desc.getPropertyEditorClass(); + if (null != cls) return (PropertyEditor) cls.newInstance(); + return PropertyEditorManager.findEditor(desc.getPropertyType()); + } + +} Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/HeaderColumnNameMappingStrategy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/Attic/HeaderColumnNameMappingStrategy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/HeaderColumnNameMappingStrategy.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,68 @@ +package au.com.bytecode.opencsv.bean; +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.IOException; + +import au.com.bytecode.opencsv.CSVReader; + +/** + Copyright 2007 Kyle Miller. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +public class HeaderColumnNameMappingStrategy implements MappingStrategy { + protected String[] header; + protected PropertyDescriptor[] descriptors; + protected Class type; + + public void captureHeader(CSVReader reader) throws IOException { + header = reader.readNext(); + } + + public PropertyDescriptor findDescriptor(int col) throws IntrospectionException { + String columnName = getColumnName(col); + return (null != columnName && columnName.trim().length()>0) ? findDescriptor(columnName) : null; + } + + protected String getColumnName(int col) { + return (null != header && col < header.length) ? header[col] : null; + } + protected PropertyDescriptor findDescriptor(String name) throws IntrospectionException { + if (null == descriptors) descriptors = loadDescriptors(getType()); //lazy load descriptors + for (int i = 0; i < descriptors.length; i++) { + PropertyDescriptor desc = descriptors[i]; + if (matches(name, desc)) return desc; // TODO: (Kyle) do null/blank check + } + return null; + } + protected boolean matches(String name, PropertyDescriptor desc) { + return desc.getName().equals(name); + } + protected PropertyDescriptor[] loadDescriptors(Class cls) throws IntrospectionException { + BeanInfo beanInfo = Introspector.getBeanInfo(cls); + return beanInfo.getPropertyDescriptors(); + } + public Object createBean() throws InstantiationException, IllegalAccessException { + return type.newInstance(); + } + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } +} Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/Attic/HeaderColumnNameTranslateMappingStrategy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/HeaderColumnNameTranslateMappingStrategy.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,32 @@ +package au.com.bytecode.opencsv.bean; +import java.util.HashMap; +import java.util.Map; + +/** + Copyright 2007 Kyle Miller. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +public class HeaderColumnNameTranslateMappingStrategy extends HeaderColumnNameMappingStrategy { + private Map columnMapping = new HashMap(); + protected String getColumnName(int col) { + return (String) getColumnMapping().get(header[col]); + } + public Map getColumnMapping() { + return columnMapping; + } + public void setColumnMapping(Map columnMapping) { + this.columnMapping = columnMapping; + } +} Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/MappingStrategy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/Attic/MappingStrategy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/MappingStrategy.java 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,41 @@ +package au.com.bytecode.opencsv.bean; + + +/** + Copyright 2007 Kyle Miller. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; +import java.io.IOException; + +import au.com.bytecode.opencsv.CSVReader; + +public interface MappingStrategy { + + /** + * Implementation will have to return a property descriptor from a bean based on the current column. + */ + public abstract PropertyDescriptor findDescriptor(int col) throws IntrospectionException; + + public abstract Object createBean() throws InstantiationException, IllegalAccessException; + + /** + * Implemention of this method can grab the header line before parsing begins to use to map columns + * to bean properties. + */ + public void captureHeader(CSVReader reader) throws IOException; + +} \ No newline at end of file Index: 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/Attic/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opencsv/au/com/bytecode/opencsv/bean/package.html 17 Aug 2012 14:57:12 -0000 1.1 @@ -0,0 +1,12 @@ + + + + + +

+A simple bean binding interface for use with opencsv. +

+
+opencsv.sourceforge.net + + Index: 3rdParty_sources/opensaml/org/opensaml/common/IdentifierGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/IdentifierGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/IdentifierGenerator.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +/** + * Interface for identifier generators. This identifier can be used for things like + * digital signature identifiers, opaque principal identifiers, etc. + */ +public interface IdentifierGenerator { + + /** + * Generates a 16 byte identifier. + * + * @return an hex encoded identifier + */ + public String generateIdentifier(); + + /** Generates a random identifier. + * + * @param size number of bytes in the identifier + * + * @return the hex encoded identifier + */ + public String generateIdentifier(int size); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/SAMLException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/SAMLException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/SAMLException.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +/** + * Base exception for SAML related exception. + */ +public class SAMLException extends Exception { + + /** Serial version UID. */ + private static final long serialVersionUID = 6308450535247361691L; + + /** + * Constructor. + */ + public SAMLException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public SAMLException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public SAMLException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public SAMLException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/common/SAMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/SAMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/SAMLObject.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +import org.opensaml.xml.validation.ValidatingXMLObject; + +/** + * A base interface for all SAML Objects. + */ +public interface SAMLObject extends ValidatingXMLObject { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/SAMLObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/SAMLObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/SAMLObjectBuilder.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +import org.opensaml.xml.XMLObjectBuilder; + +/** + * Builder for SAMLObjects. + * + * @param the type of SAMLObject being built + */ +public interface SAMLObjectBuilder extends XMLObjectBuilder { + + /** + * Builds a SAMLObject using the default name and namespace information provided SAML specifications. + * + * @return built SAMLObject + */ + public abstract SAMLObjectType buildObject(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/SAMLObjectHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/SAMLObjectHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/SAMLObjectHelper.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +import java.util.List; + +import org.opensaml.common.impl.SAMLObjectContentReference; +import org.opensaml.xml.Namespace; +import org.opensaml.xml.NamespaceManager; +import org.opensaml.xml.signature.ContentReference; +import org.opensaml.xml.signature.SignatureConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A helper class for working with SAMLObjects. + */ +public final class SAMLObjectHelper { + + /** Constructor. */ + private SAMLObjectHelper() { } + + /** + * Examines the {@link SignableSAMLObject} for the need to declare non-visible namespaces + * before marshalling and signing, and if required, performs the declarations. + * + *

+ * If the object does not already have a cached DOM, does have a signature attached, + * and the signature contains a {@link SAMLObjectContentReference} with a transform of either + * {@link SignatureConstants#TRANSFORM_C14N_EXCL_OMIT_COMMENTS} + * or {@link SignatureConstants#TRANSFORM_C14N_EXCL_WITH_COMMENTS}, + * it declares on the object all non-visible namespaces + * as determined by {@link NamespaceManager#getNonVisibleNamespaces()}. + *

+ * + * @param signableObject the signable SAML object to evaluate + */ + public static void declareNonVisibleNamespaces(SignableSAMLObject signableObject) { + Logger log = getLogger(); + if (signableObject.getDOM() == null && signableObject.getSignature() != null) { + log.debug("Examing signed object for content references with exclusive canonicalization transform"); + boolean sawExclusive = false; + for (ContentReference cr : signableObject.getSignature().getContentReferences()) { + if (cr instanceof SAMLObjectContentReference) { + List transforms = ((SAMLObjectContentReference)cr).getTransforms(); + if (transforms.contains(SignatureConstants.TRANSFORM_C14N_EXCL_WITH_COMMENTS) + || transforms.contains(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)) { + sawExclusive = true; + break; + } + } + } + + if (sawExclusive) { + log.debug("Saw exclusive transform, declaring non-visible namespaces on signed object"); + for (Namespace ns : signableObject.getNamespaceManager().getNonVisibleNamespaces()) { + signableObject.getNamespaceManager().registerNamespaceDeclaration(ns); + } + } + } + } + + /** + * Get an SLF4J Logger. + * + * @return a Logger instance + */ + private static Logger getLogger() { + return LoggerFactory.getLogger(SAMLObjectHelper.class); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/common/SAMLRuntimeException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/SAMLRuntimeException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/SAMLRuntimeException.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +/** + * Base class for runtime exceptions. + */ +public class SAMLRuntimeException extends RuntimeException { + + /** Serial version UID. */ + private static final long serialVersionUID = -593201582585161250L; + + /** + * Constructor. + */ + public SAMLRuntimeException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public SAMLRuntimeException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public SAMLRuntimeException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public SAMLRuntimeException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/common/SAMLVersion.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/SAMLVersion.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/SAMLVersion.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +/** + * A type safe SAML version enumeration. + */ +public final class SAMLVersion { + + /** SAML version 1.0. */ + public static final SAMLVersion VERSION_10 = new SAMLVersion(1, 0); + + /** SAML Version 1.1. */ + public static final SAMLVersion VERSION_11 = new SAMLVersion(1, 1); + + /** SAML Version 2.0. */ + public static final SAMLVersion VERSION_20 = new SAMLVersion(2, 0); + + /** Major version number. */ + private int majorVersion; + + /** Minor version number. */ + private int minorVersion; + + /** String representation of the version. */ + private String versionString; + + /** + * Constructor. + * + * @param major SAML major version number + * @param minor SAML minor version number + */ + private SAMLVersion(int major, int minor) { + majorVersion = major; + minorVersion = minor; + + versionString = majorVersion + "." + minorVersion; + } + + /** + * Gets the SAMLVersion given the major and minor version number. + * + * @param majorVersion major version number + * @param minorVersion minor version number + * + * @return the SAMLVersion + */ + public static final SAMLVersion valueOf(int majorVersion, int minorVersion) { + if (majorVersion == 1) { + if (minorVersion == 0) { + return SAMLVersion.VERSION_10; + } else if (minorVersion == 1) { + return SAMLVersion.VERSION_11; + } + } else if (majorVersion == 2) { + if (minorVersion == 0) { + return SAMLVersion.VERSION_20; + } + } + + return new SAMLVersion(majorVersion, minorVersion); + } + + /** + * Gets the SAMLVersion for a given version string, such as "2.0". + * + * @param version SAML version string + * + * @return SAMLVersion for the given string + */ + public static final SAMLVersion valueOf(String version) { + String[] components = version.split("\\."); + return valueOf(Integer.valueOf(components[0]), Integer.valueOf(components[1])); + } + + /** + * Gets the major version of the SAML version. + * + * @return the major version of the SAML version + */ + public int getMajorVersion() { + return majorVersion; + } + + /** + * Gets the minor version of the SAML version. + * + * @return the minor version of the SAML version + */ + public int getMinorVersion() { + return minorVersion; + } + + /** {@inheritDoc} */ + public String toString() { + return versionString; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/common/SignableSAMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/SignableSAMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/SignableSAMLObject.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common; + +import org.opensaml.xml.signature.SignableXMLObject; + +/** + * A signable SAMLObject. + */ +public interface SignableSAMLObject extends SignableXMLObject, SAMLObject { + + /** + * Gets the value of the ID attribute for this SAML object which will be used as its signature reference. + * + * @return the value of this SAMLObject ID attribute + */ + public String getSignatureReferenceID(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/package.html 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,12 @@ + + +Base classes for working with SAML as Java objects. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/AbstractEndpointSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/AbstractEndpointSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/AbstractEndpointSelector.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,185 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; + +/** + * Endpoint selectors choose the endpoint that should be used to contact a peer. + */ +public abstract class AbstractEndpointSelector { + + /** Bindings supported by the issuer. */ + private List supportedIssuerBindings; + + /** SAML request within the message flow. */ + private SAMLObject samlRequest; + + /** SAML response within the message flow. */ + private SAMLObject samlResponse; + + /** Provider of metadata for the relying party. */ + private MetadataProvider metadataProvider; + + /** Metadata of party to select endpoing for. */ + private EntityDescriptor entityMetadata; + + /** Role metadata of party to select endpoing for. */ + private RoleDescriptor entityRoleMetadata; + + /** Type of endpoint needed. */ + private QName endpointType; + + /** Constructor. */ + public AbstractEndpointSelector() { + supportedIssuerBindings = new ArrayList(5); + } + + /** + * Gets type of endpoint needed. + * + * @return type of endpoint needed + */ + public QName getEndpointType() { + return endpointType; + } + + /** + * Sets the type of endpoint needed. + * + * @param type type of endpoint needed + */ + public void setEndpointType(QName type) { + endpointType = type; + } + + /** + * Gets the metadata provider used to look up entity information. + * + * @return metadata provider used to look up entity information + */ + public MetadataProvider getMetadataProvider() { + return metadataProvider; + } + + /** + * Sets the metadata provider used to look up entity information. + * + * @param provider metadata provider used to look up entity information + */ + public void setMetadataProvider(MetadataProvider provider) { + metadataProvider = provider; + } + + /** + * Gets the metadata of the entity. + * + * @return metadata of the entity + */ + public EntityDescriptor getEntityMetadata() { + return entityMetadata; + } + + /** + * Sets the metadata of the entity. + * + * @param entity metadata of the entity + */ + public void setEntityMetadata(EntityDescriptor entity) { + entityMetadata = entity; + } + + /** + * Gets the role of the entity. + * + * @return role of the entity + */ + public RoleDescriptor getEntityRoleMetadata() { + return entityRoleMetadata; + } + + /** + * Sets the role of the entity. + * + * @param role role of the entity + */ + public void setEntityRoleMetadata(RoleDescriptor role) { + entityRoleMetadata = role; + } + + /** + * Gets the SAML request made. + * + * @return SAML request made + */ + public SAMLObject getSamlRequest() { + return samlRequest; + } + + /** + * Sets the SAML request made. + * + * @param request SAML request made + */ + public void setSamlRequest(SAMLObject request) { + samlRequest = request; + } + + /** + * Gets the response to the SAML request. + * + * @return response to the SAML request + */ + public SAMLObject getSamlResponse() { + return samlResponse; + } + + /** + * Sets the response to the SAML request. + * + * @param response response to the SAML request + */ + public void setSamlResponse(SAMLObject response) { + samlResponse = response; + } + + /** + * Gets the list of bindings supported by the message issuer. + * + * @return list of bindings supported by the message issuer + */ + public List getSupportedIssuerBindings() { + return supportedIssuerBindings; + } + + /** + * Selects the endpoint to which messages should be sent. + * + * @return endpoint to which messages should be sent, or null if no suitable endpoint can be determined + */ + public abstract Endpoint selectEndpoint(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/BasicEndpointSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/BasicEndpointSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/BasicEndpointSelector.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,159 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This endpoint selector retrieves all the endpoints for a given role. A first filter pass removes those endpoints that + * use bindings which are not supported by the issuer. If the remaining endpoints are not {@link IndexedEndpoint}s the + * first endpoint in the list is returned. If the remaining endpoints are {@link IndexedEndpoint}s the first endpoint + * with the isDefault attribute set to true is returned, if no isDefault attribute is set to true the first endpoint to + * omit this attribute is returned, and if all the endpoints have the isDefault attribute set to false then the first + * endpoint in the list is returned. + * + * Prior to selecting the endpoint the following fields must have had values set: entity role, + * endpoint type, issuer supported bindings. + * + * While this algorithm with work for selecting the endpoint for responses to AuthnRequests the SAML + * specification does stipulate additional endpoint selection criteria and as such the use of an endpoint selector + * specifically meant to handler this situation should be used, for example: AuthnResponseEndpointSelector. + */ +public class BasicEndpointSelector extends AbstractEndpointSelector { + + /** Class logger. */ + private Logger log = LoggerFactory.getLogger(BasicEndpointSelector.class); + + /** {@inheritDoc} */ + @SuppressWarnings("unchecked") + public Endpoint selectEndpoint() { + if(getEntityRoleMetadata() == null){ + return null; + } + + List endpoints = getEntityRoleMetadata().getEndpoints(getEndpointType()); + if (endpoints == null || endpoints.size() == 0) { + return null; + } + + Endpoint selectedEndpoint; + endpoints = filterEndpointsByProtocolBinding(endpoints); + if (endpoints == null || endpoints.size() == 0) { + return null; + } + if (endpoints.get(0) instanceof IndexedEndpoint) { + selectedEndpoint = selectIndexedEndpoint((List) endpoints); + } else { + selectedEndpoint = selectNonIndexedEndpoint((List) endpoints); + } + + log.debug("Selected endpoint {} for request", selectedEndpoint.getLocation()); + return selectedEndpoint; + } + + /** + * Filters the list of possible endpoints by supported outbound bindings. + * + * @param endpoints raw list of endpoints + * + * @return filtered endpoints + */ + protected List filterEndpointsByProtocolBinding(List endpoints) { + List filteredEndpoints = new ArrayList(endpoints); + Iterator endpointItr = filteredEndpoints.iterator(); + Endpoint endpoint; + while (endpointItr.hasNext()) { + endpoint = endpointItr.next(); + if (!getSupportedIssuerBindings().contains(endpoint.getBinding())) { + endpointItr.remove(); + continue; + } + } + + return filteredEndpoints; + } + + /** + * Selects an appropriate endpoint from a list of indexed endpoints. + * + * @param endpoints list of indexed endpoints + * + * @return appropriate endpoint from a list of indexed endpoints or null + */ + protected Endpoint selectIndexedEndpoint(List endpoints) { + List endpointsCopy = new ArrayList(endpoints); + Iterator endpointItr = endpointsCopy.iterator(); + IndexedEndpoint firstNoDefaultEndpoint = null; + IndexedEndpoint currentEndpoint; + while (endpointItr.hasNext()) { + currentEndpoint = endpointItr.next(); + + // endpoint is the default endpoint + if (currentEndpoint.isDefault() != null) { + if (currentEndpoint.isDefault()) { + return currentEndpoint; + } + + if (firstNoDefaultEndpoint == null) { + firstNoDefaultEndpoint = currentEndpoint; + } + } + } + + if (firstNoDefaultEndpoint != null) { + // no endpoint was marked as the default, return first unmarked endpoint + return firstNoDefaultEndpoint; + } else { + if (endpointsCopy.size() > 0) { + // no endpoint had an index so return the first one + return endpointsCopy.get(0); + } else { + // no endpoints made it through the supported binding filter + return null; + } + } + } + + /** + * Selects an appropriate endpoint from a list of non-indexed endpoints. + * + * @param endpoints list of non-indexed endpoints + * + * @return appropriate endpoint from a list of non-indexed endpoints or null + */ + protected Endpoint selectNonIndexedEndpoint(List endpoints) { + Iterator endpointItr = endpoints.iterator(); + Endpoint endpoint; + while (endpointItr.hasNext()) { + endpoint = endpointItr.next(); + + // Endpoint is first one of acceptable binding, return it. + return endpoint; + } + + // No endpoints had acceptable binding + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/BasicSAMLMessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/BasicSAMLMessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/BasicSAMLMessageContext.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,345 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.ws.message.BaseMessageContext; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Base implemention of {@link SAMLMessageContext}. + * + * @param type of inbound SAML message + * @param type of outbound SAML message + * @param type of name identifier used for subjects + */ +public class BasicSAMLMessageContext + extends BaseMessageContext implements SAMLMessageContext { + + /** Gets the artifact type used for outbound messages. */ + private byte[] artifactType; + + /** Name identifier for the Subject of the message. */ + private NameIdentifierType subjectNameIdentifer; + + /** Local entity's ID. */ + private String localEntityId; + + /** Local entity's metadata. */ + private EntityDescriptor localEntityMetadata; + + /** Asserting entity's role. */ + private QName localEntityRole; + + /** Asserting entity's role metadata. */ + private RoleDescriptor localEntityRoleMetadata; + + /** Inbound SAML message. */ + private InboundMessageType inboundSAMLMessage; + + /** Whether the inbound SAML message has been authenticated. */ + private boolean inboundSAMLMessageAuthenticated; + + /** Inbound SAML message's ID. */ + private String inboundSAMLMessageId; + + /** Inbound SAML message's issue instant. */ + private DateTime inboundSAMLMessageIssueInstant; + + /** Inbound SAML protocol. */ + private String inboundSAMLProtocol; + + /** Metadata provider used to lookup entity information. */ + private MetadataProvider metdataProvider; + + /** Outbound SAML message. */ + private OutboundMessageType outboundSAMLMessage; + + /** Outbound SAML message's ID. */ + private String outboundSAMLMessageId; + + /** Outbound SAML message's issue instant. */ + private DateTime outboundSAMLMessageIssueInstant; + + /** Outboud SAML message signing credential. */ + private Credential outboundSAMLMessageSigningCredential; + + /** Outbound SAML procotol. */ + private String outboundSAMLProtocol; + + /** Message relay state. */ + private String relayState; + + /** Peer entity's endpoint. */ + private Endpoint peerEntityEndpoint; + + /**Peer entity's ID. */ + private String peerEntityId; + + /** Peer entity's metadata. */ + private EntityDescriptor peerEntityMetadata; + + /** Peer entity's role. */ + private QName peerEntityRole; + + /** Peer entity's role metadata. */ + private RoleDescriptor peerEntityRoleMetadata; + + /** {@inheritDoc} */ + public InboundMessageType getInboundSAMLMessage() { + return inboundSAMLMessage; + } + + /** {@inheritDoc} */ + public String getInboundSAMLMessageId() { + return inboundSAMLMessageId; + } + + /** {@inheritDoc} */ + public DateTime getInboundSAMLMessageIssueInstant() { + return inboundSAMLMessageIssueInstant; + } + + /** {@inheritDoc} */ + public String getInboundSAMLProtocol() { + return inboundSAMLProtocol; + } + + /** {@inheritDoc} */ + public String getLocalEntityId() { + return localEntityId; + } + + /** {@inheritDoc} */ + public EntityDescriptor getLocalEntityMetadata() { + return localEntityMetadata; + } + + /** {@inheritDoc} */ + public QName getLocalEntityRole() { + return localEntityRole; + } + + /** {@inheritDoc} */ + public RoleDescriptor getLocalEntityRoleMetadata() { + return localEntityRoleMetadata; + } + + /** {@inheritDoc} */ + public MetadataProvider getMetadataProvider() { + return metdataProvider; + } + + /** {@inheritDoc} */ + public Credential getOuboundSAMLMessageSigningCredential() { + return outboundSAMLMessageSigningCredential; + } + + /** {@inheritDoc} */ + public OutboundMessageType getOutboundSAMLMessage() { + return outboundSAMLMessage; + } + + /** {@inheritDoc} */ + public String getOutboundSAMLMessageId() { + return outboundSAMLMessageId; + } + + /** {@inheritDoc} */ + public DateTime getOutboundSAMLMessageIssueInstant() { + return outboundSAMLMessageIssueInstant; + } + + /** {@inheritDoc} */ + public String getOutboundSAMLProtocol() { + return outboundSAMLProtocol; + } + + /** {@inheritDoc} */ + public Endpoint getPeerEntityEndpoint() { + return peerEntityEndpoint; + } + + /** {@inheritDoc} */ + public String getPeerEntityId() { + return peerEntityId; + } + + /** {@inheritDoc} */ + public EntityDescriptor getPeerEntityMetadata() { + return peerEntityMetadata; + } + + /** {@inheritDoc} */ + public QName getPeerEntityRole() { + return peerEntityRole; + } + + /** {@inheritDoc} */ + public RoleDescriptor getPeerEntityRoleMetadata() { + return peerEntityRoleMetadata; + } + + /** {@inheritDoc} */ + public String getRelayState() { + return relayState; + } + + /** {@inheritDoc} */ + public NameIdentifierType getSubjectNameIdentifier() { + return subjectNameIdentifer; + } + + /** {@inheritDoc} */ + public boolean isInboundSAMLMessageAuthenticated() { + return inboundSAMLMessageAuthenticated; + } + + /** {@inheritDoc} */ + public void setInboundSAMLMessage(InboundMessageType message) { + inboundSAMLMessage = message; + } + + /** {@inheritDoc} */ + public void setInboundSAMLMessageAuthenticated(boolean isAuthenticated) { + inboundSAMLMessageAuthenticated = isAuthenticated; + } + + /** {@inheritDoc} */ + public void setInboundSAMLMessageId(String id) { + inboundSAMLMessageId = DatatypeHelper.safeTrimOrNullString(id); + } + + /** {@inheritDoc} */ + public void setInboundSAMLMessageIssueInstant(DateTime instant) { + inboundSAMLMessageIssueInstant = instant; + } + + /** {@inheritDoc} */ + public void setInboundSAMLProtocol(String protocol) { + inboundSAMLProtocol = DatatypeHelper.safeTrimOrNullString(protocol); + } + + /** {@inheritDoc} */ + public void setLocalEntityId(String id) { + localEntityId = DatatypeHelper.safeTrimOrNullString(id); + } + + /** {@inheritDoc} */ + public void setLocalEntityMetadata(EntityDescriptor metadata) { + localEntityMetadata = metadata; + } + + /** {@inheritDoc} */ + public void setLocalEntityRole(QName role) { + localEntityRole = role; + } + + /** {@inheritDoc} */ + public void setLocalEntityRoleMetadata(RoleDescriptor role) { + localEntityRoleMetadata = role; + } + + /** {@inheritDoc} */ + public void setMetadataProvider(MetadataProvider provider) { + metdataProvider = provider; + } + + /** {@inheritDoc} */ + public void setOutboundSAMLMessage(OutboundMessageType message) { + outboundSAMLMessage = message; + } + + /** {@inheritDoc} */ + public void setOutboundSAMLMessageId(String id) { + outboundSAMLMessageId = DatatypeHelper.safeTrimOrNullString(id); + } + + /** {@inheritDoc} */ + public void setOutboundSAMLMessageIssueInstant(DateTime instant) { + outboundSAMLMessageIssueInstant = instant; + } + + /** {@inheritDoc} */ + public void setOutboundSAMLMessageSigningCredential(Credential credential) { + outboundSAMLMessageSigningCredential = credential; + } + + /** {@inheritDoc} */ + public void setOutboundSAMLProtocol(String protocol) { + outboundSAMLProtocol = DatatypeHelper.safeTrimOrNullString(protocol); + } + + /** {@inheritDoc} */ + public void setPeerEntityEndpoint(Endpoint endpoint) { + peerEntityEndpoint = endpoint; + } + + /** {@inheritDoc} */ + public void setPeerEntityId(String id) { + peerEntityId = DatatypeHelper.safeTrimOrNullString(id); + } + + /** {@inheritDoc} */ + public void setPeerEntityMetadata(EntityDescriptor metadata) { + peerEntityMetadata = metadata; + } + + /** {@inheritDoc} */ + public void setPeerEntityRole(QName role) { + peerEntityRole = role; + } + + /** {@inheritDoc} */ + public void setPeerEntityRoleMetadata(RoleDescriptor role) { + peerEntityRoleMetadata = role; + } + + /** {@inheritDoc} */ + public void setRelayState(String state) { + relayState = DatatypeHelper.safeTrimOrNullString(state); + } + + /** {@inheritDoc} */ + public void setSubjectNameIdentifier(NameIdentifierType identifier) { + subjectNameIdentifer = identifier; + } + + /** {@inheritDoc} */ + public byte[] getOutboundMessageArtifactType() { + return artifactType; + } + + /** {@inheritDoc} */ + public void setOutboundMessageArtifactType(byte[] type) { + artifactType = type; + } + + /** {@inheritDoc} */ + public boolean isIssuerAuthenticated() { + return isInboundSAMLMessageAuthenticated() || super.isIssuerAuthenticated(); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/BindingException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/BindingException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/BindingException.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding; + +import org.opensaml.common.SAMLException; + +/** + * Base exception for errors that occur when messages are encoded/decoded for a specific binding. + */ +public class BindingException extends SAMLException{ + + /** Serial version UID. */ + private static final long serialVersionUID = 8759204244381246777L; + + /** + * Constructor. + */ + public BindingException() { + super(); + } + + /** + * Constructor. + * + * @param message exception message + */ + public BindingException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public BindingException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public BindingException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/SAMLMessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/SAMLMessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/SAMLMessageContext.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,364 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.xml.security.credential.Credential; + +/** + * SAML specific extension to the more basic {@link MessageContext}. + * + * @param type of inbound SAML message + * @param type of outbound SAML message + * @param type of name identifier used for subjects + */ +public interface SAMLMessageContext + extends MessageContext { + + /** + * Gets the inbound SAML message. This may not be the same as the message returned from + * {@link MessageContext#getInboundMessage()} if the SAML message was carried in another protocol (e.g. SOAP). + * + * @return inbound SAML message + */ + public InboundMessageType getInboundSAMLMessage(); + + /** + * Gets the ID of the inbound SAML message. + * + * @return ID of the inbound SAML message + */ + public String getInboundSAMLMessageId(); + + /** + * Gets the issue instant of the incomming SAML message. + * + * @return issue instant of the incomming SAML message + */ + public DateTime getInboundSAMLMessageIssueInstant(); + + /** + * Gets the protocol used by the peer entity to communicate with the local entity. + * + * @return protocol used by the peer entity to communicate with the local entity + */ + public String getInboundSAMLProtocol(); + + /** + * Gets the local entity's ID. + * + * @return local entity's ID + */ + public String getLocalEntityId(); + + /** + * Gets the local entity metadata. + * + * @return local entity metadata + */ + public EntityDescriptor getLocalEntityMetadata(); + + /** + * Gets the role of the local entity. + * + * @return role of the local entity + */ + public QName getLocalEntityRole(); + + /** + * Gets the role metadata of the local entity. + * + * @return role metadata of the local entity + */ + public RoleDescriptor getLocalEntityRoleMetadata(); + + /** + * Gets the metadata provider used to lookup information entity information. + * + * @return metadata provider used to lookup information entity information + */ + public MetadataProvider getMetadataProvider(); + + /** + * Gets the credential used to sign the outbound SAML message. + * + * @return credential used to sign the outbound SAML message + */ + public Credential getOuboundSAMLMessageSigningCredential(); + + /** + * Gets the artifact type to use for the outbound message. + * + * @return artifact type to use for the outbound message + */ + public byte[] getOutboundMessageArtifactType(); + + /** + * Gets the outbound SAML message. This may not be the same as the message returned from + * {@link MessageContext#getOutboundMessage()} if the SAML message was carried in another protocol (e.g. SOAP). + * + * @return outbound SAML message + */ + public OutboundMessageType getOutboundSAMLMessage(); + + /** + * Gets the ID of the outbound SAML message. + * + * @return ID of the outbound SAML message + */ + public String getOutboundSAMLMessageId(); + + /** + * Gets the issue instant of the outbound SAML message. + * + * @return issue instant of the outbound SAML message + */ + public DateTime getOutboundSAMLMessageIssueInstant(); + + /** + * Gets the protocol used by the local entity to communicate with the peer entity. + * + * @return protocol used by the local entity to communicate with the peer entity + */ + public String getOutboundSAMLProtocol(); + + /** + * Gets the endpoint of for the peer entity. + * + * @return endpoint of for the peer entity + */ + public Endpoint getPeerEntityEndpoint(); + + /** + * Gets the peer's entity ID. + * + * @return peer's entity ID + */ + public String getPeerEntityId(); + + /** + * Gets the peer entity metadata. + * + * @return peer entity metadata + */ + public EntityDescriptor getPeerEntityMetadata(); + + /** + * Gets the role of the peer entity. + * + * @return role of the peer entity + */ + public QName getPeerEntityRole(); + + /** + * Gets the role of the peer entity. + * + * @return role of the peer entity + */ + public RoleDescriptor getPeerEntityRoleMetadata(); + + /** + * Gets the relay state associated with the message. + * + * @return relay state associated with the message + */ + public String getRelayState(); + + /** + * Gets the subject's SAML name identifier. + * + * @return subject's SAML name identifier + */ + public NameIdentifierType getSubjectNameIdentifier(); + + /** + * Gets whether the inbound SAML message has been authenticated. + * + * @return whether the inbound SAML message has been authenticated + */ + public boolean isInboundSAMLMessageAuthenticated(); + + /** + * Sets the inbound SAML message. + * + * @param message inbound SAML message + */ + public void setInboundSAMLMessage(InboundMessageType message); + + /** + * Sets whether the inbound SAML message has been authenticated. + * + * @param isAuthenticated whether the inbound SAML message has been authenticated + */ + public void setInboundSAMLMessageAuthenticated(boolean isAuthenticated); + + /** + * Sets the ID of the inbound SAML message. + * + * @param id ID of the inbound SAML message + */ + public void setInboundSAMLMessageId(String id); + + /** + * Sets the issue instant of the incomming SAML message. + * + * @param instant issue instant of the incomming SAML message + */ + public void setInboundSAMLMessageIssueInstant(DateTime instant); + + /** + * Sets the protocol used by the peer entity to communicate with the local entity. + * + * @param protocol protocol used by the peer entity to communicate with the local entity + */ + public void setInboundSAMLProtocol(String protocol); + + /** + * Sets the local entity's ID. + * + * @param id local entity's ID + */ + public void setLocalEntityId(String id); + + /** + * Sets the local entity metadata. + * + * @param metadata local entity metadata + */ + public void setLocalEntityMetadata(EntityDescriptor metadata); + + /** + * Sets the role of the local entity. + * + * @param role role of the local entity + */ + public void setLocalEntityRole(QName role); + + /** + * Sets the role metadata for the local entity. + * + * @param role role metadata for the local entity + */ + public void setLocalEntityRoleMetadata(RoleDescriptor role); + + /** + * Sets the metadata provider used to lookup information entity information. + * + * @param provider metadata provider used to lookup information entity information + */ + public void setMetadataProvider(MetadataProvider provider); + + /** + * Sets the artifact type to use for the outbound message. + * + * @param type artifact type to use for the outbound message + */ + public void setOutboundMessageArtifactType(byte[] type); + + /** + * Sets the outbound SAML message. + * + * @param message outbound SAML message + */ + public void setOutboundSAMLMessage(OutboundMessageType message); + + /** + * Sets the ID of the outbound SAML message. + * + * @param id ID of the outbound SAML message + */ + public void setOutboundSAMLMessageId(String id); + + /** + * Sets the issue instant of the outbound SAML message. + * + * @param instant issue instant of the outbound SAML message + */ + public void setOutboundSAMLMessageIssueInstant(DateTime instant); + + /** + * Sets the credential used to sign the outbound SAML message. + * + * @param credential credential used to sign the outbound SAML message + */ + public void setOutboundSAMLMessageSigningCredential(Credential credential); + + /** + * Sets the protocol used by the local entity to communicate with the peer entity. + * + * @param protocol protocol used by the local entity to communicate with the peer entity + */ + public void setOutboundSAMLProtocol(String protocol); + + /** + * Sets the endpoint of for the peer entity. + * + * @param endpoint endpoint of for the peer entity + */ + public void setPeerEntityEndpoint(Endpoint endpoint); + + /** + * Sets the peer's entity ID. + * + * @param id peer's entity ID + */ + public void setPeerEntityId(String id); + + /** + * Sets the peer entity metadata. + * + * @param metadata peer entity metadata + */ + public void setPeerEntityMetadata(EntityDescriptor metadata); + + /** + * Sets the role of the peer entity. + * + * @param role role of the peer entity + */ + public void setPeerEntityRole(QName role); + + /** + * Sets the role metadata for the peer entity. + * + * @param role role metadata for the peer entity + */ + public void setPeerEntityRoleMetadata(RoleDescriptor role); + + /** + * Sets the relay state associated with the message. + * + * @param relayState relay state associated with the message + */ + public void setRelayState(String relayState); + + /** + * Sets the subject's SAML name identifier. + * + * @param identifier subject's SAML name identifier + */ + public void setSubjectNameIdentifier(NameIdentifierType identifier); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/package.html 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,7 @@ + + +Classes related to SAML binding operations. +

+ + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/AbstractSAMLArtifact.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/AbstractSAMLArtifact.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/AbstractSAMLArtifact.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,130 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.artifact; + +import java.util.Arrays; + +import org.bouncycastle.util.encoders.Hex; +import org.opensaml.xml.util.Base64; + +/** + * Base class for SAML artifacts. + */ +public abstract class AbstractSAMLArtifact { + + /** 2 byte artifact type code. */ + private byte[] typeCode; + + /** + * Constructor. + * + * @param code the artifact type code + * + * @throws IllegalArgumentException thrown if the given type code is not two bytes in length + */ + protected AbstractSAMLArtifact(byte[] code) { + if(code.length != 2){ + throw new IllegalArgumentException("Type code was not 2-bytes in size"); + } + typeCode = code; + } + + /** + * Gets the bytes for the artifact. + * + * @return the bytes for the artifact + */ + public byte[] getArtifactBytes() { + byte[] remainingArtifact = getRemainingArtifact(); + byte[] artifact = new byte[2 + remainingArtifact.length]; + + System.arraycopy(getTypeCode(), 0, artifact, 0, 2); + System.arraycopy(remainingArtifact, 0, artifact, 2, remainingArtifact.length); + + return artifact; + } + + /** + * Gets the 2 byte type code for this artifact. + * + * @return the type code for this artifact + */ + public byte[] getTypeCode() { + return typeCode; + } + + /** + * Sets the 2 byte type code for this artifact. + * + * @param newTypeCode 2 byte type code for this artifact + * + * @throws IllegalArgumentException thrown if the given type code is not two bytes + */ + protected void setTypeCode(byte[] newTypeCode) { + typeCode = newTypeCode; + } + + /** + * Gets the artifact bytes minus the type code. + * + * @return artifact bytes minus the type code + */ + public abstract byte[] getRemainingArtifact(); + + /** + * Gets the Base64 encoded artifact. + * + * @return Base64 encoded artifact. + */ + public String base64Encode() { + return new String(Base64.encodeBytes(getArtifactBytes())); + } + + /** + * Gets the hex encoded artifact. + * + * @return hex encoded artifact + */ + public String hexEncode() { + return new String(Hex.encode(getArtifactBytes())); + } + + /** {@inheritDoc} */ + public boolean equals(Object o) { + if(o == this){ + return true; + } + + if (o instanceof AbstractSAMLArtifact) { + AbstractSAMLArtifact otherArtifact = (AbstractSAMLArtifact) o; + return Arrays.equals(getArtifactBytes(), otherArtifact.getArtifactBytes()); + } + + return false; + } + + /** {@inheritDoc} */ + public int hashCode() { + return Arrays.hashCode(getArtifactBytes()); + } + + /** {@inheritDoc} */ + public String toString(){ + return base64Encode(); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMap.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMap.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMap.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,167 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.artifact; + +import org.opensaml.common.SAMLObject; +import org.opensaml.util.storage.StorageService; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Basic artifact map implementation that uses a {@link StorageService} to store and retrieve artifacts. + */ +public class BasicSAMLArtifactMap implements SAMLArtifactMap { + + /** The default StorageService partition name to use. */ + public static final String DEFAULT_STORAGE_PARTITION = "artifact"; + + /** Class Logger. */ + private final Logger log = LoggerFactory.getLogger(BasicSAMLArtifactMap.class); + + /** Artifact mapping storage. */ + private StorageService artifactStore; + + /** Storage service partition used by this cache. default: artifact */ + private String partition; + + /** Lifetime of an artifact in milliseconds. */ + private long artifactLifetime; + + /** Factory for SAMLArtifactMapEntry instances. */ + private SAMLArtifactMapEntryFactory entryFactory; + + /** + * Constructor. + * + * @deprecated replacement {@link BasicSAMLArtifactMap#BasicSAMLArtifactMap(StorageService, long)} + * + * @param parser parser pool used to parse serialized messages. + * (Note: ParserPool arg is deprecated and no longer used). + * @param storage artifact mapping storage + * @param lifetime lifetime of an artifact in milliseconds + */ + public BasicSAMLArtifactMap(ParserPool parser, StorageService storage, + long lifetime) { + this(storage, DEFAULT_STORAGE_PARTITION, lifetime); + } + + /** + * Constructor. + * + * @param storage artifact mapping storage + * @param lifetime lifetime of an artifact in milliseconds + */ + public BasicSAMLArtifactMap(StorageService storage, long lifetime) { + this(storage, DEFAULT_STORAGE_PARTITION, lifetime); + } + + /** + * Constructor. + * + * @param storage artifact mapping storage + * @param storageParition name of storage service partition to use + * @param lifetime lifetime of an artifact in milliseconds + */ + public BasicSAMLArtifactMap(StorageService storage, String storageParition, + long lifetime) { + this(new BasicSAMLArtifactMapEntryFactory(), storage, storageParition, lifetime); + } + + /** + * Constructor. + * + * @param factory the SAML artifact map entry factory to use + * @param storage artifact mapping storage + * @param lifetime lifetime of an artifact in milliseconds + */ + public BasicSAMLArtifactMap(SAMLArtifactMapEntryFactory factory, + StorageService storage, long lifetime) { + this(factory, storage, DEFAULT_STORAGE_PARTITION, lifetime); + } + + /** + * Constructor. + * + * @param factory the SAML artifact map entry factory to use + * @param storage artifact mapping storage + * @param storageParition name of storage service partition to use + * @param lifetime lifetime of an artifact in milliseconds + */ + public BasicSAMLArtifactMap(SAMLArtifactMapEntryFactory factory, + StorageService storage, + String storageParition, long lifetime) { + entryFactory = factory; + artifactStore = storage; + if (!DatatypeHelper.isEmpty(storageParition)) { + partition = DatatypeHelper.safeTrim(storageParition); + } else { + partition = DEFAULT_STORAGE_PARTITION; + } + artifactLifetime = lifetime; + } + + /** {@inheritDoc} */ + public boolean contains(String artifact) { + return artifactStore.contains(partition, artifact); + } + + /** {@inheritDoc} */ + public SAMLArtifactMapEntry get(String artifact) { + log.debug("Attempting to retrieve entry for artifact: {}", artifact); + SAMLArtifactMapEntry entry = artifactStore.get(partition, artifact); + + if(entry == null){ + log.debug("No entry found for artifact: {}", artifact); + return null; + } + + if (entry.isExpired()) { + log.debug("Entry for artifact was expired: {}", artifact); + remove(artifact); + return null; + } + + log.debug("Found valid entry for artifact: {}", artifact); + return entry; + } + + /** {@inheritDoc} */ + public void put(String artifact, String relyingPartyId, String issuerId, SAMLObject samlMessage) + throws MarshallingException { + + SAMLArtifactMapEntry artifactEntry = entryFactory.newEntry(artifact, issuerId, relyingPartyId, + samlMessage, artifactLifetime); + + if (log.isDebugEnabled()) { + log.debug("Storing new artifact entry '{}' for relying party '{}', expiring at '{}'", + new Object[] {artifact, relyingPartyId, artifactEntry.getExpirationTime()}); + } + + artifactStore.put(partition, artifact, artifactEntry); + } + + /** {@inheritDoc} */ + public void remove(String artifact) { + log.debug("Removing artifact entry: {}", artifact); + artifactStore.remove(partition, artifact); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMapEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMapEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMapEntry.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,273 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.artifact; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.StringReader; +import java.io.StringWriter; + +import org.joda.time.DateTime; +import org.opensaml.Configuration; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry; +import org.opensaml.util.storage.AbstractExpiringObject; +import org.opensaml.xml.XMLRuntimeException; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.parse.XMLParserException; +import org.opensaml.xml.util.XMLObjectHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Basic implementation of {@link SAMLArtifactMapEntry}. */ +public class BasicSAMLArtifactMapEntry extends AbstractExpiringObject implements SAMLArtifactMapEntry { + + /** Serial version UID. */ + private static final long serialVersionUID = 1577232740330721369L; + + /** Class Logger. */ + private Logger log = LoggerFactory.getLogger(BasicSAMLArtifactMapEntry.class); + + /** SAML artifact being mapped. */ + private String artifact; + + /** Entity ID of the issuer of the artifact. */ + private String issuer; + + /** Entity ID of the receiver of the artifact. */ + private String relyingParty; + + /** SAML message mapped to the artifact. */ + private transient SAMLObject message; + + /** Serialized SAML object mapped to the artifact. */ + private String serializedMessage; + + /** + * Constructor. + * + * @deprecated replacement + * {@link BasicSAMLArtifactMapEntry#BasicSAMLArtifactMapEntry(String, String, String, SAMLObject, long)} + * + * @param samlArtifact artifact associated with the message + * @param issuerId issuer of the artifact + * @param relyingPartyId receiver of the artifact + * @param serializedSAML serialized SAML message mapped to the artifact + * @param lifetime lifetime of the artifact in milliseconds + */ + public BasicSAMLArtifactMapEntry(String samlArtifact, String issuerId, String relyingPartyId, + String serializedSAML, long lifetime) { + super(new DateTime().plus(lifetime)); + artifact = samlArtifact; + issuer = issuerId; + relyingParty = relyingPartyId; + serializedMessage = serializedSAML; + } + + /** + * Constructor. + * + * @param samlArtifact artifact associated with the message + * @param issuerId issuer of the artifact + * @param relyingPartyId receiver of the artifact + * @param samlMessage SAML message mapped to the artifact + * @param lifetime lifetime of the artifact in milliseconds + */ + public BasicSAMLArtifactMapEntry(String samlArtifact, String issuerId, String relyingPartyId, + SAMLObject samlMessage, long lifetime) { + super(new DateTime().plus(lifetime)); + artifact = samlArtifact; + issuer = issuerId; + relyingParty = relyingPartyId; + message = samlMessage; + } + + /** {@inheritDoc} */ + public String getArtifact() { + return artifact; + } + + /** {@inheritDoc} */ + public String getIssuerId() { + return issuer; + } + + /** {@inheritDoc} */ + public String getRelyingPartyId() { + return relyingParty; + } + + /** {@inheritDoc} */ + public SAMLObject getSamlMessage() { + if (message == null) { + try { + deserializeMessage(); + } catch (IOException e) { + throw new XMLRuntimeException("Error deserializaing SAML message data", e); + } + } + return message; + } + + /** + * Sets the SAML message mapped to the artifact. + * + * @param saml SAML message mapped to the artifact + */ + void setSAMLMessage(SAMLObject saml) { + if (saml == null) { + throw new IllegalArgumentException("SAMLObject message may not be null"); + } + message = saml; + // Clear the cached serialized version + serializedMessage = null; + } + + /** + * Gets the serialized form of the SAML message. + * + * @deprecated replacement is: {@link #getSerializedMessage()} + * + * @return serialized form of the SAML message + * + */ + String getSeralizedMessage() { + return getSerializedMessage(); + } + + /** + * Gets the serialized form of the SAML message. + * + * @return serialized form of the SAML message + */ + String getSerializedMessage() { + return serializedMessage; + } + + /** + * Serialize the SAMLObject held by the entry and store in the class. + * + *

This option is provided where explicit pre-serialization of the data + * is either necessary or desirable.

+ */ + void serializeMessage() { + if (log == null) { + log = LoggerFactory.getLogger(BasicSAMLArtifactMapEntry.class); + } + + if (serializedMessage == null) { + log.debug("Serializing SAMLObject to a string"); + StringWriter writer = new StringWriter(); + try { + XMLObjectHelper.marshallToWriter(message, writer); + } catch (MarshallingException e) { + throw new XMLRuntimeException("Error marshalling the SAMLObject: " + e.getMessage()); + } + + serializedMessage = writer.toString(); + + if (log.isTraceEnabled()) { + log.trace("Serialized SAMLObject data was:"); + log.trace(serializedMessage); + } + } else { + log.debug("SAMLObject was already serialized, skipping marshall and serialize step"); + } + } + + /** + * Deserialize the serialized message data held by the entry so that it is available + * as the SAMLObject samleMessage property. + * + *

This option is provided where explicit deserialization of the data + * is either necessary or desirable.

+ * + * @throws IOException if there is a problem parsing or unmarshalling the serialized message + */ + void deserializeMessage() throws IOException { + if (log == null) { + log = LoggerFactory.getLogger(BasicSAMLArtifactMapEntry.class); + } + + if (message == null) { + if (getSerializedMessage() == null) { + throw new XMLRuntimeException("Serialized SAML message data was not available for deserialization"); + } + + ParserPool parserPool = Configuration.getParserPool(); + if (parserPool == null) { + throw new XMLRuntimeException( + "No ParserPool was available for parsing the deserialized artifact map entry"); + } + log.debug("Deserializing SAMLObject from a string"); + if (log.isTraceEnabled()) { + log.trace("Serialized SAMLObject data was:"); + log.trace(getSerializedMessage()); + } + StringReader reader = new StringReader(getSerializedMessage()); + try { + SAMLObject samlObject = (SAMLObject) XMLObjectHelper.unmarshallFromReader(parserPool, reader); + message = samlObject; + } catch (XMLParserException e) { + throw new IOException("Error parsing XML into DOM: " + e.getMessage()); + } catch (UnmarshallingException e) { + throw new IOException("Error unmarshalling DOM into SAMLObject: " + e.getMessage()); + } + } + } + + /** + * Serialize the entry to the object output stream. + * + * @param out the output stream to which to serialize + * @throws IOException if there is a problem serializing the entry + */ + private void writeObject(ObjectOutputStream out) throws IOException { + if (log == null) { + log = LoggerFactory.getLogger(BasicSAMLArtifactMapEntry.class); + } + log.debug("Serializing object data to ObjectOutputStream"); + + serializeMessage(); + + out.defaultWriteObject(); + } + + + /** + * Deserialize the entry from the input stream. + * + * @param in the input stream from which to deserialize + * @throws IOException if the is a problem deserializing the object + * @throws ClassNotFoundException if there is a problem loading the class of the object + */ + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + if (log == null) { + log = LoggerFactory.getLogger(BasicSAMLArtifactMapEntry.class); + } + log.debug("Deserializing object data from ObjectInputStream"); + + in.defaultReadObject(); + + deserializeMessage(); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMapEntryFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMapEntryFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/BasicSAMLArtifactMapEntryFactory.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.artifact; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry; +import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntryFactory; +import org.opensaml.xml.XMLRuntimeException; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLObjectHelper; + +/** + * A basic factory for instances of {@link SAMLArtifactMapEntryFactory}. + * + *

+ * If this implementation, if the SAMLObject being stored does not have a parent, + * then it will be stored as-is. If it does have a parent, it will first be cloned, + * with its cloned and cached DOM rooted in a new Document. + *

+ * + *

+ * If the serializeMessage property is true, then the SAMLObject held by the + * entry will be internally serialized within the entry before it is returned. + * This option defaults to false. + *

+ */ +public class BasicSAMLArtifactMapEntryFactory implements SAMLArtifactMapEntryFactory { + + /** Flag determining whether the SAMLObject message should be explicitly serialized + * on creation of the new artifact map entry. */ + private boolean serializeMessage; + + /** + * Set the flag determining whether the SAMLObject message should be explicitly serialized + * on creation of the new artifact map entry. Defaults to false. + * + * @param newSerializeMessage the new flag value + */ + public void setSerializeMessage(boolean newSerializeMessage) { + serializeMessage = newSerializeMessage; + } + + /** + * Get the flag determining whether the SAMLObject message should be explicitly serialized + * on creation of the new artifact map entry. Defaults to false. + * + * @return the current flag value + */ + public boolean isSerializeMessage() { + return serializeMessage; + } + + /** {@inheritDoc} */ + public SAMLArtifactMapEntry newEntry(String artifact, String issuerId, String relyingPartyId, + SAMLObject samlMessage, long lifetime) { + + SAMLObject newSAMLMessage = getStorableSAMLMessage(samlMessage); + + BasicSAMLArtifactMapEntry entry = + new BasicSAMLArtifactMapEntry(artifact, issuerId, relyingPartyId, newSAMLMessage , lifetime); + + if (serializeMessage) { + entry.serializeMessage(); + } + return entry; + } + + /** + * Get the SAMLObject which will actually be stored in the produced SAMLArtifactMapEntry. + * + *

+ * This may or may not be the same SAMLObject that is passed in. If the SAMLObject does + * not have a parent, the same object will be returned. Otherwise, the object will be cloned + * and the cloned instance returned. + *

+ * + * @param samlMessage the SAML message to process + * @return an equivalent SAML Message + */ + private SAMLObject getStorableSAMLMessage(SAMLObject samlMessage) { + if (!samlMessage.hasParent()) { + return samlMessage; + } else { + try { + return XMLObjectHelper.cloneXMLObject(samlMessage, true); + } catch (MarshallingException e) { + throw new XMLRuntimeException("Error during marshalling of SAMLObject", e); + } catch (UnmarshallingException e) { + throw new XMLRuntimeException("Error during unmarshalling of SAMLObject", e); + } + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/SAMLArtifactMap.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/SAMLArtifactMap.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/SAMLArtifactMap.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,133 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.artifact; + +import org.opensaml.common.SAMLObject; +import org.opensaml.util.storage.ExpiringObject; +import org.opensaml.xml.io.MarshallingException; + +/** + * Maps an artifact to a SAML message and back again. + * + *

Artifacts must be thread safe.

+ * + *

+ * An implementation of this interface MUST ensure that the persisted SAML message is no longer tied to any + * parent {@link org.opensaml.xml.XMLObject} that may have contained it. This ensures that it can be safely added + * to another object once retrieved from the map. This might for example be achieved by: + * 1) cloning the SAMLObject prior to storage, or 2) by serializing it to a string and re-parsing + * and unmarhsalling it once retrieved from the underlying data store. + * This requirement may be handled by the SAMLArtifactMap directly, or by the use of of a specific + * implementation of {@link SAMLArtifactMapEntryFactory}. + *

+ */ +public interface SAMLArtifactMap { + + /** + * Checks if a given artifact has a map entry. + * + * @param artifact the artifact to check + * + * @return true of this map has an entry for the given artifact, false it not + */ + public boolean contains(String artifact); + + /** + * Creates a mapping between a given artifact and the SAML message to which it maps. + * + * @param artifact the artifact + * @param relyingPartyId ID of the party the artifact was sent to + * @param issuerId ID of the issuer of the artifact + * @param samlMessage the SAML message + * + * @throws MarshallingException thrown if the given SAML message can not be marshalled + */ + public void put(String artifact, String relyingPartyId, String issuerId, SAMLObject samlMessage) + throws MarshallingException; + + /** + * Gets the artifact entry for the given artifact. + * + * @param artifact the artifact to retrieve the entry for + * + * @return the entry or null if the artifact has already expired or did not exist + */ + public SAMLArtifactMapEntry get(String artifact); + + /** + * Removes the artifact from this map. + * + * @param artifact artifact to be removed + */ + public void remove(String artifact); + + /** + * Represents a mapping between an artifact a SAML message with some associated metadata. + */ + public interface SAMLArtifactMapEntry extends ExpiringObject { + + /** + * Gets the artifact that maps to the SAML message. + * + * @return artifact that maps to the SAML message + */ + public String getArtifact(); + + /** + * Gets the ID of the issuer of the artifact. + * + * @return ID of the issuer of the artifact + */ + public String getIssuerId(); + + /** + * Gets the ID of the relying party the artifact was sent to. + * + * @return ID of the relying party the artifact was sent to + */ + public String getRelyingPartyId(); + + /** + * Gets SAML message the artifact maps to. + * + * @return SAML message the artifact maps to + */ + public SAMLObject getSamlMessage(); + } + + /** + * A factory for producing SAMLArtifactMapEntry instances based on standard inputs. + */ + public interface SAMLArtifactMapEntryFactory { + + /** + * Factory method which produces a {@link SAMLArtifactMapEntry}. + * + * @param artifact the artifact + * @param issuerId ID of the issuer of the artifact + * @param relyingPartyId ID of the party the artifact was sent to + * @param samlMessage the SAML message + * @param lifetime the lifetime of the artifact entry, in milliseconds + * + * @return the new map entry instance + */ + public SAMLArtifactMapEntry newEntry(String artifact, String issuerId, String relyingPartyId, + SAMLObject samlMessage, long lifetime); + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/artifact/package.html 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,5 @@ + + +Classes that may be used to create and manipulate SAML artifacts. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/BaseSAMLMessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/BaseSAMLMessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/BaseSAMLMessageDecoder.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,223 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.decoding; + +import javax.servlet.http.HttpServletRequest; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.ws.message.decoder.BaseMessageDecoder; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.transport.InTransport; +import org.opensaml.ws.transport.http.HttpServletRequestAdapter; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for all SAML message decoders. + */ +public abstract class BaseSAMLMessageDecoder extends BaseMessageDecoder implements SAMLMessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseSAMLMessageDecoder.class); + + /** The URIComparator implementation to use. */ + private URIComparator uriComparator; + + /** Constructor. */ + public BaseSAMLMessageDecoder() { + super(); + setURIComparator(new BasicURLComparator()); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public BaseSAMLMessageDecoder(ParserPool pool) { + super(pool); + setURIComparator(new BasicURLComparator()); + } + + /** + * Set the {@link URIComparator} to use in {@link #compareEndpointURIs(String, String)}. + * + * @param comparator The uriComparator to set. + */ + public void setURIComparator(URIComparator comparator) { + if (comparator == null) { + throw new IllegalArgumentException("URI comparator may not be null"); + } + uriComparator = comparator; + } + + /** + * Get the {@link URIComparator} to use in {@link #compareEndpointURIs(String, String)}. + * + * @return Returns the uriComparator. + */ + public URIComparator getURIComparator() { + return uriComparator; + } + + /** + * Determine whether the SAML message represented by the message context is digitally signed. + * + *

The default behavior is to examine whether an XML signature is present on the + * SAML protocol message. Subclasses may augment or replace with binding-specific behavior.

+ * + * @param messageContext current message context + * @return true if the message is considered to be digitially signed, false otherwise + */ + protected boolean isMessageSigned(SAMLMessageContext messageContext) { + SAMLObject samlMessage = messageContext.getInboundSAMLMessage(); + if (samlMessage instanceof SignableSAMLObject) { + return ((SignableSAMLObject)samlMessage).isSigned(); + } else { + return false; + } + } + + /** + * Determine whether the binding implemented by the decoder requires the presence within the message + * of information indicating the intended message destination endpoint URI. + * + * + * @param samlMsgCtx current SAML message context + * @return true if the intended message destination endpoint is required, false if not + */ + protected abstract boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx); + + /** + * Extract the message information which indicates to what receiver endpoint URI the + * SAML message was intended to be delivered. + * + * @param samlMsgCtx the SAML message context being processed + * @return the value of the intended destination endpoint URI, or null if not present or empty + * @throws MessageDecodingException thrown if the message is not an instance of SAML message that + * could be processed by the decoder + */ + protected abstract String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) + throws MessageDecodingException; + + /** + * Extract the transport endpoint at which this message was received. + * + *

This default implementation assumes an underlying message context {@link InTransport} type + * of {@link HttpServletRequestAdapter} and returns the string representation of the underlying + * request URL as constructed via {@link HttpServletRequest#getRequestURL()}.

+ * + *

Subclasses should override if binding-specific behavior or support for other transport + * typs is required. In this case, see also {@link #compareEndpointURIs(String, String)}.

+ * + * + * @param messageContext current message context + * @return string representing the transport endpoint URI at which the current message was received + * @throws MessageDecodingException thrown if the endpoint can not be extracted from the message + * context and converted to a string representation + */ + protected String getActualReceiverEndpointURI(SAMLMessageContext messageContext) throws MessageDecodingException { + InTransport inTransport = messageContext.getInboundMessageTransport(); + if (! (inTransport instanceof HttpServletRequestAdapter)) { + log.error("Message context InTransport instance was an unsupported type: {}", + inTransport.getClass().getName()); + throw new MessageDecodingException("Message context InTransport instance was an unsupported type"); + } + HttpServletRequest httpRequest = ((HttpServletRequestAdapter)inTransport).getWrappedRequest(); + + StringBuffer urlBuilder = httpRequest.getRequestURL(); + + return urlBuilder.toString(); + } + + /** + * Compare the message endpoint URI's specified. + * + *

The comparison is performed using the configured instance of {@link URIComparator}. + * By default, the URL subtype of URI is supported, and the default comparator implementation used + * is {@link BasicURLComparator}. Other types of URI's may be supported by configuring a + * different implementation of {@link URIComparator}. + *

+ * + *

Subclasses should override if binding-specific behavior is required. + * In this case, see also {@link #getActualReceiverEndpointURI(SAMLMessageContext)}.

+ * + * @param messageDestination the intended message destination endpoint URI + * @param receiverEndpoint the endpoint URI at which the message was received + * @return true if the endpoints are equivalent, false otherwise + * @throws MessageDecodingException thrown if the endpoints specified are not equivalent + */ + protected boolean compareEndpointURIs(String messageDestination, String receiverEndpoint) + throws MessageDecodingException { + + return getURIComparator().compare(messageDestination, receiverEndpoint); + } + + /** + * Check the validity of the SAML protocol message receiver endpoint against + * requirements indicated in the message. + * + * @param messageContext current message context + * + * @throws SecurityException thrown if the message Destination attribute is invalid + * with respect to the receiver's endpoint + * @throws MessageDecodingException thrown if there is a problem decoding and processing + * the message Destination or receiver + * endpoint information + */ + protected void checkEndpointURI(SAMLMessageContext messageContext) + throws SecurityException, MessageDecodingException { + + log.debug("Checking SAML message intended destination endpoint against receiver endpoint"); + + String messageDestination = + DatatypeHelper.safeTrimOrNullString(getIntendedDestinationEndpointURI(messageContext)); + + boolean bindingRequires = isIntendedDestinationEndpointURIRequired(messageContext); + + if (messageDestination == null) { + if (bindingRequires) { + log.error("SAML message intended destination endpoint URI required by binding was empty"); + throw new SecurityException("SAML message intended destination (required by binding) was not present"); + } else { + log.debug("SAML message intended destination endpoint in message was empty, not required by binding, skipping"); + return; + } + } + + String receiverEndpoint = DatatypeHelper.safeTrimOrNullString(getActualReceiverEndpointURI(messageContext)); + + log.debug("Intended message destination endpoint: {}", messageDestination); + log.debug("Actual message receiver endpoint: {}", receiverEndpoint); + + boolean matched = compareEndpointURIs(messageDestination, receiverEndpoint); + if (!matched) { + log.error("SAML message intended destination endpoint '{}' did not match the recipient endpoint '{}'", + messageDestination, receiverEndpoint); + throw new SecurityException("SAML message intended destination endpoint did not match recipient endpoint"); + } else { + log.debug("SAML message intended destination endpoint matched recipient endpoint"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/BasicURLComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/BasicURLComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/BasicURLComparator.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.decoding; + +import org.opensaml.util.SimpleURLCanonicalizer; + +/** + * A basic implementation of {@link URIComparator} that compares + * URL's by canonicalizing them as per {@link SimpleURLCanonicalizer}, + * and then compares the resulting string representations for equality + * using String equals(). If {link {@link #isCaseInsensitive()} is true, + * then the equality test is instead performed using String equalsIgnoreCase(). + */ +public class BasicURLComparator implements URIComparator { + + /** The case-insensitivity flag. */ + private boolean caseInsensitive; + + /** + * Get the case-insensitivity flag value. + * @return Returns the caseInsensitive. + */ + public boolean isCaseInsensitive() { + return caseInsensitive; + } + + /** + * Set the case-insensitivity flag value. + * @param flag The caseInsensitive to set. + */ + public void setCaseInsensitive(boolean flag) { + caseInsensitive = flag; + } + + /** {@inheritDoc} */ + public boolean compare(String uri1, String uri2) { + if (uri1 == null) { + return uri2 == null; + } else if (uri2 == null) { + return uri1 == null; + } else { + String uri1Canon = SimpleURLCanonicalizer.canonicalize(uri1); + String uri2Canon = SimpleURLCanonicalizer.canonicalize(uri2); + if (isCaseInsensitive()) { + return uri1Canon.equalsIgnoreCase(uri2Canon); + } else { + return uri1Canon.equals(uri2Canon); + } + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/SAMLMessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/SAMLMessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/SAMLMessageDecoder.java 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.decoding; + +import org.opensaml.ws.message.decoder.MessageDecoder; + +/** + * SAML extension to the generic message decoders. + */ +public interface SAMLMessageDecoder extends MessageDecoder { + + /** + * Gets the SAML binding URI supported by this decoder. + * + * @return SAML binding URI supported by this decoder + */ + public String getBindingURI(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/URIComparator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/URIComparator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/URIComparator.java 17 Aug 2012 15:02:25 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.decoding; + +/** + * Component for testing URI's as to equality. + */ +public interface URIComparator { + + /** + * Compare two URI's (represented as strings) for equivalence. + * + * @param uri1 first URI to compare + * @param uri2 second URI to compare + * + * @return true if the URI's are equivalent, false otherwise + */ + public boolean compare(String uri1, String uri2); + +} Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/decoding/package.html 17 Aug 2012 15:02:26 -0000 1.1 @@ -0,0 +1,7 @@ + + +Classes used to decode SAML messages. A decoder takes a wire protocol, +extracts the SAML message from it, and then evaluates that message +against a security policy. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/encoding/SAMLMessageEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/encoding/SAMLMessageEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/encoding/SAMLMessageEncoder.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.encoding; + +import org.opensaml.ws.message.encoder.MessageEncoder; + +/** + * SAML extension to the generic message encoder. + */ +public interface SAMLMessageEncoder extends MessageEncoder { + + /** + * Gets the SAML binding URI supported by this encoder. + * + * @return SAML binding URI supported by this encoder + */ + public String getBindingURI(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/encoding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/encoding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/encoding/package.html 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,7 @@ + + +Classes used to encode SAML messages. An encoder takes a SAML message +and transforms it into a representation that may be transported over a +particular wire protocol (e.g. HTTP). + + Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/security/BaseSAMLSimpleSignatureSecurityPolicyRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/security/BaseSAMLSimpleSignatureSecurityPolicyRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/security/BaseSAMLSimpleSignatureSecurityPolicyRule.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,331 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.security; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.security.MetadataCriteria; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.opensaml.ws.transport.http.HttpServletRequestAdapter; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.EntityIDCriteria; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.signature.SignatureTrustEngine; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for security rules which verify simple "blob" signatures computed over some components of a request. + */ +public abstract class BaseSAMLSimpleSignatureSecurityPolicyRule implements SecurityPolicyRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(BaseSAMLSimpleSignatureSecurityPolicyRule.class); + + /** Signature trust engine used to validate raw signatures. */ + private SignatureTrustEngine trustEngine; + + /** + * Constructor. + * + * @param engine the signature trust engine to use for signature validataion + */ + protected BaseSAMLSimpleSignatureSecurityPolicyRule(SignatureTrustEngine engine) { + trustEngine = engine; + } + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + log.debug("Evaluating simple signature rule of type: {}", getClass().getName()); + if (!(messageContext instanceof SAMLMessageContext)) { + log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext"); + return; + } + + if (!(messageContext.getInboundMessageTransport() instanceof HttpServletRequestAdapter)) { + log.debug("Invalid inbound message transport type, this rule only supports HttpServletRequestAdapter"); + return; + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + HttpServletRequestAdapter requestAdapter = (HttpServletRequestAdapter) messageContext + .getInboundMessageTransport(); + HttpServletRequest request = requestAdapter.getWrappedRequest(); + + if (!ruleHandles(request, samlMsgCtx)) { + log.debug("Rule can not handle this request, skipping processing"); + return; + } + + byte[] signature = getSignature(request); + if (signature == null || signature.length == 0) { + log.debug("HTTP request was not signed via simple signature mechanism, skipping"); + return; + } + + String sigAlg = getSignatureAlgorithm(request); + if (DatatypeHelper.isEmpty(sigAlg)) { + log.warn("Signature algorithm could not be extracted from request, can not validate simple signature"); + return; + } + + byte[] signedContent = getSignedContent(request); + if (signedContent == null || signedContent.length == 0) { + log.warn("Signed content could not be extracted from HTTP request, can not validate"); + return; + } + + doEvaluate(signature, signedContent, sigAlg, request, samlMsgCtx); + } + + /** + * Evaluate the simple signature based on information in the request and/or message context. + * + * @param signature the signature value + * @param signedContent the content that was signed + * @param algorithmURI the signature algorithm URI which was used to sign the content + * @param request the HTTP servlet request being processed + * @param samlMsgCtx the SAML message context being processed + * + * @throws SecurityPolicyException thrown if there are errors during the signature validation process + * + */ + private void doEvaluate(byte[] signature, byte[] signedContent, String algorithmURI, HttpServletRequest request, + SAMLMessageContext samlMsgCtx) throws SecurityPolicyException { + + List candidateCredentials = getRequestCredentials(request, samlMsgCtx); + + String contextIssuer = samlMsgCtx.getInboundMessageIssuer(); + + if (contextIssuer != null) { + log.debug("Attempting to validate SAML protocol message simple signature using context issuer: {}", + contextIssuer); + CriteriaSet criteriaSet = buildCriteriaSet(contextIssuer, samlMsgCtx); + if (validateSignature(signature, signedContent, algorithmURI, criteriaSet, candidateCredentials)) { + log.info("Validation of request simple signature succeeded"); + if (!samlMsgCtx.isInboundSAMLMessageAuthenticated()) { + log.info("Authentication via request simple signature succeeded for context issuer entity ID {}", + contextIssuer); + samlMsgCtx.setInboundSAMLMessageAuthenticated(true); + } + return; + } else { + log.warn("Validation of request simple signature failed for context issuer: {}", contextIssuer); + throw new SecurityPolicyException("Validation of request simple signature failed for context issuer"); + } + } + + String derivedIssuer = deriveSignerEntityID(samlMsgCtx); + if (derivedIssuer != null) { + log.debug("Attempting to validate SAML protocol message simple signature using derived issuer: {}", + derivedIssuer); + CriteriaSet criteriaSet = buildCriteriaSet(derivedIssuer, samlMsgCtx); + if (validateSignature(signature, signedContent, algorithmURI, criteriaSet, candidateCredentials)) { + log.info("Validation of request simple signature succeeded"); + if (!samlMsgCtx.isInboundSAMLMessageAuthenticated()) { + log.info("Authentication via request simple signature succeeded for derived issuer {}", + derivedIssuer); + samlMsgCtx.setInboundMessageIssuer(derivedIssuer); + samlMsgCtx.setInboundSAMLMessageAuthenticated(true); + } + return; + } else { + log.warn("Validation of request simple signature failed for derived issuer: {}", derivedIssuer); + throw new SecurityPolicyException("Validation of request simple signature failed for derived issuer"); + } + } + + log.warn("Neither context nor derived issuer available, can not attempt SAML simple signature validation"); + throw new SecurityPolicyException("No message issuer available, can not attempt simple signature validation"); + } + + /** + * Validate the simple signature. + * + * @param signature the signature value + * @param signedContent the content that was signed + * @param algorithmURI the signature algorithm URI which was used to sign the content + * @param criteriaSet criteria used to describe and/or resolve the information which serves as the basis for trust + * evaluation + * @param candidateCredentials the request-derived candidate credential(s) containing the validation key for the + * signature (optional) + * @return true if signature can be verified successfully, false otherwise + * + * @throws SecurityPolicyException thrown if there are errors during the signature validation process + * + */ + protected boolean validateSignature(byte[] signature, byte[] signedContent, String algorithmURI, + CriteriaSet criteriaSet, List candidateCredentials) throws SecurityPolicyException { + + SignatureTrustEngine engine = getTrustEngine(); + + // Some bindings allow candidate signing credentials to be supplied (e.g. via ds:KeyInfo), some do not. + // So have 2 slightly different cases. + try { + if (candidateCredentials == null || candidateCredentials.isEmpty()) { + if (engine.validate(signature, signedContent, algorithmURI, criteriaSet, null)) { + log.debug("Simple signature validation (with no request-derived credentials) was successful"); + return true; + } else { + log.warn("Simple signature validation (with no request-derived credentials) failed"); + return false; + } + } else { + for (Credential cred : candidateCredentials) { + if (engine.validate(signature, signedContent, algorithmURI, criteriaSet, cred)) { + log.debug("Simple signature validation succeeded with a request-derived credential"); + return true; + } + } + log.warn("Signature validation using request-derived credentials failed"); + return false; + } + } catch (SecurityException e) { + log.warn("There was an error evaluating the request's simple signature using the trust engine", e); + throw new SecurityPolicyException("Error during trust engine evaluation of the simple signature", e); + } + } + + /** + * Extract any candidate validation credentials from the request and/or message context. + * + * Some bindings allow validataion keys for the simple signature to be supplied, and others do not. + * + * @param request the HTTP servlet request being processed + * @param samlContext the SAML message context being processed + * @return a list of candidate validation credentials in the request, or null if none were present + * @throws SecurityPolicyException thrown if there is an error during request processing + */ + protected List getRequestCredentials(HttpServletRequest request, SAMLMessageContext samlContext) + throws SecurityPolicyException { + // This will be specific to the binding and message types, so no default. + return null; + } + + /** + * Gets the engine used to validate the signature. + * + * @return engine engine used to validate the signature + */ + protected SignatureTrustEngine getTrustEngine() { + return trustEngine; + } + + /** + * Extract the signature value from the request, in the form suitable for input into + * {@link SignatureTrustEngine#validate(byte[], byte[], String, CriteriaSet, Credential)}. + * + * Defaults to the Base64-decoded value of the HTTP request parameter named Signature. + * + * @param request the HTTP servlet request + * @return the signature value + * @throws SecurityPolicyException thrown if there is an error during request processing + */ + protected byte[] getSignature(HttpServletRequest request) throws SecurityPolicyException { + String signature = request.getParameter("Signature"); + if (DatatypeHelper.isEmpty(signature)) { + return null; + } + return Base64.decode(signature); + } + + /** + * Extract the signature algorithm URI value from the request. + * + * Defaults to the HTTP request parameter named SigAlg. + * + * @param request the HTTP servlet request + * @return the signature algorithm URI value + * @throws SecurityPolicyException thrown if there is an error during request processing + */ + protected String getSignatureAlgorithm(HttpServletRequest request) throws SecurityPolicyException { + return request.getParameter("SigAlg"); + } + + /** + * Derive the signer's entity ID from the message context. + * + * This is implementation-specific and there is no default. This is primarily an extension point for subclasses. + * + * @param samlContext the SAML message context being processed + * @return the signer's derived entity ID + * @throws SecurityPolicyException thrown if there is an error during request processing + */ + protected String deriveSignerEntityID(SAMLMessageContext samlContext) throws SecurityPolicyException { + // No default + return null; + } + + /** + * Build a criteria set suitable for input to the trust engine. + * + * @param entityID the candidate issuer entity ID which is being evaluated + * @param samlContext the message context which is being evaluated + * @return a newly constructly set of criteria suitable for the configured trust engine + * @throws SecurityPolicyException thrown if criteria set can not be constructed + */ + protected CriteriaSet buildCriteriaSet(String entityID, SAMLMessageContext samlContext) + throws SecurityPolicyException { + + CriteriaSet criteriaSet = new CriteriaSet(); + if (!DatatypeHelper.isEmpty(entityID)) { + criteriaSet.add(new EntityIDCriteria(entityID)); + } + + MetadataCriteria mdCriteria = new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext + .getInboundSAMLProtocol()); + criteriaSet.add(mdCriteria); + + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + + return criteriaSet; + } + + /** + * Get the content over which to validate the signature, in the form suitable for input into + * {@link SignatureTrustEngine#validate(byte[], byte[], String, CriteriaSet, Credential)}. + * + * @param request the HTTP servlet request being processed + * @return the signed content extracted from the request, in the format suitable for input to the trust engine. + * @throws SecurityPolicyException thrown if there is an error during request processing + */ + protected abstract byte[] getSignedContent(HttpServletRequest request) throws SecurityPolicyException; + + /** + * Determine whether the rule should handle the request, based on the unwrapped HTTP servlet request and/or message + * context. + * + * @param request the HTTP servlet request being processed + * @param samlMsgCtx the SAML message context being processed + * @return true if the rule should attempt to process the request, otherwise false + * @throws SecurityPolicyException thrown if there is an error during request processing + */ + protected abstract boolean ruleHandles(HttpServletRequest request, SAMLMessageContext samlMsgCtx) + throws SecurityPolicyException; + +} Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/security/BaseSAMLXMLSignatureSecurityPolicyRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/security/BaseSAMLXMLSignatureSecurityPolicyRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/security/BaseSAMLXMLSignatureSecurityPolicyRule.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.security; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.security.MetadataCriteria; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.provider.BaseTrustEngineRule; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.EntityIDCriteria; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.security.trust.TrustEngine; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for SAML security policy rules which evaluate a signature with a signature trust engine. + */ +public abstract class BaseSAMLXMLSignatureSecurityPolicyRule extends BaseTrustEngineRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(BaseSAMLXMLSignatureSecurityPolicyRule.class); + + /** + * Constructor. + * + * @param engine Trust engine used to verify the signature + */ + public BaseSAMLXMLSignatureSecurityPolicyRule(TrustEngine engine) { + super(engine); + } + + /** {@inheritDoc} */ + protected CriteriaSet buildCriteriaSet(String entityID, MessageContext messageContext) + throws SecurityPolicyException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Supplied message context was not an instance of SAMLMessageContext, can not build criteria set from SAML metadata parameters"); + throw new SecurityPolicyException("Supplied message context was not an instance of SAMLMessageContext"); + } + + SAMLMessageContext samlContext = (SAMLMessageContext) messageContext; + + CriteriaSet criteriaSet = new CriteriaSet(); + if (! DatatypeHelper.isEmpty(entityID)) { + criteriaSet.add(new EntityIDCriteria(entityID) ); + } + + MetadataCriteria mdCriteria = + new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext.getInboundSAMLProtocol()); + criteriaSet.add(mdCriteria); + + criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); + + return criteriaSet; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/security/IssueInstantRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/security/IssueInstantRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/security/IssueInstantRule.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.security; + +import org.joda.time.DateTime; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Security policy rule implementation that checks for validity of SAML message issue instant date and time. + */ +public class IssueInstantRule implements SecurityPolicyRule { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(IssueInstantRule.class); + + /** + * Clock skew - the number of seconds before a lower time bound, or after an upper time bound, to consider still + * acceptable. + */ + private int clockSkew; + + /** Number of seconds after a message issue instant after which the message is considered expired. */ + private int expires; + + /** Whether this rule is required to be met. */ + private boolean requiredRule; + + /** + * Constructor. + * + * @param newClockSkew the new clock skew value (seconds) + * @param newExpires the new expiration value (seconds) + */ + public IssueInstantRule(int newClockSkew, int newExpires) { + clockSkew = newClockSkew; + expires = newExpires; + requiredRule = true; + } + + /** + * Gets whether this rule is required to be met. + * + * @return whether this rule is required to be met + */ + public boolean isRequiredRule() { + return requiredRule; + } + + /** + * Sets whether this rule is required to be met. + * + * @param required whether this rule is required to be met + */ + public void setRequiredRule(boolean required) { + requiredRule = required; + } + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext"); + return; + } + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + if (samlMsgCtx.getInboundSAMLMessageIssueInstant() == null) { + if(requiredRule){ + log.warn("Inbound SAML message issue instant not present in message context"); + throw new SecurityPolicyException("Inbound SAML message issue instant not present in message context"); + }else{ + return; + } + } + + DateTime issueInstant = samlMsgCtx.getInboundSAMLMessageIssueInstant(); + DateTime now = new DateTime(); + DateTime latestValid = now.plusSeconds(clockSkew); + DateTime expiration = issueInstant.plusSeconds(clockSkew + expires); + + // Check message wasn't issued in the future + if (issueInstant.isAfter(latestValid)) { + log.warn("Message was not yet valid: message time was {}, latest valid is: {}", issueInstant, latestValid); + throw new SecurityPolicyException("Message was rejected because was issued in the future"); + } + + // Check message has not expired + if (expiration.isBefore(now)) { + log.warn("Message was expired: message issue time was '" + issueInstant + "', message expired at: '" + + expiration + "', current time: '" + now + "'"); + throw new SecurityPolicyException("Message was rejected due to issue instant expiration"); + } + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/security/MessageReplayRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/security/MessageReplayRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/security/MessageReplayRule.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,105 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.security; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.util.storage.ReplayCache; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Security policy rule implementation that which checks for replay of SAML messages. + */ +public class MessageReplayRule implements SecurityPolicyRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(MessageReplayRule.class); + + /** Message replay cache instance to use. */ + private ReplayCache replayCache; + + /** Whether this rule is required to be met. */ + private boolean requiredRule; + + /** + * Constructor. + * + * @param newReplayCache the new replay cache instance + */ + public MessageReplayRule(ReplayCache newReplayCache) { + replayCache = newReplayCache; + requiredRule = true; + } + + /** + * Gets whether this rule is required to be met. + * + * @return whether this rule is required to be met + */ + public boolean isRequiredRule() { + return requiredRule; + } + + /** + * Sets whether this rule is required to be met. + * + * @param required whether this rule is required to be met + */ + public void setRequiredRule(boolean required) { + requiredRule = required; + } + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext"); + return; + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + String messageIsuer = DatatypeHelper.safeTrimOrNullString(samlMsgCtx.getInboundMessageIssuer()); + if (messageIsuer == null) { + if (requiredRule) { + log.warn("Message contained no Issuer ID, replay check not possible"); + throw new SecurityPolicyException("Message contained no Issuer ID, replay check not possible"); + } + return; + } + + String messageId = DatatypeHelper.safeTrimOrNullString(samlMsgCtx.getInboundSAMLMessageId()); + if (messageId == null) { + if (requiredRule) { + log.warn("Message contained no ID, replay check not possible"); + throw new SecurityPolicyException("SAML message from issuer " + messageIsuer + " did not contain an ID"); + } + return; + } + + if (replayCache.isReplay(messageIsuer, messageId)) { + log.warn("Replay detected of message '" + messageId + "' from issuer " + messageIsuer); + throw new SecurityPolicyException("Rejecting replayed message ID '" + messageId + "' from issuer " + + messageIsuer); + } + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/security/SAMLMDClientCertAuthRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/security/SAMLMDClientCertAuthRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/security/SAMLMDClientCertAuthRule.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.security; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.security.MetadataCriteria; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.provider.CertificateNameOptions; +import org.opensaml.ws.security.provider.ClientCertAuthRule; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.trust.TrustEngine; +import org.opensaml.xml.security.x509.X509Credential; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML specialization of {@link ClientCertAuthRule} which provides support for X509Credential trust engine validation + * based on SAML metadta. + */ +public class SAMLMDClientCertAuthRule extends ClientCertAuthRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(SAMLMDClientCertAuthRule.class); + + /** + * Constructor. + * + * @param engine Trust engine used to verify the request X509Credential + * @param nameOptions options for deriving issuer names from an X.509 certificate + */ + public SAMLMDClientCertAuthRule(TrustEngine engine, CertificateNameOptions nameOptions) { + super(engine, nameOptions); + } + + /** {@inheritDoc} */ + protected CriteriaSet buildCriteriaSet(String entityID, MessageContext messageContext) + throws SecurityPolicyException { + + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Supplied message context was not an instance of SAMLMessageContext, can not build criteria set from SAML metadata parameters"); + throw new SecurityPolicyException("Supplied message context was not an instance of SAMLMessageContext"); + } + + SAMLMessageContext samlContext = (SAMLMessageContext) messageContext; + + CriteriaSet criteriaSet = super.buildCriteriaSet(entityID, messageContext); + MetadataCriteria mdCriteria = + new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext.getInboundSAMLProtocol()); + criteriaSet.add(mdCriteria); + + return criteriaSet; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/security/SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/security/SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/security/SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,171 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.binding.security; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.security.SAMLSignatureProfileValidator; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.xml.security.trust.TrustEngine; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML security policy rule which validates the signature (if present) on the {@link SAMLObject} which represents the + * SAML protocol message being processed. + * + *

+ * If the message is not an instance of {@link SignableSAMLObject}, then no processing is performed. If signature + * validation is successful, and the SAML message context issuer was not previously authenticated, then the context's + * issuer authentication state will be set to true. + *

+ * + *

+ * If an optional {@link Validator} for {@link Signature} objects is supplied, this validator will be used to validate + * the XML Signature element prior to the actual cryptographic validation of the signature. This might for example be + * used to enforce certain signature profile requirements or to detect signatures upon which it would be unsafe to + * attempt cryptographic processing. When using the single argument constructuor form, the validator will default to + * {@link SAMLSignatureProfileValidator}. + *

+ */ +public class SAMLProtocolMessageXMLSignatureSecurityPolicyRule extends BaseSAMLXMLSignatureSecurityPolicyRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(SAMLProtocolMessageXMLSignatureSecurityPolicyRule.class); + + /** Validator for XML Signature instances. */ + private Validator sigValidator; + + /** + * Constructor. + * + * Signature pre-validator defaults to {@link SAMLSignatureProfileValidator}. + * + * @param engine Trust engine used to verify the signature + */ + public SAMLProtocolMessageXMLSignatureSecurityPolicyRule(TrustEngine engine) { + super(engine); + sigValidator = new SAMLSignatureProfileValidator(); + } + + /** + * Constructor. + * + * @param engine Trust engine used to verify the signature + * @param signatureValidator optional pre-validator used to validate Signature elements prior to the actual + * cryptographic validation operation + */ + public SAMLProtocolMessageXMLSignatureSecurityPolicyRule(TrustEngine engine, + Validator signatureValidator) { + super(engine); + sigValidator = signatureValidator; + } + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext"); + return; + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject samlMsg = samlMsgCtx.getInboundSAMLMessage(); + if (!(samlMsg instanceof SignableSAMLObject)) { + log.debug("Extracted SAML message was not a SignableSAMLObject, can not process signature"); + return; + } + SignableSAMLObject signableObject = (SignableSAMLObject) samlMsg; + if (!signableObject.isSigned()) { + log.info("SAML protocol message was not signed, skipping XML signature processing"); + return; + } + Signature signature = signableObject.getSignature(); + + performPreValidation(signature); + + doEvaluate(signature, signableObject, samlMsgCtx); + } + + /** + * Perform cryptographic validation and trust evaluation on the Signature token using the configured Signature trust + * engine. + * + * @param signature the signature which is being evaluated + * @param signableObject the signable object which contained the signature + * @param samlMsgCtx the SAML message context being processed + * @throws SecurityPolicyException thrown if the signature fails validation + */ + protected void doEvaluate(Signature signature, SignableSAMLObject signableObject, SAMLMessageContext samlMsgCtx) + throws SecurityPolicyException { + + String contextIssuer = samlMsgCtx.getInboundMessageIssuer(); + if (contextIssuer != null) { + String msgType = signableObject.getElementQName().toString(); + log.debug("Attempting to verify signature on signed SAML protocol message using context issuer message type: {}", + msgType); + + if (evaluate(signature, contextIssuer, samlMsgCtx)) { + log.info("Validation of protocol message signature succeeded, message type: {}", msgType); + if (!samlMsgCtx.isInboundSAMLMessageAuthenticated()) { + log.debug("Authentication via protocol message signature succeeded for context issuer entity ID {}", + contextIssuer); + samlMsgCtx.setInboundSAMLMessageAuthenticated(true); + } + } else { + log.debug("Validation of protocol message signature failed for context issuer '" + contextIssuer + + "', message type: " + msgType); + throw new SecurityPolicyException("Validation of protocol message signature failed"); + } + } else { + log.debug("Context issuer unavailable, can not attempt SAML protocol message signature validation"); + throw new SecurityPolicyException("Context issuer unavailable, can not validate signature"); + } + } + + /** + * Get the validator used to perform pre-validation on Signature tokens. + * + * @return the configured Signature validator, or null + */ + protected Validator getSignaturePrevalidator() { + return sigValidator; + } + + /** + * Perform pre-validation on the Signature token. + * + * @param signature the signature to evaluate + * @throws SecurityPolicyException thrown if the signature element fails pre-validation + */ + protected void performPreValidation(Signature signature) throws SecurityPolicyException { + if (getSignaturePrevalidator() != null) { + try { + getSignaturePrevalidator().validate(signature); + } catch (ValidationException e) { + log.debug("Protocol message signature failed signature pre-validation", e); + throw new SecurityPolicyException("Protocol message signature failed signature pre-validation", e); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/binding/security/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/binding/security/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/binding/security/package.html 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,6 @@ + + +Classes responsible for performing transport-related and basic message +validation of decoded SAML messages. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObject.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.opensaml.xml.validation.AbstractValidatingXMLObject; + +/** + * An abstract implementation of SAMLObject. + */ +public abstract class AbstractSAMLObject extends AbstractValidatingXMLObject { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AbstractSAMLObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public final boolean equals(Object obj) { + if(obj == this){ + return true; + } + + return super.equals(obj); + } + + /** + * A helper function for derived classes that checks to see if the old and new value are equal and if so releases + * the cached dom. Derived classes are expected to use this thus: + * this.foo = prepareForAssignment(this.foo, foo); + * + * + * This method will do a (null) safe compare of the objects and will also invalidate the DOM if appropriate + * + * @param oldValue - current value + * @param newValue - proposed new value + * + * @return The value to assign to the saved Object. + */ + protected DateTime prepareForAssignment(DateTime oldValue, DateTime newValue) { + DateTime utcValue = null; + if (newValue != null) { + utcValue = newValue.withZone(DateTimeZone.UTC); + } + + return super.prepareForAssignment(oldValue, utcValue); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectBuilder.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.SAMLObjectBuilder; +import org.opensaml.xml.AbstractXMLObjectBuilder; + +/** + * Base builder for {@link org.opensaml.common.SAMLObject}s. + * + * @param the SAML object type built + */ +public abstract class AbstractSAMLObjectBuilder extends + AbstractXMLObjectBuilder implements SAMLObjectBuilder { + + /** + * Builds a SAMLObject using the default name and namespace information provided SAML specifications. + * + * @return built SAMLObject + */ + public abstract SAMLObjectType buildObject(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectMarshaller.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import org.opensaml.common.SAMLObjectHelper; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * A thread safe, abstract implementation of the {@link org.opensaml.xml.io.Marshaller} interface that handles most of + * the boilerplate code for Marshallers. + */ +public abstract class AbstractSAMLObjectMarshaller extends AbstractXMLObjectMarshaller { + + /** + * No-op method. Extending implementations should override this method if they have attributes to marshall into the + * Element. + * + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } + + /** + * No-op method. Extending implementations should override this method if they have text content to marshall into + * the Element. + * + * {@inheritDoc} + */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + + } + + /** {@inheritDoc} */ + public Element marshall(XMLObject xmlObject, Document document) throws MarshallingException { + if (xmlObject instanceof SignableSAMLObject) { + SAMLObjectHelper.declareNonVisibleNamespaces((SignableSAMLObject) xmlObject); + } + return super.marshall(xmlObject, document); + } + + /** {@inheritDoc} */ + public Element marshall(XMLObject xmlObject, Element parentElement) throws MarshallingException { + if (xmlObject instanceof SignableSAMLObject) { + SAMLObjectHelper.declareNonVisibleNamespaces((SignableSAMLObject) xmlObject); + } + return super.marshall(xmlObject, parentElement); + } + + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSAMLObjectUnmarshaller.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * An thread safe abstract unmarshaller. This abstract marshaller only works with + * {@link org.opensaml.common.impl.AbstractSAMLObject}. + */ +public abstract class AbstractSAMLObjectUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + } + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + } + + /** + * {@inheritDoc} + */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSignableSAMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSignableSAMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/AbstractSignableSAMLObject.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.xml.AbstractValidatingSignableXMLObject; +import org.opensaml.xml.signature.Signature; + +/** + * Abstract SAMLObject implementation that also implements {@link org.opensaml.xml.signature.SignableXMLObject}. + */ +public abstract class AbstractSignableSAMLObject extends AbstractValidatingSignableXMLObject implements + SignableSAMLObject { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AbstractSignableSAMLObject(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public final boolean equals(Object obj) { + if(obj == this){ + return true; + } + + return super.equals(obj); + } + + /** + * {@inheritDoc} + * + * When a signature is added, a default content reference that uses the ID of this object will be + * created and added to the signature at the time of signing. See {@link SAMLObjectContentReference} + * for the default digest algorithm and transforms that will be used. These default values may be + * changed prior to marshalling this object. + */ + public void setSignature(Signature newSignature) { + if(newSignature != null){ + newSignature.getContentReferences().add(new SAMLObjectContentReference(this)); + } + super.setSignature(newSignature); + } + + /** + * A helper function for derived classes that checks to see if the old and new value are equal and if so releases + * the cached dom. Derived classes are expected to use this thus: + * this.foo = prepareForAssignment(this.foo, foo); + * + * + * This method will do a (null) safe compare of the objects and will also invalidate the DOM if appropriate + * + * @param oldValue - current value + * @param newValue - proposed new value + * + * @return The value to assign to the saved Object + */ + protected DateTime prepareForAssignment(DateTime oldValue, DateTime newValue) { + DateTime utcValue = null; + if (newValue != null) { + utcValue = newValue.withZone(DateTimeZone.UTC); + } + + return super.prepareForAssignment(oldValue, utcValue); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/RandomIdentifierGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/RandomIdentifierGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/RandomIdentifierGenerator.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import java.util.Random; + +import org.bouncycastle.util.encoders.Hex; +import org.opensaml.common.IdentifierGenerator; + +/** + * Generates identifiers using random data obtained from a {@link java.util.Random} instance. + */ +public class RandomIdentifierGenerator implements IdentifierGenerator { + + /** Random number generator. */ + private static Random random; + + /** + * Constructor. + */ + public RandomIdentifierGenerator() { + random = new Random(); + } + + /** {@inheritDoc} */ + public String generateIdentifier() { + return generateIdentifier(16); + } + + /** {@inheritDoc} */ + public String generateIdentifier(int size) { + byte[] buf = new byte[size]; + random.nextBytes(buf); + return "_".concat(new String(Hex.encode(buf))); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/SAMLObjectContentReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/SAMLObjectContentReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/SAMLObjectContentReference.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,206 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import java.util.List; +import java.util.Set; + +import org.apache.xml.security.signature.XMLSignature; +import org.apache.xml.security.signature.XMLSignatureException; +import org.apache.xml.security.transforms.Transform; +import org.apache.xml.security.transforms.TransformationException; +import org.apache.xml.security.transforms.Transforms; +import org.apache.xml.security.transforms.params.InclusiveNamespaces; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.Namespace; +import org.opensaml.xml.NamespaceManager; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.security.SecurityConfiguration; +import org.opensaml.xml.signature.ContentReference; +import org.opensaml.xml.signature.SignatureConstants; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.LazyList; +import org.opensaml.xml.util.LazySet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A content reference for SAML objects that will be signed. The reference is created per the SAML specification. + * + *

+ * The default digest algorithm used is the value configured in the global security configuration's + * {@link SecurityConfiguration#getSignatureReferenceDigestMethod()}, if available, otherwise + * it will be {@link SignatureConstants#ALGO_ID_DIGEST_SHA1}. + *

+ * + *

+ * The default set of transforms applied consists of {@link SignatureConstants#TRANSFORM_ENVELOPED_SIGNATURE} + * and {@link SignatureConstants#TRANSFORM_C14N_EXCL_WITH_COMMENTS}. + *

+ * + *

+ * When generating an exclusive canonicalization transform, an inclusive namespace list is + * generated from the namespaces, retrieved from {@link org.opensaml.xml.XMLObject#getNamespaces()}, + * used by the SAML object to be signed and all of it's descendants. + *

+ * + *

+ * Note that the SAML specification states that: + * 1) an exclusive canonicalization transform (either with or without comments) SHOULD be used. + * 2) transforms other than enveloped signature and one of the two exclusive canonicalizations + * SHOULD NOT be used. + * Careful consideration should be made before deviating from these recommendations. + *

+ * + */ +public class SAMLObjectContentReference implements ContentReference { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SAMLObjectContentReference.class); + + /** SAMLObject this reference refers to. */ + private SignableSAMLObject signableObject; + + /** Algorithm used to digest the content. */ + private String digestAlgorithm; + + /** Transforms applied to the content. */ + private List transforms; + + /** + * Constructor. + * + * @param newSignableObject the SAMLObject this reference refers to + */ + public SAMLObjectContentReference(SignableSAMLObject newSignableObject) { + signableObject = newSignableObject; + transforms = new LazyList(); + + // Set defaults + if (Configuration.getGlobalSecurityConfiguration() != null ) { + digestAlgorithm = Configuration.getGlobalSecurityConfiguration().getSignatureReferenceDigestMethod(); + } + if (digestAlgorithm == null) { + digestAlgorithm = SignatureConstants.ALGO_ID_DIGEST_SHA1; + } + + transforms.add(SignatureConstants.TRANSFORM_ENVELOPED_SIGNATURE); + transforms.add(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); + } + + /** + * Gets the transforms applied to the content prior to digest generation. + * + * @return the transforms applied to the content prior to digest generation + */ + public List getTransforms() { + return transforms; + } + + /** + * Gets the algorithm used to digest the content. + * + * @return the algorithm used to digest the content + */ + public String getDigestAlgorithm() { + return digestAlgorithm; + } + + /** + * Sets the algorithm used to digest the content. + * + * @param newAlgorithm the algorithm used to digest the content + */ + public void setDigestAlgorithm(String newAlgorithm) { + digestAlgorithm = newAlgorithm; + } + + /** {@inheritDoc} */ + public void createReference(XMLSignature signature) { + try { + Transforms dsigTransforms = new Transforms(signature.getDocument()); + for (int i=0; i inclusiveNamespacePrefixes = new LazySet(); + populateNamespacePrefixes(inclusiveNamespacePrefixes, signableObject); + + if (inclusiveNamespacePrefixes != null && inclusiveNamespacePrefixes.size() > 0) { + InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(signature.getDocument(), + inclusiveNamespacePrefixes); + transform.getElement().appendChild(inclusiveNamespaces.getElement()); + } + } + + /** + * Populates the given set with the non-visibly used namespace prefixes used by the given XMLObject + * and all of its descendants, as determined by the signature content object's namespace manager. + * + * @param namespacePrefixes the namespace prefix set to be populated + * @param signatureContent the XMLObject whose namespace prefixes will be used to populate the set + */ + private void populateNamespacePrefixes(Set namespacePrefixes, XMLObject signatureContent) { + for (String prefix: signatureContent.getNamespaceManager().getNonVisibleNamespacePrefixes()) { + if (prefix != null) { + // For the default namespace prefix, exclusive c14n uses the special token "#default". + // Apache xmlsec requires this to be represented in the set with the + // (completely undocumented) string "xmlns". + if (NamespaceManager.DEFAULT_NS_TOKEN.equals(prefix)) { + namespacePrefixes.add("xmlns"); + } else { + namespacePrefixes.add(prefix); + } + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/SecureRandomIdentifierGenerator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/SecureRandomIdentifierGenerator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/SecureRandomIdentifierGenerator.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.impl; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import org.bouncycastle.util.encoders.Hex; +import org.opensaml.common.IdentifierGenerator; + +/** + * Generates identifiers using random data obtained from a {@link java.security.SecureRandom} instance. + */ +public class SecureRandomIdentifierGenerator implements IdentifierGenerator { + + /** Random number generator. */ + private static SecureRandom random; + + /** + * Constructor. + * + * @throws NoSuchAlgorithmException thrown if the SHA1PRNG algorithm is not supported by the JVM + */ + public SecureRandomIdentifierGenerator() throws NoSuchAlgorithmException { + random = SecureRandom.getInstance("SHA1PRNG"); + } + + /** + * Constructor. + * + * @param algorithm the random number generation algorithm to use + * + * @throws NoSuchAlgorithmException thrown if the algorithm is not supported by the JVM + */ + public SecureRandomIdentifierGenerator(String algorithm) throws NoSuchAlgorithmException { + random = SecureRandom.getInstance(algorithm); + } + + /** {@inheritDoc} */ + public String generateIdentifier() { + return generateIdentifier(16); + } + + /** {@inheritDoc} */ + public String generateIdentifier(int size) { + byte[] buf = new byte[size]; + random.nextBytes(buf); + return "_".concat(new String(Hex.encode(buf))); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/impl/package.html 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,14 @@ + + +Base classes for various SAMLObjects constructs. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/xml/SAMLConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/xml/SAMLConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/xml/SAMLConstants.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,247 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.xml; + +import org.opensaml.xml.util.XMLConstants; + +/** + * XML related constants used in the SAML specifications. +. */ +public class SAMLConstants extends XMLConstants{ + //**************************** + // HTTP Constants + //**************************** + /** HTTP Request Method - POST. */ + public static final String POST_METHOD = "POST"; + + /** HTTP Method - GET. */ + public static final String GET_METHOD = "GET"; + + //**************************** + // OpenSAML 2 + //**************************** + /** Directory, on the classpath, schemas are located in. */ + public static final String SCHEMA_DIR = "/schema/"; + + //**************************** + // Core XML + //**************************** + /** XML core schema system Id. */ + public static final String XML_SCHEMA_LOCATION = SCHEMA_DIR + "xml.xsd"; + + /** XML Signature schema Id. */ + public static final String XMLSIG_SCHEMA_LOCATION = SCHEMA_DIR + "xmldsig-core-schema.xsd"; + + /** XML Encryption schema Id. */ + public static final String XMLENC_SCHEMA_LOCATION = SCHEMA_DIR + "xenc-schema.xsd"; + + //**************************** + // SOAP + //**************************** + /** SOAP 1.1 schema Id. */ + public static final String SOAP11ENV_SCHEMA_LOCATION = SCHEMA_DIR + SCHEMA_DIR + "soap-envelope.xsd"; + + /** SOAP 1.1 Envelope XML namespace. */ + public static final String SOAP11ENV_NS = "http://schemas.xmlsoap.org/soap/envelope/"; + + /** SOAP 1.1 Envelope QName prefix. */ + public static final String SOAP11ENV_PREFIX = "SOAP-ENV"; + + /** Liberty PAOS XML Namespace. */ + public static final String PAOS_NS = "urn:liberty:paos:2003-08"; + + /** Liberty PAOS QName prefix. */ + public static final String PAOS_PREFIX = "paos"; + + //**************************** + // SAML 1.X + //**************************** + /** SAML 1.0 Assertion schema system Id. */ + public static final String SAML10_SCHEMA_LOCATION = SCHEMA_DIR + "cs-sstc-schema-assertion-01.xsd"; + + /** SAML 1.1 Assertion schema system Id. */ + public static final String SAML11_SCHEMA_LOCATION = SCHEMA_DIR + "cs-sstc-schema-assertion-1.1.xsd"; + + /** SAML 1.X XML namespace. */ + public static final String SAML1_NS = "urn:oasis:names:tc:SAML:1.0:assertion"; + + /** SAML 1.0 Protocol schema system Id. */ + public static final String SAML10P_SCHEMA_LOCATION = SCHEMA_DIR + "cs-sstc-schema-protocol-01.xsd"; + + /** SAML 1.1 Protocol schema system Id. */ + public static final String SAML11P_SCHEMA_LOCATION = SCHEMA_DIR + "cs-sstc-schema-protocol-1.1.xsd"; + + /** SAML 1.X protocol XML namespace. */ + public static final String SAML10P_NS = "urn:oasis:names:tc:SAML:1.0:protocol"; + + /** SAML 1.1 protocol XML namespace, used only in SAML 2 metadata protocolSupportEnumeration. */ + public static final String SAML11P_NS = "urn:oasis:names:tc:SAML:1.1:protocol"; + + /** SAML 1.X Protocol QName prefix. */ + public static final String SAML1P_PREFIX = "saml1p"; + + /** SAML 1.X Assertion QName prefix. */ + public static final String SAML1_PREFIX = "saml1"; + + /** SAML 1 Metadata extension XML namespace. */ + public static final String SAML1MD_NS = "urn:oasis:names:tc:SAML:profiles:v1metadata"; + + /** SAML 1 Metadata extension schema system Id. */ + public static final String SAML1MD_SCHEMA_LOCATION = SCHEMA_DIR + "sstc-saml1x-metadata.xsd"; + + /** SAML 1 Metadata extension namespace prefix. */ + public static final String SAML1MD_PREFIX = "saml1md"; + + /** URI for SAML 1 Artifact binding. */ + public static final String SAML1_ARTIFACT_BINDING_URI = "urn:oasis:names:tc:SAML:1.0:profiles:artifact-01"; + + /** URI for SAML 1 POST binding. */ + public static final String SAML1_POST_BINDING_URI = "urn:oasis:names:tc:SAML:1.0:profiles:browser-post"; + + /** URI for SAML 1 SOAP 1.1 binding. */ + public static final String SAML1_SOAP11_BINDING_URI = "urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding"; + + //**************************** + // SAML 2.0 + //**************************** + /** SAML 2.0 Assertion schema Id. */ + public static final String SAML20_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-assertion-2.0.xsd"; + + /** SAML 2.0 Assertion XML Namespace. */ + public static final String SAML20_NS = "urn:oasis:names:tc:SAML:2.0:assertion"; + + /** SAML 2.0 Assertion QName prefix. */ + public static final String SAML20_PREFIX ="saml2"; + + /** SAML 2.0 Protocol schema Id. */ + public static final String SAML20P_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-protocol-2.0.xsd"; + + /** SAML 2.0 Protocol XML Namespace. */ + public static final String SAML20P_NS = "urn:oasis:names:tc:SAML:2.0:protocol"; + + /** SAML 2.0 Protocol QName prefix. */ + public static final String SAML20P_PREFIX ="saml2p"; + + /** SAML 2.0 Protocol Third-party extension schema Id. */ + public static final String SAML20PTHRPTY_SCHEMA_LOCATION = SCHEMA_DIR + "sstc-saml-protocol-ext-thirdparty.xsd"; + + /** SAML 2.0 Protocol XML Namespace. */ + public static final String SAML20PTHRPTY_NS = "urn:oasis:names:tc:SAML:protocol:ext:third-party"; + + /** SAML 2.0 Protocol QName prefix. */ + public static final String SAML20PTHRPTY_PREFIX ="thrpty"; + + /** SAML 2.0 Metadata schema Id. */ + public static final String SAML20MD_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-metadata-2.0.xsd"; + + /** SAML 2.0 Metadata XML Namespace. */ + public static final String SAML20MD_NS ="urn:oasis:names:tc:SAML:2.0:metadata"; + + /** SAML 2.0 Standalone Query Metadata extension XML namespace. */ + public static final String SAML20MDQUERY_NS = "urn:oasis:names:tc:SAML:metadata:ext:query"; + + /** SAML 2.0 Standalone Query Metadata extension schema system Id. */ + public static final String SAML20MDQUERY_SCHEMA_LOCATION = SCHEMA_DIR + "sstc-saml-metadata-ext-query.xsd"; + + /** SAML 2.0 Standalone Query Metadata extension prefix. */ + public static final String SAML20MDQUERY_PREFIX = "query"; + + /** SAML 2.0 Metadata QName prefix. */ + public static final String SAML20MD_PREFIX = "md"; + + /** SAML 2.0 Authentication Context schema Id. */ + public static final String SAML20AC_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-authn-context-2.0.xsd"; + + /** SAML 2.0 Authentication Context XML Namespace. */ + public static final String SAML20AC_NS ="urn:oasis:names:tc:SAML:2.0:ac"; + + /** SAML 2.0 Authentication Context QName prefix. */ + public static final String SAML20AC_PREFIX = "ac"; + + /** SAML 2.0 Enhanced Client/Proxy SSO Profile schema Id. */ + public static final String SAML20ECP_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-ecp-2.0.xsd"; + + /** SAML 2.0 Enhanced Client/Proxy SSO Profile XML Namespace. */ + public static final String SAML20ECP_NS = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp"; + + /** SAML 2.0 Enhanced Client/Proxy SSO Profile QName prefix. */ + public static final String SAML20ECP_PREFIX = "ecp"; + + /** SAML 2.0 Condition for Delegation Restriction schema Id. */ + public static final String SAML20DEL_SCHEMA_LOCATION = SCHEMA_DIR + "sstc-saml-delegation.xsd"; + + /** SAML 2.0 Condition for Delegation Restriction XML Namespace. */ + public static final String SAML20DEL_NS = "urn:oasis:names:tc:SAML:2.0:conditions:delegation"; + + /** SAML 2.0 Condition for Delegation Restriction QName prefix. */ + public static final String SAML20DEL_PREFIX = "del"; + + /** SAML V2.0 Metadata Extension for Entity Attributes schema ID . */ + public static final String SAML20MDATTR_SCHEMA_LOCATION = SCHEMA_DIR + "sstc-metadata-attr.xsd"; + + /** SAML V2.0 Metadata Extension for Entity Attributes XML Namespace. */ + public static final String SAML20MDATTR_NS = "urn:oasis:names:tc:SAML:metadata:attribute"; + + /** SAML V2.0 Metadata Extension for Entity Attributes QName prefix. */ + public static final String SAML20MDATTR_PREFIX = "mdattr"; + + /** SAML 2.0 DCE PAC Attribute Profile schema Id. */ + public static final String SAML20DCE_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-dce-2.0.xsd"; + + /** SAML 2.0 DCE PAC Attribute Profile XML Namespace. */ + public static final String SAML20DCE_NS = "urn:oasis:names:tc:SAML:2.0:profiles:attribute:DCE"; + + /** SAML 2.0 DCE PAC Attribute Profile QName prefix. */ + public static final String SAML20DCE_PREFIX = "DCE"; + + /** SAML 2.0 X.500 Attribute Profile schema Id. */ + public static final String SAML20X500_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-x500-2.0.xsd"; + + /** SAML 2.0 X.500 Attribute Profile XML Namespace. */ + public static final String SAML20X500_NS = "urn:oasis:names:tc:SAML:2.0:profiles:attribute:X500"; + + /** SAML 2.0 X.500 Attribute Profile QName prefix. */ + public static final String SAML20X500_PREFIX = "x500"; + + /** SAML 2.0 XACML Attribute Profile schema Id. */ + public static final String SAML20XACML_SCHEMA_LOCATION = SCHEMA_DIR + "saml-schema-xacml-2.0.xsd"; + + /** SAML 2.0 XACML Attribute Profile XML Namespace. */ + public static final String SAML20XACML_NS = "urn:oasis:names:tc:SAML:2.0:profiles:attribute:XACML"; + + /** SAML 2.0 XACML Attribute Profile QName prefix. */ + public static final String SAML20XACML_PREFIX = "xacmlprof"; + + /** URI for SAML 2 Artifact binding. */ + public static final String SAML2_ARTIFACT_BINDING_URI = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"; + + /** URI for SAML 2 POST binding. */ + public static final String SAML2_POST_BINDING_URI = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"; + + /** URI for SAML 2 POST-SimpleSign binding. */ + public static final String SAML2_POST_SIMPLE_SIGN_BINDING_URI = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign"; + + /** URI for SAML 2 HTTP redirect binding. */ + public static final String SAML2_REDIRECT_BINDING_URI = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"; + + /** URI for SAML 2 SOAP binding. */ + public static final String SAML2_SOAP11_BINDING_URI = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP"; + + /** URI for SAML 2 PAOS binding. */ + public static final String SAML2_PAOS_BINDING_URI = "urn:oasis:names:tc:SAML:2.0:bindings:PAOS"; +} Index: 3rdParty_sources/opensaml/org/opensaml/common/xml/SAMLSchemaBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/xml/SAMLSchemaBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/xml/SAMLSchemaBuilder.java 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,238 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.common.xml; + +import java.lang.ref.SoftReference; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.XMLConstants; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.opensaml.xml.parse.ClasspathResolver; +import org.opensaml.xml.parse.LoggingErrorHandler; +import org.slf4j.LoggerFactory; +import org.xml.sax.SAXException; + +/** + * A convenience builder for creating {@link Schema}s for validating SAML 1_0, 1_1, and 2_0. + * + * Additional schema may be registered by {@link #addExtensionSchema(String)} with the given argument a relative or + * absolute path that will be resolved against the classpath. Note that relative paths are relative to this + * class. Also, schema files must be provided in the order they are referenced, that is if schema B depends on schema A + * then schema A must appear first in the list of registered extension schemas. + * + * Schemas may use a schema location attribute. These schema locations will be resolved by the {@link ClasspathResolver}. + * If schema locations are used they will be resolved and will meet the aformentioned schema ordering requirement. + * + * The schema objects produced here are thread safe and should be re-used, to that end the schema builder will cache + * created schema using {@link SoftReference}s, allowing the VM to reclaim the memory used by schemas if necessary. + */ +public final class SAMLSchemaBuilder { + + /** SAML 1_0 Schema with SAML 2_0 schemas and extensions. */ + private static SoftReference saml10Schema; + + /** SAML 1_0 Schema with SAML 2_0 schemas and extensions. */ + private static SoftReference saml11Schema; + + /** Classpath relative location of basic XML schemas. */ + private static String[] baseXMLSchemas = { "/schema/xml.xsd", "/schema/XMLSchema.xsd", + "/schema/xmldsig-core-schema.xsd", "/schema/xenc-schema.xsd", }; + + /** Classpath relative location of SOAP 1_1 schemas. */ + private static String[] soapSchemas = { "/schema/soap-envelope.xsd", }; + + /** Classpath relative location of SAML 1_0 schemas. */ + private static String[] saml10Schemas = { "/schema/cs-sstc-schema-assertion-01.xsd", + "/schema/cs-sstc-schema-protocol-01.xsd", }; + + /** Classpath relative location of SAML 1_1 schemas. */ + private static String[] saml11Schemas = { "/schema/cs-sstc-schema-assertion-1.1.xsd", + "/schema/cs-sstc-schema-protocol-1.1.xsd", }; + + /** Classpath relative location of SAML 2_0 schemas. */ + private static String[] saml20Schemas = { + "/schema/saml-schema-assertion-2.0.xsd", + "/schema/saml-schema-authn-context-2.0.xsd", + "/schema/saml-schema-authn-context-auth-telephony-2.0.xsd", + "/schema/saml-schema-authn-context-ip-2.0.xsd", + "/schema/saml-schema-authn-context-ippword-2.0.xsd", + "/schema/saml-schema-authn-context-kerberos-2.0.xsd", + "/schema/saml-schema-authn-context-mobileonefactor-reg-2.0.xsd", + "/schema/saml-schema-authn-context-mobileonefactor-unreg-2.0.xsd", + "/schema/saml-schema-authn-context-mobiletwofactor-reg-2.0.xsd", + "/schema/saml-schema-authn-context-mobiletwofactor-unreg-2.0.xsd", + "/schema/saml-schema-authn-context-nomad-telephony-2.0.xsd", + "/schema/saml-schema-authn-context-personal-telephony-2.0.xsd", + "/schema/saml-schema-authn-context-pgp-2.0.xsd", + "/schema/saml-schema-authn-context-ppt-2.0.xsd", + "/schema/saml-schema-authn-context-pword-2.0.xsd", + "/schema/saml-schema-authn-context-session-2.0.xsd", + "/schema/saml-schema-authn-context-smartcard-2.0.xsd", + "/schema/saml-schema-authn-context-smartcardpki-2.0.xsd", + "/schema/saml-schema-authn-context-softwarepki-2.0.xsd", + "/schema/saml-schema-authn-context-spki-2.0.xsd", + "/schema/saml-schema-authn-context-srp-2.0.xsd", + "/schema/saml-schema-authn-context-sslcert-2.0.xsd", + "/schema/saml-schema-authn-context-telephony-2.0.xsd", + "/schema/saml-schema-authn-context-timesync-2.0.xsd", + "/schema/saml-schema-authn-context-types-2.0.xsd", + "/schema/saml-schema-authn-context-x509-2.0.xsd", + "/schema/saml-schema-authn-context-xmldsig-2.0.xsd", + "/schema/saml-schema-dce-2.0.xsd", + "/schema/saml-schema-ecp-2.0.xsd", + "/schema/saml-schema-metadata-2.0.xsd", + "/schema/saml-schema-protocol-2.0.xsd", + "/schema/saml-schema-x500-2.0.xsd", + "/schema/saml-schema-xacml-2.0.xsd", + "/schema/sstc-saml-delegation.xsd", + "/schema/sstc-saml-idp-discovery.xsd", + "/schema/sstc-saml-metadata-ext-query.xsd", + "/schema/sstc-saml-protocol-ext-thirdparty.xsd", + "/schema/sstc-saml1x-metadata.xsd", + }; + + /** Classpath relative location of SAML extension schemas. */ + private static String[] baseExtSchemas = { "/schema/sstc-saml-protocol-ext-thirdparty.xsd", + "/schema/sstc-saml-metadata-ext-query.xsd", "/schema/sstc-saml1x-metadata.xsd", }; + + /** Additional schema locations relative to classpath. */ + private static List extensionSchema = new ArrayList(); + + /** Constructor. */ + private SAMLSchemaBuilder() { + + } + + /** + * Gets a schema that can validate SAML 1.0, 2.0, and all registered extensions. + * + * @return schema that can validate SAML 1.0, 2.0, and all registered extensions + * + * @throws SAXException thrown if a schema object can not be created + */ + public static synchronized Schema getSAML10Schema() throws SAXException { + if (saml10Schema == null || saml10Schema.get() == null) { + saml10Schema = new SoftReference(buildSchema(saml10Schemas)); + } + + return saml10Schema.get(); + } + + /** + * Gets a schema that can validate SAML 1.1, 2.0, and all registered extensions. + * + * @return schema that can validate SAML 1.1, 2.0, and all registered extensions + * + * @throws SAXException thrown if a schema object can not be created + */ + public static synchronized Schema getSAML11Schema() throws SAXException { + if (saml11Schema == null || saml11Schema.get() == null) { + saml11Schema = new SoftReference(buildSchema(saml11Schemas)); + } + + return saml11Schema.get(); + } + + /** + * Gets an unmodifiable list of currently registered schema extension. + * + * @return unmodifiable list of currently registered schema extension + */ + public static List getExtensionSchema() { + return Collections.unmodifiableList(extensionSchema); + } + + /** + * Registers a new schema extension. The schema location will be searched for on the classpath. + * + * @param schema new schema extension + */ + public static void addExtensionSchema(String schema) { + extensionSchema.add(schema); + + saml10Schema = null; + + saml11Schema = null; + } + + /** + * Removes a currently registered schema. + * + * @param schema currently registered schema + */ + public static void removeSchema(String schema) { + extensionSchema.remove(schema); + + synchronized (saml10Schema) { + saml10Schema = null; + } + + synchronized (saml11Schema) { + saml11Schema = null; + } + } + + /** + * Builds a schema object based on the given SAML 1_X schema set. + * + * @param saml1Schema SAML 1_X schema set + * + * @return constructed schema + * + * @throws SAXException thrown if a schema object can not be created + */ + private static Schema buildSchema(String[] saml1Schema) throws SAXException { + Class clazz = SAMLSchemaBuilder.class; + List schemaSources = new ArrayList(); + + for (String source : baseXMLSchemas) { + schemaSources.add(new StreamSource(clazz.getResourceAsStream(source))); + } + + for (String source : soapSchemas) { + schemaSources.add(new StreamSource(clazz.getResourceAsStream(source))); + } + + for (String source : saml1Schema) { + schemaSources.add(new StreamSource(clazz.getResourceAsStream(source))); + } + + for (String source : saml20Schemas) { + schemaSources.add(new StreamSource(clazz.getResourceAsStream(source))); + } + + for (String source : baseExtSchemas) { + schemaSources.add(new StreamSource(clazz.getResourceAsStream(source))); + } + + for (String source : extensionSchema) { + schemaSources.add(new StreamSource(clazz.getResourceAsStream(source))); + } + + SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + schemaFactory.setResourceResolver(new ClasspathResolver()); + schemaFactory.setErrorHandler(new LoggingErrorHandler(LoggerFactory.getLogger(clazz))); + return schemaFactory.newSchema(schemaSources.toArray(new StreamSource[0])); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/common/xml/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/common/xml/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/common/xml/package.html 17 Aug 2012 15:02:27 -0000 1.1 @@ -0,0 +1,14 @@ + + +Parser pool manager and SAML constants. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/SAML1ArtifactMessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/SAML1ArtifactMessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/SAML1ArtifactMessageContext.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding; + +import java.util.Collection; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.saml1.core.Assertion; + +/** + * Extensions to the base SAML message context that carries artifact related information. + * + * @param type of inbound SAML message + * @param type of outbound SAML message + * @param type of name identifier used for subjects + */ +public interface SAML1ArtifactMessageContext + extends SAMLMessageContext { + + /** + * Gets the Base64 encoded artifacts to be resolved. + * + * @return artifacts to be resolved + */ + public Collection getArtifacts(); + + /** + * Sets the Base64 encoded artifacts to be resolved. + * + * @param artifacts artifacts to be resolved + */ + public void setArtifacts(Collection artifacts); + + /** + * Gets the assertions dereferenced from the artifacts. + * + * @return assertions dereferenced from the artifacts + */ + public Collection getDereferencedAssertions(); + + /** + * Sets the assertions dereferenced from the artifacts. + * + * @param assertions assertions dereferenced from the artifacts + */ + public void setDereferencedAssertions(Collection assertions); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/package.html 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,12 @@ + + +Classes for working with SAML 1 bindings. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/AbstractSAML1Artifact.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/AbstractSAML1Artifact.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/AbstractSAML1Artifact.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.artifact; + +import org.opensaml.common.binding.artifact.AbstractSAMLArtifact; + +/** + * SAML 1 Artifact marker. + */ +public abstract class AbstractSAML1Artifact extends AbstractSAMLArtifact { + + /** + * Constructor. + * + * @param typeCode artifact type code + */ + protected AbstractSAML1Artifact(byte[] typeCode) { + super(typeCode); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactBuilder.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.artifact; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.saml1.core.Response; + +/** + * Builder of typed SAML 1 artifacts. + * + * Builders must be thread safe and reusable. + * + * @param type of artifact built by this builder + */ +public interface SAML1ArtifactBuilder { + + /** + * Builds an artifact, for the given assertion, destined for the outbound message recipient. + * + * @param requestContext request context + * @param assertion assertion to build artifact for + * + * @return constructed artifcate + */ + public ArtifactType buildArtifact(SAMLMessageContext requestContext, + Assertion assertion); + + /** + * Builds a populated artifact given the artifact's byte-array representation. + * + * @param artifact the byte representation of the artifact + * + * @return populated artifact + */ + public ArtifactType buildArtifact(byte[] artifact); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactBuilderFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactBuilderFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactBuilderFactory.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,90 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.artifact; + +import java.util.HashMap; +import java.util.Map; + +import org.opensaml.xml.util.Base64; + +/** + * Factory used to construct SAML 1 artifact builders. + */ +public class SAML1ArtifactBuilderFactory { + + /** Registered artifact builders. */ + private Map artifactBuilders; + + /** Constructor. */ + public SAML1ArtifactBuilderFactory() { + artifactBuilders = new HashMap(2); + artifactBuilders.put(new String(SAML1ArtifactType0001.TYPE_CODE), new SAML1ArtifactType0001Builder()); + artifactBuilders.put(new String(SAML1ArtifactType0002.TYPE_CODE), new SAML1ArtifactType0002Builder()); + } + + /** + * Gets the currently registered artifact builders. + * + * @return currently registered artifact builders + */ + public Map getArtifactBuilders() { + return artifactBuilders; + } + + /** + * Gets the artifact builder for the given type. + * + * @param type type of artifact to be built + * + * @return artifact builder for the given type + */ + public SAML1ArtifactBuilder getArtifactBuilder(byte[] type) { + return artifactBuilders.get(new String(type)); + } + + /** + * Convenience method for getting an artifact builder and parsing the given Base64 encoded artifact with it. + * + * @param base64Artifact Base64 encoded artifact to parse + * + * @return constructed artifact + */ + public AbstractSAML1Artifact buildArtifact(String base64Artifact){ + return buildArtifact(Base64.decode(base64Artifact)); + } + + /** + * Convenience method for getting an artifact builder and parsing the given artifact with it. + * + * @param artifact artifact to parse + * + * @return constructed artifact + */ + public AbstractSAML1Artifact buildArtifact(byte[] artifact) { + if(artifact == null){ + return null; + } + + byte[] type = new byte[2]; + type[0] = artifact[0]; + type[1] = artifact[1]; + + SAML1ArtifactBuilder artifactBuilder = getArtifactBuilder(type); + return artifactBuilder.buildArtifact(artifact); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0001.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0001.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0001.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.artifact; + +import java.util.Arrays; + +/** + * SAML 1.X Type 0x0001 Artifact. SAML 1, type 1, artifacts contains a 2 byte type code with a value of 1 followed by a + * 20 byte source ID followed by a 20 byte assertion handle. + */ +public class SAML1ArtifactType0001 extends AbstractSAML1Artifact { + + /** Artifact type code (0x0001). */ + public static final byte[] TYPE_CODE = { 0, 1 }; + + /** 20 byte artifact source ID. */ + private byte[] sourceID; + + /** 20 byte assertion handle. */ + private byte[] assertionHandle; + + /** Constructor. */ + public SAML1ArtifactType0001() { + super(TYPE_CODE); + } + + /** + * Constructor. + * + * @param source 20 byte source ID of the artifact + * @param handle 20 byte assertion handle of the artifact + * + * @throws IllegalArgumentException thrown if the given source ID or message handle are not of the current length + * (20 bytes) + */ + public SAML1ArtifactType0001(byte[] source, byte[] handle) { + super(TYPE_CODE); + + setSourceID(source); + setAssertionHandle(handle); + } + + /** + * Constructs a SAML 1 artifact from its byte array representation. + * + * @param artifact the byte array representing the artifact + * + * @return the artifact created from the byte array + * + * @throws IllegalArgumentException thrown if the artifact is not the right type or lenght (42 bytes) or is not of + * the correct type (0x0001) + */ + public static SAML1ArtifactType0001 parseArtifact(byte[] artifact) { + if (artifact.length != 42) { + throw new IllegalArgumentException("Artifact length must be 42 bytes it was " + artifact.length + "bytes"); + } + + byte[] typeCode = { artifact[0], artifact[1] }; + if (!Arrays.equals(typeCode, TYPE_CODE)) { + throw new IllegalArgumentException("Artifact is not of appropriate type."); + } + + byte[] sourceID = new byte[20]; + System.arraycopy(artifact, 2, sourceID, 0, 20); + + byte[] assertionHandle = new byte[20]; + System.arraycopy(artifact, 22, assertionHandle, 0, 20); + + return new SAML1ArtifactType0001(sourceID, assertionHandle); + } + + /** + * Gets the 20 byte source ID of the artifact. + * + * @return the source ID of the artifact + */ + public byte[] getSourceID() { + return sourceID; + } + + /** + * Sets the 20 byte source ID of the artifact. + * + * @param newSourceID 20 byte source ID of the artifact + * + * @throws IllegalArgumentException thrown if the given source ID is not 20 bytes + */ + protected void setSourceID(byte[] newSourceID) { + if (newSourceID.length != 20) { + throw new IllegalArgumentException("Artifact source ID must be 20 bytes long"); + } + sourceID = newSourceID; + } + + /** + * Gets the artifiact's 20 byte assertion handle. + * + * @return artifiact's 20 byte assertion handle + */ + public byte[] getAssertionHandle() { + return assertionHandle; + } + + /** + * Sets the artifiact's 20 byte assertion handle. + * + * @param handle artifiact's 20 byte assertion handle + */ + public void setAssertionHandle(byte[] handle) { + if (handle.length != 20) { + throw new IllegalArgumentException("Artifact assertion handle must be 20 bytes long"); + } + assertionHandle = handle; + } + + /** {@inheritDoc} */ + public byte[] getRemainingArtifact() { + byte[] remainingArtifact = new byte[40]; + + System.arraycopy(getSourceID(), 0, remainingArtifact, 0, 20); + System.arraycopy(getAssertionHandle(), 0, remainingArtifact, 20, 20); + + return remainingArtifact; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0001Builder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0001Builder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0001Builder.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.artifact; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.saml1.core.Response; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Builder of SAML 1, type 0x001, artifacts. + */ +public class SAML1ArtifactType0001Builder implements SAML1ArtifactBuilder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SAML1ArtifactType0001Builder.class); + + /** {@inheritDoc} */ + public SAML1ArtifactType0001 buildArtifact(byte[] artifact) { + return SAML1ArtifactType0001.parseArtifact(artifact); + } + + /** {@inheritDoc} */ + public SAML1ArtifactType0001 buildArtifact( + SAMLMessageContext requestContext, Assertion assertion) { + try { + MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1"); + byte[] source = sha1Digester.digest(requestContext.getLocalEntityId().getBytes()); + + SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG"); + byte[] assertionHandle = new byte[20]; + handleGenerator.nextBytes(assertionHandle); + + return new SAML1ArtifactType0001(source, assertionHandle); + } catch (NoSuchAlgorithmException e) { + log.error("JVM does not support required cryptography algorithms.", e); + throw new InternalError("JVM does not support required cryptography algorithms: SHA-1 and/or SHA1PRNG."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0002.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0002.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0002.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,140 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.artifact; + +import java.util.Arrays; + +import org.opensaml.xml.util.DatatypeHelper; + +/** + * SAML 1 Type 0x0002 Artifact. SAML 1, type 2, artifacts contains a 2 byte type code with a value of 1 followed by a 20 + * byte assertion handle followed by an unspecified number of bytes which are a UTF-8 encoded source location string. + */ +public class SAML1ArtifactType0002 extends AbstractSAML1Artifact { + + /** Artifact type code (0x0002). */ + public static final byte[] TYPE_CODE = { 0, 2 }; + + /** 20 byte assertion handle. */ + private byte[] assertionHandle; + + /** Artifact source location component. */ + private String sourceLocation; + + /** Constructor. */ + public SAML1ArtifactType0002() { + super(TYPE_CODE); + } + + /** + * Constructor. + * + * @param handle 20 byte assertion handle artifact component + * @param location source location artifact component + * + * @throws IllegalArgumentException thrown if the given assertion handle is not 20 bytes or the source location is + * null or empty + */ + public SAML1ArtifactType0002(byte[] handle, String location) { + super(TYPE_CODE); + + setAssertionHandle(handle); + setSourceLocation(location); + } + + /** + * Constructs a SAML 1 artifact from its byte representation. + * + * @param artifact the byte array representing the artifact + * @return the artifact parsed from the byte representation + * + * @throws IllegalArgumentException thrown if the artifact type is not 0x0002 + */ + public static SAML1ArtifactType0002 parseArtifact(byte[] artifact) { + byte[] typeCode = { artifact[0], artifact[1] }; + if (!Arrays.equals(typeCode, TYPE_CODE)) { + throw new IllegalArgumentException("Artifact is not of appropriate type."); + } + + byte[] assertionHandle = new byte[20]; + System.arraycopy(artifact, 2, assertionHandle, 0, 20); + + int locationLength = artifact.length - 22; + byte[] sourceLocation = new byte[locationLength]; + System.arraycopy(artifact, 22, sourceLocation, 0, locationLength); + + return new SAML1ArtifactType0002(assertionHandle, new String(sourceLocation)); + } + + /** + * Gets the artifiact's 20 byte assertion handle. + * + * @return artifiact's 20 byte assertion handle + */ + public byte[] getAssertionHandle() { + return assertionHandle; + } + + /** + * Sets the artifiact's 20 byte assertion handle. + * + * @param handle artifiact's 20 byte assertion handle + */ + public void setAssertionHandle(byte[] handle) { + if (handle.length != 20) { + throw new IllegalArgumentException("Artifact assertion handle must be 20 bytes long"); + } + assertionHandle = handle; + } + + /** + * Gets the source location component of this artifact. + * + * @return source location component of this artifact + */ + public String getSourceLocation() { + return sourceLocation; + } + + /** + * Sets source location component of this artifact. + * + * @param newLocation source location component of this artifact + * + * @throws IllegalArgumentException thrown if the given location is empty or null + */ + protected void setSourceLocation(String newLocation) { + String location = DatatypeHelper.safeTrimOrNullString(newLocation); + if (location == null) { + throw new IllegalArgumentException("Artifact source location may not be a null or empty string"); + } + + sourceLocation = location; + } + + /** {@inheritDoc} */ + public byte[] getRemainingArtifact() { + byte[] location = getSourceLocation().getBytes(); + byte[] remainingArtifact = new byte[20 + location.length]; + + System.arraycopy(getAssertionHandle(), 0, remainingArtifact, 0, 20); + System.arraycopy(location, 0, remainingArtifact, 20, location.length); + + return remainingArtifact; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0002Builder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0002Builder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/SAML1ArtifactType0002Builder.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.artifact; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import org.opensaml.common.binding.BasicEndpointSelector; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.saml1.core.Response; +import org.opensaml.saml2.metadata.ArtifactResolutionService; +import org.opensaml.saml2.metadata.Endpoint; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 1, type 0x0002, artifact builder. + */ +public class SAML1ArtifactType0002Builder implements SAML1ArtifactBuilder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SAML1ArtifactType0002Builder.class); + + /** {@inheritDoc} */ + public SAML1ArtifactType0002 buildArtifact(byte[] artifact) { + return SAML1ArtifactType0002.parseArtifact(artifact); + } + + /** {@inheritDoc} */ + public SAML1ArtifactType0002 buildArtifact( + SAMLMessageContext requestContext, Assertion assertion) { + try { + String sourceLocation = getSourceLocation(requestContext); + if (sourceLocation == null) { + return null; + } + + SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG"); + byte[] assertionHandle = new byte[20]; + handleGenerator.nextBytes(assertionHandle); + return new SAML1ArtifactType0002(assertionHandle, sourceLocation); + } catch (NoSuchAlgorithmException e) { + log.error("JVM does not support required cryptography algorithms: SHA1PRNG.", e); + throw new InternalError("JVM does not support required cryptography algorithms: SHA1PRNG."); + } + } + + /** + * Gets the source location used to for the artifacts created by this encoder. + * + * @param requestContext current request context + * + * @return source location used to for the artifacts created by this encoder + */ + protected String getSourceLocation(SAMLMessageContext requestContext) { + BasicEndpointSelector selector = new BasicEndpointSelector(); + selector.setEndpointType(ArtifactResolutionService.DEFAULT_ELEMENT_NAME); + selector.getSupportedIssuerBindings().add(SAMLConstants.SAML1_SOAP11_BINDING_URI); + selector.setMetadataProvider(requestContext.getMetadataProvider()); + selector.setEntityMetadata(requestContext.getLocalEntityMetadata()); + selector.setEntityRoleMetadata(requestContext.getLocalEntityRoleMetadata()); + + Endpoint acsEndpoint = selector.selectEndpoint(); + + if (acsEndpoint == null) { + log.error("Unable to select source location for artifact. No artifact resolution service defined for issuer."); + return null; + } + + return acsEndpoint.getLocation(); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/artifact/package.html 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,5 @@ + + +Classes that may be used to create and manipulate SAML artifacts. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/BaseSAML1MessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/BaseSAML1MessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/BaseSAML1MessageDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,362 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.decoding; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.artifact.SAMLArtifactMap; +import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry; +import org.opensaml.common.binding.decoding.BaseSAMLMessageDecoder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.AssertionArtifact; +import org.opensaml.saml1.core.AttributeQuery; +import org.opensaml.saml1.core.AuthorizationDecisionQuery; +import org.opensaml.saml1.core.Request; +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.saml1.core.Response; +import org.opensaml.saml1.core.ResponseAbstractType; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for SAML 1 message decoders. + */ +public abstract class BaseSAML1MessageDecoder extends BaseSAMLMessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseSAML1MessageDecoder.class); + + /** Map used to map artifacts to SAML. */ + private SAMLArtifactMap artifactMap; + + /** Whether to use the resource of an attribute query as the relying party entity ID. */ + private boolean useQueryResourceAsEntityId; + + /** Constructor. */ + public BaseSAML1MessageDecoder() { + super(); + useQueryResourceAsEntityId = true; + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public BaseSAML1MessageDecoder(ParserPool pool) { + super(pool); + useQueryResourceAsEntityId = true; + } + + /** + * Constructor. + * + * @param map used to map artifacts to SAML + * + * @deprecated + */ + public BaseSAML1MessageDecoder(SAMLArtifactMap map) { + super(); + artifactMap = map; + useQueryResourceAsEntityId = true; + } + + /** + * Constructor. + * + * @param map used to map artifacts to SAML + * @param pool parser pool used to deserialize messages + * + * @deprecated + */ + public BaseSAML1MessageDecoder(SAMLArtifactMap map, ParserPool pool) { + super(pool); + artifactMap = map; + useQueryResourceAsEntityId = true; + } + + /** {@inheritDoc} */ + public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException { + super.decode(messageContext); + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + if (samlMsgCtx.getInboundSAMLMessage() instanceof ResponseAbstractType) { + checkEndpointURI(samlMsgCtx); + } + } + + /** + * Gets the artifact map used to retrieve SAML information from an artifact. + * + * @return artifact map used to retrieve SAML information from an artifact + */ + public SAMLArtifactMap getArtifactMap() { + return artifactMap; + } + + /** + * Gets whether to use the Resource attribute of some SAML 1 queries as the entity ID of the inbound message issuer. + * + * @return whether to use the Resource attribute of some SAML 1 queries as the entity ID of the inbound message + * issuer + */ + public boolean getUseQueryResourceAsEntityId() { + return useQueryResourceAsEntityId; + } + + /** + * Sets whether to use the Resource attribute of some SAML 1 queries as the entity ID of the inbound message issuer. + * + * @param useResource whether to use the Resource attribute of some SAML 1 queries as the entity ID of the inbound + * message issuer + */ + public void setUseQueryResourceAsEntityId(boolean useResource) { + useQueryResourceAsEntityId = useResource; + } + + /** + * Populates the message context with the message ID, issue instant, and issuer as well as the peer's entity + * descriptor if a metadata provider is present in the message context and the peer's role descriptor if its entity + * descriptor was retrieved and the message context has a populated peer role name. + * + * @param messageContext message context to populate + * + * @throws MessageDecodingException thrown if there is a problem populating the message context + */ + protected void populateMessageContext(SAMLMessageContext messageContext) throws MessageDecodingException { + populateMessageIdIssueInstantIssuer(messageContext); + populateRelyingPartyMetadata(messageContext); + } + + /** + * Extracts the message ID, issue instant, and issuer from the incoming SAML message and populates the message + * context with it. + * + * @param messageContext current message context + * + * @throws MessageDecodingException thrown if there is a problem populating the message context + */ + protected void populateMessageIdIssueInstantIssuer(SAMLMessageContext messageContext) + throws MessageDecodingException { + SAMLObject samlMsg = messageContext.getInboundSAMLMessage(); + if (samlMsg == null) { + return; + } + + if (samlMsg instanceof RequestAbstractType) { + log.debug("Extracting ID, issuer and issue instant from request"); + extractRequestInfo(messageContext, (RequestAbstractType) samlMsg); + } else if (samlMsg instanceof Response) { + log.debug("Extracting ID, issuer and issue instant from response"); + extractResponseInfo(messageContext, (Response) samlMsg); + } else { + throw new MessageDecodingException("SAML 1.x message was not a request or a response"); + } + } + + /** + * Extract information from a SAML RequestAbstractType message. + * + * @param messageContext current message context + * @param abstractRequest the SAML message to process + */ + protected void extractRequestInfo(SAMLMessageContext messageContext, RequestAbstractType abstractRequest) { + messageContext.setInboundSAMLMessageId(abstractRequest.getID()); + messageContext.setInboundSAMLMessageIssueInstant(abstractRequest.getIssueInstant()); + + if (abstractRequest instanceof Request) { + Request request = (Request) abstractRequest; + if (request.getAttributeQuery() != null) { + extractAttributeQueryInfo(messageContext, request.getAttributeQuery()); + } + + if (request.getAuthorizationDecisionQuery() != null) { + extractAuthorizationDecisionQueryInfo(messageContext, request.getAuthorizationDecisionQuery()); + } + + if (request.getAssertionArtifacts() != null) { + extractAssertionArtifactInfo(messageContext, request.getAssertionArtifacts()); + } + } + } + + /** + * Extract the issuer, and populate message context, from the Resource attribute of the Attribute query if + * {@link #useQueryResourceAsEntityId} is true. + * + * @param messageContext current message context + * @param query query to extract resource name from + */ + protected void extractAttributeQueryInfo(SAMLMessageContext messageContext, AttributeQuery query) { + if (useQueryResourceAsEntityId) { + log.debug("Attempting to extract issuer from SAML 1 AttributeQuery Resource attribute"); + String resource = DatatypeHelper.safeTrimOrNullString(query.getResource()); + + if (resource != null) { + messageContext.setInboundMessageIssuer(resource); + log.debug("Extracted issuer from SAML 1.x AttributeQuery: {}", resource); + } + } + } + + /** + * Extract the issuer, and populate message context, from the Resource attribute of the AuthorizationDecisionQuery + * query if {@link #useQueryResourceAsEntityId} is true. + * + * @param messageContext current message context + * @param query query to extract resource name from + */ + protected void extractAuthorizationDecisionQueryInfo(SAMLMessageContext messageContext, + AuthorizationDecisionQuery query) { + if (useQueryResourceAsEntityId) { + log.debug("Attempting to extract issuer from SAML 1 AuthorizationDecisionQuery Resource attribute"); + String resource = DatatypeHelper.safeTrimOrNullString(query.getResource()); + + if (resource != null) { + messageContext.setInboundMessageIssuer(resource); + log.debug("Extracted issuer from SAML 1.x AuthorizationDecisionQuery: {}", resource); + } + } + } + + /** + * Extract the issuer, and populate message context, as the relying party corresponding to the first + * AssertionArtifact in the message. + * + * @param messageContext current message context + * @param artifacts AssertionArtifacts in the request + */ + protected void extractAssertionArtifactInfo(SAMLMessageContext messageContext, List artifacts) { + if (artifacts.size() == 0) { + return; + } + + log.debug("Attempting to extract issuer based on first AssertionArtifact in request"); + AssertionArtifact artifact = artifacts.get(0); + SAMLArtifactMapEntry artifactEntry = artifactMap.get(artifact.getAssertionArtifact()); + messageContext.setInboundMessageIssuer(artifactEntry.getRelyingPartyId()); + + log.debug("Extracted issuer from SAML 1.x AssertionArtifact: {}", messageContext.getInboundMessageIssuer()); + } + + /** + * Extract information from a SAML StatusResponse message. + * + * @param messageContext current message context + * @param response the SAML message to process + * + * @throws MessageDecodingException thrown if the assertions within the response contain differening issuer IDs + */ + protected void extractResponseInfo(SAMLMessageContext messageContext, Response response) + throws MessageDecodingException { + + messageContext.setInboundSAMLMessageId(response.getID()); + messageContext.setInboundSAMLMessageIssueInstant(response.getIssueInstant()); + + String issuer = null; + List assertions = ((Response) response).getAssertions(); + if (assertions != null && assertions.size() > 0) { + log.info("Attempting to extract issuer from enclosed SAML 1.x Assertion(s)"); + for (Assertion assertion : assertions) { + if (assertion != null && assertion.getIssuer() != null) { + if (issuer != null && !issuer.equals(assertion.getIssuer())) { + throw new MessageDecodingException("SAML 1.x assertions, within response " + response.getID() + + " contain different issuer IDs"); + } + issuer = assertion.getIssuer(); + } + } + } + + if (issuer == null) { + log.warn("Issuer could not be extracted from standard SAML 1.x response message"); + } + + messageContext.setInboundMessageIssuer(issuer); + } + + /** + * Populates the peer's entity metadata if a metadata provide is present in the message context. Populates the + * peer's role descriptor if the entity metadata was available and the role name is present in the message context. + * + * @param messageContext current message context + * + * @throws MessageDecodingException thrown if there is a problem populating the message context + */ + protected void populateRelyingPartyMetadata(SAMLMessageContext messageContext) throws MessageDecodingException { + MetadataProvider metadataProvider = messageContext.getMetadataProvider(); + try { + if (metadataProvider != null) { + EntityDescriptor relyingPartyMD = metadataProvider.getEntityDescriptor(messageContext + .getInboundMessageIssuer()); + messageContext.setPeerEntityMetadata(relyingPartyMD); + + QName relyingPartyRole = messageContext.getPeerEntityRole(); + if (relyingPartyMD != null && relyingPartyRole != null) { + List roles = relyingPartyMD.getRoleDescriptors(relyingPartyRole, + SAMLConstants.SAML11P_NS); + if (roles != null && roles.size() > 0) { + messageContext.setPeerEntityRoleMetadata(roles.get(0)); + } + } + } + } catch (MetadataProviderException e) { + log.error("Error retrieving metadata for relying party " + messageContext.getInboundMessageIssuer(), e); + throw new MessageDecodingException("Error retrieving metadata for relying party " + + messageContext.getInboundMessageIssuer(), e); + } + } + + /** + * {@inheritDoc} + * + *

This SAML 1-specific implementation extracts the value of the ResponseAbstractType + * protocol message Recipient attribute.

+ * + * */ + protected String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) throws MessageDecodingException { + SAMLObject samlMessage = samlMsgCtx.getInboundSAMLMessage(); + String messageDestination = null; + if (samlMessage instanceof ResponseAbstractType) { + ResponseAbstractType response = (ResponseAbstractType) samlMessage; + messageDestination = DatatypeHelper.safeTrimOrNullString(response.getRecipient()); + } else if (samlMessage instanceof RequestAbstractType) { + // don't treat as an error, just return null + return null; + } else { + log.error("Invalid SAML message type encountered: {}", samlMessage.getElementQName().toString()); + throw new MessageDecodingException("Invalid SAML message type encountered"); + } + return messageDestination; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPArtifactDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPArtifactDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPArtifactDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,130 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.decoding; + +import java.util.List; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.artifact.SAMLArtifactMap; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 1.X HTTP Artifact message decoder. + * + * NOTE: This decoder is not yet implemented. + */ +public class HTTPArtifactDecoder extends BaseSAML1MessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPArtifactDecoder.class); + + /** + * Constructor. + * + * @param map used to map artifacts to SAML + * @param pool parser pool used to deserialize messages + */ + public HTTPArtifactDecoder(SAMLArtifactMap map, ParserPool pool) { + super(map, pool); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML1_ARTIFACT_BINDING_URI; + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this decoder only support SAMLMessageContext"); + throw new MessageDecodingException( + "Invalid message context type, this decoder only support SAMLMessageContext"); + } + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + decodeTarget(samlMsgCtx); + processArtifacts(samlMsgCtx); + + populateMessageContext(samlMsgCtx); + } + + /** + * Decodes the TARGET parameter and adds it to the message context. + * + * @param samlMsgCtx current message context + * + * @throws MessageDecodingException thrown if there is a problem decoding the TARGET parameter. + */ + protected void decodeTarget(SAMLMessageContext samlMsgCtx) throws MessageDecodingException { + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + + String target = DatatypeHelper.safeTrim(inTransport.getParameterValue("TARGET")); + if (target == null) { + log.error("URL TARGET parameter was missing or did not contain a value."); + throw new MessageDecodingException("URL TARGET parameter was missing or did not contain a value."); + } + samlMsgCtx.setRelayState(target); + } + + /** + * Process the incoming artifacts by decoding the artifacts, dereferencing them from the artifact source and + * storing the resulting response (with assertions) in the message context. + * + * @param samlMsgCtx current message context + * + * @throws MessageDecodingException thrown if there is a problem decoding or dereferencing the artifacts + */ + protected void processArtifacts(SAMLMessageContext samlMsgCtx) throws MessageDecodingException { + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + List encodedArtifacts = inTransport.getParameterValues("SAMLart"); + if (encodedArtifacts == null || encodedArtifacts.size() == 0) { + log.error("URL SAMLart parameter was missing or did not contain a value."); + throw new MessageDecodingException("URL SAMLart parameter was missing or did not contain a value."); + } + + // TODO decode artifact(s); resolve issuer resolution endpoint; dereference using + // Request/AssertionArtifact(s) over synchronous backchannel binding; + // store response as the inbound SAML message. + } + + /** {@inheritDoc} */ + protected boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx) { + return false; + } + + /** {@inheritDoc} */ + protected String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) throws MessageDecodingException { + // Not relevant in this binding/profile, there is neither SAML message + // nor binding parameter with this information + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPPostDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPPostDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPPostDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.decoding; + +import java.io.ByteArrayInputStream; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.artifact.SAMLArtifactMap; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.ResponseAbstractType; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 1.X HTTP POST message decoder. + */ +public class HTTPPostDecoder extends BaseSAML1MessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPPostDecoder.class); + + /** Constructor. */ + public HTTPPostDecoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPPostDecoder(ParserPool pool) { + super(pool); + } + + /** + * Constructor. + * + * @param map Artifact to SAML map + * + * @deprecated + */ + public HTTPPostDecoder(SAMLArtifactMap map) { + super(map); + } + + /** + * Constructor. + * + * @param map used to map artifacts to SAML + * @param pool parser pool used to deserialize messages + * + * @deprecated + */ + public HTTPPostDecoder(SAMLArtifactMap map, ParserPool pool) { + super(map, pool); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML1_POST_BINDING_URI; + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this decoder only support SAMLMessageContext"); + throw new MessageDecodingException( + "Invalid message context type, this decoder only support SAMLMessageContext"); + } + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) { + throw new MessageDecodingException("This message deocoder only supports the HTTP POST method"); + } + + String relayState = inTransport.getParameterValue("TARGET"); + samlMsgCtx.setRelayState(relayState); + log.debug("Decoded SAML relay state (TARGET parameter) of: {}", relayState); + + String base64Message = inTransport.getParameterValue("SAMLResponse"); + byte[] decodedBytes = Base64.decode(base64Message); + if (decodedBytes == null) { + log.error("Unable to Base64 decode SAML message"); + throw new MessageDecodingException("Unable to Base64 decode SAML message"); + } + + SAMLObject inboundMessage = (SAMLObject) unmarshallMessage(new ByteArrayInputStream(decodedBytes)); + samlMsgCtx.setInboundMessage(inboundMessage); + samlMsgCtx.setInboundSAMLMessage(inboundMessage); + log.debug("Decoded SAML message"); + + populateMessageContext(samlMsgCtx); + } + + /** {@inheritDoc} */ + protected boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx) { + return samlMsgCtx.getInboundSAMLMessage() instanceof ResponseAbstractType; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPSOAP11Decoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPSOAP11Decoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/HTTPSOAP11Decoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,207 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.decoding; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.artifact.SAMLArtifactMap; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.LazyList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 1.1 HTTP SOAP 1.1 binding decoder. + */ +public class HTTPSOAP11Decoder extends BaseSAML1MessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPSOAP11Decoder.class); + + /** QNames of understood SOAP headers. */ + private List understoodHeaders; + + /** QName of SOAP mustUnderstand header attribute. */ + private final QName soapMustUnderstand = new QName(SAMLConstants.SOAP11ENV_NS, "mustUnderstand"); + + /** Constructor. */ + public HTTPSOAP11Decoder() { + super(); + understoodHeaders = new LazyList(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPSOAP11Decoder(ParserPool pool) { + super(pool); + understoodHeaders = new LazyList(); + } + + /** + * Constructor. + * + * @param map Artifact to SAML map + * + * @deprecated + */ + public HTTPSOAP11Decoder(SAMLArtifactMap map) { + super(map); + understoodHeaders = new LazyList(); + } + + /** + * Constructor. + * + * @param map used to map artifacts to SAML + * @param pool parser pool used to deserialize messages + * + * @deprecated + */ + public HTTPSOAP11Decoder(SAMLArtifactMap map, ParserPool pool) { + super(map, pool); + understoodHeaders = new LazyList(); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML1_SOAP11_BINDING_URI; + } + + /** + * Gets the SOAP header names that are understood by the application. + * + * @return SOAP header names that are understood by the application + */ + public List getUnderstoodHeaders() { + return understoodHeaders; + } + + /** + * Sets the SOAP header names that are understood by the application. + * + * @param headerNames SOAP header names that are understood by the application + */ + public void setUnderstoodHeaders(List headerNames) { + understoodHeaders.clear(); + if (headerNames != null) { + understoodHeaders.addAll(headerNames); + } + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this decoder only support SAMLMessageContext"); + throw new MessageDecodingException( + "Invalid message context type, this decoder only support SAMLMessageContext"); + } + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) { + throw new MessageDecodingException("This message deocoder only supports the HTTP POST method"); + } + + log.debug("Unmarshalling SOAP message"); + Envelope soapMessage = (Envelope) unmarshallMessage(inTransport.getIncomingStream()); + samlMsgCtx.setInboundMessage(soapMessage); + + Header messageHeader = soapMessage.getHeader(); + if (messageHeader != null) { + checkUnderstoodSOAPHeaders(soapMessage.getHeader().getUnknownXMLObjects()); + } + + List soapBodyChildren = soapMessage.getBody().getUnknownXMLObjects(); + if (soapBodyChildren.size() < 1 || soapBodyChildren.size() > 1) { + log.error("Unexpected number of children in the SOAP body, " + soapBodyChildren.size() + + ". Unable to extract SAML message"); + throw new MessageDecodingException( + "Unexpected number of children in the SOAP body, unable to extract SAML message"); + } + + XMLObject incommingMessage = soapBodyChildren.get(0); + if (!(incommingMessage instanceof SAMLObject)) { + log.error("Unexpected SOAP body content. Expected a SAML request but recieved {}", incommingMessage + .getElementQName()); + throw new MessageDecodingException("Unexpected SOAP body content. Expected a SAML request but recieved " + + incommingMessage.getElementQName()); + } + + SAMLObject samlMessage = (SAMLObject) incommingMessage; + log.debug("Decoded SOAP messaged which included SAML message of type {}", samlMessage.getElementQName()); + samlMsgCtx.setInboundSAMLMessage(samlMessage); + + populateMessageContext(samlMsgCtx); + } + + /** + * Checks that, if any SOAP headers, require understand that they are in the understood header list. + * + * @param headers SOAP headers to check + * + * @throws MessageDecodingException thrown if a SOAP header requires understanding but is not understood by the + * decoder + */ + protected void checkUnderstoodSOAPHeaders(List headers) throws MessageDecodingException { + if (headers == null || headers.isEmpty()) { + return; + } + + AttributeExtensibleXMLObject attribExtensObject; + for (XMLObject header : headers) { + if (header instanceof AttributeExtensibleXMLObject) { + attribExtensObject = (AttributeExtensibleXMLObject) header; + if (DatatypeHelper.safeEquals("1", attribExtensObject.getUnknownAttributes().get(soapMustUnderstand))) { + if (!understoodHeaders.contains(header.getElementQName())) { + throw new MessageDecodingException("SOAP decoder encountered a header, " + + header.getElementQName() + + ", that requires undestanding however this decoder does not understand that header"); + } + } + } + } + } + + /** {@inheritDoc} */ + protected boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx) { + return false; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/decoding/package.html 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,7 @@ + + +Classes used to decode SAML messages. A decoder takes a wire protocol, +extracts the SAML message from it, and then evaluates that message +against a security policy. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/BaseSAML1MessageEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/BaseSAML1MessageEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/BaseSAML1MessageEncoder.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,168 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.encoding; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.Configuration; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.encoding.SAMLMessageEncoder; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.util.URLBuilder; +import org.opensaml.ws.message.encoder.BaseMessageEncoder; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.XMLObjectBuilder; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.SignatureException; +import org.opensaml.xml.signature.Signer; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for SAML 1 message encoders. + */ +public abstract class BaseSAML1MessageEncoder extends BaseMessageEncoder implements SAMLMessageEncoder{ + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseSAML1MessageEncoder.class); + + /** The list of schemes allowed to appear in URLs related to the encoded message. Defaults to 'http' and 'https'. */ + private List allowedURLSchemes; + + public BaseSAML1MessageEncoder() { + super(); + setAllowedURLSchemes(new String[] { "http", "https" }); + } + + /** + * Gets the unmodifiable list of schemes allowed to appear in URLs related to the encoded message. + * + * @return list of URL schemes allowed to appear in a message + */ + public List getAllowedURLSchemes() { + return allowedURLSchemes; + } + + /** + * Sets the list of list of schemes allowed to appear in URLs related to the encoded message. Note, the appearance + * of schemes such as 'javascript' may open the system up to attacks (e.g. cross-site scripting attacks). + * + * @param schemes URL schemes allowed to appear in a message + */ + public void setAllowedURLSchemes(String[] schemes) { + if (schemes == null || schemes.length == 0) { + allowedURLSchemes = Collections.emptyList(); + } else { + List temp = new ArrayList(); + for (String scheme : schemes) { + temp.add(scheme); + } + allowedURLSchemes = Collections.unmodifiableList(temp); + } + } + + /** + * Gets the response URL from the relying party endpoint. If the SAML message is a {@link Response} and the relying + * party endpoint contains a response location then that location is returned otherwise the normal endpoint location + * is returned. + * + * @param messageContext current message context + * + * @return response URL from the relying party endpoint + * + * @throws MessageEncodingException throw if no relying party endpoint is available + */ + protected URLBuilder getEndpointURL(SAMLMessageContext messageContext) throws MessageEncodingException { + Endpoint endpoint = messageContext.getPeerEntityEndpoint(); + if (endpoint == null) { + throw new MessageEncodingException("Endpoint for relying party was null."); + } + + URLBuilder urlBuilder; + if (messageContext.getOutboundMessage() instanceof Response + && !DatatypeHelper.isEmpty(endpoint.getResponseLocation())) { + urlBuilder = new URLBuilder(endpoint.getResponseLocation()); + } else { + if (DatatypeHelper.isEmpty(endpoint.getLocation())) { + throw new MessageEncodingException("Relying party endpoint location was null or empty."); + } + urlBuilder = new URLBuilder(endpoint.getLocation()); + } + + if(!getAllowedURLSchemes().contains(urlBuilder.getScheme())){ + throw new MessageEncodingException("Relying party endpoint used the untrusted URL scheme " + urlBuilder.getScheme()); + } + return urlBuilder; + } + + /** + * Signs the given SAML message if it a {@link SignableSAMLObject} and this encoder has signing credentials. + * + * @param messageContext current message context + * + * @throws MessageEncodingException thrown if there is a problem preparing the signature for signing + */ + @SuppressWarnings("unchecked") + protected void signMessage(SAMLMessageContext messageContext) throws MessageEncodingException { + SAMLObject outboundMessage = messageContext.getOutboundSAMLMessage(); + if (outboundMessage instanceof SignableSAMLObject + && messageContext.getOuboundSAMLMessageSigningCredential() != null) { + log.debug("Signing outbound SAML message."); + SignableSAMLObject signableMessage = (SignableSAMLObject) outboundMessage; + Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential(); + + XMLObjectBuilder signatureBuilder = Configuration.getBuilderFactory().getBuilder( + Signature.DEFAULT_ELEMENT_NAME); + Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME); + signature.setSigningCredential(signingCredential); + + try { + // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added + // TODO pull binding-specific keyInfoGenName from encoder setting, etc? + SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null); + } catch (SecurityException e) { + throw new MessageEncodingException("Error preparing signature for signing", e); + } + + signableMessage.setSignature(signature); + + try { + Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(signableMessage); + marshaller.marshall(signableMessage); + Signer.signObject(signature); + } catch (MarshallingException e) { + log.error("Unable to marshall protocol message in preparation for signing", e); + throw new MessageEncodingException("Unable to marshall protocol message in preparation for signing", e); + } catch (SignatureException e) { + log.error("Unable to sign protocol message", e); + throw new MessageEncodingException("Unable to sign protocol message", e); + } + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPArtifactEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPArtifactEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPArtifactEncoder.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,139 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.encoding; + +import java.util.List; + +import org.opensaml.Configuration; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.artifact.SAMLArtifactMap; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.binding.artifact.AbstractSAML1Artifact; +import org.opensaml.saml1.binding.artifact.SAML1ArtifactBuilder; +import org.opensaml.saml1.binding.artifact.SAML1ArtifactType0001; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.saml1.core.Response; +import org.opensaml.util.URLBuilder; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.Pair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 1.X HTTP Artifact message encoder. + */ +public class HTTPArtifactEncoder extends BaseSAML1MessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPArtifactEncoder.class); + + /** SAML artifact map used to store created artifacts for later retrival. */ + private SAMLArtifactMap artifactMap; + + /** Default artifact type to use when encoding messages. */ + private byte[] defaultArtifactType; + + /** + * Constructor. + * + * @param map SAML artifact map used to store created artifacts for later retrival + */ + public HTTPArtifactEncoder(SAMLArtifactMap map) { + artifactMap = map; + defaultArtifactType = SAML1ArtifactType0001.TYPE_CODE; + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML1_ARTIFACT_BINDING_URI; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + SAMLMessageContext artifactContext = (SAMLMessageContext) messageContext; + HTTPOutTransport outTransport = (HTTPOutTransport) artifactContext.getOutboundMessageTransport(); + + URLBuilder urlBuilder = getEndpointURL(artifactContext); + + List> params = urlBuilder.getQueryParams(); + + params.add(new Pair("TARGET", artifactContext.getRelayState())); + + SAML1ArtifactBuilder artifactBuilder; + if (artifactContext.getOutboundMessageArtifactType() != null) { + artifactBuilder = Configuration.getSAML1ArtifactBuilderFactory().getArtifactBuilder( + artifactContext.getOutboundMessageArtifactType()); + } else { + artifactBuilder = Configuration.getSAML1ArtifactBuilderFactory().getArtifactBuilder(defaultArtifactType); + artifactContext.setOutboundMessageArtifactType(defaultArtifactType); + } + + AbstractSAML1Artifact artifact; + String artifactString; + for (Assertion assertion : artifactContext.getOutboundSAMLMessage().getAssertions()) { + artifact = artifactBuilder.buildArtifact(artifactContext, assertion); + if(artifact == null){ + log.error("Unable to build artifact for message to relying party"); + throw new MessageEncodingException("Unable to builder artifact for message to relying party"); + } + + try { + artifactMap.put(artifact.base64Encode(), messageContext.getInboundMessageIssuer(), messageContext + .getOutboundMessageIssuer(), assertion); + } catch (MarshallingException e) { + log.error("Unable to marshall assertion to be represented as an artifact", e); + throw new MessageEncodingException("Unable to marshall assertion to be represented as an artifact", e); + } + artifactString = artifact.base64Encode(); + params.add(new Pair("SAMLart", artifactString)); + } + + String redirectUrl = urlBuilder.buildURL(); + + log.debug("Sending redirect to URL {} to relying party {}", redirectUrl, artifactContext + .getInboundMessageIssuer()); + outTransport.sendRedirect(urlBuilder.buildURL()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPPostEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPPostEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPPostEncoder.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,162 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.encoding; + +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; + +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.ResponseAbstractType; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.XMLHelper; +import org.owasp.esapi.ESAPI; +import org.owasp.esapi.Encoder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 1.X HTTP POST message encoder. + */ +public class HTTPPostEncoder extends BaseSAML1MessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPPostEncoder.class); + + /** Velocity engine used to evaluate the template when performing POST encoding. */ + private VelocityEngine velocityEngine; + + /** ID of the velocity template used when performing POST encoding. */ + private String velocityTemplateId; + + /** + * Constructor. + * + * @param engine velocity engine instance used to create POST body + * @param templateId ID of the template used to create POST body + */ + public HTTPPostEncoder(VelocityEngine engine, String templateId) { + super(); + velocityEngine = engine; + velocityTemplateId = templateId; + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML1_POST_BINDING_URI; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage(); + if (outboundMessage == null) { + throw new MessageEncodingException("No outbound SAML message contained in message context"); + } + String endpointURL = getEndpointURL(samlMsgCtx).buildURL(); + + if (samlMsgCtx.getOutboundSAMLMessage() instanceof ResponseAbstractType) { + ((ResponseAbstractType) samlMsgCtx.getOutboundSAMLMessage()).setRecipient(endpointURL); + } + + signMessage(samlMsgCtx); + samlMsgCtx.setOutboundMessage(outboundMessage); + + postEncode(samlMsgCtx, endpointURL); + } + + /** + * Base64 and POST encodes the outbound message and writes it to the outbound transport. + * + * @param messageContext current message context + * @param endpointURL endpoint URL to encode message to + * + * @throws MessageEncodingException thrown if there is a problem encoding the message + */ + protected void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException { + log.debug("Invoking velocity template to create POST body"); + + try { + VelocityContext context = new VelocityContext(); + Encoder esapiEncoder = ESAPI.encoder(); + + String encodedEndpointURL = esapiEncoder.encodeForHTMLAttribute(endpointURL); + log.debug("Encoding action url of '{}' with encoded value '{}'", endpointURL, encodedEndpointURL); + context.put("action", encodedEndpointURL); + + log.debug("Marshalling and Base64 encoding SAML message"); + String messageXML = XMLHelper.nodeToString(marshallMessage(messageContext.getOutboundSAMLMessage())); + String encodedMessage = Base64.encodeBytes(messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES); + context.put("SAMLResponse", encodedMessage); + + if (messageContext.getRelayState() != null) { + String encodedRelayState = esapiEncoder.encodeForHTMLAttribute(messageContext.getRelayState()); + log.debug("Setting TARGET parameter to: '{}', encoded as '{}'", messageContext.getRelayState(), encodedRelayState); + context.put("TARGET", encodedRelayState); + } + + HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(outTransport); + HTTPTransportUtils.setUTF8Encoding(outTransport); + HTTPTransportUtils.setContentType(outTransport, "text/html"); + + OutputStream transportOutStream = outTransport.getOutgoingStream(); + Writer out = new OutputStreamWriter(transportOutStream, "UTF-8"); + velocityEngine.mergeTemplate(velocityTemplateId, "UTF-8", context, out); + out.flush(); + }catch(UnsupportedEncodingException e){ + log.error("UTF-8 encoding is not supported, this VM is not Java compliant."); + throw new MessageEncodingException("Unable to encode message, UTF-8 encoding is not supported"); + } catch (Exception e) { + log.error("Error invoking velocity template", e); + throw new MessageEncodingException("Error creating output document", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPSOAP11Encoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPSOAP11Encoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/HTTPSOAP11Encoder.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,158 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.binding.encoding; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; + +import org.opensaml.Configuration; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.xml.XMLObjectBuilderFactory; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * SAML 1.X HTTP SOAP 1.1 binding message encoder. + */ +public class HTTPSOAP11Encoder extends BaseSAML1MessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPSOAP11Encoder.class); + + /** Constructor. */ + public HTTPSOAP11Encoder() { + super(); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML1_SOAP11_BINDING_URI; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + if (messageContext.getOutboundMessageTransport().isConfidential()) { + return true; + } + + return false; + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + if (messageContext.getOutboundMessageTransport().isIntegrityProtected()) { + return true; + } + + return false; + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + validateMessageContent(messageContext); + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject samlMessage = samlMsgCtx.getOutboundSAMLMessage(); + if (samlMessage == null) { + throw new MessageEncodingException("No outbound SAML message contained in message context"); + } + + signMessage(samlMsgCtx); + Envelope envelope = buildSOAPMessage(samlMessage); + samlMsgCtx.setOutboundMessage(envelope); + + Element envelopeElem = marshallMessage(envelope); + try { + HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(outTransport); + HTTPTransportUtils.setUTF8Encoding(outTransport); + HTTPTransportUtils.setContentType(outTransport, "text/xml"); + outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security"); + + Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); + XMLHelper.writeNode(envelopeElem, out); + out.flush(); + } catch (UnsupportedEncodingException e) { + log.error("JVM does not support required UTF-8 encoding"); + throw new MessageEncodingException("JVM does not support required UTF-8 encoding"); + } catch (IOException e) { + log.error("Unable to write message content to outbound stream", e); + throw new MessageEncodingException("Unable to write message content to outbound stream", e); + } + } + + /** + * Builds the SOAP message to be encoded. + * + * @param samlMessage body of the SOAP message + * + * @return the SOAP message + */ + @SuppressWarnings("unchecked") + protected Envelope buildSOAPMessage(SAMLObject samlMessage) { + log.debug("Building SOAP message"); + XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); + + SOAPObjectBuilder envBuilder = (SOAPObjectBuilder) builderFactory + .getBuilder(Envelope.DEFAULT_ELEMENT_NAME); + Envelope envelope = envBuilder.buildObject(); + + log.debug("Adding SAML message to the SOAP message's body"); + SOAPObjectBuilder bodyBuilder = (SOAPObjectBuilder) builderFactory + .getBuilder(Body.DEFAULT_ELEMENT_NAME); + Body body = bodyBuilder.buildObject(); + body.getUnknownXMLObjects().add(samlMessage); + envelope.setBody(body); + + return envelope; + } + + /** + * Validates that the message context is a {@link SAMLMessageContext} and that its outbound transport is HTTP. + * + * @param messageContext current message context + * + * @throws MessageEncodingException thrown if the message context conditions are not met + */ + protected void validateMessageContent(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/binding/encoding/package.html 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,7 @@ + + +Classes used to encode SAML messages. An encoder takes a SAML message +and transforms it into a representation that may be transported over a +particular wire protocol (e.g. HTTP). + + Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Action.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Action.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Action.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * Interface describing how a SAML1.1 Action element behaves + */ +public interface Action extends SAMLObject { + + /** Default element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Action"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for the Namespace attribute */ + public final static String NAMESPACEATTRIB_NAME = "Namespace"; + + /** Return the value of Namespace */ + public String getNamespace(); + + /** Set the value of Namespace */ + public void setNamespace(String namespace); + + /** Return the contents */ + public String getContents(); + + /** Set the contents */ + public void setContents(String contents); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Advice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Advice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Advice.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * This interface defines how the object representing a SAML 1 Advice element behaves. + */ +public interface Advice extends SAMLObject, ElementExtensibleXMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Advice"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AdviceType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** + * Get the AssertionIdReferences. + * + * @return The AssertionIdReferences in order + */ + public List getAssertionIDReferences(); + + /** + * Get the Assertions. + * + * @return the assertions (in order) + */ + public List getAssertions(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Assertion.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Assertion.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Assertion.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,200 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 1 Assertion element behaves. + */ +public interface Assertion extends SignableSAMLObject, Evidentiary { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Assertion"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AssertionType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for the attribute which defines Major Version (attribute's value must be 1) */ + public final static String MAJORVERSION_ATTRIB_NAME = "MajorVersion"; + + /** Name for the attribute which defines Minor Version. */ + public final static String MINORVERSION_ATTRIB_NAME = "MinorVersion"; + + /** Name for the attribute which defines Assertion ID */ + public final static String ASSERTIONID_ATTRIB_NAME = "AssertionID"; + + /** Name for the attribute which defines Issuer */ + public final static String ISSUER_ATTRIB_NAME = "Issuer"; + + /** Name for the attribute which defines the issue instant */ + public final static String ISSUEINSTANT_ATTRIB_NAME = "IssueInstant"; + + /** Name for the attribute which defines the Issue Instant. */ + public final static String ID_ATTRIB_NAME = "AssertionID"; + + /* attributes */ + + /** + * Get the MajorVersion attribute. + * + * @return The stored MajorVersion + */ + public int getMajorVersion(); + + /** + * Get the MinorVersion attribute. + * + * @return The stored MinorVersion + */ + public int getMinorVersion(); + + /** + * Sets the SAML version of this assertion. + * + * @param version the SAML version of this assertion + */ + public void setVersion(SAMLVersion version); + + /** + * Get the Issuer (which is an attribute) . + * + * @return the Issuer + */ + public String getIssuer(); + + /** + * Set the Issuer (attribute). + * + * @param Issuer the value to set + */ + public void setIssuer(String Issuer); + + /** + * Get the IssueInstant (attribute). + * + * @return the Issue Instant (as a Date) + */ + public DateTime getIssueInstant(); + + /** Set the ID */ + public String getID(); + + /** Get the ID */ + public void setID(String id); + + /** + * Set the IssueInstance (attribute). + * + * @param issueInstant the issue instant value to set + */ + public void setIssueInstant(DateTime issueInstant); + + /* Singleton Elements */ + + /** + * Return the (singleton) Object, representing the Conditions sub element. + * + * @return the Conditions object. + */ + public Conditions getConditions(); + + /** + * Set the Object representing the Conditions Sub element. + * + * @param conditions the condition to List + * + * @throws IllegalArgumentException if the condition has already been set into another object + */ + public void setConditions(Conditions conditions) throws IllegalArgumentException; + + /** + * advice is a (singleton) Object, representing the Advice sub element + * + * @return the advice object in this assertion + */ + public Advice getAdvice(); + + /** + * Set the Object representing the Advice sub element. + * + * @param advice the object to set + * + * @throws IllegalArgumentException if the object has already been put into another SAMLObject + */ + public void setAdvice(Advice advice) throws IllegalArgumentException; + + /* Multiple Elements */ + + /** + * Return the List representing all the Statement sub elements. + * + * @return the List representing all the statements + */ + public List getStatements(); + + /** + * Return the List representing all the Statement sub elements with a given schema type or element name. + * + * @param typeOrName the schema type or element name + * + * @return the List representing all the statements + */ + public List getStatements(QName typeOrName); + + /** + * Return the List representing all the SubjectStatement sub elements. + * + * @return all the SubjectStatements + */ + public List getSubjectStatements(); + + /** + * Return the List representing all the AuthenticationStatement sub elements. + * + * @return all the AuthenticationStatements + */ + public List getAuthenticationStatements(); + + /** + * Return the List representing all the AuthorizationStatement sub elements. + * + * @return all the authorizationDecisionStatements. + */ + public List getAuthorizationDecisionStatements(); + + /** + * Return all the AttributeStatement elements + * + * @return all the attributeStatements + */ + public List getAttributeStatements(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AssertionArtifact.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AssertionArtifact.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AssertionArtifact.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface is for the SAML1 AssertionArtifact extention point. + */ +public interface AssertionArtifact extends SAMLObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AssertionArtifact"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AssertionArtifactType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML1P_PREFIX); + + /** + * Get the contents of the artifact. + * + * @return contents of the artifact + */ + public String getAssertionArtifact(); + + /** + * Set the contents of the artficat. + * + * @param assertionArtifact contents of the artifact + */ + public void setAssertionArtifact(String assertionArtifact); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AssertionIDReference.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AssertionIDReference.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AssertionIDReference.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 1 AssertionIDReference element behaves. + */ +public interface AssertionIDReference extends SAMLObject, Evidentiary { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AssertionIDReference"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Get the reference */ + public String getReference(); + + /** + * Set the reference. + * + * @param newReference what to add + */ + public void setReference(String newReference); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Attribute.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Attribute.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Attribute.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.XMLObject; + +/** + * This interface defines how the object representing a SAML 1 Attribute element behaves. + */ +public interface Attribute extends AttributeDesignator { + + /** Element name, no namespace. */ + + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Attribute"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AttributeType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Get all the subsiduary AttributeValue elements */ + public List getAttributeValues(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeDesignator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeDesignator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeDesignator.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 1 AttributeDesignator element behaves. + */ +public interface AttributeDesignator extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeDesignator"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AttributeDesignatorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for the AttributeName attribute */ + public final static String ATTRIBUTENAME_ATTRIB_NAME = "AttributeName"; + + /** Name for the AttributeNamespace attribute */ + public final static String ATTRIBUTENAMESPACE_ATTRIB_NAME = "AttributeNamespace"; + + /** Get the contents of the AttributeName attribute */ + public String getAttributeName(); + + /** Set the contents of the AttributeName attribute */ + public void setAttributeName(String attributeName); + + /** Get the contents of the AttributeNamespace attribute */ + public String getAttributeNamespace(); + + /** Set the contents of the AttributeNamespace attribute */ + public void setAttributeNamespace(String attributeNamespace); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeQuery.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * Description of the behaviour of the AttributeQuery element + */ +public interface AttributeQuery extends SubjectQuery { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeQuery"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AttributeQueryType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** AuthenticationMethod attribute name */ + public final static String RESOURCE_ATTRIB_NAME = "Resource"; + + /** Get list of AttributeDesignators */ + public List getAttributeDesignators(); + + /** Get Resource attribute */ + public String getResource(); + + /** Set Resource attribute */ + public void setResource(String resource); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeStatement.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 1 AttributeStatement element behaves. + */ +public interface AttributeStatement extends SAMLObject, SubjectStatement { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeStatement"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AttributeStatementType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Get all the subsiduary Attribute elements */ + public List getAttributes(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeValue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeValue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AttributeValue.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 1 AttributeValue element behaves. + */ +public interface AttributeValue extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeValue"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Audience.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Audience.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Audience.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface describes how ab object representing a SAML1 Audience element will behave. + */ +public interface Audience extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Audience"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Return the URI which makes up the Body */ + public String getUri(); + + /** Set the Uri which makes up the body text */ + public void setUri(String uri); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AudienceRestrictionCondition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AudienceRestrictionCondition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AudienceRestrictionCondition.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface describes how ab object representing a SAML1 AudienceRestrictionCondition element will + * behave. + */ +public interface AudienceRestrictionCondition extends Condition { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AudienceRestrictionCondition"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AudienceRestrictionConditionType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Return all the audience elements */ + public List getAudiences(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthenticationQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthenticationQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthenticationQuery.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * Description of the behaviour of the AuthenticationQuery element + */ +public interface AuthenticationQuery extends SubjectQuery { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthenticationQuery"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AuthenticationQueryType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** AuthenticationMethod attribute name */ + public final static String AUTHENTICATIONMETHOD_ATTRIB_NAME = "AuthenticationMethod"; + + /** Get AuthenticationMethod attribute */ + public String getAuthenticationMethod(); + + /** Set AuthenticationMethod attribute */ + public void setAuthenticationMethod(String authenticationMethod); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthenticationStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthenticationStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthenticationStatement.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML1 AuthenticationStatment element behaves. + */ +public interface AuthenticationStatement extends SAMLObject, SubjectStatement { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthenticationStatement"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AuthenticationStatementType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name of the AuthenticationMethod attribute */ + public final static String AUTHENTICATIONMETHOD_ATTRIB_NAME = "AuthenticationMethod"; + + /** Name of the AuthenticationInstant attribute */ + public final static String AUTHENTICATIONINSTANT_ATTRIB_NAME = "AuthenticationInstant"; + + /** Return the contents of the AuthenticationMethod attribute */ + public String getAuthenticationMethod(); + + /** Set the contents of the AuthenticationMethod attribute */ + public void setAuthenticationMethod(String authenticationMethod); + + /** Return the contents of the AuthenticationInstant attribute */ + public DateTime getAuthenticationInstant(); + + /** Set the contents of the AuthenticationInstant attribute */ + public void setAuthenticationInstant(DateTime authenticationInstant); + + /** Set the (single) SubjectLocality child element */ + public SubjectLocality getSubjectLocality(); + + /** Get the (single) SubjectLocality child element + * @throws IllegalArgumentException */ + public void setSubjectLocality(SubjectLocality subjectLocality) throws IllegalArgumentException; + + /** return all the AuthorityBinding subelement */ + public List getAuthorityBindings(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorityBinding.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorityBinding.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorityBinding.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * Interface to define how a AuthorityBinding <\code> element behaves + */ +public interface AuthorityBinding extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthorityBinding"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AuthorityBindingType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for the AuthorityKind attribute */ + public final static String AUTHORITYKIND_ATTRIB_NAME = "AuthorityKind"; + + /** Name for the Location attribute */ + public final static String LOCATION_ATTRIB_NAME = "Location"; + + /** Name for the Binding attribute */ + public final static String BINDING_ATTRIB_NAME = "Binding"; + + /** Getter for AuthorityKind */ + public QName getAuthorityKind(); + + /** Setter for AuthorityKind */ + public void setAuthorityKind(QName authorityKind); + + /** Getter for Location */ + public String getLocation(); + + /** Setter for Location */ + public void setLocation(String location); + + /** Getter for Binding */ + public String getBinding(); + + /** Setter for Binding */ + public void setBinding(String binding); + + + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorizationDecisionQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorizationDecisionQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorizationDecisionQuery.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * Description of the behaviour of the AuthorizationDecisionQuery element + */ +public interface AuthorizationDecisionQuery extends SubjectQuery { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthorizationDecisionQuery"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AuthorizationDecisionQueryType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** AuthenticationMethod attribute name */ + public final static String RESOURCE_ATTRIB_NAME = "Resource"; + + /** Get Resource attribute */ + public String getResource(); + + /** Set Resource attribute */ + public void setResource(String resource); + + /** Get list of Action child elements */ + public List getActions(); + + /** Get the Evidence child element */ + public Evidence getEvidence(); + + /** Set the Evidence child element */ + public void setEvidence(Evidence evidence); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorizationDecisionStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorizationDecisionStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/AuthorizationDecisionStatement.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML1 AuthorizationDecisionStatement element + * behaves. + */ +public interface AuthorizationDecisionStatement extends SAMLObject, SubjectStatement { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthorizationDecisionStatement"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AuthorizationDecisionStatementType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for Resource attribute */ + public final static String RESOURCE_ATTRIB_NAME = "Resource"; + + /** Name for Decision attribute */ + public final static String DECISION_ATTRIB_NAME = "Decision"; + + /** Return the contents of the Resource attribute */ + public String getResource(); + + /** Set the contents of the Resource attribute */ + public void setResource(String resource); + + /** Return the contents of the Decision attribute */ + public DecisionTypeEnumeration getDecision(); + + /** Set the contents of the Decision attribute */ + public void setDecision(DecisionTypeEnumeration decision); + + /** Get the Action Elements */ + public List getActions(); + + /** Return the Evidence element */ + public Evidence getEvidence(); + + /** Set the Evidence element + * @throws IllegalArgumentException */ + public void setEvidence(Evidence evidence) throws IllegalArgumentException; + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Condition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Condition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Condition.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface describes how a object representing a SAML1 Condition element will behave. + */ +public interface Condition extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Condition"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ConditionAbstractType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Conditions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Conditions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Conditions.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML1 Conditions element behaves. + */ +public interface Conditions extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Conditions"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ConditionsType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for the NotBefore attribute. */ + public final static String NOTBEFORE_ATTRIB_NAME = "NotBefore"; + + /** Name for the NotBefore attribute. */ + public final static String NOTONORAFTER_ATTRIB_NAME = "NotOnOrAfter"; + + /** Return the value of the NotBefore attribute. */ + public DateTime getNotBefore(); + + /** List the value of the NotBefore attribute. */ + public void setNotBefore(DateTime notBefore); + + /** Return the value of the NotOnOrAfter attribute. */ + public DateTime getNotOnOrAfter(); + + /** List the value of the NotOnOrAfter attribute. */ + public void setNotOnOrAfter(DateTime notOnOrAfter); + + /** + * Return the List representing all the Condition sub elements. + */ + public List getConditions(); + + /** + * Return the List representing all the Conditions with the given schema type or element name. + * + * @param typeOrName the schema type or element name + */ + public List getConditions(QName typeOrName); + + /** + * Return the List representing all the AudienceRestrictionCondition sub elements. + */ + public List getAudienceRestrictionConditions(); + + /** + * Return the List representing all the DoNotCacheCondition sub elements. + */ + public List getDoNotCacheConditions(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/ConfirmationMethod.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/ConfirmationMethod.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/ConfirmationMethod.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML1 ConfirmationMethod element behaves. + */ +public interface ConfirmationMethod extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "ConfirmationMethod"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ConfirmationMethodType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** + * Gets the confirmation method. + * + * @return the confirmation method + */ + public String getConfirmationMethod(); + + /** + * Sets the confirmation method. + * + * @param confirmationMethod the confirmation method + */ + public void setConfirmationMethod(String confirmationMethod); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/DecisionTypeEnumeration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/DecisionTypeEnumeration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/DecisionTypeEnumeration.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +/** + * A type safe "enumeration" of {@link org.opensaml.saml1.core.AuthorizationDecisionStatement} Decision types. + */ +public final class DecisionTypeEnumeration { + + /** "Permit" decision type */ + public final static DecisionTypeEnumeration PERMIT = new DecisionTypeEnumeration("Permit"); + + /** "Deny" decision type */ + public final static DecisionTypeEnumeration DENY = new DecisionTypeEnumeration("Deny"); + + /** "Indeterminate" decision type */ + public final static DecisionTypeEnumeration INDETERMINATE = new DecisionTypeEnumeration("Indeterminate"); + + /** The decision type sting */ + private String decisionType; + + /** + * Constructor + * + * @param newDecisionType + */ + protected DecisionTypeEnumeration(String newDecisionType) { + this.decisionType = newDecisionType; + } + + /** {@inheritDoc} */ + public String toString() { + return this.decisionType; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/DoNotCacheCondition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/DoNotCacheCondition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/DoNotCacheCondition.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + + +/** + * This interface describes how ab object representing a SAML1 DoNotCacheCondition element will behave. + */ +public interface DoNotCacheCondition extends Condition { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "DoNotCacheCondition"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "DoNotCacheConditionType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + // No sub elements or members +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Evidence.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Evidence.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Evidence.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * Interface describing how a SAML1.1 Evidence element behaves + */ +public interface Evidence extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Evidence"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "EvidenceType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Get the ordered list of all Evidentiary child elements */ + public List getEvidence(); + + /** Get the list of the AssertionIdReference */ + public List getAssertionIDReferences(); + + /** Get the list of Assertions */ + public List getAssertions(); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Evidentiary.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Evidentiary.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Evidentiary.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import org.opensaml.common.SAMLObject; + +/** + * Marker interface for element types that can constitute evidence within a @{org.opensaml.saml1.core.Evidence} object. + */ +public interface Evidentiary extends SAMLObject { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/NameIdentifier.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/NameIdentifier.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/NameIdentifier.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** Interface to define how a NameIdentifier element behaves. */ +public interface NameIdentifier extends SAMLObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "NameIdentifier"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "NameIdentifierType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for the attribute which defines Name Qualifier. */ + public static final String NAMEQUALIFIER_ATTRIB_NAME = "NameQualifier"; + + /** Name for the attribute which defines Name Qualifier. */ + public static final String FORMAT_ATTRIB_NAME = "Format"; + + /** URI for unspecified name format. */ + public static final String UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"; + + /** URI for email name format. */ + public static final String EMAIL = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"; + + /** URI for X509 subject name format. */ + public static final String X509_SUBJECT = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName"; + + /** URI for windows domain qualified name name format. */ + public static final String WIN_DOMAIN_QUALIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName"; + + /** + * Gets the name qualifier for this identifier. + * + * @return name qualifier for this identifier + */ + public String getNameQualifier(); + + /** + * Sets the name qualifier for this identifier. + * + * @param nameQualifier name qualifier for this identifier + */ + public void setNameQualifier(String nameQualifier); + + /** + * Gets the format of this identifier. + * + * @return format of this identifier + */ + public String getFormat(); + + /** + * Sets the format of this identifier. + * + * @param format format of this identifier + */ + public void setFormat(String format); + + /** + * Gets the identifier. + * + * @return the identifier + */ + public String getNameIdentifier(); + + /** + * Sets the identifier. + * + * @param nameIdentifier the identifier. + */ + public void setNameIdentifier(String nameIdentifier); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Query.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Query.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Query.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface is for the SAML1 Query extention point. + */ +public interface Query extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Query"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "QueryAbstractType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Request.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Request.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Request.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the SAML1 Request objects behave. + */ +public interface Request extends RequestAbstractType { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Request"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "RequestType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /* + * A bit odd this, it s a choice so only one of these will return any value + */ + + /** Get the request Query, SubjectQuery, AuthenticationQuery, AttributeQuery, or AuthorizationDecisionQuery */ + public Query getQuery(); + + /** Get the request SubjectQuery, AuthenticationQuery, AttributeQuery, or AuthorizationDecisionQuery */ + public SubjectQuery getSubjectQuery(); + + /** Get the query AuthenticationQuery */ + public AuthenticationQuery getAuthenticationQuery(); + + /** Get the request AttributeQuery */ + public AttributeQuery getAttributeQuery(); + + /** Get the request AuthorizationDecisionQuery */ + public AuthorizationDecisionQuery getAuthorizationDecisionQuery(); + + /** Set the query (Query, SubjectQuery, AuthenticationQuery, AttributeQuery, AuthorizationDecisioonQuery + */ + public void setQuery(Query query) throws IllegalArgumentException; + + /** Get the lists of AssertionIDReferences */ + public List getAssertionIDReferences(); + + /** Get the lists of */ + public List getAssertionArtifacts(); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/RequestAbstractType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/RequestAbstractType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/RequestAbstractType.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.SignableSAMLObject; + +/** + * This interface describes the base class for types derived from + * RequestAbstractType + */ +public interface RequestAbstractType extends SignableSAMLObject { + + /** Name for the attribute which defines the Major Version (which must be "1". */ + public final static String MAJORVERSION_ATTRIB_NAME = "MajorVersion"; + + /** Name for the attribute which defines the Minor Version. */ + public final static String MINORVERSION_ATTRIB_NAME = "MinorVersion"; + + /** Name for the attribute which defines the Issue Instant. */ + public final static String ISSUEINSTANT_ATTRIB_NAME = "IssueInstant"; + + /** Name for the attribute which defines the Issue Instant. */ + public final static String ID_ATTRIB_NAME = "RequestID"; + + /** + * Gets the major version of this SAML message. + * + * @return the major version of this SAML message + */ + public int getMajorVersion(); + + /** + * Gets the minor version of this SAML message. + * + * @return the minor version of this SAML message + */ + public int getMinorVersion(); + + public void setVersion(SAMLVersion version); + + /** Get the issue instant */ + public DateTime getIssueInstant(); + + /** Get the ID */ + public String getID(); + + /** Set the ID */ + public void setID(String id); + + /** Set the issue instant */ + public void setIssueInstant(DateTime date); + + /** Return the list of RespondWith elements */ + public List getRespondWiths(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/RespondWith.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/RespondWith.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/RespondWith.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSQName; + +/** + * This interface defines how the (deprecated) RespondWith element would behave. + */ +public interface RespondWith extends SAMLObject, XSQName { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RespondWith"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1P_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Response.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Response.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Response.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + + +/** + * This interface defines how the object representing a SAML1 Response element behaves. + */ +public interface Response extends ResponseAbstractType { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Response"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ResponseAbstractType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Return the object representing the Status (element). */ + Status getStatus(); + + /** Set the object representing the Status (element). */ + void setStatus(Status status) throws IllegalArgumentException; + + /** Return the object representing the Assertion (element). */ + public List getAssertions(); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/ResponseAbstractType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/ResponseAbstractType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/ResponseAbstractType.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.SignableSAMLObject; + +/** + * This interface defines the base class for type derived from the SAML1 ResponseAbstractType . + */ +public interface ResponseAbstractType extends SignableSAMLObject { + + /** Name for the attribute which defines InResponseTo. */ + public final static String INRESPONSETO_ATTRIB_NAME = "InResponseTo"; + + /** Name for the attribute which defines the Major Version (which must be "1". */ + public final static String MAJORVERSION_ATTRIB_NAME = "MajorVersion"; + + /** Name for the attribute which defines the Minor Version. */ + public final static String MINORVERSION_ATTRIB_NAME = "MinorVersion"; + + /** Name for the attribute which defines the Issue Instant. */ + public final static String ISSUEINSTANT_ATTRIB_NAME = "IssueInstant"; + + /** Name for the attribute which defines the Recipient. */ + public final static String RECIPIENT_ATTRIB_NAME = "Recipient"; + + /** Name for the attribute which defines the Issue Instant. */ + public final static String ID_ATTRIB_NAME = "ResponseID"; + + /** Return the InResponseTo (attribute). */ + String getInResponseTo(); + + /** Set the InResponseTo (attribute). */ + void setInResponseTo(String who); + + /** Get the ID */ + public String getID(); + + /** Set the ID */ + public void setID(String id); + + /** Return the Minor Version (attribute). */ + public int getMinorVersion(); + + /** + * Gets the major version of this SAML message. + * + * @return the major version of this SAML message + */ + public int getMajorVersion(); + + /** + * Sets the SAML version for this message. + * + * @param version the SAML version for this message + */ + public void setVersion(SAMLVersion version); + + /** Return the Issue Instant (attribute). */ + public DateTime getIssueInstant(); + + /** Set the Issue Instant (attribute). */ + public void setIssueInstant(DateTime date); + + /** Return the Recipient (attribute). */ + public String getRecipient(); + + /** Set the Recipient (attribute). */ + public void setRecipient(String recipient); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Statement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Statement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Statement.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML1 Statement element behaves. + */ +public interface Statement extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Statement"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "StatementAbstractType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Status.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Status.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Status.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 1 Status element behaves. + */ +public interface Status extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Status"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "StatusType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Return the object representing the StatusMessage (element). */ + public StatusMessage getStatusMessage(); + + /** Set the object representing the StatusMessage (element). */ + public void setStatusMessage(StatusMessage statusMessage) throws IllegalArgumentException; + + /** Return the object representing the StatusCode (element). */ + public StatusCode getStatusCode(); + + /** Set the object representing the StatusCode (element). */ + public void setStatusCode(StatusCode statusCode) throws IllegalArgumentException; + + /** Return the object representing the StatusDetail (element). */ + + public StatusDetail getStatusDetail(); + + /** Set the object representing the StatusDetail (element). */ + public void setStatusDetail(StatusDetail statusDetail) throws IllegalArgumentException; +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusCode.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusCode.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusCode.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 1 StatusCode element behaves. + */ +public interface StatusCode extends SAMLObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "StatusCode"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusCodeType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML1P_PREFIX); + + /** Success status value. */ + public static final QName SUCCESS = new QName(SAMLConstants.SAML10P_NS, "Success", SAMLConstants.SAML1P_PREFIX); + + /** VersionMismatch status value. */ + public static final QName VERSION_MISMATCH = new QName(SAMLConstants.SAML10P_NS, "VersionMismatch", + SAMLConstants.SAML1P_PREFIX); + + /** Requester status value. */ + public static final QName REQUESTER = new QName(SAMLConstants.SAML10P_NS, "Requester", SAMLConstants.SAML1P_PREFIX); + + /** Responder status value. */ + public static final QName RESPONDER = new QName(SAMLConstants.SAML10P_NS, "Responder", SAMLConstants.SAML1P_PREFIX); + + /** RequestVersionTooHigh status value. */ + public static final QName REQUEST_VERSION_TOO_HIGH = new QName(SAMLConstants.SAML10P_NS, "RequestVersionTooHigh", + SAMLConstants.SAML1P_PREFIX); + + /** RequestVersionTooLow status value. */ + public static final QName REQUEST_VERSION_TOO_LOW = new QName(SAMLConstants.SAML10P_NS, "RequestVersionTooLow", + SAMLConstants.SAML1P_PREFIX); + + /** RequestVersionDepricated status value. */ + public static final QName REQUEST_VERSION_DEPRICATED = new QName(SAMLConstants.SAML10P_NS, + "RequestVersionDepricated", SAMLConstants.SAML1P_PREFIX); + + /** TooManyResponses status value. */ + public static final QName TOO_MANY_RESPONSES = new QName(SAMLConstants.SAML10P_NS, "TooManyResponses", + SAMLConstants.SAML1P_PREFIX); + + /** RequestDenied status value. */ + public static final QName REQUEST_DENIED = new QName(SAMLConstants.SAML10P_NS, "RequestDenied", + SAMLConstants.SAML1P_PREFIX); + + /** ResourceNotRecognized status value. */ + public static final QName RESOURCE_NOT_RECOGNIZED = new QName(SAMLConstants.SAML10P_NS, "ResourceNotRecognized", + SAMLConstants.SAML1P_PREFIX); + + /** Name for the attribute which defines the Value. */ + public static final String VALUE_ATTRIB_NAME = "Value"; + + /** + * Gets the value of the status code. + * + * @return value of the status code + */ + public QName getValue(); + + /** + * Sets the value of the status code. + * + * @param value value of the status code + */ + public void setValue(QName value); + + /** + * Gets the second level status code. + * + * @return second level status code + */ + public StatusCode getStatusCode(); + + /** + * Sets the second level status code. + * + * @param statusCode second level status code + * @throws IllegalArgumentException + */ + public void setStatusCode(StatusCode statusCode); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusDetail.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusDetail.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusDetail.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * Interface to describe how a StatusDetail <\code> element behaves + */ +public interface StatusDetail extends SAMLObject, ElementExtensibleXMLObject { + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "StatusDetail"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "StatusDetailype"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusMessage.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusMessage.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/StatusMessage.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML1 StatusMessage element behaves. + */ +public interface StatusMessage extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "StatusMessage"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Return the contents of this */ + String getMessage(); + + /** Set the contents of this */ + void setMessage(String message); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/Subject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/Subject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/Subject.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * Interface to describe how the Subject elements work. + */ +public interface Subject extends SAMLObject { + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Subject"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Gets the NameIdentifier of this Subject */ + public NameIdentifier getNameIdentifier(); + + /** Sets the NameIdentifier of this Subject */ + public void setNameIdentifier(NameIdentifier nameIdentifier) throws IllegalArgumentException; + + /** Gets the SubjectConfirmation of this Subject */ + public SubjectConfirmation getSubjectConfirmation(); + + /** Sets the SubjectConfirmation of this Subject */ + public void setSubjectConfirmation(SubjectConfirmation subjectConfirmation) throws IllegalArgumentException; + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectConfirmation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectConfirmation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectConfirmation.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.signature.KeyInfo; + +/** + * Interface to define how a SubjectConfirmation element behaves + */ +public interface SubjectConfirmation extends SAMLObject { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectConfirmation"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "SubjectConfirmationType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Get the list with all the ConfirmationMethods. This suitable for calls to add() */ + public List getConfirmationMethods(); + + /** Set the SubjectConfirmationData */ + public void setSubjectConfirmationData(XMLObject subjectConfirmationData) throws IllegalArgumentException; + + /** Return the SubjectConfirmationData */ + public XMLObject getSubjectConfirmationData(); + + /** + * Gets the key information for the subject. + * + * @return the key information for the subject + */ + public KeyInfo getKeyInfo(); + + /** + * Sets the key information for the subject. + * + * @param keyInfo the key information for the subject + */ + public void setKeyInfo(KeyInfo keyInfo); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectConfirmationData.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectConfirmationData.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectConfirmationData.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML1 SubjectConfirmationData element behaves. + */ +public interface SubjectConfirmationData extends SAMLObject { + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectConfirmationData"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectLocality.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectLocality.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectLocality.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * Interface to define how a SubjectLocality element behaves. + */ +public interface SubjectLocality extends SAMLObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectLocality"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SubjectLocalityType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Name for the IPAddress attribute. */ + public static final String IPADDRESS_ATTRIB_NAME = "IPAddress"; + + /** Name for the DNSAddress attribute. */ + public static final String DNSADDRESS_ATTRIB_NAME = "DNSAddress"; + + /** + * Gets the IP address of the locality. + * + * @return IP address of the locality + */ + public String getIPAddress(); + + /** + * Sets the IP address of the locality. + * + * @param address IP address of the locality + */ + public void setIPAddress(String address); + + /** + * Gets the DNS name of the locality. + * + * @return DNS name of the locality + */ + public String getDNSAddress(); + + /** + * Sets the DNS name of the locality. + * + * @param address DNS name of the locality + */ + public void setDNSAddress(String address); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectQuery.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface is for the SAML1 SubjectQuery extention point. + */ +public interface SubjectQuery extends Query { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectQuery"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML10P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "SubjectQueryAbstractType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML10P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + + /** Get Subject child element */ + public Subject getSubject(); + + /** Set Subject child element */ + public void setSubject(Subject subject); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/SubjectStatement.java 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * Interface to descibe how the anchor point SubjectStatement would work. + */ +public interface SubjectStatement extends SAMLObject, Statement { + + /** Element name, no namespace. */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectStatement"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML1_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "SubjectStatementAbstractType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML1_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + + public Subject getSubject(); + + public void setSubject(Subject subject) throws IllegalArgumentException; +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/package.html 17 Aug 2012 15:03:38 -0000 1.1 @@ -0,0 +1,14 @@ + + +Interfaces for SAML 1.0 and 1.1 types and elements. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Action; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.ActionImpl} objects. + */ +public class ActionBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ActionBuilder() { + + } + + /** {@inheritDoc} */ + public Action buildObject() { + return buildObject(SAMLConstants.SAML1_NS, Action.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Action buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.Action; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml1.core.Action} + */ +public class ActionImpl extends AbstractSAMLObject implements Action { + + /** Place to store the namespace */ + private String namespace; + + /** Where to store the contents */ + private String contents; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ActionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getNamespace() { + return namespace; + } + + /** {@inheritDoc} */ + public void setNamespace(String namespace) { + this.namespace = prepareForAssignment(this.namespace, namespace); + } + + /** {@inheritDoc} */ + public String getContents() { + return contents; + } + + /** {@inheritDoc} */ + public void setContents(String contents) { + this.contents = prepareForAssignment(this.contents, contents); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No elements + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.Action; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Action} objects. + */ +public class ActionMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + + Action action = (Action) samlElement; + + if (action.getNamespace() != null) { + domElement.setAttributeNS(null, Action.NAMESPACEATTRIB_NAME, action.getNamespace()); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Action action = (Action) samlObject; + + if (action.getContents() != null) { + XMLHelper.appendTextContent(domElement, action.getContents()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ActionUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Action; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.Action} objects. + */ +public class ActionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + if (Action.NAMESPACEATTRIB_NAME.equals(attribute.getLocalName())) { + Action action = (Action) samlObject; + action.setNamespace(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Action action = (Action) samlObject; + action.setContents(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceBuilder.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Advice; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AdviceImpl} objects. + */ +public class AdviceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AdviceBuilder() { + + } + + /** {@inheritDoc} */ + public Advice buildObject() { + return buildObject(SAMLConstants.SAML1_NS, Advice.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Advice buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AdviceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceImpl.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,98 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Advice; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete Implementation of the {@link org.opensaml.saml1.core.Advice} Object + */ +public class AdviceImpl extends AbstractSAMLObject implements Advice { + + /** Contains all the SAML objects we have added */ + private final IndexedXMLObjectChildrenList assertionChildren; + + /** "any" children */ + private final IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AdviceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + assertionChildren = new IndexedXMLObjectChildrenList(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAssertionIDReferences() { + // + // The cast in the line below is unsafe. (it's checking against the erasure of l - which is List. + // We are, howeverever guaranteed by sublist that although l is 'just' a List it + // will only contain explicit code in IndexedXMLObjectChildrenList$ListView.indexCheck + // helps us be sure. + + QName assertionIDRefQName = new QName(SAMLConstants.SAML1_NS, AssertionIDReference.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) assertionChildren.subList(assertionIDRefQName); + } + + /** {@inheritDoc} */ + public List getAssertions() { + // See Comment for getAssertionIDReference as to why this unsafe casting is OK + QName assertionQname = new QName(SAMLConstants.SAML1_NS, Assertion.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) assertionChildren.subList(assertionQname); + } + + /** + * {@inheritDoc} + */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(assertionChildren); + children.addAll(unknownChildren); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceMarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Advice} objects. + */ +public class AdviceMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AdviceUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Advice; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.Advice} objects. + */ +public class AdviceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Advice advice = (Advice) parentSAMLObject; + + if (childSAMLObject instanceof Assertion) { + advice.getAssertions().add((Assertion) childSAMLObject); + } else if (childSAMLObject instanceof AssertionIDReference) { + advice.getAssertionIDReferences().add((AssertionIDReference) childSAMLObject); + } else { + advice.getUnknownXMLObjects().add(childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AssertionArtifact; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AssertionArtifactImpl} objects. + */ +public class AssertionArtifactBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AssertionArtifactBuilder() { + + } + + /** {@inheritDoc} */ + public AssertionArtifact buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, AssertionArtifact.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionArtifact buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionArtifactImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactImpl.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.AssertionArtifact; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation if {@link org.opensaml.saml1.core.AssertionArtifact} + */ +public class AssertionArtifactImpl extends AbstractSAMLObject implements AssertionArtifact { + + /** The assertion artifact */ + private String assertionArtifact; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AssertionArtifactImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAssertionArtifact() { + return assertionArtifact; + } + + /** {@inheritDoc} */ + public void setAssertionArtifact(String assertionArtifact) { + this.assertionArtifact = prepareForAssignment(this.assertionArtifact, assertionArtifact); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactMarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.AssertionArtifact; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AssertionArtifact} objects. + */ +public class AssertionArtifactMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AssertionArtifact assertionArtifact = (AssertionArtifact) samlObject; + if (assertionArtifact.getAssertionArtifact() != null) { + XMLHelper.appendTextContent(domElement, assertionArtifact.getAssertionArtifact()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionArtifactUnmarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.AssertionArtifact; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AssertionArtifact} objects. + */ +public class AssertionArtifactUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AssertionArtifact assertionArtifact = (AssertionArtifact) samlObject; + + assertionArtifact.setAssertionArtifact(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionBuilder.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Assertion; + +/** + * Builder of {@link AssertionImpl} objects. + */ +public class AssertionBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AssertionBuilder() { + + } + + /** {@inheritDoc} */ + public AssertionImpl buildObject() { + return new AssertionImpl(SAMLConstants.SAML1_NS, Assertion.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionImpl buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceBuilder.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AssertionIDReference; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AssertionIDReferenceImpl} objects. + */ +public class AssertionIDReferenceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AssertionIDReferenceBuilder() { + + } + + /** {@inheritDoc} */ + public AssertionIDReference buildObject() { + return buildObject(SAMLConstants.SAML1_NS, AssertionIDReference.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionIDReference buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionIDReferenceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.xml.XMLObject; + +/** + * Concrete Implementation of {@link org.opensaml.saml1.core.AssertionIDReference} Object + */ +public class AssertionIDReferenceImpl extends AbstractSAMLObject implements AssertionIDReference { + + /** String to contain the NCName */ + private String NCName; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AssertionIDReferenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getReference() { + return NCName; + } + + /** {@inheritDoc} */ + public void setReference(String NCName) { + this.NCName = prepareForAssignment(this.NCName, NCName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceMarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AssertionIDReference} objects + */ +public class AssertionIDReferenceMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AssertionIDReference assertionIDReference = (AssertionIDReference) samlObject; + if (assertionIDReference.getReference() != null) { + XMLHelper.appendTextContent(domElement, assertionIDReference.getReference()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionIDReferenceUnmarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.xml.XMLObject; + +/** A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AssertionIDReference} objects. */ +public class AssertionIDReferenceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AssertionIDReference assertionIDReference = (AssertionIDReference) samlObject; + + assertionIDReference.setReference(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionImpl.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,210 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Advice; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.AttributeStatement; +import org.opensaml.saml1.core.AuthenticationStatement; +import org.opensaml.saml1.core.AuthorizationDecisionStatement; +import org.opensaml.saml1.core.Conditions; +import org.opensaml.saml1.core.Statement; +import org.opensaml.saml1.core.SubjectStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * This class implements the SAML 1 Assertion statement. + */ +public class AssertionImpl extends AbstractSignableSAMLObject implements Assertion { + + /** The AssertionID attrribute */ + private String id; + + /** SAML version of this assertion */ + private SAMLVersion version; + + /** Object version of the Issuer attribute. */ + private String issuer; + + /** Object version of the IssueInstant attribute. */ + private DateTime issueInstant; + + /** (Possibly null) Singleton object version of the Conditions element. */ + private Conditions conditions; + + /** (Possibly null) Singleton object version of the Advice element. */ + private Advice advice; + + /** Object representnation of all the Statement <\code> elements. */ + private final IndexedXMLObjectChildrenList statements; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AssertionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + statements = new IndexedXMLObjectChildrenList(this); + version = SAMLVersion.VERSION_11; + } + + /** {@inheritDoc} */ + public int getMajorVersion(){ + return version.getMajorVersion(); + } + + /** {@inheritDoc} */ + public int getMinorVersion() { + return version.getMinorVersion(); + } + + /** {@inheritDoc} */ + public void setVersion(SAMLVersion newVersion){ + version = prepareForAssignment(version, newVersion); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String id) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, id); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public String getIssuer() { + return this.issuer; + } + + /** {@inheritDoc} */ + public void setIssuer(String issuer) { + this.issuer = prepareForAssignment(this.issuer, issuer); + } + + /** {@inheritDoc} */ + public DateTime getIssueInstant() { + return this.issueInstant; + } + + /** {@inheritDoc} */ + public void setIssueInstant(DateTime issueInstant) { + this.issueInstant = prepareForAssignment(this.issueInstant, issueInstant); + } + + /** {@inheritDoc} */ + public Conditions getConditions() { + return conditions; + } + + /** {@inheritDoc} */ + public void setConditions(Conditions conditions) throws IllegalArgumentException { + this.conditions = prepareForAssignment(this.conditions, conditions); + } + + /** {@inheritDoc} */ + public Advice getAdvice() { + return advice; + } + + /** {@inheritDoc} */ + public void setAdvice(Advice advice) throws IllegalArgumentException { + this.advice = prepareForAssignment(this.advice, advice); + } + + /** {@inheritDoc} */ + public List getStatements() { + return statements; + } + + /** {@inheritDoc} */ + public List getStatements(QName typeOrName) { + return (List) statements.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getSubjectStatements() { + QName statementQName = new QName(SAMLConstants.SAML1_NS, SubjectStatement.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) statements.subList(statementQName); + } + + /** {@inheritDoc} */ + public List getAuthenticationStatements() { + QName statementQName = new QName(SAMLConstants.SAML1_NS, AuthenticationStatement.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) statements.subList(statementQName); + } + + /** {@inheritDoc} */ + public List getAuthorizationDecisionStatements() { + QName statementQName = new QName(SAMLConstants.SAML1_NS, AuthorizationDecisionStatement.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) statements.subList(statementQName); + } + + /** {@inheritDoc} */ + public List getAttributeStatements() { + QName statementQName = new QName(SAMLConstants.SAML1_NS, AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) statements.subList(statementQName); + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID(){ + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + if (conditions != null) { + children.add(conditions); + } + + if (advice != null) { + children.add(advice); + } + + children.addAll(statements); + + if(getSignature() != null){ + children.add(getSignature()); + } + + if (children.size() == 0) { + return null; + } + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionMarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.joda.time.format.ISODateTimeFormat; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Assertion} objects. + */ +public class AssertionMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + + Assertion assertion = (Assertion) samlElement; + + if (assertion.getID() != null) { + domElement.setAttributeNS(null, Assertion.ID_ATTRIB_NAME, assertion.getID()); + if (assertion.getMinorVersion() != 0) { + domElement.setIdAttributeNS(null, Assertion.ID_ATTRIB_NAME, true); + } + } + + if (assertion.getIssuer() != null) { + domElement.setAttributeNS(null, Assertion.ISSUER_ATTRIB_NAME, assertion.getIssuer()); + } + + if (assertion.getIssueInstant() != null) { + String date = ISODateTimeFormat.dateTime().print(assertion.getIssueInstant()); + domElement.setAttributeNS(null, Assertion.ISSUEINSTANT_ATTRIB_NAME, date); + } + + domElement.setAttributeNS(null, Assertion.MAJORVERSION_ATTRIB_NAME, "1"); + if (assertion.getMinorVersion() == 0) { + domElement.setAttributeNS(null, Assertion.MINORVERSION_ATTRIB_NAME, "0"); + } else { + domElement.setAttributeNS(null, Assertion.MINORVERSION_ATTRIB_NAME, "1"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AssertionUnmarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,92 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Advice; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.Conditions; +import org.opensaml.saml1.core.Statement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.Assertion} objects. + */ +public class AssertionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + public XMLObject unmarshall(Element domElement) throws UnmarshallingException { + // After regular unmarshalling, check the minor version and set ID-ness if not SAML 1.0 + Assertion assertion = (Assertion) super.unmarshall(domElement); + if (assertion.getMinorVersion() != 0 && !DatatypeHelper.isEmpty(assertion.getID())) { + domElement.setIdAttributeNS(null, Assertion.ID_ATTRIB_NAME, true); + } + return assertion; + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Assertion assertion = (Assertion) parentSAMLObject; + + if (childSAMLObject instanceof Signature) { + assertion.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof Conditions) { + assertion.setConditions((Conditions) childSAMLObject); + } else if (childSAMLObject instanceof Advice) { + assertion.setAdvice((Advice) childSAMLObject); + } else if (childSAMLObject instanceof Statement) { + assertion.getStatements().add((Statement) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + Assertion assertion = (Assertion) samlObject; + + if (Assertion.ID_ATTRIB_NAME.equals(attribute.getLocalName())) { + assertion.setID(attribute.getValue()); + } else if (Assertion.ISSUER_ATTRIB_NAME.equals(attribute.getLocalName())) { + assertion.setIssuer(attribute.getValue()); + } else if (Assertion.ISSUEINSTANT_ATTRIB_NAME.equals(attribute.getLocalName()) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (Assertion.MINORVERSION_ATTRIB_NAME.equals(attribute.getLocalName())) { + if (attribute.getValue().equals("0")) { + assertion.setVersion(SAMLVersion.VERSION_10); + } else { + assertion.setVersion(SAMLVersion.VERSION_11); + } + } else { + super.processAttribute(samlObject, attribute); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Attribute; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AttributeImpl} objects. + */ +public class AttributeBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeBuilder() { + + } + + /** {@inheritDoc} */ + public Attribute buildObject() { + return buildObject(SAMLConstants.SAML1_NS, Attribute.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Attribute buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorBuilder.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AttributeDesignator; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AttributeDesignatorImpl} objects. + */ +public class AttributeDesignatorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeDesignatorBuilder() { + } + + /** {@inheritDoc} */ + public AttributeDesignator buildObject() { + return buildObject(SAMLConstants.SAML1_NS, AttributeDesignator.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeDesignator buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeDesignatorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorImpl.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.AttributeDesignator; +import org.opensaml.xml.XMLObject; + +/** + * Concrete Implementation of the {@link org.opensaml.saml1.core.AttributeDesignator} interface. + */ +public class AttributeDesignatorImpl extends AbstractSAMLObject implements AttributeDesignator { + + /** Contains the AttributeName */ + private String attributeName; + + /** Contains the AttributeNamespace */ + private String attributeNamespace; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeDesignatorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAttributeName() { + return attributeName; + } + + /** {@inheritDoc} */ + public void setAttributeName(String attributeName) { + this.attributeName = prepareForAssignment(this.attributeName, attributeName); + } + + /** {@inheritDoc} */ + public String getAttributeNamespace() { + return attributeNamespace; + } + + /** {@inheritDoc} */ + public void setAttributeNamespace(String attributeNamespace) { + this.attributeNamespace = prepareForAssignment(this.attributeNamespace, attributeNamespace); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.AttributeDesignator; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** Marshaller of {@link AttributeDesignator} objects. */ +public class AttributeDesignatorMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AttributeDesignator designator = (AttributeDesignator) samlElement; + + if (designator.getAttributeName() != null) { + domElement.setAttributeNS(null, AttributeDesignator.ATTRIBUTENAME_ATTRIB_NAME, designator + .getAttributeName()); + } + + if (designator.getAttributeNamespace() != null) { + domElement.setAttributeNS(null, AttributeDesignator.ATTRIBUTENAMESPACE_ATTRIB_NAME, designator + .getAttributeNamespace()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeDesignatorUnmarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.AttributeDesignator; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link AttributeDesignator} objects. */ +public class AttributeDesignatorUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + AttributeDesignator designator = (AttributeDesignator) samlObject; + + if (AttributeDesignator.ATTRIBUTENAME_ATTRIB_NAME.equals(attribute.getLocalName())) { + designator.setAttributeName(attribute.getValue()); + } else if (AttributeDesignator.ATTRIBUTENAMESPACE_ATTRIB_NAME.equals(attribute.getLocalName())) { + designator.setAttributeNamespace(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml1.core.Attribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A Concrete implementation of the {@link org.opensaml.saml1.core.Attribute} Interface + */ +public class AttributeImpl extends AttributeDesignatorImpl implements Attribute { + + /** Contains the AttributeValues */ + private final XMLObjectChildrenList attributeValues; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeValues = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributeValues() { + return attributeValues; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return Collections.unmodifiableList(attributeValues); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeMarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Attribute} objects. + */ +public class AttributeMarshaller extends AttributeDesignatorMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryBuilder.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AttributeQuery; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AttributeQueryImpl} objects. + */ +public class AttributeQueryBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeQueryBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeQuery buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, AttributeQuery.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeQuery buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeQueryImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml1.core.AttributeDesignator; +import org.opensaml.saml1.core.AttributeQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of the {@link org.opensaml.saml1.core.AttributeQuery} interface + */ +public class AttributeQueryImpl extends SubjectQueryImpl implements AttributeQuery { + + /** Contains the resource attribute */ + private String resource; + + /** Contains all the child AttributeDesignators */ + private final XMLObjectChildrenList attributeDesignators; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeDesignators = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getResource() { + return resource; + } + + /** {@inheritDoc} */ + public void setResource(String resource) { + this.resource = prepareForAssignment(this.resource, resource); + } + + /** {@inheritDoc} */ + public List getAttributeDesignators() { + return attributeDesignators; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List list = new ArrayList(attributeDesignators.size() + 1); + + if (super.getOrderedChildren() != null) { + list.addAll(super.getOrderedChildren()); + } + + list.addAll(attributeDesignators); + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryMarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.AttributeQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml1.core.AttributeQuery} objects. + */ +public class AttributeQueryMarshaller extends SubjectQueryMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + + AttributeQuery attributeQuery = (AttributeQuery) samlElement; + + if (attributeQuery.getResource() != null) { + domElement.setAttributeNS(null, AttributeQuery.RESOURCE_ATTRIB_NAME, attributeQuery.getResource()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeQueryUnmarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.AttributeDesignator; +import org.opensaml.saml1.core.AttributeQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AttributeQuery} objects. + */ +public class AttributeQueryUnmarshaller extends SubjectQueryUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + AttributeQuery attributeQuery = (AttributeQuery) parentSAMLObject; + + if (childSAMLObject instanceof AttributeDesignator) { + attributeQuery.getAttributeDesignators().add((AttributeDesignator) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + AttributeQuery attributeQuery = (AttributeQuery) samlObject; + + if (attribute.getLocalName().equals(AttributeQuery.RESOURCE_ATTRIB_NAME)) { + attributeQuery.setResource(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AttributeStatement; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AttributeStatementImpl} objects. + */ +public class AttributeStatementBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeStatementBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeStatement buildObject() { + return buildObject(SAMLConstants.SAML1_NS, AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeStatement buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeStatementImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml1.core.Attribute; +import org.opensaml.saml1.core.AttributeStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A Concrete implementation of the {@link org.opensaml.saml1.core.AttributeStatement} Interface + */ +public class AttributeStatementImpl extends SubjectStatementImpl implements AttributeStatement { + + /** Contains the Attributes (in order) */ + private final XMLObjectChildrenList attributes; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeStatementImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List list = new ArrayList(attributes.size() + 1); + + if (super.getOrderedChildren() != null) { + list.addAll(super.getOrderedChildren()); + } + + list.addAll(attributes); + + if (list.size() == 0) { + return null; + } + + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementMarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml1.core.AttributeStatement} objects. + */ +public class AttributeStatementMarshaller extends SubjectStatementMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeStatementUnmarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.Attribute; +import org.opensaml.saml1.core.AttributeStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AttributeStatement} objects. + */ +public class AttributeStatementUnmarshaller extends SubjectStatementUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + AttributeStatement attributeStatement = (AttributeStatement) parentSAMLObject; + + if (childSAMLObject instanceof Attribute) { + attributeStatement.getAttributes().add((Attribute) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AttributeUnmarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Attribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.impl.AttributeImpl} objects. + */ +public class AttributeUnmarshaller extends AttributeDesignatorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Attribute attribute = (Attribute) parentSAMLObject; + + QName childQName = childSAMLObject.getElementQName(); + if (childQName.getLocalPart().equals("AttributeValue") + && childQName.getNamespaceURI().equals(SAMLConstants.SAML1_NS)) { + attribute.getAttributeValues().add(childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Audience; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AudienceImpl} objects. + */ +public class AudienceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AudienceBuilder() { + + } + + /** {@inheritDoc} */ + public Audience buildObject() { + return buildObject(SAMLConstants.SAML1_NS, Audience.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Audience buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AudienceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceImpl.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.Audience; +import org.opensaml.xml.XMLObject; + +/** + * Concrete class implementation of {@link org.opensaml.saml1.core.Audience} + */ +public class AudienceImpl extends AbstractSAMLObject implements Audience { + + /** String to hold the URI */ + private String uri; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AudienceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getUri() { + return uri; + } + + /** {@inheritDoc} */ + public void setUri(String uri) { + + this.uri = prepareForAssignment(this.uri, uri); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceMarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.Audience; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Audience} objects. + */ +public class AudienceMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Audience audience = (Audience) samlObject; + + XMLHelper.appendTextContent(domElement, audience.getUri()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionBuilder.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AudienceRestrictionCondition; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AudienceRestrictionConditionImpl} objects. + */ +public class AudienceRestrictionConditionBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AudienceRestrictionConditionBuilder() { + + } + + /** {@inheritDoc} */ + public AudienceRestrictionCondition buildObject() { + return buildObject(SAMLConstants.SAML1_NS, AudienceRestrictionCondition.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public AudienceRestrictionCondition buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AudienceRestrictionConditionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.Audience; +import org.opensaml.saml1.core.AudienceRestrictionCondition; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of the org.opensaml.saml1.core.AudienceRestrictionCondition + */ +public class AudienceRestrictionConditionImpl extends AbstractSAMLObject implements AudienceRestrictionCondition { + + /** Audiences */ + private final XMLObjectChildrenList audiences; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AudienceRestrictionConditionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + audiences = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAudiences() { + return audiences; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + if (audiences.size() == 0) { + return null; + } + ArrayList children = new ArrayList(audiences); + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AudienceRestrictionCondition} objects. + */ +public class AudienceRestrictionConditionMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceRestrictionConditionUnmarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Audience; +import org.opensaml.saml1.core.AudienceRestrictionCondition; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AudienceRestrictionCondition} objects. + */ +public class AudienceRestrictionConditionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + AudienceRestrictionCondition audienceRestrictionCondition = (AudienceRestrictionCondition) parentSAMLObject; + + if (childSAMLObject instanceof Audience) { + audienceRestrictionCondition.getAudiences().add((Audience) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AudienceUnmarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Audience; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.Audience} objects. + */ +public class AudienceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Audience audience = (Audience) samlObject; + audience.setUri(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryBuilder.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AuthenticationQuery; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AuthenticationQueryImpl} objects. + */ +public class AuthenticationQueryBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthenticationQueryBuilder() { + + } + + /** {@inheritDoc} */ + public AuthenticationQuery buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, AuthenticationQuery.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public AuthenticationQuery buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthenticationQueryImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml1.core.AuthenticationQuery; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of the {@link org.opensaml.saml1.core.AuthenticationQuery} interface + */ +public class AuthenticationQueryImpl extends SubjectQueryImpl implements AuthenticationQuery { + + /** The method used to do the authentication */ + private String authenticationMethod; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthenticationQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAuthenticationMethod() { + return authenticationMethod; + } + + /** {@inheritDoc} */ + public void setAuthenticationMethod(String authenticationMethod) { + this.authenticationMethod = prepareForAssignment(this.authenticationMethod, authenticationMethod); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List list = new ArrayList(); + + if (super.getOrderedChildren() != null) { + list.addAll(super.getOrderedChildren()); + } + + if (list.size() == 0) { + return null; + } + + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryMarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.AuthenticationQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AuthenticationQuery} objects. + */ +public class AuthenticationQueryMarshaller extends SubjectQueryMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthenticationQuery authenticationQuery = (AuthenticationQuery) samlObject; + + if (authenticationQuery.getAuthenticationMethod() != null) { + domElement.setAttributeNS(null, AuthenticationQuery.AUTHENTICATIONMETHOD_ATTRIB_NAME, authenticationQuery + .getAuthenticationMethod()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationQueryUnmarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.AuthenticationQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AuthenticationQuery} objects. + */ +public class AuthenticationQueryUnmarshaller extends SubjectQueryUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AuthenticationQuery authenticationQuery = (AuthenticationQuery) samlObject; + + if (AuthenticationQuery.AUTHENTICATIONMETHOD_ATTRIB_NAME.equals(attribute.getLocalName())) { + authenticationQuery.setAuthenticationMethod(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementBuilder.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AuthenticationStatement; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AuthenticationStatementImpl} objects. + */ +public class AuthenticationStatementBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthenticationStatementBuilder() { + + } + + /** {@inheritDoc} */ + public AuthenticationStatement buildObject() { + return buildObject(SAMLConstants.SAML1_NS, AuthenticationStatement.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public AuthenticationStatement buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthenticationStatementImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.saml1.core.AuthenticationStatement; +import org.opensaml.saml1.core.AuthorityBinding; +import org.opensaml.saml1.core.SubjectLocality; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A Concrete implementation of the {@link org.opensaml.saml1.core.AuthenticationStatement} Interface + */ +public class AuthenticationStatementImpl extends SubjectStatementImpl implements AuthenticationStatement { + + /** Contains the AuthenticationMethod attribute contents */ + private String authenticationMethod; + + /** Contains the AuthenticationMethod attribute contents */ + private DateTime authenticationInstant; + + /** Contains the SubjectLocality subelement */ + private SubjectLocality subjectLocality; + + /** Contains the AuthorityBinding subelements */ + private final XMLObjectChildrenList authorityBindings; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthenticationStatementImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + authorityBindings = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getAuthenticationMethod() { + return authenticationMethod; + } + + /** {@inheritDoc} */ + public void setAuthenticationMethod(String authenticationMethod) { + this.authenticationMethod = prepareForAssignment(this.authenticationMethod, authenticationMethod); + } + + /** {@inheritDoc} */ + public DateTime getAuthenticationInstant() { + return authenticationInstant; + } + + /** {@inheritDoc} */ + public void setAuthenticationInstant(DateTime authenticationInstant) { + this.authenticationInstant = prepareForAssignment(this.authenticationInstant, authenticationInstant); + } + + // + // Elements + // + + /** {@inheritDoc} */ + public SubjectLocality getSubjectLocality() { + return subjectLocality; + } + + /** {@inheritDoc} */ + public void setSubjectLocality(SubjectLocality subjectLocality) throws IllegalArgumentException { + this.subjectLocality = prepareForAssignment(this.subjectLocality, subjectLocality); + } + + /** {@inheritDoc} */ + public List getAuthorityBindings() { + return authorityBindings; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List list = new ArrayList(authorityBindings.size() + 2); + + if (super.getOrderedChildren() != null) { + list.addAll(super.getOrderedChildren()); + } + + if (subjectLocality != null) { + list.add(subjectLocality); + } + + list.addAll(authorityBindings); + + if (list.size() == 0) { + return null; + } + + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementMarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.saml1.core.AuthenticationStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AuthenticationStatement} objects. + */ +public class AuthenticationStatementMarshaller extends SubjectStatementMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AuthenticationStatement authenticationStatement = (AuthenticationStatement) samlElement; + + if (authenticationStatement.getAuthenticationMethod() != null) { + domElement.setAttributeNS(null, AuthenticationStatement.AUTHENTICATIONMETHOD_ATTRIB_NAME, + authenticationStatement.getAuthenticationMethod()); + } + + if (authenticationStatement.getAuthenticationInstant() != null) { + String value = Configuration.getSAMLDateFormatter().print( + authenticationStatement.getAuthenticationInstant()); + domElement.setAttributeNS(null, AuthenticationStatement.AUTHENTICATIONINSTANT_ATTRIB_NAME, value); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthenticationStatementUnmarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.saml1.core.AuthenticationStatement; +import org.opensaml.saml1.core.AuthorityBinding; +import org.opensaml.saml1.core.SubjectLocality; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AuthenticationStatement} objects. + */ +public class AuthenticationStatementUnmarshaller extends SubjectStatementUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + AuthenticationStatement authenticationStatement = (AuthenticationStatement) parentSAMLObject; + + if (childSAMLObject instanceof SubjectLocality) { + authenticationStatement.setSubjectLocality((SubjectLocality) childSAMLObject); + } else if (childSAMLObject instanceof AuthorityBinding) { + authenticationStatement.getAuthorityBindings().add((AuthorityBinding) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AuthenticationStatement authenticationStatement = (AuthenticationStatement) samlObject; + + if (AuthenticationStatement.AUTHENTICATIONINSTANT_ATTRIB_NAME.equals(attribute.getLocalName()) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + DateTime value = new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()); + authenticationStatement.setAuthenticationInstant(value); + } else if (AuthenticationStatement.AUTHENTICATIONMETHOD_ATTRIB_NAME.equals(attribute.getLocalName())) { + authenticationStatement.setAuthenticationMethod(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingBuilder.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AuthorityBinding; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AuthorityBindingImpl} objects. + */ +public class AuthorityBindingBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthorityBindingBuilder() { + + } + + /** {@inheritDoc} */ + public AuthorityBinding buildObject() { + return buildObject(SAMLConstants.SAML1_NS, AuthorityBinding.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + public AuthorityBinding buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthorityBindingImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingImpl.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.AuthorityBinding; +import org.opensaml.xml.XMLObject; + +/** + * A concrete impementation of the {@link org.opensaml.saml1.core.SubjectLocality} interface + */ +public class AuthorityBindingImpl extends AbstractSAMLObject implements AuthorityBinding { + + /** The AuthorityKind */ + private QName authorityKind; + + /** The Location */ + private String location; + + /** The Binding */ + private String binding; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthorityBindingImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public QName getAuthorityKind() { + return authorityKind; + } + + /** {@inheritDoc} */ + public void setAuthorityKind(QName authorityKind) { + this.authorityKind = prepareAttributeValueForAssignment(AuthorityBinding.AUTHORITYKIND_ATTRIB_NAME, + this.authorityKind, authorityKind); + } + + /** {@inheritDoc} */ + public String getLocation() { + return location; + } + + /** {@inheritDoc} */ + public void setLocation(String location) { + this.location = prepareForAssignment(this.location, location); + } + + /** {@inheritDoc} */ + public String getBinding() { + return binding; + } + + /** {@inheritDoc} */ + public void setBinding(String binding) { + this.binding = prepareForAssignment(this.binding, binding); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingMarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.AuthorityBinding; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AuthorityBinding} objects. + */ +public class AuthorityBindingMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + public void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AuthorityBinding authorityBinding = (AuthorityBinding) samlElement; + + if (authorityBinding.getAuthorityKind() != null) { + QName authKind = authorityBinding.getAuthorityKind(); + domElement.setAttributeNS(null, AuthorityBinding.AUTHORITYKIND_ATTRIB_NAME, XMLHelper + .qnameToContentString(authKind)); + } + + if (authorityBinding.getBinding() != null) { + domElement.setAttributeNS(null, AuthorityBinding.BINDING_ATTRIB_NAME, authorityBinding.getBinding()); + } + + if (authorityBinding.getLocation() != null) { + domElement.setAttributeNS(null, AuthorityBinding.LOCATION_ATTRIB_NAME, authorityBinding.getLocation()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorityBindingUnmarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.AuthorityBinding; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe {@link org.opensaml.xml.io.Unmarshaller} for {@link org.opensaml.saml1.core.AuthorityBinding} objects. + */ +public class AuthorityBindingUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + AuthorityBinding authorityBinding = (AuthorityBinding) samlObject; + + if (AuthorityBinding.AUTHORITYKIND_ATTRIB_NAME.equals(attribute.getLocalName())) { + authorityBinding.setAuthorityKind(XMLHelper.getAttributeValueAsQName(attribute)); + } else if (AuthorityBinding.LOCATION_ATTRIB_NAME.equals(attribute.getLocalName())) { + authorityBinding.setLocation(attribute.getValue()); + } else if (AuthorityBinding.BINDING_ATTRIB_NAME.equals(attribute.getLocalName())) { + authorityBinding.setBinding(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryBuilder.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AuthorizationDecisionQuery; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AuthorizationDecisionQueryImpl} objects. + */ +public class AuthorizationDecisionQueryBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthorizationDecisionQueryBuilder() { + + } + + /** {@inheritDoc} */ + public AuthorizationDecisionQuery buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, AuthorizationDecisionQuery.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public AuthorizationDecisionQuery buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthorizationDecisionQueryImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryImpl.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,102 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Action; +import org.opensaml.saml1.core.AuthorizationDecisionQuery; +import org.opensaml.saml1.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of the {@link org.opensaml.saml1.core.AuthorizationDecisionQuery} interface + */ +public class AuthorizationDecisionQueryImpl extends SubjectQueryImpl implements AuthorizationDecisionQuery { + + /** Contains the resource attribute */ + private String resource; + + /** Contains all the Action child elements */ + private final XMLObjectChildrenList actions; + + /** Contains the Evidence child element */ + private Evidence evidence; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthorizationDecisionQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + setElementNamespacePrefix(SAMLConstants.SAML1P_PREFIX); + actions = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getResource() { + return resource; + } + + /** {@inheritDoc} */ + public void setResource(String resource) { + this.resource = prepareForAssignment(this.resource, resource); + } + + /** {@inheritDoc} */ + public List getActions() { + return actions; + } + + /** {@inheritDoc} */ + public Evidence getEvidence() { + return evidence; + } + + /** {@inheritDoc} */ + public void setEvidence(Evidence evidence) { + this.evidence = prepareForAssignment(this.evidence, evidence); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List list = new ArrayList(actions.size() + 2); + + if (super.getOrderedChildren() != null) { + list.addAll(super.getOrderedChildren()); + } + + list.addAll(actions); + if (evidence != null) { + list.add(evidence); + } + + if (list.size() == 0) { + return null; + } + + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryMarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.AuthorizationDecisionQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AuthorizationDecisionQuery} objects. + */ +public class AuthorizationDecisionQueryMarshaller extends SubjectQueryMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AuthorizationDecisionQuery authorizationDecisionQuery = (AuthorizationDecisionQuery) samlElement; + + if (authorizationDecisionQuery.getResource() != null) { + domElement.setAttributeNS(null, AuthorizationDecisionQuery.RESOURCE_ATTRIB_NAME, authorizationDecisionQuery + .getResource()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionQueryUnmarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.Action; +import org.opensaml.saml1.core.AuthorizationDecisionQuery; +import org.opensaml.saml1.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.AuthorizationDecisionQuery} objects. + */ +public class AuthorizationDecisionQueryUnmarshaller extends SubjectQueryUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + AuthorizationDecisionQuery authorizationDecisionQuery; + authorizationDecisionQuery = (AuthorizationDecisionQuery) parentSAMLObject; + + if (childSAMLObject instanceof Action) { + authorizationDecisionQuery.getActions().add((Action) childSAMLObject); + } else if (childSAMLObject instanceof Evidence) { + authorizationDecisionQuery.setEvidence((Evidence) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + AuthorizationDecisionQuery authorizationDecisionQuery; + authorizationDecisionQuery = (AuthorizationDecisionQuery) samlObject; + + if (attribute.getLocalName().equals(AuthorizationDecisionQuery.RESOURCE_ATTRIB_NAME)) { + authorizationDecisionQuery.setResource(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementBuilder.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AuthorizationDecisionStatement; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.AuthorizationDecisionStatementImpl} objects. + */ +public class AuthorizationDecisionStatementBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthorizationDecisionStatementBuilder() { + + } + + /** {@inheritDoc} */ + public AuthorizationDecisionStatement buildObject() { + return buildObject(SAMLConstants.SAML1_NS, AuthorizationDecisionStatement.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public AuthorizationDecisionStatement buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthorizationDecisionStatementImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml1.core.Action; +import org.opensaml.saml1.core.AuthorizationDecisionStatement; +import org.opensaml.saml1.core.DecisionTypeEnumeration; +import org.opensaml.saml1.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml1.core.AuthorizationDecisionStatement} + */ +public class AuthorizationDecisionStatementImpl extends SubjectStatementImpl implements AuthorizationDecisionStatement { + + /** Contains the Resource attribute */ + private String resource; + + /** Contains the Decision attribute */ + private DecisionTypeEnumeration decision; + + /** Contains the list of Action elements */ + private final XMLObjectChildrenList actions; + + /** Contains the (single) Evidence element */ + private Evidence evidence; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthorizationDecisionStatementImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + actions = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getResource() { + return resource; + } + + /** {@inheritDoc} */ + public void setResource(String resource) { + this.resource = prepareForAssignment(this.resource, resource); + } + + /** {@inheritDoc} */ + public DecisionTypeEnumeration getDecision() { + return decision; + } + + /** {@inheritDoc} */ + public void setDecision(DecisionTypeEnumeration decision) { + this.decision = prepareForAssignment(this.decision, decision); + } + + /** {@inheritDoc} */ + public List getActions() { + return actions; + } + + /** {@inheritDoc} */ + public Evidence getEvidence() { + return evidence; + } + + /** {@inheritDoc} */ + public void setEvidence(Evidence evidence) throws IllegalArgumentException { + this.evidence = prepareForAssignment(this.evidence, evidence); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List list = new ArrayList(actions.size() + 2); + + if (super.getOrderedChildren() != null) { + list.addAll(super.getOrderedChildren()); + } + list.addAll(actions); + if (evidence != null) { + list.add(evidence); + } + if (list.size() == 0) { + return null; + } + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementMarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.AuthorizationDecisionStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.AuthorizationDecisionStatement} objects. + */ +public class AuthorizationDecisionStatementMarshaller extends SubjectStatementMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AuthorizationDecisionStatement authorizationDecisionStatement; + + authorizationDecisionStatement = (AuthorizationDecisionStatement) samlElement; + + if (authorizationDecisionStatement.getResource() != null) { + domElement.setAttributeNS(null, AuthorizationDecisionStatement.RESOURCE_ATTRIB_NAME, + authorizationDecisionStatement.getResource()); + } + + if (authorizationDecisionStatement.getDecision() != null) { + domElement.setAttributeNS(null, AuthorizationDecisionStatement.DECISION_ATTRIB_NAME, + authorizationDecisionStatement.getDecision().toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/AuthorizationDecisionStatementUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.Action; +import org.opensaml.saml1.core.AuthorizationDecisionStatement; +import org.opensaml.saml1.core.DecisionTypeEnumeration; +import org.opensaml.saml1.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.impl.AuthorizationDecisionStatementImpl} objects. + */ +public class AuthorizationDecisionStatementUnmarshaller extends SubjectStatementUnmarshaller { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(AuthorizationDecisionStatementUnmarshaller.class); + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + AuthorizationDecisionStatement authorizationDecisionStatement; + authorizationDecisionStatement = (AuthorizationDecisionStatement) parentSAMLObject; + + if (childSAMLObject instanceof Action) { + authorizationDecisionStatement.getActions().add((Action) childSAMLObject); + } else if (childSAMLObject instanceof Evidence) { + authorizationDecisionStatement.setEvidence((Evidence) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + AuthorizationDecisionStatement authorizationDecisionStatement; + authorizationDecisionStatement = (AuthorizationDecisionStatement) samlObject; + + if (AuthorizationDecisionStatement.DECISION_ATTRIB_NAME.equals(attribute.getLocalName())) { + String value = attribute.getValue(); + if (value.equals(DecisionTypeEnumeration.PERMIT.toString())) { + authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.PERMIT); + } else if (value.equals(DecisionTypeEnumeration.DENY.toString())) { + authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.DENY); + } else if (value.equals(DecisionTypeEnumeration.INDETERMINATE.toString())) { + authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.INDETERMINATE); + } else { + log.error("Unknown value for DecisionType '" + value + "'"); + throw new UnmarshallingException("Unknown value for DecisionType '" + value + "'"); + } + } else if (AuthorizationDecisionStatement.RESOURCE_ATTRIB_NAME.equals(attribute.getLocalName())) { + authorizationDecisionStatement.setResource(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Conditions; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.ConditionsImpl} objects. + */ +public class ConditionsBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ConditionsBuilder() { + + } + + /** {@inheritDoc} */ + public Conditions buildObject() { + return buildObject(SAMLConstants.SAML1_NS, Conditions.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Conditions buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ConditionsImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsImpl.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,113 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.AudienceRestrictionCondition; +import org.opensaml.saml1.core.Condition; +import org.opensaml.saml1.core.Conditions; +import org.opensaml.saml1.core.DoNotCacheCondition; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * This is a concrete implementation of the {@link org.opensaml.saml1.core.Conditions} interface. + */ +public class ConditionsImpl extends AbstractSAMLObject implements Conditions { + + /** Value saved in the NotBefore attribute */ + private DateTime notBefore; + + /** Value saved in the NotOnOrAfter attribute */ + private DateTime notOnOrAfter; + + /** Set containing all the Conditions */ + private final IndexedXMLObjectChildrenList conditions; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ConditionsImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + conditions = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public DateTime getNotBefore() { + return notBefore; + } + + /** {@inheritDoc} */ + public void setNotBefore(DateTime notBefore) { + this.notBefore = prepareForAssignment(this.notBefore, notBefore); + } + + /** {@inheritDoc} */ + public DateTime getNotOnOrAfter() { + return notOnOrAfter; + } + + /** {@inheritDoc} */ + public void setNotOnOrAfter(DateTime notOnOrAfter) { + this.notOnOrAfter = prepareForAssignment(this.notOnOrAfter, notOnOrAfter); + } + + /** {@inheritDoc} */ + public List getConditions() { + return conditions; + } + + /** {@inheritDoc} */ + public List getConditions(QName typeOrName) { + return conditions; + } + + /** {@inheritDoc} */ + public List getAudienceRestrictionConditions() { + QName qname = new QName(SAMLConstants.SAML1_NS, AudienceRestrictionCondition.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) conditions.subList(qname); + } + + /** {@inheritDoc} */ + public List getDoNotCacheConditions() { + QName qname = new QName(SAMLConstants.SAML1_NS, DoNotCacheCondition.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) conditions.subList(qname); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + if (conditions.size() == 0) { + return null; + } + ArrayList children = new ArrayList(); + children.addAll(conditions); + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsMarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.Conditions; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.Conditions} objects. + */ +public class ConditionsMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + + Conditions conditions = (Conditions) samlElement; + + if (conditions.getNotBefore() != null) { + String date = Configuration.getSAMLDateFormatter().print(conditions.getNotBefore()); + domElement.setAttributeNS(null, Conditions.NOTBEFORE_ATTRIB_NAME, date); + } + + if (conditions.getNotOnOrAfter() != null) { + String date = Configuration.getSAMLDateFormatter().print(conditions.getNotOnOrAfter()); + domElement.setAttributeNS(null, Conditions.NOTONORAFTER_ATTRIB_NAME, date); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConditionsUnmarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Condition; +import org.opensaml.saml1.core.Conditions; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.Conditions} objects. + */ +public class ConditionsUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Conditions conditions = (Conditions) parentSAMLObject; + + if (childSAMLObject instanceof Condition) { + conditions.getConditions().add((Condition) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + Conditions conditions = (Conditions) samlObject; + + if (Conditions.NOTBEFORE_ATTRIB_NAME.equals(attribute.getLocalName()) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + conditions.setNotBefore(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (Conditions.NOTONORAFTER_ATTRIB_NAME.equals(attribute.getLocalName()) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + conditions.setNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else { + processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodBuilder.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.ConfirmationMethod; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.ConfirmationMethodImpl} objects. + */ +public class ConfirmationMethodBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ConfirmationMethodBuilder() { + + } + + /** {@inheritDoc} */ + public ConfirmationMethod buildObject() { + return buildObject(SAMLConstants.SAML1_NS, ConfirmationMethod.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public ConfirmationMethod buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ConfirmationMethodImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodImpl.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.ConfirmationMethod; +import org.opensaml.xml.XMLObject; + +/** + * Concrete Implementation of the {@link org.opensaml.saml1.core.ConfirmationMethod} interface + */ +public class ConfirmationMethodImpl extends AbstractSAMLObject implements ConfirmationMethod { + + /** Contains the content string */ + private String confirmationMethod; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ConfirmationMethodImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getConfirmationMethod() { + return confirmationMethod; + } + + /** {@inheritDoc} */ + public void setConfirmationMethod(String confirmationMethod) { + this.confirmationMethod = prepareForAssignment(this.confirmationMethod, confirmationMethod); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.ConfirmationMethod; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.ConfirmationMethod} objects. + */ +public class ConfirmationMethodMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + ConfirmationMethod confirmationMethod = (ConfirmationMethod) samlObject; + + XMLHelper.appendTextContent(domElement, confirmationMethod.getConfirmationMethod()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ConfirmationMethodUnmarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.ConfirmationMethod; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.ConfirmationMethod} objects. + */ +public class ConfirmationMethodUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + ConfirmationMethod confirmationMethod = (ConfirmationMethod) samlObject; + + confirmationMethod.setConfirmationMethod(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.DoNotCacheCondition; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.DoNotCacheConditionImpl} objects. + */ +public class DoNotCacheConditionBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public DoNotCacheConditionBuilder() { + + } + + /** {@inheritDoc} */ + public DoNotCacheCondition buildObject() { + return buildObject(SAMLConstants.SAML1_NS, DoNotCacheCondition.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public DoNotCacheCondition buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DoNotCacheConditionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.DoNotCacheCondition; +import org.opensaml.xml.XMLObject; + +/** + * Concrete Implementation of a {@link org.opensaml.saml1.core.DoNotCacheCondition} Objects. + */ +public class DoNotCacheConditionImpl extends AbstractSAMLObject implements DoNotCacheCondition { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected DoNotCacheConditionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionMarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * Thread safe Marshaller for {@link org.opensaml.saml1.core.DoNotCacheCondition} objects. + */ +public class DoNotCacheConditionMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/DoNotCacheConditionUnmarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.DoNotCacheCondition} objects. + */ +public class DoNotCacheConditionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceBuilder.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Evidence; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.EvidenceImpl} objects. + */ +public class EvidenceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public EvidenceBuilder() { + + } + + /** {@inheritDoc} */ + public Evidence buildObject() { + return buildObject(SAMLConstants.SAML1_NS, Evidence.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Evidence buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EvidenceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.saml1.core.Evidence; +import org.opensaml.saml1.core.Evidentiary; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of the {@link org.opensaml.saml1.core.Evidence} interface. + */ +public class EvidenceImpl extends AbstractSAMLObject implements Evidence { + + /** The Evidentiary child elements. */ + private final IndexedXMLObjectChildrenList evidence; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EvidenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + evidence = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAssertionIDReferences() { + QName qname = new QName(SAMLConstants.SAML1_NS, AssertionIDReference.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) evidence.subList(qname); + } + + /** {@inheritDoc} */ + public List getAssertions() { + QName qname = new QName(SAMLConstants.SAML1_NS, Assertion.DEFAULT_ELEMENT_LOCAL_NAME); + return (List) evidence.subList(qname); + } + + /** {@inheritDoc} */ + public List getEvidence() { + return evidence; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + if (evidence.size() == 0) { + return null; + } + + ArrayList list = new ArrayList(); + list.addAll(evidence); + + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceMarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Evidence} objects. + */ +public class EvidenceMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/EvidenceUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.saml1.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml1.core.Evidence} objects. + */ +public class EvidenceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Evidence evidence = (Evidence) parentSAMLObject; + + if (childSAMLObject instanceof AssertionIDReference) { + evidence.getAssertionIDReferences().add((AssertionIDReference) childSAMLObject); + } else if (childSAMLObject instanceof Assertion) { + evidence.getAssertions().add((Assertion) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierBuilder.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.NameIdentifier; + +/** + * Builder of{@link org.opensaml.saml1.core.impl.NameIdentifierImpl} objects. + */ +public class NameIdentifierBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public NameIdentifierBuilder() { + + } + + /** {@inheritDoc} */ + public NameIdentifier buildObject() { + return buildObject(SAMLConstants.SAML1_NS, NameIdentifier.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public NameIdentifier buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NameIdentifierImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.xml.XMLObject; + +/** + * Complete implementation of {@link org.opensaml.saml1.core.impl.NameIdentifierImpl} + */ +public class NameIdentifierImpl extends AbstractSAMLObject implements NameIdentifier { + + /** Contents of the NameQualifierAttribute */ + String nameQualifier; + + /** Contents of the Format */ + String format; + + /** Contents of the elemen body */ + String nameIdentifier; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected NameIdentifierImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getNameQualifier() { + return nameQualifier; + } + + /** {@inheritDoc} */ + public String getFormat() { + return this.format; + } + + /** {@inheritDoc} */ + public String getNameIdentifier() { + return nameIdentifier; + } + + /** {@inheritDoc} */ + public void setNameQualifier(String nameQualifier) { + this.nameQualifier = prepareForAssignment(this.nameQualifier, nameQualifier); + } + + public void setFormat(String format) { + this.format = prepareForAssignment(this.format, format); + } + + public void setNameIdentifier(String nameIdentifier) { + this.nameIdentifier = prepareForAssignment(this.nameIdentifier, nameIdentifier); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierMarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.NameIdentifier} objects. + */ +public class NameIdentifierMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + NameIdentifier nameIdentifier = (NameIdentifier) samlElement; + + if (nameIdentifier.getNameQualifier() != null) { + domElement + .setAttributeNS(null, NameIdentifier.NAMEQUALIFIER_ATTRIB_NAME, nameIdentifier.getNameQualifier()); + } + + if (nameIdentifier.getFormat() != null) { + domElement.setAttributeNS(null, NameIdentifier.FORMAT_ATTRIB_NAME, nameIdentifier.getFormat()); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + NameIdentifier nameIdentifier = (NameIdentifier) samlObject; + + if (nameIdentifier.getNameIdentifier() != null) { + XMLHelper.appendTextContent(domElement, nameIdentifier.getNameIdentifier()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/NameIdentifierUnmarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml1.core.NameIdentifier} objects. + */ +public class NameIdentifierUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + NameIdentifier nameIdentifier = (NameIdentifier) samlObject; + + if (NameIdentifier.FORMAT_ATTRIB_NAME.equals(attribute.getLocalName())) { + nameIdentifier.setFormat(attribute.getValue()); + } else if (NameIdentifier.NAMEQUALIFIER_ATTRIB_NAME.equals(attribute.getLocalName())) { + nameIdentifier.setNameQualifier(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + NameIdentifier nameIdentifier = (NameIdentifier) samlObject; + nameIdentifier.setNameIdentifier(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeImpl.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,121 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.saml1.core.RespondWith; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link org.opensaml.saml1.core.RequestAbstractType}. + */ +public abstract class RequestAbstractTypeImpl extends AbstractSignableSAMLObject implements RequestAbstractType { + + /** Contains the ID */ + private String id; + + /** Containt the IssueInstant */ + private DateTime issueInstant; + + /** Version of this SAML message */ + private SAMLVersion version; + + /** Contains the respondWiths */ + public final XMLObjectChildrenList respondWiths; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RequestAbstractTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + version = SAMLVersion.VERSION_11; + respondWiths = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String id) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, id); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public int getMajorVersion() { + return version.getMajorVersion(); + } + + /** {@inheritDoc} */ + public int getMinorVersion() { + return version.getMinorVersion(); + } + + /** {@inheritDoc} */ + public void setVersion(SAMLVersion newVersion) { + version = prepareForAssignment(version, newVersion); + } + + /** {@inheritDoc} */ + public DateTime getIssueInstant() { + return issueInstant; + } + + /** {@inheritDoc} */ + public void setIssueInstant(DateTime instant) { + this.issueInstant = prepareForAssignment(this.issueInstant, instant); + } + + /** {@inheritDoc} */ + public List getRespondWiths() { + return respondWiths; + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID(){ + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + + children.addAll(respondWiths); + + if(getSignature() != null){ + children.add(getSignature()); + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeMarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.RequestAbstractType} objects. + */ +public class RequestAbstractTypeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + RequestAbstractType request = (RequestAbstractType) samlElement; + + if (request.getID() != null) { + domElement.setAttributeNS(null, RequestAbstractType.ID_ATTRIB_NAME, request.getID()); + if (request.getMinorVersion() != 0) { + domElement.setIdAttributeNS(null, RequestAbstractType.ID_ATTRIB_NAME, true); + } + } + + if (request.getIssueInstant() != null) { + String date = Configuration.getSAMLDateFormatter().print(request.getIssueInstant()); + domElement.setAttributeNS(null, RequestAbstractType.ISSUEINSTANT_ATTRIB_NAME, date); + } + if (request.getMinorVersion() != 0) { + domElement.setAttributeNS(null, RequestAbstractType.MAJORVERSION_ATTRIB_NAME, "1"); + domElement.setAttributeNS(null, RequestAbstractType.MINORVERSION_ATTRIB_NAME, Integer.toString(request + .getMinorVersion())); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestAbstractTypeUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.saml1.core.RespondWith; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml1.core.RequestAbstractType} objects. + */ +public abstract class RequestAbstractTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(RequestAbstractType.class); + + /** {@inheritDoc} */ + public XMLObject unmarshall(Element domElement) throws UnmarshallingException { + // After regular unmarshalling, check the minor version and set ID-ness if not SAML 1.0 + RequestAbstractType request = (RequestAbstractType) super.unmarshall(domElement); + if (request.getMinorVersion() != 0 && !DatatypeHelper.isEmpty(request.getID())) { + domElement.setIdAttributeNS(null, RequestAbstractType.ID_ATTRIB_NAME, true); + } + return request; + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + RequestAbstractType request = (RequestAbstractType) parentSAMLObject; + + if (childSAMLObject instanceof Signature) { + request.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof RespondWith) { + request.getRespondWiths().add((RespondWith) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlElement, Attr attribute) throws UnmarshallingException { + RequestAbstractType request = (RequestAbstractType) samlElement; + + if (RequestAbstractType.ID_ATTRIB_NAME.equals(attribute.getLocalName())) { + request.setID(attribute.getValue()); + } else if (RequestAbstractType.ISSUEINSTANT_ATTRIB_NAME.equals(attribute.getLocalName()) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + DateTime cal = new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()); + request.setIssueInstant(cal); + } else if (RequestAbstractType.MINORVERSION_ATTRIB_NAME.equals(attribute.getLocalName())) { + int minor; + try { + minor = Integer.parseInt(attribute.getValue()); + } catch (NumberFormatException n) { + log.error("Unable to parse minor version string", n); + throw new UnmarshallingException(n); + } + if (minor == 0) { + request.setVersion(SAMLVersion.VERSION_10); + } else if (minor == 1) { + request.setVersion(SAMLVersion.VERSION_11); + } + } else { + super.processAttribute(samlElement, attribute); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestBuilder.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Request; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.RequestImpl} objects. + */ +public class RequestBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public RequestBuilder() { + + } + + /** {@inheritDoc} */ + public Request buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, Request.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Request buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,126 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml1.core.AssertionArtifact; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.saml1.core.AttributeQuery; +import org.opensaml.saml1.core.AuthenticationQuery; +import org.opensaml.saml1.core.AuthorizationDecisionQuery; +import org.opensaml.saml1.core.Query; +import org.opensaml.saml1.core.Request; +import org.opensaml.saml1.core.SubjectQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml1.core.Request} + */ +public class RequestImpl extends RequestAbstractTypeImpl implements Request { + + /** Saves the query (one of Query, SubjectQuery, AuthenticationQuery, AttributeQuery, AuthorizationDecisionQuery */ + private Query query; + + /** The List of AssertionIDReferences */ + private final XMLObjectChildrenList assertionIDReferences; + + /** The List of AssertionArtifacts */ + private final XMLObjectChildrenList assertionArtifacts; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RequestImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + assertionIDReferences = new XMLObjectChildrenList(this); + assertionArtifacts = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Query getQuery() { + return query; + } + + /** {@inheritDoc} */ + public SubjectQuery getSubjectQuery() { + return (query instanceof SubjectQuery ? (SubjectQuery) query : null); + } + + /** {@inheritDoc} */ + public AttributeQuery getAttributeQuery() { + return (query instanceof AttributeQuery ? (AttributeQuery) query : null); + } + + /** {@inheritDoc} */ + public AuthenticationQuery getAuthenticationQuery() { + return (query instanceof AuthenticationQuery ? (AuthenticationQuery) query : null); + } + + /** {@inheritDoc} */ + public AuthorizationDecisionQuery getAuthorizationDecisionQuery() { + return (query instanceof AuthorizationDecisionQuery ? (AuthorizationDecisionQuery) query : null); + } + + /** {@inheritDoc} */ + public void setQuery(Query query) throws IllegalArgumentException { + this.query = prepareForAssignment(this.query, query); + } + + /** {@inheritDoc} */ + public List getAssertionIDReferences() { + return assertionIDReferences; + } + + /** {@inheritDoc} */ + public List getAssertionArtifacts() { + return assertionArtifacts; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + List list = new ArrayList(); + + if (super.getOrderedChildren() != null) { + list.addAll(super.getOrderedChildren()); + } + if (query != null) { + list.add(query); + } + if (assertionIDReferences.size() != 0) { + list.addAll(assertionIDReferences); + } + if (assertionArtifacts.size() != 0) { + list.addAll(assertionArtifacts); + } + + if (list.size() == 0) { + return null; + } + + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestMarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Request} objects. + */ +public class RequestMarshaller extends RequestAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RequestUnmarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.AssertionArtifact; +import org.opensaml.saml1.core.AssertionIDReference; +import org.opensaml.saml1.core.Query; +import org.opensaml.saml1.core.Request; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml1.core.Request} objects. + */ +public class RequestUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentElement, XMLObject childElement) throws UnmarshallingException { + Request request = (Request) parentElement; + + try { + if (childElement instanceof Query) { + request.setQuery((Query) childElement); + } else if (childElement instanceof AssertionIDReference) { + request.getAssertionIDReferences().add((AssertionIDReference) childElement); + } else if (childElement instanceof AssertionArtifact) { + request.getAssertionArtifacts().add((AssertionArtifact) childElement); + } else { + super.processChildElement(parentElement, childElement); + } + } catch (IllegalArgumentException e) { + throw new UnmarshallingException(e); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RespondWithBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RespondWithBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RespondWithBuilder.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.RespondWith; + +/** + * Builder of {@link RespondWithImpl} objects. + */ +public class RespondWithBuilder extends AbstractSAMLObjectBuilder { + + /** {@inheritDoc} */ + public RespondWith buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, RespondWith.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public RespondWith buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RespondWithImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RespondWithImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RespondWithImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/RespondWithImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.RespondWith; +import org.opensaml.xml.XMLObject; + +/** + * Implementation of {@link RespondWith}. + */ +public class RespondWithImpl extends AbstractSAMLObject implements RespondWith { + + /** Value of this element. */ + private QName value; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RespondWithImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public QName getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(QName newValue) { + value = prepareElementContentForAssignment(value, newValue); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml1.core.ResponseAbstractType; +import org.opensaml.xml.XMLObject; + +/** + * Abstract implementation of {@link org.opensaml.saml1.core.ResponseAbstractType} Object + */ +public abstract class ResponseAbstractTypeImpl extends AbstractSignableSAMLObject implements ResponseAbstractType { + + /** Contains the ID */ + private String id; + + private SAMLVersion version; + + /** Contents of the InResponseTo attribute */ + private String inResponseTo = null; + + /** Contents of the Date attribute */ + private DateTime issueInstant = null; + + /** Contents of the recipient attribute */ + private String recipient = null; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResponseAbstractTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + version = SAMLVersion.VERSION_11; + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String id) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, id); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public String getInResponseTo() { + return inResponseTo; + } + + /** {@inheritDoc} */ + public void setInResponseTo(String inResponseTo) { + this.inResponseTo = prepareForAssignment(this.inResponseTo, inResponseTo); + } + + /** {@inheritDoc} */ + public int getMinorVersion() { + return version.getMinorVersion(); + } + + /** {@inheritDoc} */ + public int getMajorVersion() { + return version.getMajorVersion(); + } + + /** {@inheritDoc} */ + public void setVersion(SAMLVersion newVersion) { + version = prepareForAssignment(version, newVersion); + } + + /** {@inheritDoc} */ + public DateTime getIssueInstant() { + + return issueInstant; + } + + /** {@inheritDoc} */ + public void setIssueInstant(DateTime date) { + this.issueInstant = prepareForAssignment(this.issueInstant, date); + } + + /** {@inheritDoc} */ + public String getRecipient() { + return recipient; + } + + /** {@inheritDoc} */ + public void setRecipient(String recipient) { + this.recipient = prepareForAssignment(this.recipient, recipient); + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID(){ + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + List children = new ArrayList(); + + if(getSignature() != null){ + children.add(getSignature()); + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.ResponseAbstractType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.ResponseAbstractType} objects. + */ +public abstract class ResponseAbstractTypeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + ResponseAbstractType response = (ResponseAbstractType) samlElement; + + if (response.getID() != null) { + domElement.setAttributeNS(null, ResponseAbstractType.ID_ATTRIB_NAME, response.getID()); + if (response.getMinorVersion() != 0) { + domElement.setIdAttributeNS(null, ResponseAbstractType.ID_ATTRIB_NAME, true); + } + } + + if (response.getInResponseTo() != null) { + domElement.setAttributeNS(null, ResponseAbstractType.INRESPONSETO_ATTRIB_NAME, response.getInResponseTo()); + } + + if (response.getIssueInstant() != null) { + String date = Configuration.getSAMLDateFormatter().print(response.getIssueInstant()); + domElement.setAttributeNS(null, ResponseAbstractType.ISSUEINSTANT_ATTRIB_NAME, date); + } + + if (response.getMinorVersion() != 0) { + String minorVersion = Integer.toString(response.getMinorVersion()); + domElement.setAttributeNS(null, ResponseAbstractType.MINORVERSION_ATTRIB_NAME, minorVersion); + domElement.setAttributeNS(null, ResponseAbstractType.MAJORVERSION_ATTRIB_NAME, "1"); + } + + if (response.getRecipient() != null) { + domElement.setAttributeNS(null, ResponseAbstractType.RECIPIENT_ATTRIB_NAME, response.getRecipient()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseAbstractTypeUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.ResponseAbstractType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe {@link org.opensaml.xml.io.Unmarshaller} for {@link org.opensaml.saml1.core.ResponseAbstractType} + * objects. + */ +public abstract class ResponseAbstractTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(ResponseUnmarshaller.class); + + /** {@inheritDoc} */ + public XMLObject unmarshall(Element domElement) throws UnmarshallingException { + // After regular unmarshalling, check the minor version and set ID-ness if not SAML 1.0 + ResponseAbstractType response = (ResponseAbstractType) super.unmarshall(domElement); + if (response.getMinorVersion() != 0 && !DatatypeHelper.isEmpty(response.getID())) { + domElement.setIdAttributeNS(null, ResponseAbstractType.ID_ATTRIB_NAME, true); + } + return response; + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + ResponseAbstractType response = (ResponseAbstractType) parentSAMLObject; + + if (childSAMLObject instanceof Signature) { + response.setSignature((Signature) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + ResponseAbstractType response = (ResponseAbstractType) samlObject; + + if (attribute.getLocalName().equals(ResponseAbstractType.ID_ATTRIB_NAME)) { + response.setID(attribute.getValue()); + } else if (attribute.getLocalName().equals(ResponseAbstractType.INRESPONSETO_ATTRIB_NAME)) { + response.setInResponseTo(attribute.getValue()); + } else if (attribute.getLocalName().equals(ResponseAbstractType.ISSUEINSTANT_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + response.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(ResponseAbstractType.MINORVERSION_ATTRIB_NAME)) { + int minor; + try { + minor = Integer.parseInt(attribute.getValue()); + } catch (NumberFormatException n) { + log.error("Parsing minor version ", n); + throw new UnmarshallingException(n); + } + if (minor == 0) { + response.setVersion(SAMLVersion.VERSION_10); + } else if (minor == 1) { + response.setVersion(SAMLVersion.VERSION_11); + } + } else if (attribute.getLocalName().equals(ResponseAbstractType.RECIPIENT_ATTRIB_NAME)) { + response.setRecipient(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseBuilder.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Response; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.ResponseImpl} objects. + */ +public class ResponseBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ResponseBuilder() { + + } + + /** {@inheritDoc} */ + public Response buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, Response.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public Response buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.Response; +import org.opensaml.saml1.core.Status; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of the {@link org.opensaml.saml1.core.Response} Object + */ +public class ResponseImpl extends ResponseAbstractTypeImpl implements Response { + + /** Status associated with this element */ + private Status status = null; + + /** List of all the Assertions */ + private final XMLObjectChildrenList assertions; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + assertions = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAssertions() { + return assertions; + } + + /** {@inheritDoc} */ + public Status getStatus() { + return status; + } + + /** {@inheritDoc} */ + public void setStatus(Status status) throws IllegalArgumentException { + this.status = prepareForAssignment(this.status, status); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(1 + assertions.size()); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + if (status != null) { + children.add(status); + } + + children.addAll(assertions); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseMarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Response} objects. + */ +public class ResponseMarshaller extends ResponseAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/ResponseUnmarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.Response; +import org.opensaml.saml1.core.Status; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe {@link org.opensaml.xml.io.Unmarshaller} for {@link org.opensaml.saml1.core.Response} objects. + */ +public class ResponseUnmarshaller extends ResponseAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Response response = (Response) parentSAMLObject; + + if (childSAMLObject instanceof Assertion) { + response.getAssertions().add((Assertion) childSAMLObject); + } else if (childSAMLObject instanceof Status) { + response.setStatus((Status) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusBuilder.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Status; + +/** + * Builder of {@link StatusImpl} objects. + */ +public class StatusBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public StatusBuilder() { + + } + + /** {@inheritDoc} */ + public Status buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, Status.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public Status buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeBuilder.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.StatusCode; + +/** + * Builder of {@link StatusCodeImpl} objects. + */ +public class StatusCodeBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public StatusCodeBuilder() { + + } + + /** {@inheritDoc} */ + public StatusCode buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, StatusCode.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public StatusCode buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusCodeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeImpl.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.StatusCode; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml1.core.StatusCode} Object. + */ +public class StatusCodeImpl extends AbstractSAMLObject implements StatusCode { + + /** Contents of the Value attribute. */ + private QName value = null; + + /** The child StatusCode sub element. */ + private StatusCode childStatusCode = null; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusCodeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public QName getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(QName newValue) { + this.value = prepareAttributeValueForAssignment(StatusCode.VALUE_ATTRIB_NAME, this.value, newValue); + } + + /** {@inheritDoc} */ + public StatusCode getStatusCode() { + return childStatusCode; + } + + /** {@inheritDoc} */ + public void setStatusCode(StatusCode statusCode) { + childStatusCode = prepareForAssignment(childStatusCode, statusCode); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + if (childStatusCode != null) { + ArrayList contents = new ArrayList(1); + contents.add(childStatusCode); + return Collections.unmodifiableList(contents); + } else { + return null; + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeMarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.StatusCode; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.StatusCode} objects. + */ +public class StatusCodeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + StatusCode statusCode = (StatusCode) samlElement; + + QName statusValue = statusCode.getValue(); + if (statusValue != null) { + domElement.setAttributeNS(null, StatusCode.VALUE_ATTRIB_NAME, XMLHelper.qnameToContentString(statusValue)); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusCodeUnmarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.StatusCode; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.StatusCode} objects. + */ +public class StatusCodeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + StatusCode statusCode = (StatusCode) parentSAMLObject; + + if (childSAMLObject instanceof StatusCode) { + statusCode.setStatusCode((StatusCode) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + StatusCode statusCode = (StatusCode) samlObject; + + if (attribute.getName().equals(StatusCode.VALUE_ATTRIB_NAME)) { + statusCode.setValue(XMLHelper.getAttributeValueAsQName(attribute)); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.StatusDetail; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.StatusDetailImpl} + */ +public class StatusDetailBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public StatusDetailBuilder() { + + } + + /** + * {@inheritDoc} + */ + public StatusDetail buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, StatusDetail.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** + * {@inheritDoc} + */ + public StatusDetail buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusDetailImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailImpl.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.StatusDetail; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.StatusDetail} + */ +public class StatusDetailImpl extends AbstractSAMLObject implements StatusDetail { + + /** child "any" elements */ + private final IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusDetailImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** + * {@inheritDoc} + */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + /** + * {@inheritDoc} + */ + public List getOrderedChildren() { + return Collections.unmodifiableList(unknownChildren); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.StatusDetail} objects. + */ +public class StatusDetailMarshaller extends AbstractSAMLObjectMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusDetailUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.StatusDetail; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.StatusDetail} objects. + */ +public class StatusDetailUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + StatusDetail statusDetail = (StatusDetail) parentSAMLObject; + + statusDetail.getUnknownXMLObjects().add(childSAMLObject); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusImpl.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.Status; +import org.opensaml.saml1.core.StatusCode; +import org.opensaml.saml1.core.StatusDetail; +import org.opensaml.saml1.core.StatusMessage; +import org.opensaml.xml.XMLObject; + +/** + * Concrete Implementation {@link org.opensaml.saml1.core.Status} + */ +public class StatusImpl extends AbstractSAMLObject implements Status { + + /** Representation of the StatusMessage element. */ + private StatusMessage statusMessage; + + /** Representation of the StatusCode element. */ + private StatusCode statusCode; + + /** Representation of the StatusDetail element. */ + private StatusDetail statusDetail; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public StatusMessage getStatusMessage() { + return statusMessage; + } + + /** {@inheritDoc} */ + public void setStatusMessage(StatusMessage statusMessage) throws IllegalArgumentException { + this.statusMessage = prepareForAssignment(this.statusMessage, statusMessage); + } + + /** {@inheritDoc} */ + public StatusCode getStatusCode() { + return statusCode; + } + + /** {@inheritDoc} */ + public void setStatusCode(StatusCode statusCode) throws IllegalArgumentException { + this.statusCode = prepareForAssignment(this.statusCode, statusCode); + } + + /** {@inheritDoc} */ + public StatusDetail getStatusDetail() { + return statusDetail; + } + + /** {@inheritDoc} */ + public void setStatusDetail(StatusDetail statusDetail) throws IllegalArgumentException { + this.statusDetail = prepareForAssignment(this.statusDetail, statusDetail); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(3); + + if (statusCode != null) { + children.add(statusCode); + } + + if (statusMessage != null) { + children.add(statusMessage); + } + + if (statusDetail != null) { + children.add(statusDetail); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Status} objects. + */ +public class StatusMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageBuilder.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.StatusMessage; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.StatusMessageImpl} objects. + */ +public class StatusMessageBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public StatusMessageBuilder() { + + } + + /** {@inheritDoc} */ + public StatusMessage buildObject() { + return buildObject(SAMLConstants.SAML10P_NS, StatusMessage.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1P_PREFIX); + } + + /** {@inheritDoc} */ + public StatusMessage buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusMessageImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageImpl.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.StatusMessage; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of org.opensaml.saml1.core StatusMessage object + */ +public class StatusMessageImpl extends AbstractSAMLObject implements StatusMessage { + + /** + * Contents of the element + */ + private String message; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusMessageImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getMessage() { + return message; + } + + /** {@inheritDoc} */ + public void setMessage(String message) { + this.message = prepareForAssignment(this.message, message); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.StatusMessage; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.StatusMessage} objects. + */ +public class StatusMessageMarshaller extends AbstractSAMLObjectMarshaller { + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + StatusMessage statusMessage = (StatusMessage) samlObject; + + if (statusMessage.getMessage() != null) { + XMLHelper.appendTextContent(domElement, statusMessage.getMessage()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusMessageUnmarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.StatusMessage; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.StatusMessage} objects. + */ +public class StatusMessageUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + StatusMessage statusMessage = (StatusMessage) samlObject; + statusMessage.setMessage(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/StatusUnmarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Status; +import org.opensaml.saml1.core.StatusCode; +import org.opensaml.saml1.core.StatusDetail; +import org.opensaml.saml1.core.StatusMessage; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.Status} objects. + */ +public class StatusUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Status status = (Status) parentSAMLObject; + + if (childSAMLObject instanceof StatusCode) { + status.setStatusCode((StatusCode) childSAMLObject); + } else if (childSAMLObject instanceof StatusMessage) { + status.setStatusMessage((StatusMessage) childSAMLObject); + } else if (childSAMLObject instanceof StatusDetail) { + + status.setStatusDetail((StatusDetail) childSAMLObject); + + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectBuilder.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.Subject; + +/** + * Builder of (@link org.opensaml.saml1.core.impl.SubjectImpl} objects. + */ +public class SubjectBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public SubjectBuilder() { + + } + + /** {@inheritDoc} */ + public Subject buildObject() { + return buildObject(SAMLConstants.SAML1_NS, Subject.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public Subject buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationBuilder.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.SubjectConfirmation; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.SubjectConfirmationImpl} objects. + */ +public class SubjectConfirmationBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public SubjectConfirmationBuilder() { + + } + + /** {@inheritDoc} */ + public SubjectConfirmation buildObject() { + return buildObject(SAMLConstants.SAML1_NS, SubjectConfirmation.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public SubjectConfirmation buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectConfirmationImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationImpl.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,104 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.ConfirmationMethod; +import org.opensaml.saml1.core.SubjectConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.signature.KeyInfo; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of a SubjectConfirmation object + */ +public class SubjectConfirmationImpl extends AbstractSAMLObject implements SubjectConfirmation { + + /** Contains the list of ConfirmationMethods */ + private final XMLObjectChildrenList confirmationMethods; + + /** Contains the SubjectConfirmationData element */ + private XMLObject subjectConfirmationData; + + /** Contains the KeyInfo element */ + private KeyInfo keyInfo; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectConfirmationImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + confirmationMethods = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getConfirmationMethods() { + return confirmationMethods; + } + + /** {@inheritDoc} */ + public void setSubjectConfirmationData(XMLObject subjectConfirmationData) + throws IllegalArgumentException { + + this.subjectConfirmationData = prepareForAssignment(this.subjectConfirmationData, subjectConfirmationData); + } + + /** {@inheritDoc} */ + public XMLObject getSubjectConfirmationData() { + return subjectConfirmationData; + } + + /** {@inheritDoc} */ + public KeyInfo getKeyInfo() { + return keyInfo; + } + + /** {@inheritDoc} */ + public void setKeyInfo(KeyInfo keyInfo) { + this.keyInfo = prepareForAssignment(this.keyInfo, keyInfo); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + List list = new ArrayList(confirmationMethods.size() + 1); + + list.addAll(confirmationMethods); + + if (subjectConfirmationData != null) { + list.add(subjectConfirmationData); + } + + if(keyInfo != null){ + list.add(keyInfo); + } + + if (list.size() == 0) { + return null; + } + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationMarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.SubjectConfirmation} objects. + */ +public class SubjectConfirmationMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectConfirmationUnmarshaller.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.ConfirmationMethod; +import org.opensaml.saml1.core.SubjectConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.SubjectConfirmation} objects. + */ +public class SubjectConfirmationUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + SubjectConfirmation subjectConfirmation = (SubjectConfirmation) parentSAMLObject; + + if (childSAMLObject instanceof ConfirmationMethod) { + subjectConfirmation.getConfirmationMethods().add((ConfirmationMethod) childSAMLObject); + } else { + subjectConfirmation.setSubjectConfirmationData(childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectImpl.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,90 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.saml1.core.Subject; +import org.opensaml.saml1.core.SubjectConfirmation; +import org.opensaml.xml.XMLObject; + +/** + * Complete implementation of {@link org.opensaml.saml1.core.Subject} + */ +public class SubjectImpl extends AbstractSAMLObject implements Subject { + + /** Contains the NameIdentifier inside the Subject */ + private NameIdentifier nameIdentifier; + + /** Contains the SubjectConfirmation inside the Subject */ + private SubjectConfirmation subjectConfirmation; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public NameIdentifier getNameIdentifier() { + return nameIdentifier; + } + + /** {@inheritDoc} */ + public void setNameIdentifier(NameIdentifier nameIdentifier) throws IllegalArgumentException { + this.nameIdentifier = prepareForAssignment(this.nameIdentifier, nameIdentifier); + } + + /** {@inheritDoc} */ + public SubjectConfirmation getSubjectConfirmation() { + return subjectConfirmation; + } + + /** {@inheritDoc} */ + public void setSubjectConfirmation(SubjectConfirmation subjectConfirmation) throws IllegalArgumentException { + this.subjectConfirmation = prepareForAssignment(this.subjectConfirmation, subjectConfirmation); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + List list = new ArrayList(2); + + if (nameIdentifier != null) { + list.add(nameIdentifier); + } + + if (subjectConfirmation != null) { + list.add(subjectConfirmation); + } + if (list.size() == 0) { + return null; + } + + return Collections.unmodifiableList(list); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityBuilder.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.SubjectLocality; + +/** + * Builder of {@link org.opensaml.saml1.core.impl.SubjectLocalityImpl} objects. + */ +public class SubjectLocalityBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public SubjectLocalityBuilder() { + + } + + /** {@inheritDoc} */ + public SubjectLocality buildObject() { + return buildObject(SAMLConstants.SAML1_NS, SubjectLocality.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX); + } + + /** {@inheritDoc} */ + public SubjectLocality buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectLocalityImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityImpl.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.SubjectLocality; +import org.opensaml.xml.XMLObject; + +/** + * A concrete impementation of the {@link org.opensaml.saml1.core.SubjectLocality} interface + */ +public class SubjectLocalityImpl extends AbstractSAMLObject implements SubjectLocality { + + /** The ipAddress */ + private String ipAddress; + + /** The DNS Address */ + private String dnsAddress; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectLocalityImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getIPAddress() { + return ipAddress; + } + + /** {@inheritDoc} */ + public void setIPAddress(String address) { + ipAddress = prepareForAssignment(ipAddress, address); + } + + /** {@inheritDoc} */ + public String getDNSAddress() { + return dnsAddress; + } + + /** {@inheritDoc} */ + public void setDNSAddress(String address) { + dnsAddress = prepareForAssignment(dnsAddress, address); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityMarshaller.java 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml1.core.SubjectLocality; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.SubjectLocality} objects. + */ +public class SubjectLocalityMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + public void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + SubjectLocality subjectLocality = (SubjectLocality) samlElement; + + if (subjectLocality.getIPAddress() != null) { + domElement.setAttributeNS(null, SubjectLocality.IPADDRESS_ATTRIB_NAME, subjectLocality.getIPAddress()); + } + + if (subjectLocality.getDNSAddress() != null) { + domElement.setAttributeNS(null, SubjectLocality.DNSADDRESS_ATTRIB_NAME, subjectLocality.getDNSAddress()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectLocalityUnmarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.SubjectLocality; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.SubjectLocality} objects. + */ +public class SubjectLocalityUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + SubjectLocality subjectLocality = (SubjectLocality) samlObject; + + if (SubjectLocality.DNSADDRESS_ATTRIB_NAME.equals(attribute.getLocalName())) { + subjectLocality.setDNSAddress(attribute.getValue()); + } else if (SubjectLocality.IPADDRESS_ATTRIB_NAME.equals(attribute.getLocalName())) { + subjectLocality.setIPAddress(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectMarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.Subject} objects. + */ +public class SubjectMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryImpl.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.Subject; +import org.opensaml.saml1.core.SubjectQuery; +import org.opensaml.xml.XMLObject; + +/** + * Concrete (but abstract) implementation of {@link org.opensaml.saml1.core.SubjectQuery} abstract type + */ +public abstract class SubjectQueryImpl extends AbstractSAMLObject implements SubjectQuery { + + /** Contains the Subject subelement */ + private Subject subject; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Subject getSubject() { + return subject; + } + + /** {@inheritDoc} */ + public void setSubject(Subject subject) { + this.subject = prepareForAssignment(this.subject, subject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + if (subject == null) { + return null; + } + + List children = new ArrayList(); + children.add(subject); + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryMarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml1.core.SubjectQuery} objects. + */ +public abstract class SubjectQueryMarshaller extends AbstractSAMLObjectMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectQueryUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Subject; +import org.opensaml.saml1.core.SubjectQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml1.core.SubjectQuery} objects. + */ +public abstract class SubjectQueryUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + SubjectQuery query = (SubjectQuery) parentSAMLObject; + + if (childSAMLObject instanceof Subject) { + query.setSubject((Subject) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementImpl.java 17 Aug 2012 15:03:29 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml1.core.Subject; +import org.opensaml.saml1.core.SubjectStatement; +import org.opensaml.xml.XMLObject; + +/** + * Abstract type to implement SubjectStatementType + */ +public abstract class SubjectStatementImpl extends AbstractSAMLObject implements SubjectStatement { + + /** Contains the Subject subelement */ + private Subject subject; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectStatementImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Subject getSubject() { + return subject; + } + + /** {@inheritDoc} */ + public void setSubject(Subject subject) throws IllegalArgumentException { + this.subject = prepareForAssignment(this.subject, subject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + if (subject == null) { + return null; + } + + List children = new ArrayList(); + children.add(subject); + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementMarshaller.java 17 Aug 2012 15:03:25 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * Marshaller for {@link org.opensaml.saml1.core.SubjectStatement} XMLObjects. + */ +public abstract class SubjectStatementMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectStatementUnmarshaller.java 17 Aug 2012 15:03:27 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.Subject; +import org.opensaml.saml1.core.SubjectStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unamershaller for {@link SubjectStatement}s. + */ +public abstract class SubjectStatementUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + SubjectStatement statement = (SubjectStatement) parentSAMLObject; + + if (childSAMLObject instanceof Subject) { + statement.setSubject((Subject) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/SubjectUnmarshaller.java 17 Aug 2012 15:03:26 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml1.core.NameIdentifier; +import org.opensaml.saml1.core.Subject; +import org.opensaml.saml1.core.SubjectConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml1.core.Subject} objects. + */ +public class SubjectUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Subject subject = (Subject) parentSAMLObject; + + if (childSAMLObject instanceof NameIdentifier) { + subject.setNameIdentifier((NameIdentifier) childSAMLObject); + } else if (childSAMLObject instanceof SubjectConfirmation) { + subject.setSubjectConfirmation((SubjectConfirmation) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/impl/package.html 17 Aug 2012 15:03:28 -0000 1.1 @@ -0,0 +1,14 @@ + + +Implementations of SAML 1.0 and 1.1 types and elements interfaces. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ActionSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ActionSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ActionSpecValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Action; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.Action} for Schema compliance. + */ +public class ActionSpecValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(Action action) throws ValidationException { + if (DatatypeHelper.isEmpty(action.getContents())) { + throw new ValidationException("Action label must be specified"); + } + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AssertionSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AssertionSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AssertionSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,102 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import java.util.List; + +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.Statement; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.Assertion} for Schema compliance. + */ +public class AssertionSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(Assertion assertion) throws ValidationException { + validateVersion(assertion); + validateId(assertion); + validateIssuer(assertion); + validateIssueInstant(assertion); + validateStatements(assertion); + } + + /** + * Test that the version is SAML1.1 or 1.0 + * @param assertion what to test + * @throws ValidationException + */ + protected void validateVersion(Assertion assertion) throws ValidationException { + if ((assertion.getMajorVersion() != 1) && + (assertion.getMinorVersion() != 0 || assertion.getMinorVersion() != 1)) { + throw new ValidationException("Invalid Version"); + } + } + + /** + * Test that the ID is present + * @param assertion + * @throws ValidationException + */ + protected void validateId(Assertion assertion) throws ValidationException { + if (DatatypeHelper.isEmpty(assertion.getID())) { + throw new ValidationException("ID not present"); + } + } + + /** + * Test that the issuer is present + * @param assertion + * @throws ValidationException + */ + protected void validateIssuer(Assertion assertion) throws ValidationException { + if (DatatypeHelper.isEmpty(assertion.getIssuer())) { + throw new ValidationException("Issuer not present"); + } + } + + /** + * Test that the IssueInstant is present + * @param assertion + * @throws ValidationException + */ + protected void validateIssueInstant(Assertion assertion) throws ValidationException { + if (assertion.getIssueInstant() == null) { + throw new ValidationException("IssueInstant not present"); + } + } + + /** + * Test that the provided assertion has some statements in + * @param assertion + * @throws ValidationException + */ + protected void validateStatements(Assertion assertion) throws ValidationException { + List list = assertion.getStatements(); + if (list == null || list.size() == 0) { + throw new ValidationException("No Statements present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AssertionSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AssertionSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AssertionSpecValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Assertion; +import org.opensaml.saml1.core.Condition; +import org.opensaml.saml1.core.Conditions; +import org.opensaml.saml1.core.DoNotCacheCondition; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Spec validator for {@link org.opensaml.saml1.core.Assertion} + */ +public class AssertionSpecValidator implements Validator { + + public void validate(Assertion assertion) throws ValidationException { + validateDoNotCache(assertion); + } + + protected void validateDoNotCache(Assertion assertion) throws ValidationException { + + if (assertion.getMinorVersion() == 0) { + Conditions conditions = assertion.getConditions(); + if (conditions != null) { + for (Condition condition : conditions.getConditions()) { + if (condition instanceof DoNotCacheCondition) { + throw new ValidationException("DoNotCacheCondition not valid in SAML1.0"); + } + } + } + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeDesignatorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeDesignatorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeDesignatorSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AttributeDesignator; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.AttributeDesignator} for Schema compliance. + */ +public class AttributeDesignatorSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(AttributeDesignatorType attributeDesignator) throws ValidationException { + validateName(attributeDesignator); + validateNameSpace(attributeDesignator); + } + + /** + * Checks that the AttributeNameSpace attribute is present and valid + * @param designator + * @throws ValidationException + */ + protected void validateNameSpace(AttributeDesignator designator) throws ValidationException { + if (DatatypeHelper.isEmpty(designator.getAttributeNamespace())) { + throw new ValidationException("AttributeNameSpace attribute not present or invalid"); + } + } + + /** + * Checks that the AttributeName attribute is present and valid + * @param designator + * @throws ValidationException + */ + protected void validateName(AttributeDesignator designator) throws ValidationException { + if (DatatypeHelper.isEmpty(designator.getAttributeName())) { + throw new ValidationException("AttributeName attribute not present or invalid"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeQuerySchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AttributeQuery; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.AttributeQuery} for Schema compliance. + */ +public class AttributeQuerySchemaValidator extends SubjectQuerySchemaValidator { + + /** {@inheritDoc} */ + public void validate(AttributeQuery attributeQuery) throws ValidationException { + super.validate(attributeQuery); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Attribute; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.Attribute} for Schema compliance. + */ +public class AttributeSchemaValidator extends AttributeDesignatorSchemaValidator { + + /** {@inheritDoc} */ + public void validate(Attribute attribute) throws ValidationException { + super.validate(attribute); + + validateAttributeValue(attribute); + } + + /** + * Validates that the attribute has at least one attribute value. + * + * @param attribute attribute to validate + * + * @throws ValidationException thrown if the attribute does not have any values + */ + protected void validateAttributeValue(Attribute attribute) throws ValidationException { + if (attribute.getAttributeValues().size() == 0) { + throw new ValidationException("No AttributeValue elements present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeStatementSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeStatementSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AttributeStatementSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AttributeStatement; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.AttributeStatement} for Schema compliance. + */ +public class AttributeStatementSchemaValidator extends SubjectStatementSchemaValidator { + + /** {@inheritDoc} */ + public void validate(AttributeStatement attributeStatement) throws ValidationException { + super.validate(attributeStatement); + + if (attributeStatement.getAttributes().size() == 0) { + throw new ValidationException("No Attribute Element present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AudienceRestrictionConditionSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AudienceRestrictionConditionSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AudienceRestrictionConditionSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AudienceRestrictionCondition; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.AudienceRestrictionCondition} for Schema compliance. + */ +public class AudienceRestrictionConditionSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(AudienceRestrictionCondition audienceRestrictionCondition) throws ValidationException { + validateAudiences(audienceRestrictionCondition); + } + + /** + * Validates that the condition specifies at least one audience. + * + * @param audienceRestrictionCondition condition to validate + * + * @throws ValidationException thrown if now audience is specified in the condition + */ + protected void validateAudiences(AudienceRestrictionCondition audienceRestrictionCondition) throws ValidationException{ + if (audienceRestrictionCondition.getAudiences() == null || + audienceRestrictionCondition.getAudiences().size() == 0) { + throw new ValidationException("No Audience statements present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AudienceSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AudienceSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AudienceSpecValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Audience; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.AudienceRestrictionCondition} for Spec compliance. + */ +public class AudienceSpecValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(Audience audience) throws ValidationException { + validateURIPresent(audience); + } + + protected void validateURIPresent(Audience audience) throws ValidationException { + if (DatatypeHelper.isEmpty(audience.getUri())) { + throw new ValidationException("AudienceURI Required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthenticationQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthenticationQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthenticationQuerySchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AuthenticationQuery; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.AuthenticationQuery} for Schema compliance. + */ +public class AuthenticationQuerySchemaValidator extends SubjectQuerySchemaValidator { + + /** {@inheritDoc} */ + public void validate(AuthenticationQuery authnQuery) throws ValidationException { + super.validate(authnQuery); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthenticationStatementSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthenticationStatementSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthenticationStatementSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AuthenticationStatement; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.AuthenticationStatement} for Schema compliance. + */ +public class AuthenticationStatementSchemaValidator extends SubjectStatementSchemaValidator { + + /** {@inheritDoc} */ + public void validate(AuthenticationStatement authenticationStatement) throws ValidationException { + super.validate(authenticationStatement); + + validateAuthenticationMethod(authenticationStatement); + + validateAuthenticationInstant(authenticationStatement); + } + + /** + * Validates that the authentication statement has an authentication method. + * + * @param authenticationStatement the statement to validate + * + * @throws ValidationException thrown if the statement does not have an authentication method + */ + protected void validateAuthenticationMethod(AuthenticationStatement authenticationStatement) + throws ValidationException { + if (DatatypeHelper.isEmpty(authenticationStatement.getAuthenticationMethod())) { + throw new ValidationException("No authenticationStatement URI is null"); + } + } + + /** + * Validates that the authentication statement has an authentication instant. + * + * @param authenticationStatement the statement to validate + * + * @throws ValidationException thrown if the statement does not have an authentication instant + */ + protected void validateAuthenticationInstant(AuthenticationStatement authenticationStatement) + throws ValidationException { + if (authenticationStatement.getAuthenticationInstant() == null) { + throw new ValidationException("No authenticationInstant present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorityBindingSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorityBindingSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorityBindingSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import javax.xml.namespace.QName; + +import org.opensaml.saml1.core.AuthorityBinding; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.AuthorityBinding} for Schema compliance. + */ +public class AuthorityBindingSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(AuthorityBinding authorityBinding) throws ValidationException { + validateAuthorityKind(authorityBinding); + validateBinding(authorityBinding); + validateLocation(authorityBinding); + } + + /** + * Check that the AuthorityKind is valid + * @param authorityBinding + * @throws ValidationException + */ + protected void validateAuthorityKind(AuthorityBinding authorityBinding) throws ValidationException { + // + // TODO may need to do more validation on the QName here - need to make sure + // that the prefix is valid - cases of + // 1) no incoming XML validation was performed + // 2) validating parser that doesn't properly validate this QName value. + // + QName authorityKind = authorityBinding.getAuthorityKind(); + if (authorityKind == null) { + throw new ValidationException("No AuthorityKind attribute present"); + } + } + + /** + * Check the location Attribute for validity + * @param authorityBinding + * @throws ValidationException + */ + protected void validateLocation(AuthorityBinding authorityBinding) throws ValidationException { + if (DatatypeHelper.isEmpty(authorityBinding.getLocation())) { + throw new ValidationException("Location attribute not present or invalid "); + } + } + + /** + * Check the binding Attribute for validity + * @param authorityBinding + * @throws ValidationException + */ + protected void validateBinding(AuthorityBinding authorityBinding) throws ValidationException { + if (DatatypeHelper.isEmpty(authorityBinding.getBinding())) { + throw new ValidationException("Binding attribute not present or invalid "); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorizationDecisionQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorizationDecisionQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorizationDecisionQuerySchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AuthorizationDecisionQuery; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.AuthorizationDecisionQuery} for Schema compliance. + */ +public class AuthorizationDecisionQuerySchemaValidator extends SubjectQuerySchemaValidator { + + /** {@inheritDoc} */ + public void validate(AuthorizationDecisionQuery query) throws ValidationException { + super.validate(query); + validateActions(query); + + validateResourcePresent(query); + + } + + /** + * Validates that the Resource attribute is present and valid + * + * @param query + * @throws ValidationException + */ + protected void validateResourcePresent(AuthorizationDecisionQuery query) throws ValidationException { + if (DatatypeHelper.isEmpty(query.getResource())) { + throw new ValidationException("No Resource attribute present"); + } + } + + /** + * Validates that there is at least one Action Element present. + * + * @param query + * @throws ValidationException + */ + protected void validateActions(AuthorizationDecisionQuery query) throws ValidationException { + if (query.getActions().size() == 0) { + throw new ValidationException("No Action elements present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorizationDecisionStatementSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorizationDecisionStatementSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/AuthorizationDecisionStatementSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.AuthorizationDecisionStatement; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.AuthorizationDecisionStatement} for Schema compliance. + */ +public class AuthorizationDecisionStatementSchemaValidator extends SubjectStatementSchemaValidator { + + /** {@inheritDoc} */ + public void validate(AuthorizationDecisionStatement authorizationDecisionStatement) throws ValidationException { + super.validate(authorizationDecisionStatement); + + validateResource(authorizationDecisionStatement); + + validateDecision(authorizationDecisionStatement); + + validateActions(authorizationDecisionStatement); + } + + /** + * Check that the resource attribute is present and valid + * @param statement the AuthorizationDecisionStatement under question + * @throws ValidationException + */ + protected void validateResource(AuthorizationDecisionStatement statement) throws ValidationException { + if (DatatypeHelper.isEmpty(statement.getResource())) { + throw new ValidationException("Resource attribute not present or invalid"); + } + } + + /** + * Check that the Decision element is present + * @param statement the AuthorizationDecisionStatement under question + * @throws ValidationException + */ + protected void validateDecision(AuthorizationDecisionStatement statement) throws ValidationException { + if (statement.getDecision() == null) { + throw new ValidationException("No Decision element present"); + } + } + + /** + * Check that there is at least one Action element + * @param statement the AuthorizationDecisionStatement under question + * @throws ValidationException + */ + protected void validateActions(AuthorizationDecisionStatement statement) throws ValidationException { + if (statement.getActions().size() == 0) { + throw new ValidationException("No Action elements present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/EvidenceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/EvidenceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/EvidenceSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Evidence; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.Evidence} for Schema compliance. + */ +public class EvidenceSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(Evidence evidence) throws ValidationException { + validateEvidence(evidence); + } + + /** + * Check that there is an assertion of AddsertionIDRef + * @param evidence + * @throws ValidationException + */ + protected void validateEvidence(Evidence evidence) throws ValidationException { + if (evidence.getEvidence().size() == 0) { + throw new ValidationException("At least one Assertion or AssertionIDReference is required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/RequestAbstractTypeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/RequestAbstractTypeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/RequestAbstractTypeSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.RequestAbstractType; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.RequestAbstractType} for Schema compliance. + */ +public class RequestAbstractTypeSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(RequestType requestAbstractType) throws ValidationException { + validateVersion(requestAbstractType); + + validateID(requestAbstractType); + + validateIssueInstant(requestAbstractType); + } + + /** + * Validates that this is SAML1.0 or SAML 1.1 + * + * @param request + * @throws ValidationException + */ + protected void validateVersion(RequestAbstractType request) throws ValidationException { + if ((request.getMajorVersion() != 1) && (request.getMinorVersion() != 0 || request.getMinorVersion() != 1)) { + throw new ValidationException("Invalid Version"); + } + } + + /** + * Validate that the ID is present and valid + * + * @param request + * @throws ValidationException + */ + protected void validateID(RequestAbstractType request) throws ValidationException { + if (DatatypeHelper.isEmpty(request.getID())) { + throw new ValidationException("RequestID is null, empty or whitespace"); + } + } + + /** + * Validate that the IssueInstant is present. + * + * @param request + * @throws ValidationException + */ + protected void validateIssueInstant(RequestAbstractType request) throws ValidationException { + if (request.getIssueInstant() == null) { + throw new ValidationException("No IssueInstant attribute present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/RequestSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/RequestSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/RequestSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Request; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.Request} for Schema compliance. + */ +public class RequestSchemaValidator extends RequestAbstractTypeSchemaValidator { + + /** {@inheritDoc} */ + public void validate(Request request) throws ValidationException { + super.validate(request); + validateAssertion(request); + } + + /** + * Validates thats the request has an some form of assertion (directly, reference, or artifact) or query, but not + * both. + * + * @param request the request to validate + * + * @throws ValidationException thrown if the request has more than one assertion or both an assertion and a query + */ + protected void validateAssertion(Request request) throws ValidationException { + if (request.getQuery() != null) { + if (request.getAssertionArtifacts().size() != 0) { + throw new ValidationException("Both Query and one or more AssertionAtrifacts present"); + } + if (request.getAssertionIDReferences().size() != 0) { + throw new ValidationException("Both Query and one ore more AsertionIDReferences present"); + } + } else if (request.getAssertionArtifacts().size() != 0) { + if (request.getAssertionIDReferences().size() != 0) { + throw new ValidationException( + "Both one or more AssertionAtrifacts and one ore more AsertionIDReferences present"); + } + } else if (request.getAssertionIDReferences().size() == 0) { + throw new ValidationException("No AssertionAtrifacts, No Query, and No AsertionIDReferences present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ResponseAbstractTypeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ResponseAbstractTypeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ResponseAbstractTypeSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.ResponseAbstractType; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.ResponseAbstractType} for Schema compliance. + */ +public class ResponseAbstractTypeSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(ResponseType response) throws ValidationException { + validateVersion(response); + + validateID(response); + + validateIssueInstant(response); + } + + /** + * Validates that this is SAML1.0 or SAML 1.1 + * + * @param response + * @throws ValidationException + */ + protected void validateVersion(ResponseAbstractType response) throws ValidationException { + if ((response.getMajorVersion() != 1) && (response.getMinorVersion() != 0 || response.getMinorVersion() != 1)) { + throw new ValidationException("Invalid Version"); + } + } + + /** + * Validate that the ID is present and valid + * + * @param response + * @throws ValidationException + */ + protected void validateID(ResponseAbstractType response) throws ValidationException { + if (DatatypeHelper.isEmpty(response.getID())) { + throw new ValidationException("RequestID is null, empty or whitespace"); + } + } + + /** + * Validate that the IssueInstant is present. + * + * @param response + * @throws ValidationException + */ + protected void validateIssueInstant(ResponseAbstractType response) throws ValidationException { + if (response.getIssueInstant() == null) { + throw new ValidationException("No IssueInstant attribute present"); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ResponseSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ResponseSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/ResponseSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Response; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml1.core.Response} for Schema compliance. + */ +public class ResponseSchemaValidator extends ResponseAbstractTypeSchemaValidator { + + /** {@inheritDoc} */ + public void validate(Response response) throws ValidationException { + super.validate(response); + validateStatus(response); + } + + /** + * Validates that the response has a status. + * + * @param response response to validate + * + * @throws ValidationException thrown if the response does not have a status + */ + protected void validateStatus(Response response) throws ValidationException{ + if (response.getStatus() == null) { + throw new ValidationException("No Status present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/StatusCodeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/StatusCodeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/StatusCodeSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,86 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml1.core.StatusCode; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.StatusCode} for Schema compliance. + */ +public class StatusCodeSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(StatusCode statusCode) throws ValidationException { + validateValue(statusCode); + validateValueContent(statusCode); + } + + /** + * Validates that the status code has a value. + * + * @param statusCode status code to validate + * + * @throws ValidationException thrown if the status code does not have a value + */ + protected void validateValue(StatusCode statusCode) throws ValidationException { + QName value = statusCode.getValue(); + if (value == null) { + throw new ValidationException("No Value attribute present"); + } + } + + /** + * Validates that the status code local name is one of the allowabled values. + * + * @param statusCode the status code to validate + * + * @throws ValidationException thrown if the status code local name is not an allowed value + */ + protected void validateValueContent(StatusCode statusCode) throws ValidationException { + QName statusValue = statusCode.getValue(); + + if (SAMLConstants.SAML10P_NS.equals(statusValue.getNamespaceURI())) { + if (!(statusValue.equals(StatusCode.SUCCESS) + || statusValue.equals(StatusCode.VERSION_MISMATCH) + || statusValue.equals(StatusCode.REQUESTER) + || statusValue.equals(StatusCode.RESPONDER) + || statusValue.equals(StatusCode.REQUEST_VERSION_TOO_HIGH) + || statusValue.equals(StatusCode.REQUEST_VERSION_TOO_LOW) + || statusValue.equals(StatusCode.REQUEST_VERSION_DEPRICATED) + || statusValue.equals(StatusCode.TOO_MANY_RESPONSES) + || statusValue.equals(StatusCode.REQUEST_DENIED) + || statusValue.equals(StatusCode.RESOURCE_NOT_RECOGNIZED))) { + throw new ValidationException( + "Status code value was in the SAML 1 protocol namespace but was not of an allowed value: " + + statusValue); + } + } else if (SAMLConstants.SAML1_NS.equals(statusValue.getNamespaceURI())) { + throw new ValidationException( + "Status code value was in the SAML 1 assertion namespace, no values are allowed in that namespace"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/StatusSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/StatusSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/StatusSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Status; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.Status} for Schema compliance. + */ +public class StatusSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(Status status) throws ValidationException { + validateStatusCode(status); + } + + /** + * Validates that given status has a status code. + * + * @param status status to validate + * + * @throws ValidationException thrown if the status does not have a status code + */ + protected void validateStatusCode(Status status) throws ValidationException { + if (status.getStatusCode() == null) { + throw new ValidationException("No StatusCode element present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectConfirmationSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectConfirmationSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectConfirmationSchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.SubjectConfirmation; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.SubjectConfirmation} for Schema compliance. + */ +public class SubjectConfirmationSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(SubjectConfirmation subjectConfirmation) throws ValidationException { + validateSubjectConfirmationMethods(subjectConfirmation); + } + + /** + * Validates that the given subject confirmation has a confirmation method. + * + * @param subjectConfirmation subject confirmation to validate + * + * @throws ValidationException thrown if the given confirmation does not have a confirmation method + */ + protected void validateSubjectConfirmationMethods(SubjectConfirmation subjectConfirmation) + throws ValidationException { + if (subjectConfirmation.getConfirmationMethods().size() == 0) { + throw new ValidationException("At least Confirmation Method should be present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectQuerySchemaValidator.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.SubjectQuery; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.SubjectQuery} for Schema compliance. + */ +public class SubjectQuerySchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(QueryType subjectQuery) throws ValidationException { + if (subjectQuery.getSubject() == null) { + throw new ValidationException("Subject element is missing"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.Subject; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.Subject} for Schema compliance. + */ +public class SubjectSchemaValidator implements Validator { + + /** {@inheritDoc} */ + public void validate(Subject subject) throws ValidationException { + validateNameIdentifierSubjectConfirmation(subject); + } + + /** + * Validates that the subject has either a name identifier or subject confirmation + * + * @param subject subject to validate + * + * @throws ValidationException thrown if the subject has neither a name identifier or subject confirmation + */ + protected void validateNameIdentifierSubjectConfirmation(Subject subject) throws ValidationException { + if (subject.getNameIdentifier() == null && subject.getSubjectConfirmation() == null) { + throw new ValidationException("Either a NameIdentifier or SubjectConfirmation should be present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectStatementSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectStatementSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/SubjectStatementSchemaValidator.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml1.core.validator; + +import org.opensaml.saml1.core.SubjectStatement; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml1.core.SubjectStatement} for Schema compliance. + */ +public class SubjectStatementSchemaValidator implements + Validator { + + /** {@inheritDoc} */ + public void validate(SubjectStatementType subjectStatement) throws ValidationException { + validateSubject(subjectStatement); + } + + /** + * Validates that the statement has a subject. + * + * @param subjectStatement statement to validate + * + * @throws ValidationException thrown if the statement does not have a subject + */ + protected void validateSubject(SubjectStatementType subjectStatement) throws ValidationException { + if (subjectStatement.getSubject() == null) { + throw new ValidationException("No Subject present"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml1/core/validator/package.html 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,15 @@ + + +Validation rules for SAML 1.0 and 1.1 types and elements. +

+Schema validators check to ensure that SAMLObjects adhere to the SAML 1.0/1.1 XML schemas while spec validators ensure +the objects adhere to the additional constraints placed upon the object by the SAML 1.0/1.1 specification. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/AuthnResponseEndpointSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/AuthnResponseEndpointSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/AuthnResponseEndpointSelector.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,212 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.opensaml.common.binding.BasicEndpointSelector; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * An endpoint selector that implements the additional selection constraints described within the SAML 2.0 AuthnRequest + * specification. If an endpoint can not be resolved using either the information within the assertion consumer service + * index or the assertion consumer service URL given in the authentication request, or if this information isn't + * present, than the rules for the {@link BasicEndpointSelector} are used. + */ +public class AuthnResponseEndpointSelector extends BasicEndpointSelector { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(AuthnResponseEndpointSelector.class); + + /** {@inheritDoc} */ + @SuppressWarnings("unchecked") + public Endpoint selectEndpoint() { + if (getEntityRoleMetadata() == null) { + log.debug("Unable to select endpoint, no entity role metadata available."); + return null; + } + + List endpoints = getEntityRoleMetadata().getEndpoints(getEndpointType()); + if (endpoints == null || endpoints.size() == 0) { + return null; + } + + Endpoint endpoint = null; + AuthnRequest request = (AuthnRequest) getSamlRequest(); + if (request != null) { + endpoints = filterEndpointsByProtocolBinding(endpoints); + if (endpoints == null || endpoints.isEmpty()) { + return null; + } + + if (request.getAssertionConsumerServiceIndex() != null) { + log.debug("Selecting endpoint by ACS index '{}' for request '{}' from entity '{}'", new Object[] { + request.getAssertionConsumerServiceIndex(), request.getID(), getEntityMetadata().getEntityID()}); + endpoint = selectEndpointByACSIndex(request, (List) endpoints); + } else if (request.getAssertionConsumerServiceURL() != null) { + log.debug( + "Selecting endpoint by ACS URL '{}' and protocol binding '{}' for request '{}' from entity '{}'", + new Object[] {request.getAssertionConsumerServiceURL(), request.getProtocolBinding(), + request.getID(), getEntityMetadata().getEntityID()}); + endpoint = selectEndpointByACSURL(request, (List) endpoints); + } + } + + if (endpoint == null && request.getAssertionConsumerServiceIndex() == null + && request.getAssertionConsumerServiceURL() == null) { + log.debug("No ACS index or URL given, selecting endpoint without additional constraints."); + if (endpoints.get(0) instanceof IndexedEndpoint) { + endpoint = selectIndexedEndpoint((List) endpoints); + } else { + endpoint = selectNonIndexedEndpoint((List) endpoints); + } + } + + return endpoint; + } + + /** + * Filters the list of possible endpoints by supported outbound bindings and, if the authentication request contains + * a requested binding and not an ACS index, that too is used to filter the list. + * + * @param endpoints raw list of endpoints + * + * @return filtered endpoints + */ + protected List filterEndpointsByProtocolBinding(List endpoints) { + log.debug("Filtering peer endpoints. Supported peer endpoint bindings: {}", getSupportedIssuerBindings()); + AuthnRequest request = (AuthnRequest) getSamlRequest(); + + boolean filterByRequestBinding = false; + String acsBinding = DatatypeHelper.safeTrimOrNullString(request.getProtocolBinding()); + if (acsBinding != null && request.getAssertionConsumerServiceIndex() != null) { + filterByRequestBinding = true; + } + + List filteredEndpoints = new ArrayList(endpoints); + Iterator endpointItr = filteredEndpoints.iterator(); + Endpoint endpoint; + while (endpointItr.hasNext()) { + endpoint = endpointItr.next(); + if (!getSupportedIssuerBindings().contains(endpoint.getBinding())) { + log.debug("Removing endpoint {} because its binding {} is not supported", endpoint.getLocation(), + endpoint.getBinding()); + endpointItr.remove(); + continue; + } + + if (filterByRequestBinding && !endpoint.getBinding().equals(acsBinding)) { + log.debug("Removing endpoint {} because its binding {} does not match request's requested binding", + endpoint.getLocation(), endpoint.getBinding()); + endpointItr.remove(); + } + } + + return filteredEndpoints; + } + + /** + * Selects the endpoint by way of the assertion consumer service index given in the AuthnRequest. + * + * @param request the AuthnRequest + * @param endpoints list of endpoints to select from + * + * @return the selected endpoint + */ + protected Endpoint selectEndpointByACSIndex(AuthnRequest request, List endpoints) { + Integer acsIndex = request.getAssertionConsumerServiceIndex(); + for (IndexedEndpoint endpoint : endpoints) { + if (endpoint == null || !getSupportedIssuerBindings().contains(endpoint.getBinding())) { + log.debug( + "Endpoint '{}' with binding '{}' discarded because it requires an unsupported outbound binding.", + endpoint.getLocation(), endpoint.getBinding()); + continue; + } + + if (DatatypeHelper.safeEquals(acsIndex, endpoint.getIndex())) { + return endpoint; + } else { + log.debug("Endpoint '{}' with index '{}' discard because it does have the required index '{}'", + new Object[] {endpoint.getLocation(), endpoint.getIndex(), acsIndex}); + } + } + + log.warn("Relying party '{}' requested the response to be returned to endpoint with ACS index '{}' " + + "however no endpoint, with that index and using a supported binding, can be found " + + " in the relying party's metadata ", getEntityMetadata().getEntityID(), acsIndex); + return null; + } + + /** + * Selects the endpoint by way of the assertion consumer service URL given in the AuthnRequest. + * + * @param request the AuthnRequest + * @param endpoints list of endpoints to select from + * + * @return the selected endpoint + */ + protected Endpoint selectEndpointByACSURL(AuthnRequest request, List endpoints) { + String acsBinding = DatatypeHelper.safeTrimOrNullString(request.getProtocolBinding()); + + for (IndexedEndpoint endpoint : endpoints) { + if (!getSupportedIssuerBindings().contains(endpoint.getBinding())) { + log.debug( + "Endpoint '{}' with binding '{}' discarded because that is not a supported outbound binding.", + endpoint.getLocation(), endpoint.getBinding()); + continue; + } + + if (acsBinding != null) { + if (!DatatypeHelper.safeEquals(acsBinding, endpoint.getBinding())) { + log.debug( + "Endpoint '{}' with binding '{}' discarded because it does not meet protocol binding selection criteria", + endpoint.getLocation(), endpoint.getBinding()); + continue; + } + } + + String responseLocation = DatatypeHelper.safeTrim(endpoint.getResponseLocation()); + if (responseLocation != null){ + if(DatatypeHelper.safeEquals(responseLocation, request.getAssertionConsumerServiceURL())) { + return endpoint; + } + }else{ + String location = DatatypeHelper.safeTrim(endpoint.getLocation()); + if (location != null && DatatypeHelper.safeEquals(location, request.getAssertionConsumerServiceURL())) { + return endpoint; + } + } + + log.debug("Endpoint with Location '{}' discarded because neither its Location nor ResponseLocation match ACS URL '{}'", + endpoint.getLocation(), request.getAssertionConsumerServiceURL()); + } + + log.warn("Relying party '{}' requested the response to be returned to endpoint with ACS URL '{}' " + + " and binding '{}' however no endpoint, with that URL and using a supported binding, " + + " can be found in the relying party's metadata ", new Object[] {getEntityMetadata().getEntityID(), + request.getAssertionConsumerServiceURL(), (acsBinding == null) ? "any" : acsBinding}); + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/SAML2ArtifactMessageContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/SAML2ArtifactMessageContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/SAML2ArtifactMessageContext.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; + +/** + * Extensions to the base SAML message context that carries artifact related information. + * + * @param type of inbound SAML message + * @param type of outbound SAML message + * @param type of name identifier used for subjects + */ +public interface SAML2ArtifactMessageContext + extends SAMLMessageContext { + + /** + * Gets the Base64-encoded artifact to be resolved. + * + * @return artifact to be resolved + */ + public String getArtifact(); + + /** + * Sets the Base64-encoded artifact to be resolved. + * + * @param artifact artifact to be resolved + */ + public void setArtifact(String artifact); + + /** + * Gets the SAML message referenced by the artifact. + * + * @return SAML message referenced by the artifact + */ + public SAMLObject getReferencedMessage(); + + /** + * Sets the SAML message referenced by the artifact. + * + * @param message SAML message referenced by the artifact + */ + public void setReferencedMessage(SAMLObject message); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/package.html 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,12 @@ + + +Class for working with SAML 2 bindings. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/AbstractSAML2Artifact.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/AbstractSAML2Artifact.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/AbstractSAML2Artifact.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.artifact; + +import org.opensaml.common.binding.artifact.AbstractSAMLArtifact; + +/** + * SAML 2 Artifact base class. SAML 2 artifacts contains a 2 byte type code followed by a 2 byte endpoint index followed + * by remaining artifact data. + */ +public abstract class AbstractSAML2Artifact extends AbstractSAMLArtifact { + + /** 2 byte artifact endpoint index. */ + private byte[] endpointIndex; + + /** + * Constructor. + * + * @param artifactType artifact type code + */ + protected AbstractSAML2Artifact(byte[] artifactType) { + super(artifactType); + } + + /** + * Constructor. + * + * @param artifactType artifact type code + * @param index 2 byte endpoint index of the artifact + * + * @throws IllegalArgumentException thrown if the endpoint index, source ID, or message handle arrays are not of the + * right size + */ + public AbstractSAML2Artifact(byte[] artifactType, byte[] index) { + super(artifactType); + setEndpointIndex(index); + } + + /** + * Gets the bytes for the artifact. + * + * @return the bytes for the artifact + */ + public byte[] getArtifactBytes() { + byte[] remainingArtifact = getRemainingArtifact(); + byte[] artifact = new byte[4 + remainingArtifact.length]; + + System.arraycopy(getTypeCode(), 0, artifact, 0, 2); + System.arraycopy(getEndpointIndex(), 0, artifact, 2, 2); + System.arraycopy(remainingArtifact, 0, artifact, 4, remainingArtifact.length); + + return artifact; + } + + /** + * Gets the 2 byte endpoint index for this artifact. + * + * @return 2 byte endpoint index for this artifact + */ + public byte[] getEndpointIndex() { + return endpointIndex; + } + + /** + * Sets the 2 byte endpoint index for this artifact. + * + * @param newIndex 2 byte endpoint index for this artifact + * + * @throws IllegalArgumentException thrown if the given index is not 2 bytes + */ + public void setEndpointIndex(byte[] newIndex) { + if (newIndex.length != 2) { + throw new IllegalArgumentException("Artifact endpoint index must be two bytes long"); + } + + endpointIndex = newIndex; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactBuilder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.artifact; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.saml2.core.NameID; + +/** + * Builder of typed SAML 2 artifacts. + * + * Builders must be thread safe and reusable. + * + * @param type of artifact built by this builder + */ +public interface SAML2ArtifactBuilder { + + /** + * Builds an artifact, for the given assertion, destined for the outbound message recipient. + * + * @param requestContext request context + * + * @return constructed artifcate + */ + public ArtifactType buildArtifact(SAMLMessageContext requestContext); + + /** + * Builds a populated artifact given the artifact's byte-array representation. + * + * @param artifact the byte representation of the artifact + * + * @return populated artifact + */ + public ArtifactType buildArtifact(byte[] artifact); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactBuilderFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactBuilderFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactBuilderFactory.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.artifact; + +import java.util.Map; + +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.LazyMap; + +/** + * Factory used to construct SAML 2 artifact builders. + */ +public class SAML2ArtifactBuilderFactory { + + /** Registered artifact builders. */ + private Map artifactBuilders; + + /** Constructor. */ + public SAML2ArtifactBuilderFactory() { + artifactBuilders = new LazyMap(); + artifactBuilders.put(new String(SAML2ArtifactType0004.TYPE_CODE), new SAML2ArtifactType0004Builder()); + } + + /** + * Gets the currently registered artifact builders. + * + * @return currently registered artifact builders + */ + public Map getArtifactBuilders() { + return artifactBuilders; + } + + /** + * Gets the artifact builder for the given type. + * + * @param type type of artifact to be built + * + * @return artifact builder for the given type + */ + public SAML2ArtifactBuilder getArtifactBuilder(byte[] type) { + return artifactBuilders.get(new String(type)); + } + + /** + * Convenience method for getting an artifact builder and parsing the given Base64 encoded artifact with it. + * + * @param base64Artifact Base64 encoded artifact to parse + * + * @return constructed artifact + */ + public AbstractSAML2Artifact buildArtifact(String base64Artifact){ + return buildArtifact(Base64.decode(base64Artifact)); + } + + /** + * convenience method for getting an artifact builder and parsing the given artifact with it. + * + * @param artifact artifact to parse + * + * @return constructed artifact + */ + public AbstractSAML2Artifact buildArtifact(byte[] artifact) { + if(artifact == null){ + return null; + } + + byte[] type = new byte[2]; + type[0] = artifact[0]; + type[1] = artifact[1]; + + SAML2ArtifactBuilder artifactBuilder = getArtifactBuilder(type); + return artifactBuilder.buildArtifact(artifact); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactType0004.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactType0004.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactType0004.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,141 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.artifact; + +import java.util.Arrays; + +/** + * SAML 2 Type 0x004 Artifact. SAML 2, type 4, artifacts contains a 2 byte type code with a value of 4 follwed by a 2 + * byte endpoint index followed by a 20 byte source ID followed by a 20 byte message handle. + */ +public class SAML2ArtifactType0004 extends AbstractSAML2Artifact { + + /** SAML 2 artifact type code (0x0004). */ + public static final byte[] TYPE_CODE = { 0, 4 }; + + /** 20 byte artifact source ID. */ + private byte[] sourceID; + + /** 20 byte message handle. */ + private byte[] messageHandle; + + /** Constructor. */ + public SAML2ArtifactType0004() { + super(TYPE_CODE); + } + + /** + * Constructor. + * + * @param endpointIndex 2 byte endpoint index of the artifact + * @param source 20 byte source ID of the artifact + * @param handle 20 byte message handle of the artifact + * + * @throws IllegalArgumentException thrown if the endpoint index, source ID, or message handle arrays are not of the + * right size + */ + public SAML2ArtifactType0004(byte[] endpointIndex, byte[] source, byte[] handle) { + super(TYPE_CODE, endpointIndex); + setSourceID(source); + setMessageHandle(handle); + } + + /** + * Constructs a SAML 2 artifact from its byte array representation. + * + * @param artifact the byte array representing the artifact + * + * @return the type 0x0004 artifact created from the byte array + * + * @throws IllegalArgumentException thrown if the artifact is not the right type or lenght (44 bytes) + */ + public static SAML2ArtifactType0004 parseArtifact(byte[] artifact) { + if (artifact.length != 44) { + throw new IllegalArgumentException("Artifact length must be 44 bytes it was " + artifact.length + "bytes"); + } + + byte[] typeCode = { artifact[0], artifact[1] }; + if (!Arrays.equals(typeCode, TYPE_CODE)) { + throw new IllegalArgumentException("Illegal artifact type code"); + } + + byte[] endpointIndex = { artifact[2], artifact[3] }; + + byte[] sourceID = new byte[20]; + System.arraycopy(artifact, 4, sourceID, 0, 20); + + byte[] messageHandle = new byte[20]; + System.arraycopy(artifact, 24, messageHandle, 0, 20); + + return new SAML2ArtifactType0004(endpointIndex, sourceID, messageHandle); + } + + /** + * Gets the 20 byte source ID of the artifact. + * + * @return the source ID of the artifact + */ + public byte[] getSourceID() { + return sourceID; + } + + /** + * Sets the 20 byte source ID of the artifact. + * + * @param newSourceID 20 byte source ID of the artifact + * + * @throws IllegalArgumentException thrown if the given source ID is not 20 bytes + */ + public void setSourceID(byte[] newSourceID) { + if (newSourceID.length != 20) { + throw new IllegalArgumentException("Artifact source ID must be 20 bytes long"); + } + sourceID = newSourceID; + } + + /** + * Gets the 20 byte message handle of the artifact. + * + * @return 20 byte message handle of the artifact + */ + public byte[] getMessageHandle() { + return messageHandle; + } + + /** + * Sets the 20 byte message handle of the artifact. + * + * @param handle 20 byte message handle of the artifact + */ + public void setMessageHandle(byte[] handle) { + if (handle.length != 20) { + throw new IllegalArgumentException("Artifact message handle must be 20 bytes long"); + } + messageHandle = handle; + } + + /** {@inheritDoc} */ + public byte[] getRemainingArtifact() { + byte[] remainingArtifact = new byte[40]; + + System.arraycopy(getSourceID(), 0, remainingArtifact, 0, 20); + System.arraycopy(getMessageHandle(), 0, remainingArtifact, 20, 20); + + return remainingArtifact; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactType0004Builder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactType0004Builder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/SAML2ArtifactType0004Builder.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,102 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.artifact; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.BasicEndpointSelector; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.metadata.ArtifactResolutionService; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2, type 0x0004, artifact builder. + */ +public class SAML2ArtifactType0004Builder implements SAML2ArtifactBuilder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SAML2ArtifactType0004Builder.class); + + /** {@inheritDoc} */ + public SAML2ArtifactType0004 buildArtifact(byte[] artifact) { + return SAML2ArtifactType0004.parseArtifact(artifact); + } + + /** {@inheritDoc} */ + public SAML2ArtifactType0004 buildArtifact(SAMLMessageContext requestContext) { + try { + IndexedEndpoint acsEndpoint = (IndexedEndpoint) getAcsEndpoint(requestContext); + if (acsEndpoint == null) { + return null; + } + + byte[] endpointIndex = DatatypeHelper.intToByteArray(acsEndpoint.getIndex()); + byte[] trimmedIndex = new byte[2]; + trimmedIndex[0] = endpointIndex[2]; + trimmedIndex[1] = endpointIndex[3]; + + MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1"); + byte[] source = sha1Digester.digest(requestContext.getLocalEntityId().getBytes()); + + SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG"); + byte[] assertionHandle; + assertionHandle = new byte[20]; + handleGenerator.nextBytes(assertionHandle); + + return new SAML2ArtifactType0004(trimmedIndex, source, assertionHandle); + } catch (NoSuchAlgorithmException e) { + log.error("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.", e); + throw new InternalError("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG."); + } + } + + /** + * Gets the source location used to for the artifacts created by this encoder. + * + * @param requestContext current request context + * + * @return source location used to for the artifacts created by this encoder + */ + protected Endpoint getAcsEndpoint(SAMLMessageContext requestContext) { + BasicEndpointSelector selector = new BasicEndpointSelector(); + selector.setEndpointType(ArtifactResolutionService.DEFAULT_ELEMENT_NAME); + selector.getSupportedIssuerBindings().add(SAMLConstants.SAML2_SOAP11_BINDING_URI); + selector.setMetadataProvider(requestContext.getMetadataProvider()); + selector.setEntityMetadata(requestContext.getLocalEntityMetadata()); + selector.setEntityRoleMetadata(requestContext.getLocalEntityRoleMetadata()); + + Endpoint acsEndpoint = selector.selectEndpoint(); + + if (acsEndpoint == null) { + log.error("No artifact resolution service endpoint defined for the entity " + + requestContext.getOutboundMessageIssuer()); + return null; + } + + return acsEndpoint; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/artifact/package.html 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,5 @@ + + +Classes that may be used to create and manipulate SAML 2 artifacts. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/BaseSAML2MessageDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/BaseSAML2MessageDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/BaseSAML2MessageDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,260 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.decoding; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.decoding.BaseSAMLMessageDecoder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for SAML 2 message decoders. + */ +public abstract class BaseSAML2MessageDecoder extends BaseSAMLMessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseSAML2MessageDecoder.class); + + /** Constructor. */ + public BaseSAML2MessageDecoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public BaseSAML2MessageDecoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException { + super.decode(messageContext); + + checkEndpointURI((SAMLMessageContext) messageContext); + } + + /** + * Populates the message context with the message ID, issue instant, and issuer as well as the peer's entity + * descriptor if a metadata provider is present in the message context and the peer's role descriptor if its entity + * descriptor was retrieved and the message context has a populated peer role name. + * + * @param messageContext message context to populate + * + * @throws MessageDecodingException thrown if there is a problem populating the message context + */ + protected void populateMessageContext(SAMLMessageContext messageContext) throws MessageDecodingException { + populateMessageIdIssueInstantIssuer(messageContext); + populateRelyingPartyMetadata(messageContext); + } + + /** + * Extracts the message ID, issue instant, and issuer from the incoming SAML message and populates the message + * context with it. + * + * @param messageContext current message context + * + * @throws MessageDecodingException thrown if there is a problem populating the message context + */ + protected void populateMessageIdIssueInstantIssuer(SAMLMessageContext messageContext) + throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.debug("Invalid message context type, this policy rule only support SAMLMessageContext"); + return; + } + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject samlMsg = samlMsgCtx.getInboundSAMLMessage(); + if (samlMsg == null) { + log.error("Message context did not contain inbound SAML message"); + throw new MessageDecodingException("Message context did not contain inbound SAML message"); + } + + if (samlMsg instanceof RequestAbstractType) { + log.debug("Extracting ID, issuer and issue instant from request"); + extractRequestInfo(samlMsgCtx, (RequestAbstractType) samlMsg); + } else if (samlMsg instanceof StatusResponseType) { + log.debug("Extracting ID, issuer and issue instant from status response"); + extractResponseInfo(samlMsgCtx, (StatusResponseType) samlMsg); + } else { + throw new MessageDecodingException("SAML 2 message was not a request or a response"); + } + + if (samlMsgCtx.getInboundMessageIssuer() == null) { + log.warn("Issuer could not be extracted from SAML 2 message"); + } + + } + + /** + * Extract information from a SAML StatusResponse message. + * + * @param messageContext current message context + * @param statusResponse the SAML message to process + * + * @throws MessageDecodingException thrown if the response issuer has a format other than {@link NameIDType#ENTITY} + * or, if the response does not contain an issuer, if the contained assertions contain issuers that are + * not of {@link NameIDType#ENTITY} format or if the assertions contain different issuers + */ + protected void extractResponseInfo(SAMLMessageContext messageContext, StatusResponseType statusResponse) + throws MessageDecodingException { + + messageContext.setInboundSAMLMessageId(statusResponse.getID()); + messageContext.setInboundSAMLMessageIssueInstant(statusResponse.getIssueInstant()); + + // If response doesn't have an issuer, look at the first + // enclosed assertion + String messageIssuer = null; + if (statusResponse.getIssuer() != null) { + messageIssuer = extractEntityId(statusResponse.getIssuer()); + } else if (statusResponse instanceof Response) { + List assertions = ((Response) statusResponse).getAssertions(); + if (assertions != null && assertions.size() > 0) { + log.info("Status response message had no issuer, attempting to extract issuer from enclosed Assertion(s)"); + String assertionIssuer; + for (Assertion assertion : assertions) { + if (assertion != null && assertion.getIssuer() != null) { + assertionIssuer = extractEntityId(assertion.getIssuer()); + if (messageIssuer != null && !messageIssuer.equals(assertionIssuer)) { + throw new MessageDecodingException("SAML 2 assertions, within response " + + statusResponse.getID() + " contain different issuer IDs"); + } + messageIssuer = assertionIssuer; + } + } + } + } + + messageContext.setInboundMessageIssuer(messageIssuer); + } + + /** + * Extract information from a SAML RequestAbstractType message. + * + * @param messageContext current message context + * @param request the SAML message to process + * + * @throws MessageDecodingException thrown if the request issuer has a format other than {@link NameIDType#ENTITY} + */ + protected void extractRequestInfo(SAMLMessageContext messageContext, RequestAbstractType request) + throws MessageDecodingException { + messageContext.setInboundSAMLMessageId(request.getID()); + messageContext.setInboundSAMLMessageIssueInstant(request.getIssueInstant()); + messageContext.setInboundMessageIssuer(extractEntityId(request.getIssuer())); + } + + /** + * Extracts the entity ID from the SAML 2 Issuer. + * + * @param issuer issuer to extract the entityID from + * + * @return entity ID of the issuer + * + * @throws MessageDecodingException thrown if the given issuer has a format other than {@link NameIDType#ENTITY} + */ + protected String extractEntityId(Issuer issuer) throws MessageDecodingException { + if (issuer != null) { + if (issuer.getFormat() == null || issuer.getFormat().equals(NameIDType.ENTITY)) { + return issuer.getValue(); + } else { + throw new MessageDecodingException("SAML 2 Issuer is not of ENTITY format type"); + } + } + + return null; + } + + + /** + * Populates the peer's entity metadata if a metadata provide is present in the message context. Populates the + * peer's role descriptor if the entity metadata was available and the role name is present in the message context. + * + * @param messageContext current message context + * + * @throws MessageDecodingException thrown if there is a problem populating the message context + */ + protected void populateRelyingPartyMetadata(SAMLMessageContext messageContext) throws MessageDecodingException { + MetadataProvider metadataProvider = messageContext.getMetadataProvider(); + try { + if (metadataProvider != null) { + EntityDescriptor relyingPartyMD = metadataProvider.getEntityDescriptor(messageContext + .getInboundMessageIssuer()); + messageContext.setPeerEntityMetadata(relyingPartyMD); + + QName relyingPartyRole = messageContext.getPeerEntityRole(); + if (relyingPartyMD != null && relyingPartyRole != null) { + List roles = relyingPartyMD.getRoleDescriptors(relyingPartyRole, + SAMLConstants.SAML11P_NS); + if (roles != null && roles.size() > 0) { + messageContext.setPeerEntityRoleMetadata(roles.get(0)); + } + } + } + } catch (MetadataProviderException e) { + log.error("Error retrieving metadata for relying party " + messageContext.getInboundMessageIssuer(), e); + throw new MessageDecodingException("Error retrieving metadata for relying party " + + messageContext.getInboundMessageIssuer(), e); + } + } + + /** + * {@inheritDoc} + * + *

This SAML 2-specific implementation extracts the value of the protocol message Destination attribute.

+ * + * */ + protected String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) throws MessageDecodingException { + SAMLObject samlMessage = samlMsgCtx.getInboundSAMLMessage(); + String messageDestination = null; + if (samlMessage instanceof RequestAbstractType) { + RequestAbstractType request = (RequestAbstractType) samlMessage; + messageDestination = DatatypeHelper.safeTrimOrNullString(request.getDestination()); + } else if (samlMessage instanceof StatusResponseType) { + StatusResponseType response = (StatusResponseType) samlMessage; + messageDestination = DatatypeHelper.safeTrimOrNullString(response.getDestination()); + } else { + log.error("Invalid SAML message type encountered: {}", samlMessage.getElementQName().toString()); + throw new MessageDecodingException("Invalid SAML message type encountered"); + } + return messageDestination; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPArtifactDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPArtifactDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPArtifactDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.decoding; + + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2 Artifact Binding decoder, support both HTTP GET and POST. + * + * NOTE: This decoder is not yet implemented. + * */ +public class HTTPArtifactDecoder extends BaseSAML2MessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPArtifactDecoder.class); + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPArtifactDecoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_ARTIFACT_BINDING_URI; + } + + /** {@inheritDoc} */ + protected boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx) { + return false; + } + + /** {@inheritDoc} */ + protected String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) throws MessageDecodingException { + // Not relevant in this binding/profile, there is neither SAML message + // nor binding parameter with this information + return null; + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this decoder only support SAMLMessageContext"); + throw new MessageDecodingException( + "Invalid message context type, this decoder only support SAMLMessageContext"); + } + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + String relayState = DatatypeHelper.safeTrim(inTransport.getParameterValue("RelayState")); + samlMsgCtx.setRelayState(relayState); + + processArtifact(samlMsgCtx); + + populateMessageContext(samlMsgCtx); + } + + /** + * Process the incoming artifact by decoding the artifacts, dereferencing it from the artifact issuer and + * storing the resulting protocol message in the message context. + * + * @param samlMsgCtx current message context + * + * @throws MessageDecodingException thrown if there is a problem decoding or dereferencing the artifact + */ + protected void processArtifact(SAMLMessageContext samlMsgCtx) throws MessageDecodingException { + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + String encodedArtifact = DatatypeHelper.safeTrimOrNullString(inTransport.getParameterValue("SAMLart")); + if (encodedArtifact == null) { + log.error("URL SAMLart parameter was missing or did not contain a value."); + throw new MessageDecodingException("URL TARGET parameter was missing or did not contain a value."); + } + + // TODO decode artifact; resolve issuer resolution endpoint; dereference using ArtifactResolve + // over synchronous backchannel binding; store resultant protocol message as the inbound SAML message. + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPPostDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPPostDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPPostDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,131 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.decoding; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Message decoder implementing the SAML 2.0 HTTP POST binding. */ +public class HTTPPostDecoder extends BaseSAML2MessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPPostDecoder.class); + + /** Constructor. */ + public HTTPPostDecoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPPostDecoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_POST_BINDING_URI; + } + + /** {@inheritDoc} */ + protected boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx) { + return isMessageSigned(samlMsgCtx); + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this decoder only support SAMLMessageContext"); + throw new MessageDecodingException( + "Invalid message context type, this decoder only support SAMLMessageContext"); + } + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) { + throw new MessageDecodingException("This message deocoder only supports the HTTP POST method"); + } + + String relayState = inTransport.getParameterValue("RelayState"); + samlMsgCtx.setRelayState(relayState); + log.debug("Decoded SAML relay state of: {}", relayState); + + InputStream base64DecodedMessage = getBase64DecodedMessage(inTransport); + SAMLObject inboundMessage = (SAMLObject) unmarshallMessage(base64DecodedMessage); + samlMsgCtx.setInboundMessage(inboundMessage); + samlMsgCtx.setInboundSAMLMessage(inboundMessage); + log.debug("Decoded SAML message"); + + populateMessageContext(samlMsgCtx); + } + + /** + * Gets the Base64 encoded message from the request and decodes it. + * + * @param transport inbound message transport + * + * @return decoded message + * + * @throws MessageDecodingException thrown if the message does not contain a base64 encoded SAML message + */ + protected InputStream getBase64DecodedMessage(HTTPInTransport transport) throws MessageDecodingException { + log.debug("Getting Base64 encoded message from request"); + String encodedMessage = transport.getParameterValue("SAMLRequest"); + if (DatatypeHelper.isEmpty(encodedMessage)) { + encodedMessage = transport.getParameterValue("SAMLResponse"); + } + + if (DatatypeHelper.isEmpty(encodedMessage)) { + log.error("Request did not contain either a SAMLRequest or " + + "SAMLResponse paramter. Invalid request for SAML 2 HTTP POST binding."); + throw new MessageDecodingException("No SAML message present in request"); + } + + log.trace("Base64 decoding SAML message:\n{}", encodedMessage); + byte[] decodedBytes = Base64.decode(encodedMessage); + if(decodedBytes == null){ + log.error("Unable to Base64 decode SAML message"); + throw new MessageDecodingException("Unable to Base64 decode SAML message"); + } + + log.trace("Decoded SAML message:\n{}", new String(decodedBytes)); + return new ByteArrayInputStream(decodedBytes); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPPostSimpleSignDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPPostSimpleSignDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPPostSimpleSignDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.decoding; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.DatatypeHelper; + +/** Message decoder implementing the SAML 2.0 HTTP POST-SimpleSign binding. */ +public class HTTPPostSimpleSignDecoder extends HTTPPostDecoder { + + /** + * Constructor. + * + */ + public HTTPPostSimpleSignDecoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPPostSimpleSignDecoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI; + } + + /** {@inheritDoc} */ + protected boolean isMessageSigned(SAMLMessageContext messageContext) { + HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport(); + String sigParam = inTransport.getParameterValue("Signature"); + return (!DatatypeHelper.isEmpty(sigParam)) || super.isMessageSigned(messageContext); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPRedirectDeflateDecoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPRedirectDeflateDecoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPRedirectDeflateDecoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,144 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.decoding; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2.0 HTTP Redirect decoder using the DEFLATE encoding method. + * + * This decoder only supports DEFLATE compression. + */ +public class HTTPRedirectDeflateDecoder extends BaseSAML2MessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPRedirectDeflateDecoder.class); + + /** Constructor. */ + public HTTPRedirectDeflateDecoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPRedirectDeflateDecoder(ParserPool pool) { + super(pool); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_REDIRECT_BINDING_URI; + } + + /** {@inheritDoc} */ + protected boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx) { + return isMessageSigned(samlMsgCtx); + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this decoder only support SAMLMessageContext"); + throw new MessageDecodingException( + "Invalid message context type, this decoder only support SAMLMessageContext"); + } + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + String relayState = inTransport.getParameterValue("RelayState"); + samlMsgCtx.setRelayState(relayState); + log.debug("Decoded RelayState: {}", relayState); + + InputStream samlMessageIns; + if (!DatatypeHelper.isEmpty(inTransport.getParameterValue("SAMLRequest"))) { + samlMessageIns = decodeMessage(inTransport.getParameterValue("SAMLRequest")); + } else if (!DatatypeHelper.isEmpty(inTransport.getParameterValue("SAMLResponse"))) { + samlMessageIns = decodeMessage(inTransport.getParameterValue("SAMLResponse")); + } else { + throw new MessageDecodingException( + "No SAMLRequest or SAMLResponse query path parameter, invalid SAML 2 HTTP Redirect message"); + } + + SAMLObject samlMessage = (SAMLObject) unmarshallMessage(samlMessageIns); + samlMsgCtx.setInboundSAMLMessage(samlMessage); + samlMsgCtx.setInboundMessage(samlMessage); + log.debug("Decoded SAML message"); + + populateMessageContext(samlMsgCtx); + } + + /** {@inheritDoc} */ + protected boolean isMessageSigned(SAMLMessageContext messageContext) { + HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport(); + String sigParam = inTransport.getParameterValue("Signature"); + return (!DatatypeHelper.isEmpty(sigParam)) || super.isMessageSigned(messageContext); + } + + /** + * Base64 decodes the SAML message and then decompresses the message. + * + * @param message Base64 encoded, DEFALTE compressed, SAML message + * + * @return the SAML message + * + * @throws MessageDecodingException thrown if the message can not be decoded + */ + protected InputStream decodeMessage(String message) throws MessageDecodingException { + log.debug("Base64 decoding and inflating SAML message"); + + byte[] decodedBytes = Base64.decode(message); + if(decodedBytes == null){ + log.error("Unable to Base64 decode incoming message"); + throw new MessageDecodingException("Unable to Base64 decode incoming message"); + } + + try { + ByteArrayInputStream bytesIn = new ByteArrayInputStream(decodedBytes); + InflaterInputStream inflater = new InflaterInputStream(bytesIn, new Inflater(true)); + return inflater; + } catch (Exception e) { + log.error("Unable to Base64 decode and inflate SAML message", e); + throw new MessageDecodingException("Unable to Base64 decode and inflate SAML message", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPSOAP11Decoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPSOAP11Decoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HTTPSOAP11Decoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,181 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.decoding; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.LazyList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2.0 SOAP 1.1 over HTTP binding decoder. + */ +public class HTTPSOAP11Decoder extends BaseSAML2MessageDecoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPSOAP11Decoder.class); + + /** QNames of understood SOAP headers. */ + private List understoodHeaders; + + /** QName of SOAP mustUnderstand header attribute. */ + private final QName soapMustUnderstand = new QName(SAMLConstants.SOAP11ENV_NS, "mustUnderstand"); + + /** Constructor. */ + public HTTPSOAP11Decoder() { + super(); + understoodHeaders = new LazyList(); + } + + /** + * Constructor. + * + * @param pool parser pool used to deserialize messages + */ + public HTTPSOAP11Decoder(ParserPool pool) { + super(pool); + understoodHeaders = new LazyList(); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_SOAP11_BINDING_URI; + } + + /** {@inheritDoc} */ + protected boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx) { + return false; + } + + /** + * Gets the SOAP header names that are understood by the application. + * + * @return SOAP header names that are understood by the application + */ + public List getUnderstoodHeaders() { + return understoodHeaders; + } + + /** + * Sets the SOAP header names that are understood by the application. + * + * @param headerNames SOAP header names that are understood by the application + */ + public void setUnderstoodHeaders(List headerNames) { + understoodHeaders.clear(); + if (headerNames != null) { + understoodHeaders.addAll(headerNames); + } + } + + /** {@inheritDoc} */ + protected void doDecode(MessageContext messageContext) throws MessageDecodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this decoder only support SAMLMessageContext"); + throw new MessageDecodingException( + "Invalid message context type, this decoder only support SAMLMessageContext"); + } + + if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { + log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); + throw new MessageDecodingException( + "Invalid inbound message transport type, this decoder only support HTTPInTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); + if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) { + throw new MessageDecodingException("This message deocoder only supports the HTTP POST method"); + } + + log.debug("Unmarshalling SOAP message"); + Envelope soapMessage = (Envelope) unmarshallMessage(inTransport.getIncomingStream()); + samlMsgCtx.setInboundMessage(soapMessage); + + Header messageHeader = soapMessage.getHeader(); + if (messageHeader != null) { + checkUnderstoodSOAPHeaders(soapMessage.getHeader().getUnknownXMLObjects()); + } + + List soapBodyChildren = soapMessage.getBody().getUnknownXMLObjects(); + if (soapBodyChildren.size() < 1 || soapBodyChildren.size() > 1) { + log.error("Unexpected number of children in the SOAP body, " + soapBodyChildren.size() + + ". Unable to extract SAML message"); + throw new MessageDecodingException( + "Unexpected number of children in the SOAP body, unable to extract SAML message"); + } + + XMLObject incommingMessage = soapBodyChildren.get(0); + if (!(incommingMessage instanceof SAMLObject)) { + log.error("Unexpected SOAP body content. Expected a SAML request but recieved {}", incommingMessage + .getElementQName()); + throw new MessageDecodingException("Unexpected SOAP body content. Expected a SAML request but recieved " + + incommingMessage.getElementQName()); + } + + SAMLObject samlMessage = (SAMLObject) incommingMessage; + log.debug("Decoded SOAP messaged which included SAML message of type {}", samlMessage.getElementQName()); + samlMsgCtx.setInboundSAMLMessage(samlMessage); + + populateMessageContext(samlMsgCtx); + } + + /** + * Checks that, if any SOAP headers, require understand that they are in the understood header list. + * + * @param headers SOAP headers to check + * + * @throws MessageDecodingException thrown if a SOAP header requires understanding but is not understood by the + * decoder + */ + protected void checkUnderstoodSOAPHeaders(List headers) throws MessageDecodingException { + if (headers == null || headers.isEmpty()) { + return; + } + + AttributeExtensibleXMLObject attribExtensObject; + for (XMLObject header : headers) { + if (header instanceof AttributeExtensibleXMLObject) { + attribExtensObject = (AttributeExtensibleXMLObject) header; + if (DatatypeHelper.safeEquals("1", attribExtensObject.getUnknownAttributes().get(soapMustUnderstand))) { + if (!understoodHeaders.contains(header.getElementQName())) { + throw new MessageDecodingException("SOAP decoder encountered a header, " + + header.getElementQName() + + ", that requires understanding however this decoder does not understand that header"); + } + } + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HandlerChainAwareHTTPSOAP11Decoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HandlerChainAwareHTTPSOAP11Decoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/HandlerChainAwareHTTPSOAP11Decoder.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,145 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.decoding; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.ws.message.handler.HandlerChain; +import org.opensaml.ws.message.handler.HandlerChainAware; +import org.opensaml.ws.message.handler.HandlerChainResolver; +import org.opensaml.ws.message.handler.HandlerException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.security.SecurityException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2.0 SOAP 1.1 over HTTP binding decoder with support for handler chains. + */ +public class HandlerChainAwareHTTPSOAP11Decoder extends HTTPSOAP11Decoder implements HandlerChainAware { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HandlerChainAwareHTTPSOAP11Decoder.class); + + /** Constructor. */ + public HandlerChainAwareHTTPSOAP11Decoder() { + super(); + } + + /** + * Constructor. + * + * @param pool parser pool to use + */ + public HandlerChainAwareHTTPSOAP11Decoder(ParserPool pool) { + super(pool); + } + + // TODO: The rest of the methods here are copied from BaseHandlerChainAwareMessageDecoder and + // should drop out once the SAML decoders are aligned to that base class. + + /** {@inheritDoc} */ + public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException { + log.debug("Beginning to decode message from inbound transport of type: {}", messageContext + .getInboundMessageTransport().getClass().getName()); + + doDecode(messageContext); + + logDecodedMessage(messageContext); + + processPreSecurityInboundHandlerChain(messageContext); + log.debug("Successfully processed pre-SecurityPolicy inbound handler chain."); + + processSecurityPolicy(messageContext); + + processPostSecurityInboundHandlerChain(messageContext); + log.debug("Successfully processed post-SecurityPolicy inbound handler chain."); + + log.debug("Successfully decoded message."); + + // TODO: This gets executed by BaseSAML2MessageDecoder. Probably needs to be + // factored out somehow to avoid brittleness in the decode() override. + checkEndpointURI((SAMLMessageContext) messageContext); + } + + /** + * Process the pre-SecurityPolicy inbound {@link HandlerChain} for the message context, if any. + * + * @param messageContext the message context to process + * @throws MessageDecodingException thrown if a handler indicates a problem handling the message + */ + protected void processPreSecurityInboundHandlerChain(MessageContext messageContext) + throws MessageDecodingException { + HandlerChainResolver inboundHandlerChainResolver = messageContext.getPreSecurityInboundHandlerChainResolver(); + if (inboundHandlerChainResolver != null) { + log.debug("Invoking pre-SecurityPolicy inbound handler chain on message context"); + try { + for (HandlerChain inboundHandlerChain : inboundHandlerChainResolver.resolve(messageContext)) { + if (inboundHandlerChain != null) { + invokeHandlerChain(inboundHandlerChain, messageContext); + } + } + } catch (HandlerException e) { + log.error("Encountered pre-SecurityPolicy HandlerException when decoding message: {}", e.getMessage()); + throw new MessageDecodingException("Pre-SecurityPolicy Handler exception while decoding message", e); + } + } + } + + /** + * Process the post-SecurityPolicy inbound {@link HandlerChain} for the message context, if any. + * + * @param messageContext the message context to process + * @throws MessageDecodingException thrown if a handler indicates a problem handling the message + */ + protected void processPostSecurityInboundHandlerChain(MessageContext messageContext) + throws MessageDecodingException { + HandlerChainResolver inboundHandlerChainResolver = messageContext.getPostSecurityInboundHandlerChainResolver(); + if (inboundHandlerChainResolver != null) { + log.debug("Invoking post-SecurityPolicy inbound handler chain on message context"); + try { + for (HandlerChain inboundHandlerChain : inboundHandlerChainResolver.resolve(messageContext)) { + if (inboundHandlerChain != null) { + invokeHandlerChain(inboundHandlerChain, messageContext); + } + } + } catch (HandlerException e) { + log.error("Encountered post-SecurityPolicy HandlerException when decoding message: {}", e.getMessage()); + throw new MessageDecodingException("Handler exception while decoding message", e); + } + } + } + + /** + * Invoke a handler chain on the specified message context. + * + * @param handlerChain the handle chain to invoke + * @param messageContext the message context to process + * + * @throws HandlerException if handler chain encountered a problem handling the message context + */ + protected void invokeHandlerChain(HandlerChain handlerChain, MessageContext messageContext) + throws HandlerException { + if (handlerChain != null && messageContext != null) { + handlerChain.invoke(messageContext); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/decoding/package.html 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,7 @@ + + +Classes used to decode SAML 2 messages. A decoder takes a wire protocol, +extracts the SAML message from it, and then evaluates that message +against a security policy. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/BaseSAML2MessageEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/BaseSAML2MessageEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/BaseSAML2MessageEncoder.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,203 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.encoding; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.Configuration; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.encoding.SAMLMessageEncoder; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.util.URLBuilder; +import org.opensaml.ws.message.encoder.BaseMessageEncoder; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.XMLObjectBuilder; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.SignatureException; +import org.opensaml.xml.signature.Signer; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Base class for SAML 2 message encoders. + */ +public abstract class BaseSAML2MessageEncoder extends BaseMessageEncoder implements SAMLMessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(BaseSAML2MessageEncoder.class); + + /** The list of schemes allowed to appear in URLs related to the encoded message. Defaults to 'http' and 'https'. */ + private List allowedURLSchemes; + + public BaseSAML2MessageEncoder(){ + super(); + setAllowedURLSchemes(new String[] { "http", "https" }); + } + + /** + * Gets the unmodifiable list of schemes allowed to appear in URLs related to the encoded message. + * + * @return list of URL schemes allowed to appear in a message + */ + public List getAllowedURLSchemes() { + return allowedURLSchemes; + } + + /** + * Sets the list of list of schemes allowed to appear in URLs related to the encoded message. Note, the appearance + * of schemes such as 'javascript' may open the system up to attacks (e.g. cross-site scripting attacks). + * + * @param schemes URL schemes allowed to appear in a message + */ + public void setAllowedURLSchemes(String[] schemes) { + if (schemes == null || schemes.length == 0) { + allowedURLSchemes = Collections.emptyList(); + } else { + List temp = new ArrayList(); + for (String scheme : schemes) { + temp.add(scheme); + } + allowedURLSchemes = Collections.unmodifiableList(temp); + } + } + + /** + * Gets the response URL from the relying party endpoint. If the SAML message is a {@link StatusResponseType} and the relying + * party endpoint contains a response location then that location is returned otherwise the normal endpoint location + * is returned. + * + * @param messageContext current message context + * + * @return response URL from the relying party endpoint + * + * @throws MessageEncodingException throw if no relying party endpoint is available + */ + protected URLBuilder getEndpointURL(SAMLMessageContext messageContext) throws MessageEncodingException { + Endpoint endpoint = messageContext.getPeerEntityEndpoint(); + if (endpoint == null) { + throw new MessageEncodingException("Endpoint for relying party was null."); + } + + URLBuilder urlBuilder; + if (messageContext.getOutboundMessage() instanceof StatusResponseType + && !DatatypeHelper.isEmpty(endpoint.getResponseLocation())) { + urlBuilder = new URLBuilder(endpoint.getResponseLocation()); + } else { + if (DatatypeHelper.isEmpty(endpoint.getLocation())) { + throw new MessageEncodingException("Relying party endpoint location was null or empty."); + } + urlBuilder = new URLBuilder(endpoint.getLocation()); + } + + if(!getAllowedURLSchemes().contains(urlBuilder.getScheme())){ + throw new MessageEncodingException("Relying party endpoint used the untrusted URL scheme " + urlBuilder.getScheme()); + } + return urlBuilder; + } + + /** + * Checks that the relay state is 80 bytes or less if it is not null. + * + * @param relayState relay state to check + * + * @return true if the relay state is not empty and is less than 80 bytes + */ + protected boolean checkRelayState(String relayState) { + if (!DatatypeHelper.isEmpty(relayState)) { + if (relayState.getBytes().length > 80) { + log.warn("Relay state exceeds 80 bytes, some application may not support this."); + } + + return true; + } + + return false; + } + + /** + * Sets the destination attribute on the outbound message if it is a {@link StatusResponseType} message. + * + * @param outboundMessage outbound SAML message + * @param endpointURL destination endpoint + */ + protected void setResponseDestination(SAMLObject outboundMessage, String endpointURL) { + if (outboundMessage instanceof StatusResponseType) { + ((StatusResponseType) outboundMessage).setDestination(endpointURL); + } + } + + /** + * Signs the given SAML message if it a {@link SignableSAMLObject} and this encoder has signing credentials. + * + * @param messageContext current message context + * + * @throws MessageEncodingException thrown if there is a problem marshalling or signing the outbound message + */ + @SuppressWarnings("unchecked") + protected void signMessage(SAMLMessageContext messageContext) throws MessageEncodingException { + SAMLObject outboundSAML = messageContext.getOutboundSAMLMessage(); + Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential(); + + if (outboundSAML instanceof SignableSAMLObject && signingCredential != null) { + SignableSAMLObject signableMessage = (SignableSAMLObject) outboundSAML; + + XMLObjectBuilder signatureBuilder = Configuration.getBuilderFactory().getBuilder( + Signature.DEFAULT_ELEMENT_NAME); + Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME); + + signature.setSigningCredential(signingCredential); + try { + //TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added + //TODO pull binding-specific keyInfoGenName from encoder setting, etc? + SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null); + } catch (SecurityException e) { + throw new MessageEncodingException("Error preparing signature for signing", e); + } + + signableMessage.setSignature(signature); + + try { + Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(signableMessage); + if (marshaller == null) { + throw new MessageEncodingException("No marshaller registered for " + + signableMessage.getElementQName() + ", unable to marshall in preperation for signing"); + } + marshaller.marshall(signableMessage); + + Signer.signObject(signature); + } catch (MarshallingException e) { + log.error("Unable to marshall protocol message in preparation for signing", e); + throw new MessageEncodingException("Unable to marshall protocol message in preparation for signing", e); + } catch (SignatureException e) { + log.error("Unable to sign protocol message", e); + throw new MessageEncodingException("Unable to sign protocol message", e); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPArtifactEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPArtifactEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPArtifactEncoder.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,244 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.encoding; + +import java.io.OutputStreamWriter; +import java.util.List; + +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.opensaml.Configuration; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.artifact.AbstractSAMLArtifact; +import org.opensaml.common.binding.artifact.SAMLArtifactMap; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.binding.artifact.AbstractSAML2Artifact; +import org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilder; +import org.opensaml.saml2.binding.artifact.SAML2ArtifactType0004; +import org.opensaml.util.URLBuilder; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.Pair; +import org.owasp.esapi.ESAPI; +import org.owasp.esapi.Encoder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2 Artifact Binding encoder, support both HTTP GET and POST. + */ +public class HTTPArtifactEncoder extends BaseSAML2MessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPArtifactEncoder.class); + + /** Whether the POST encoding should be used, instead of GET. */ + private boolean postEncoding; + + /** Velocity engine used to evaluate the template when performing POST encoding. */ + private VelocityEngine velocityEngine; + + /** ID of the velocity template used when performing POST encoding. */ + private String velocityTemplateId; + + /** SAML artifact map used to store created artifacts for later retrieval. */ + private SAMLArtifactMap artifactMap; + + /** Default artifact type to use when encoding messages. */ + private byte[] defaultArtifactType; + + /** + * Constructor. + * + * @param engine velocity engine used to construct the POST form + * @param template ID of velocity template used to construct the POST form + * @param map artifact map used to store artifact/message bindings + */ + public HTTPArtifactEncoder(VelocityEngine engine, String template, SAMLArtifactMap map) { + super(); + postEncoding = false; + velocityEngine = engine; + velocityTemplateId = template; + artifactMap = map; + defaultArtifactType = SAML2ArtifactType0004.TYPE_CODE; + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_ARTIFACT_BINDING_URI; + } + + /** + * Gets whether the encoder will encode the artifact via POST encoding. + * + * @return true if POST encoding will be used, false if GET encoding will be used + */ + public boolean isPostEncoding() { + return postEncoding; + } + + /** + * Sets whether the encoder will encode the artifact via POST encoding. + * + * @param post true if POST encoding will be used, false if GET encoding will be used + */ + public void setPostEncoding(boolean post) { + postEncoding = post; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + SAMLMessageContext artifactContext = (SAMLMessageContext) messageContext; + HTTPOutTransport outTransport = (HTTPOutTransport) artifactContext.getOutboundMessageTransport(); + outTransport.setCharacterEncoding("UTF-8"); + + if (postEncoding) { + postEncode(artifactContext, outTransport); + } else { + getEncode(artifactContext, outTransport); + } + } + + /** + * Performs HTTP POST based encoding. + * + * @param artifactContext current request context + * @param outTransport outbound HTTP transport + * + * @throws MessageEncodingException thrown if there is a problem POST encoding the artifact + */ + protected void postEncode(SAMLMessageContext artifactContext, HTTPOutTransport outTransport) + throws MessageEncodingException { + log.debug("Performing HTTP POST SAML 2 artifact encoding"); + + log.debug("Creating velocity context"); + VelocityContext context = new VelocityContext(); + Encoder esapiEncoder = ESAPI.encoder(); + String endpointURL = getEndpointURL(artifactContext).toString(); + String encodedEndpointURL = esapiEncoder.encodeForHTMLAttribute(endpointURL); + log.debug("Setting action parameter to: '{}', encoded as '{}'", endpointURL, encodedEndpointURL); + context.put("action", encodedEndpointURL); + context.put("SAMLArt", buildArtifact(artifactContext).base64Encode()); + + if (checkRelayState(artifactContext.getRelayState())) { + String encodedRelayState = esapiEncoder.encodeForHTMLAttribute(artifactContext.getRelayState()); + log.debug("Setting RelayState parameter to: '{}', encoded as '{}'", artifactContext.getRelayState(), encodedRelayState); + context.put("RelayState", encodedRelayState); + } + + try { + log.debug("Invoking velocity template"); + OutputStreamWriter outWriter = new OutputStreamWriter(outTransport.getOutgoingStream()); + velocityEngine.mergeTemplate(velocityTemplateId, "UTF-8", context, outWriter); + } catch (Exception e) { + log.error("Error invoking velocity template to create POST form", e); + throw new MessageEncodingException("Error creating output document", e); + } + } + + /** + * Performs HTTP GET based encoding. + * + * @param artifactContext current request context + * @param outTransport outbound HTTP transport + * + * @throws MessageEncodingException thrown if there is a problem GET encoding the artifact + */ + protected void getEncode(SAMLMessageContext artifactContext, HTTPOutTransport outTransport) + throws MessageEncodingException { + log.debug("Performing HTTP GET SAML 2 artifact encoding"); + + URLBuilder urlBuilder = getEndpointURL(artifactContext); + + List> params = urlBuilder.getQueryParams(); + + AbstractSAMLArtifact artifact = buildArtifact(artifactContext); + if(artifact == null){ + log.error("Unable to build artifact for message to relying party"); + throw new MessageEncodingException("Unable to builder artifact for message to relying party"); + } + params.add(new Pair("SAMLart", artifact.base64Encode())); + + if (checkRelayState(artifactContext.getRelayState())) { + params.add(new Pair("RelayState", artifactContext.getRelayState())); + } + + outTransport.sendRedirect(urlBuilder.buildURL()); + } + + /** + * Builds the SAML 2 artifact for the outgoing message. + * + * @param artifactContext current request context + * + * @return SAML 2 artifact for outgoing message + * + * @throws MessageEncodingException thrown if the artifact can not be created + */ + protected AbstractSAML2Artifact buildArtifact(SAMLMessageContext artifactContext) throws MessageEncodingException { + + SAML2ArtifactBuilder artifactBuilder; + if (artifactContext.getOutboundMessageArtifactType() != null) { + artifactBuilder = Configuration.getSAML2ArtifactBuilderFactory().getArtifactBuilder( + artifactContext.getOutboundMessageArtifactType()); + } else { + artifactBuilder = Configuration.getSAML2ArtifactBuilderFactory().getArtifactBuilder(defaultArtifactType); + artifactContext.setOutboundMessageArtifactType(defaultArtifactType); + } + + AbstractSAML2Artifact artifact = artifactBuilder.buildArtifact(artifactContext); + if(artifact == null){ + log.error("Unable to build artifact for message to relying party"); + throw new MessageEncodingException("Unable to builder artifact for message to relying party"); + } + String encodedArtifact = artifact.base64Encode(); + try { + artifactMap.put(encodedArtifact, artifactContext.getInboundMessageIssuer(), artifactContext + .getOutboundMessageIssuer(), artifactContext.getOutboundSAMLMessage()); + } catch (MarshallingException e) { + log.error("Unable to marshall assertion to be represented as an artifact", e); + throw new MessageEncodingException("Unable to marshall assertion to be represented as an artifact", e); + } + + return artifact; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPPostEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPPostEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPPostEncoder.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,188 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.encoding; + +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; + +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.XMLHelper; +import org.owasp.esapi.ESAPI; +import org.owasp.esapi.Encoder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2.0 HTTP Post binding message encoder. + */ +public class HTTPPostEncoder extends BaseSAML2MessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPPostEncoder.class); + + /** Velocity engine used to evaluate the template when performing POST encoding. */ + private VelocityEngine velocityEngine; + + /** ID of the Velocity template used when performing POST encoding. */ + private String velocityTemplateId; + + /** + * Constructor. + * + * @param engine Velocity engine instance used to create POST body + * @param templateId ID of the template used to create POST body + */ + public HTTPPostEncoder(VelocityEngine engine, String templateId) { + super(); + velocityEngine = engine; + velocityTemplateId = templateId; + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_POST_BINDING_URI; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage(); + if (outboundMessage == null) { + throw new MessageEncodingException("No outbound SAML message contained in message context"); + } + String endpointURL = getEndpointURL(samlMsgCtx).buildURL(); + + if (samlMsgCtx.getOutboundSAMLMessage() instanceof StatusResponseType) { + ((StatusResponseType) samlMsgCtx.getOutboundSAMLMessage()).setDestination(endpointURL); + } + + signMessage(samlMsgCtx); + samlMsgCtx.setOutboundMessage(outboundMessage); + + postEncode(samlMsgCtx, endpointURL); + } + + /** + * Base64 and POST encodes the outbound message and writes it to the outbound transport. + * + * @param messageContext current message context + * @param endpointURL endpoint URL to which to encode message + * + * @throws MessageEncodingException thrown if there is a problem encoding the message + */ + protected void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException { + log.debug("Invoking Velocity template to create POST body"); + try { + VelocityContext context = new VelocityContext(); + + populateVelocityContext(context, messageContext, endpointURL); + + HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(outTransport); + HTTPTransportUtils.setUTF8Encoding(outTransport); + HTTPTransportUtils.setContentType(outTransport, "text/html"); + + Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); + velocityEngine.mergeTemplate(velocityTemplateId, "UTF-8", context, out); + out.flush(); + } catch (Exception e) { + log.error("Error invoking Velocity template", e); + throw new MessageEncodingException("Error creating output document", e); + } + } + + /** + * Populate the Velocity context instance which will be used to render the POST body. + * + * @param velocityContext the Velocity context instance to populate with data + * @param messageContext the SAML message context source of data + * @param endpointURL endpoint URL to which to encode message + * @throws MessageEncodingException thrown if there is a problem encoding the message + */ + protected void populateVelocityContext(VelocityContext velocityContext, SAMLMessageContext messageContext, + String endpointURL) throws MessageEncodingException { + + Encoder esapiEncoder = ESAPI.encoder(); + + String encodedEndpointURL = esapiEncoder.encodeForHTMLAttribute(endpointURL); + log.debug("Encoding action url of '{}' with encoded value '{}'", endpointURL, encodedEndpointURL); + velocityContext.put("action", encodedEndpointURL); + + log.debug("Marshalling and Base64 encoding SAML message"); + if (messageContext.getOutboundSAMLMessage().getDOM() == null) { + marshallMessage(messageContext.getOutboundSAMLMessage()); + } + try { + String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM()); + String encodedMessage = Base64.encodeBytes(messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES); + if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) { + velocityContext.put("SAMLRequest", encodedMessage); + } else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) { + velocityContext.put("SAMLResponse", encodedMessage); + } else { + throw new MessageEncodingException( + "SAML message is neither a SAML RequestAbstractType or StatusResponseType"); + } + } catch (UnsupportedEncodingException e) { + log.error("UTF-8 encoding is not supported, this VM is not Java compliant."); + throw new MessageEncodingException("Unable to encode message, UTF-8 encoding is not supported"); + } + + String relayState = messageContext.getRelayState(); + if (checkRelayState(relayState)) { + String encodedRelayState = esapiEncoder.encodeForHTMLAttribute(relayState); + log.debug("Setting RelayState parameter to: '{}', encoded as '{}'", relayState, encodedRelayState); + velocityContext.put("RelayState", encodedRelayState); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPPostSimpleSignEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPPostSimpleSignEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPPostSimpleSignEncoder.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,273 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.encoding; + +import java.io.UnsupportedEncodingException; + +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityConfiguration; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.SigningUtil; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; +import org.opensaml.xml.signature.KeyInfo; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2.0 HTTP-POST-SimpleSign binding message encoder. + * + *

+ * The spec does not preclude the SAML 2 protocol message from being signed using the XML Signature method, in addition + * to the SimpleSign method specified by this binding. Signing via XML Signature over the SAML request and response + * payload may be toggled by the signXMLProtocolMessage parameter to the constructor + * {@link HTTPPostSimpleSignEncoder#HTTPPostSimpleSignEncoder(VelocityEngine, String, boolean)}. If this constructor + * variant is not used, the flag defaults to false. + *

+ */ +public class HTTPPostSimpleSignEncoder extends HTTPPostEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPPostSimpleSignEncoder.class); + + /** + * Flag to indicate whether the SAML 2 protocol message should additionally be signed using the XML Signature, in + * addition to SimpleSign. + */ + private boolean signProtocolMessageWithXMLDSIG; + + /** + * Constructor. + * + * @param engine Velocity engine instance used to create POST body + * @param templateId ID of the template used to create POST body + */ + public HTTPPostSimpleSignEncoder(VelocityEngine engine, String templateId) { + super(engine, templateId); + signProtocolMessageWithXMLDSIG = false; + } + + /** + * Constructor. + * + * @param engine Velocity engine instance used to create POST body + * @param templateId ID of the template used to create POST body + * @param signXMLProtocolMessage if true, the protocol message will be signed according to the XML Signature + * specification, in addition to the HTTP-POST-SimpleSign binding specification + */ + public HTTPPostSimpleSignEncoder(VelocityEngine engine, String templateId, boolean signXMLProtocolMessage) { + super(engine, templateId); + signProtocolMessageWithXMLDSIG = signXMLProtocolMessage; + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI; + } + + /** {@inheritDoc} */ + protected void signMessage(SAMLMessageContext messageContext) throws MessageEncodingException { + if (signProtocolMessageWithXMLDSIG) { + super.signMessage(messageContext); + } + } + + /** {@inheritDoc} */ + protected void populateVelocityContext(VelocityContext velocityContext, SAMLMessageContext messageContext, + String endpointURL) throws MessageEncodingException { + + super.populateVelocityContext(velocityContext, messageContext, endpointURL); + + Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential(); + if (signingCredential == null) { + log.debug("No signing credential was supplied, skipping HTTP-Post simple signing"); + return; + } + + // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added + // TODO pull binding-specific keyInfoGenName from encoder setting, etc? + String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null); + velocityContext.put("SigAlg", sigAlgURI); + + String formControlData = buildFormDataToSign(velocityContext, messageContext, sigAlgURI); + velocityContext.put("Signature", generateSignature(signingCredential, sigAlgURI, formControlData)); + + KeyInfoGenerator kiGenerator = SecurityHelper.getKeyInfoGenerator(signingCredential, null, null); + if (kiGenerator != null) { + String kiBase64 = buildKeyInfo(signingCredential, kiGenerator); + if (!DatatypeHelper.isEmpty(kiBase64)) { + velocityContext.put("KeyInfo", kiBase64); + } + } + } + + /** + * Build the {@link KeyInfo} from the signing credential. + * + * @param signingCredential the credential used for signing + * @param kiGenerator the generator for the KeyInfo + * @throws MessageEncodingException thrown if there is an error generating or marshalling the KeyInfo + * @return the marshalled, serialized and base64-encoded KeyInfo, or null if none was generated + */ + protected String buildKeyInfo(Credential signingCredential, KeyInfoGenerator kiGenerator) + throws MessageEncodingException { + + try { + KeyInfo keyInfo = kiGenerator.generate(signingCredential); + if (keyInfo != null) { + Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(keyInfo); + if (marshaller == null) { + log.error("No KeyInfo marshaller available from configuration"); + throw new MessageEncodingException("No KeyInfo marshaller was configured"); + } + String kiXML = XMLHelper.nodeToString(marshaller.marshall(keyInfo)); + String kiBase64 = Base64.encodeBytes(kiXML.getBytes(), Base64.DONT_BREAK_LINES); + return kiBase64; + } else { + return null; + } + } catch (SecurityException e) { + log.error("Error generating KeyInfo from signing credential", e); + throw new MessageEncodingException("Error generating KeyInfo from signing credential", e); + } catch (MarshallingException e) { + log.error("Error marshalling KeyInfo based on signing credential", e); + throw new MessageEncodingException("Error marshalling KeyInfo based on signing credential", e); + } + } + + /** + * Build the form control data string over which the signature is computed. + * + * @param velocityContext the Velocity context which is already populated with the values for SAML message and relay + * state + * @param messageContext the SAML message context being processed + * @param sigAlgURI the signature algorithm URI + * + * @return the form control data string for signature computation + */ + protected String buildFormDataToSign(VelocityContext velocityContext, SAMLMessageContext messageContext, String sigAlgURI) { + StringBuilder builder = new StringBuilder(); + + boolean isRequest = false; + if (velocityContext.get("SAMLRequest") != null) { + isRequest = true; + } + + String msgB64; + if (isRequest) { + msgB64 = (String) velocityContext.get("SAMLRequest"); + } else { + msgB64 = (String) velocityContext.get("SAMLResponse"); + } + + String msg = null; + try { + msg = new String(Base64.decode(msgB64), "UTF-8"); + } catch (UnsupportedEncodingException e) { + // All JVM's required to support UTF-8 + } + + if (isRequest) { + builder.append("SAMLRequest=" + msg); + } else { + builder.append("SAMLResponse=" + msg); + } + + if (messageContext.getRelayState() != null) { + builder.append("&RelayState=" + messageContext.getRelayState()); + } + + builder.append("&SigAlg=" + sigAlgURI); + + return builder.toString(); + } + + /** + * Gets the signature algorithm URI to use with the given signing credential. + * + * @param credential the credential that will be used to sign the message + * @param config the SecurityConfiguration to use (may be null) + * + * @return signature algorithm to use with the given signing credential + * + * @throws MessageEncodingException thrown if the algorithm URI could not be derived from the supplied credential + */ + protected String getSignatureAlgorithmURI(Credential credential, SecurityConfiguration config) + throws MessageEncodingException { + + SecurityConfiguration secConfig; + if (config != null) { + secConfig = config; + } else { + secConfig = Configuration.getGlobalSecurityConfiguration(); + } + + String signAlgo = secConfig.getSignatureAlgorithmURI(credential); + + if (signAlgo == null) { + throw new MessageEncodingException("The signing credential's algorithm URI could not be derived"); + } + + return signAlgo; + } + + /** + * Generates the signature over the string of concatenated form control data as indicated by the SimpleSign spec. + * + * @param signingCredential credential that will be used to sign + * @param algorithmURI algorithm URI of the signing credential + * @param formData form control data to be signed + * + * @return base64 encoded signature of form control data + * + * @throws MessageEncodingException there is an error computing the signature + */ + protected String generateSignature(Credential signingCredential, String algorithmURI, String formData) + throws MessageEncodingException { + + log.debug(String.format( + "Generating signature with key type '%s', algorithm URI '%s' over form control string '%s'", + SecurityHelper.extractSigningKey(signingCredential).getAlgorithm(), algorithmURI, formData)); + + String b64Signature = null; + try { + byte[] rawSignature = SigningUtil.signWithURI(signingCredential, algorithmURI, formData.getBytes("UTF-8")); + b64Signature = Base64.encodeBytes(rawSignature, Base64.DONT_BREAK_LINES); + log.debug("Generated digital signature value (base64-encoded) {}", b64Signature); + } catch (SecurityException e) { + log.error("Error during URL signing process", e); + throw new MessageEncodingException("Unable to sign form control string", e); + } catch (UnsupportedEncodingException e) { + // UTF-8 encoding is required to be supported by all JVMs + } + + return b64Signature; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPRedirectDeflateEncoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPRedirectDeflateEncoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPRedirectDeflateEncoder.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,261 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.encoding; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.zip.Deflater; +import java.util.zip.DeflaterOutputStream; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.util.URLBuilder; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.security.SecurityConfiguration; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.SigningUtil; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.Pair; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * SAML 2.0 HTTP Redirect encoder using the DEFLATE encoding method. + * + * This encoder only supports DEFLATE compression and DSA-SHA1 and RSA-SHA1 signatures. + */ +public class HTTPRedirectDeflateEncoder extends BaseSAML2MessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPRedirectDeflateEncoder.class); + + /** Constructor. */ + public HTTPRedirectDeflateEncoder() { + super(); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_REDIRECT_BINDING_URI; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + return false; + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + String endpointURL = getEndpointURL(samlMsgCtx).buildURL(); + + setResponseDestination(samlMsgCtx.getOutboundSAMLMessage(), endpointURL); + + removeSignature(samlMsgCtx); + + String encodedMessage = deflateAndBase64Encode(samlMsgCtx.getOutboundSAMLMessage()); + + String redirectURL = buildRedirectURL(samlMsgCtx, endpointURL, encodedMessage); + + HTTPOutTransport out = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(out); + HTTPTransportUtils.setUTF8Encoding(out); + + out.sendRedirect(redirectURL); + } + + /** + * Removes the signature from the protocol message. + * + * @param messageContext current message context + */ + protected void removeSignature(SAMLMessageContext messageContext) { + SignableSAMLObject message = (SignableSAMLObject) messageContext.getOutboundSAMLMessage(); + if (message.isSigned()) { + log.debug("Removing SAML protocol message signature"); + message.setSignature(null); + } + } + + /** + * DEFLATE (RFC1951) compresses the given SAML message. + * + * @param message SAML message + * + * @return DEFLATE compressed message + * + * @throws MessageEncodingException thrown if there is a problem compressing the message + */ + protected String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException { + log.debug("Deflating and Base64 encoding SAML message"); + try { + String messageStr = XMLHelper.nodeToString(marshallMessage(message)); + + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + Deflater deflater = new Deflater(Deflater.DEFLATED, true); + DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater); + deflaterStream.write(messageStr.getBytes("UTF-8")); + deflaterStream.finish(); + + return Base64.encodeBytes(bytesOut.toByteArray(), Base64.DONT_BREAK_LINES); + } catch (IOException e) { + throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e); + } + } + + /** + * Builds the URL to redirect the client to. + * + * @param messagesContext current message context + * @param endpointURL endpoint URL to send encoded message to + * @param message Deflated and Base64 encoded message + * + * @return URL to redirect client to + * + * @throws MessageEncodingException thrown if the SAML message is neither a RequestAbstractType or Response + */ + protected String buildRedirectURL(SAMLMessageContext messagesContext, String endpointURL, String message) + throws MessageEncodingException { + log.debug("Building URL to redirect client to"); + URLBuilder urlBuilder = new URLBuilder(endpointURL); + + List> queryParams = urlBuilder.getQueryParams(); + queryParams.clear(); + + if (messagesContext.getOutboundSAMLMessage() instanceof RequestAbstractType) { + queryParams.add(new Pair("SAMLRequest", message)); + } else if (messagesContext.getOutboundSAMLMessage() instanceof StatusResponseType) { + queryParams.add(new Pair("SAMLResponse", message)); + } else { + throw new MessageEncodingException( + "SAML message is neither a SAML RequestAbstractType or StatusResponseType"); + } + + String relayState = messagesContext.getRelayState(); + if (checkRelayState(relayState)) { + queryParams.add(new Pair("RelayState", relayState)); + } + + Credential signingCredential = messagesContext.getOuboundSAMLMessageSigningCredential(); + if (signingCredential != null) { + // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added + String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null); + Pair sigAlg = new Pair("SigAlg", sigAlgURI); + queryParams.add(sigAlg); + String sigMaterial = urlBuilder.buildQueryString(); + + queryParams.add(new Pair("Signature", generateSignature(signingCredential, sigAlgURI, + sigMaterial))); + } + + return urlBuilder.buildURL(); + } + + /** + * Gets the signature algorithm URI to use with the given signing credential. + * + * @param credential the credential that will be used to sign the message + * @param config the SecurityConfiguration to use (may be null) + * + * @return signature algorithm to use with the given signing credential + * + * @throws MessageEncodingException thrown if the algorithm URI could not be derived from the supplied credential + */ + protected String getSignatureAlgorithmURI(Credential credential, SecurityConfiguration config) + throws MessageEncodingException { + + SecurityConfiguration secConfig; + if (config != null) { + secConfig = config; + } else { + secConfig = Configuration.getGlobalSecurityConfiguration(); + } + + String signAlgo = secConfig.getSignatureAlgorithmURI(credential); + + if (signAlgo == null) { + throw new MessageEncodingException("The signing credential's algorithm URI could not be derived"); + } + + return signAlgo; + } + + /** + * Generates the signature over the query string. + * + * @param signingCredential credential that will be used to sign query string + * @param algorithmURI algorithm URI of the signing credential + * @param queryString query string to be signed + * + * @return base64 encoded signature of query string + * + * @throws MessageEncodingException there is an error computing the signature + */ + protected String generateSignature(Credential signingCredential, String algorithmURI, String queryString) + throws MessageEncodingException { + + log.debug(String.format("Generating signature with key type '%s', algorithm URI '%s' over query string '%s'", + SecurityHelper.extractSigningKey(signingCredential).getAlgorithm(), algorithmURI, queryString)); + + String b64Signature = null; + try { + byte[] rawSignature = SigningUtil.signWithURI(signingCredential, algorithmURI, queryString + .getBytes("UTF-8")); + b64Signature = Base64.encodeBytes(rawSignature, Base64.DONT_BREAK_LINES); + log.debug("Generated digital signature value (base64-encoded) {}", b64Signature); + } catch (SecurityException e) { + log.error("Error during URL signing process", e); + throw new MessageEncodingException("Unable to sign URL query string", e); + } catch (UnsupportedEncodingException e) { + // UTF-8 encoding is required to be supported by all JVMs + } + + return b64Signature; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPSOAP11Encoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPSOAP11Encoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HTTPSOAP11Encoder.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,151 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.encoding; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; + +import org.opensaml.Configuration; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.xml.XMLObjectBuilderFactory; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * SAML 2.0 SOAP 1.1 over HTTP binding encoder. + */ +public class HTTPSOAP11Encoder extends BaseSAML2MessageEncoder { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPSOAP11Encoder.class); + + /** Constructor. */ + public HTTPSOAP11Encoder() { + super(); + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_SOAP11_BINDING_URI; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + if (messageContext.getOutboundMessageTransport().isConfidential()) { + return true; + } + + return false; + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + if (messageContext.getOutboundMessageTransport().isIntegrityProtected()) { + return true; + } + + return false; + } + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject samlMessage = samlMsgCtx.getOutboundSAMLMessage(); + if (samlMessage == null) { + throw new MessageEncodingException("No outbound SAML message contained in message context"); + } + + signMessage(samlMsgCtx); + Envelope envelope = buildSOAPMessage(samlMessage); + samlMsgCtx.setOutboundMessage(envelope); + + Element envelopeElem = marshallMessage(envelope); + try { + HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(outTransport); + HTTPTransportUtils.setUTF8Encoding(outTransport); + HTTPTransportUtils.setContentType(outTransport, "text/xml"); + outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security"); + Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); + XMLHelper.writeNode(envelopeElem, out); + out.flush(); + } catch (UnsupportedEncodingException e) { + log.error("JVM does not support required UTF-8 encoding"); + throw new MessageEncodingException("JVM does not support required UTF-8 encoding"); + } catch (IOException e) { + log.error("Unable to write message content to outbound stream", e); + throw new MessageEncodingException("Unable to write message content to outbound stream", e); + } + } + + /** + * Builds the SOAP message to be encoded. + * + * @param samlMessage body of the SOAP message + * + * @return the SOAP message + */ + @SuppressWarnings("unchecked") + protected Envelope buildSOAPMessage(SAMLObject samlMessage) { + if (log.isDebugEnabled()) { + log.debug("Building SOAP message"); + } + XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); + + SOAPObjectBuilder envBuilder = (SOAPObjectBuilder) builderFactory + .getBuilder(Envelope.DEFAULT_ELEMENT_NAME); + Envelope envelope = envBuilder.buildObject(); + + if (log.isDebugEnabled()) { + log.debug("Adding SAML message to the SOAP message's body"); + } + SOAPObjectBuilder bodyBuilder = (SOAPObjectBuilder) builderFactory + .getBuilder(Body.DEFAULT_ELEMENT_NAME); + Body body = bodyBuilder.buildObject(); + body.getUnknownXMLObjects().add(samlMessage); + envelope.setBody(body); + + return envelope; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HandlerChainAwareHTTPSOAP11Encoder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HandlerChainAwareHTTPSOAP11Encoder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/HandlerChainAwareHTTPSOAP11Encoder.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,261 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.encoding; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.util.List; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.message.handler.HandlerChain; +import org.opensaml.ws.message.handler.HandlerChainAware; +import org.opensaml.ws.message.handler.HandlerChainResolver; +import org.opensaml.ws.message.handler.HandlerException; +import org.opensaml.ws.soap.common.SOAPObjectBuilder; +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.ws.soap.soap11.Header; +import org.opensaml.ws.soap.soap11.encoder.SOAP11Encoder; +import org.opensaml.ws.transport.OutTransport; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.ws.wsaddressing.Action; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.XMLObjectBuilderFactory; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * + */ +public class HandlerChainAwareHTTPSOAP11Encoder extends BaseSAML2MessageEncoder implements HandlerChainAware { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HandlerChainAwareHTTPSOAP11Encoder.class); + + /** SOAP Envelope builder. */ + private SOAPObjectBuilder envBuilder; + + /** SOAP Body builder. */ + private SOAPObjectBuilder bodyBuilder; + + /** Overrides binding confidentiality. */ + private boolean notConfidential = false; + + /** Constructor. */ + public HandlerChainAwareHTTPSOAP11Encoder() { + super(); + XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); + envBuilder = (SOAPObjectBuilder) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME); + bodyBuilder = (SOAPObjectBuilder) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME); + } + + /** + * Returns confidentiality override flag. + * @return true iff the encoder cannot provide confidentiality + */ + public boolean isNotConfidential() { + return notConfidential; + } + + /** + * Sets confidentiality override flag. + * @param flag override flag + */ + public void setNotConfidential(boolean flag) { + notConfidential = flag; + } + + /** {@inheritDoc} */ + public String getBindingURI() { + return SAMLConstants.SAML2_SOAP11_BINDING_URI; + } + + /** {@inheritDoc} */ + public boolean providesMessageConfidentiality(MessageContext messageContext) throws MessageEncodingException { + if (notConfidential) { + return false; + } + return messageContext.getOutboundMessageTransport().isConfidential(); + } + + /** {@inheritDoc} */ + public boolean providesMessageIntegrity(MessageContext messageContext) throws MessageEncodingException { + return messageContext.getOutboundMessageTransport().isIntegrityProtected(); + } + + // TODO: The rest of the methods here are copied from BaseHandlerChainAwareMessageDecoder and + // the SOAP subclasses on that "branch", and should drop out once the SAML encoders are aligned + // to that base class. + + /** {@inheritDoc} */ + protected void doEncode(MessageContext messageContext) throws MessageEncodingException { + + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) { + log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + throw new MessageEncodingException( + "Invalid outbound message transport type, this encoder only support HTTPOutTransport"); + } + + prepareMessageContext(messageContext); + + processOutboundHandlerChain(messageContext); + + encodeToTransport(messageContext); + } + + /** + * Perform final binding-specific processing of message context and prepare it for encoding + * to the transport. + * + *

+ * This should include constructing and populating all binding-specific structure and data that needs to be + * reflected by the message context's properties. + *

+ * + *

+ * This method is called prior to {@link #processOutboundHandlerChain(MessageContext)}. + *

+ * + * @param messageContext the message context to process + * @throws MessageEncodingException thrown if there is a problem preparing the message context + * for encoding + */ + protected void prepareMessageContext(MessageContext messageContext) throws MessageEncodingException { + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject samlMessage = samlMsgCtx.getOutboundSAMLMessage(); + if (samlMessage == null) { + throw new MessageEncodingException("No outbound SAML message contained in message context"); + } + + signMessage(samlMsgCtx); + + log.debug("Building SOAP envelope"); + + Envelope envelope = envBuilder.buildObject(); + Body body = bodyBuilder.buildObject(); + envelope.setBody(body); + body.getUnknownXMLObjects().add(samlMessage); + + messageContext.setOutboundMessage(envelope); + } + + /** + * Encode the message context to the transport. + * + * @param messageContext the message context to process + * @throws MessageEncodingException thrown if there is a problem encoding the message context + * to the transport + */ + protected void encodeToTransport(MessageContext messageContext) throws MessageEncodingException { + Element envelopeElem = marshallMessage(messageContext.getOutboundMessage()); + + preprocessTransport(messageContext); + + try { + OutTransport outTransport = messageContext.getOutboundMessageTransport(); + Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); + XMLHelper.writeNode(envelopeElem, out); + out.flush(); + } catch (UnsupportedEncodingException e) { + log.error("JVM does not support required UTF-8 encoding"); + throw new MessageEncodingException("JVM does not support required UTF-8 encoding"); + } catch (IOException e) { + log.error("Unable to write message content to outbound stream", e); + throw new MessageEncodingException("Unable to write message content to outbound stream", e); + } + } + + /** + *

+ * This implementation performs the following actions on the context's {@link HTTPOutTransport}: + *

    + *
  1. Adds the HTTP header: "Cache-control: no-cache, no-store"
  2. + *
  3. Adds the HTTP header: "Pragma: no-cache"
  4. + *
  5. Sets the character encoding to: "UTF-8"
  6. + *
  7. Sets the content type to: "text/xml"
  8. + *
  9. Sets the SOAPAction HTTP header
  10. + *
+ *

+ * + * @param messageContext the current message context being processed + * + * @throws MessageEncodingException thrown if there is a problem preprocessing the transport + */ + protected void preprocessTransport(MessageContext messageContext) throws MessageEncodingException { + HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(outTransport); + HTTPTransportUtils.setUTF8Encoding(outTransport); + HTTPTransportUtils.setContentType(outTransport, "text/xml"); + outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security"); + } + + /** + * Process the outbound {@link HandlerChain} for the message context, if any. + * + * @param messageContext the message context to process + * @throws MessageEncodingException thrown if a handler indicates a problem handling the message + */ + protected void processOutboundHandlerChain(MessageContext messageContext) throws MessageEncodingException { + HandlerChainResolver outboundHandlerChainResolver = messageContext.getOutboundHandlerChainResolver(); + if (outboundHandlerChainResolver != null) { + log.debug("Invoking outbound handler chain on message context"); + try { + for (HandlerChain outboundHandlerChain : outboundHandlerChainResolver.resolve(messageContext)) { + if (outboundHandlerChain != null) { + invokeHandlerChain(outboundHandlerChain, messageContext); + } + } + } catch (HandlerException e) { + log.error("Encountered HandlerException when encoding message: {}", e.getMessage()); + throw new MessageEncodingException("Handler exception while encoding message", e); + } + } + } + + /** + * Invoke a handler chain on the specified message context. + * + * @param handlerChain the handle chain to invoke + * @param messageContext the message context to process + * + * @throws HandlerException if handler chain encountered a problem handling the message context + */ + protected void invokeHandlerChain(HandlerChain handlerChain, MessageContext messageContext) + throws HandlerException { + if (handlerChain != null && messageContext != null) { + handlerChain.invoke(messageContext); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/encoding/package.html 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,7 @@ + + +Classes used to encode SAML 2 messages. An encoder takes a SAML message +and transforms it into a representation that may be transported over a +particular wire protocol (e.g. HTTP). + + Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2AuthnRequestsSignedRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2AuthnRequestsSignedRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2AuthnRequestsSignedRule.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,123 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.security; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.ws.message.MessageContext; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.security.SecurityPolicyRule; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Security policy rule implementation that enforces the AuthnRequestsSigned flag of + * SAML 2 metadata element @{link {@link SPSSODescriptor}. + */ +public class SAML2AuthnRequestsSignedRule implements SecurityPolicyRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(SAML2AuthnRequestsSignedRule.class); + + /** {@inheritDoc} */ + public void evaluate(MessageContext messageContext) throws SecurityPolicyException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext"); + return; + } + SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + SAMLObject samlMessage = samlMsgCtx.getInboundSAMLMessage(); + if (! (samlMessage instanceof AuthnRequest) ) { + log.debug("Inbound message is not an instance of AuthnRequest, skipping evaluation..."); + return; + } + + String messageIssuer = samlMsgCtx.getInboundMessageIssuer(); + if (DatatypeHelper.isEmpty(messageIssuer)) { + log.warn("Inbound message issuer was empty, unable to evaluate rule"); + return; + } + + MetadataProvider metadataProvider = samlMsgCtx.getMetadataProvider(); + if (metadataProvider == null) { + log.warn("Message context did not contain a metadata provider, unable to evaluate rule"); + return; + } + + SPSSODescriptor spssoRole; + try { + spssoRole = (SPSSODescriptor) metadataProvider + .getRole(messageIssuer, SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS); + } catch (MetadataProviderException e) { + log.warn("Error resolving SPSSODescriptor metadata for entityID '{}': {}", messageIssuer, e.getMessage()); + throw new SecurityPolicyException("Error resolving metadata for entity ID", e); + } + + if (spssoRole == null) { + log.warn("SPSSODescriptor role metadata for entityID '{}' could not be resolved", messageIssuer); + return; + } + + if (spssoRole.isAuthnRequestsSigned() == Boolean.TRUE) { + if (! isMessageSigned(samlMsgCtx)) { + log.error("SPSSODescriptor for entity ID '{}' indicates AuthnRequests must be signed, " + + "but inbound message was not signed", messageIssuer); + throw new SecurityPolicyException("Inbound AuthnRequest was required to be signed but was not"); + } + } else { + log.debug("SPSSODescriptor for entity ID '{}' does not require AuthnRequests to be signed", messageIssuer); + } + + } + + /** + * Determine whether the inbound message is signed. + * + * @param messageContext the message context being evaluated + * @return true if the inbound message is signed, otherwise false + */ + protected boolean isMessageSigned(SAMLMessageContext messageContext) { + // TODO this really should be determined by the decoders and supplied to the rule + // in some fashion, to handle binding-specific signature mechanisms. See JIRA issue JOWS-4. + // + // For now evaluate here inline for XML Signature and HTTP-Redirect and HTTP-Post-SimpleSign. + + SAMLObject samlMessage = messageContext.getInboundSAMLMessage(); + if (samlMessage instanceof SignableSAMLObject) { + SignableSAMLObject signableMessage = (SignableSAMLObject) samlMessage; + if (signableMessage.isSigned()) { + return true; + } + } + + // This handles HTTP-Redirect and HTTP-POST-SimpleSign bindings. + HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport(); + String sigParam = inTransport.getParameterValue("Signature"); + return !DatatypeHelper.isEmpty(sigParam); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2HTTPPostSimpleSignRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2HTTPPostSimpleSignRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2HTTPPostSimpleSignRule.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,172 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.security; + +import java.io.ByteArrayInputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.security.BaseSAMLSimpleSignatureSecurityPolicyRule; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.parse.XMLParserException; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.keyinfo.KeyInfoCredentialResolver; +import org.opensaml.xml.security.keyinfo.KeyInfoCriteria; +import org.opensaml.xml.signature.KeyInfo; +import org.opensaml.xml.signature.SignatureTrustEngine; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * Security policy which evaluates simple "blob" signatures according to the SAML 2 HTTP-POST-SimpleSign binding. + */ +public class SAML2HTTPPostSimpleSignRule extends BaseSAMLSimpleSignatureSecurityPolicyRule { + + /** Logger. */ + private Logger log = LoggerFactory.getLogger(SAML2HTTPPostSimpleSignRule.class); + + /** Parser pool to use to process KeyInfo request parameter. */ + private ParserPool parser; + + /** KeyInfo resolver to use to process KeyInfo request parameter. */ + private KeyInfoCredentialResolver keyInfoResolver; + + /** + * Constructor. + * + * @param engine the trust engine to use + * @param parserPool the parser pool used to parse the KeyInfo request parameter + * @param keyInfoCredResolver the KeyInfo credential resovler to use to extract credentials from the KeyInfo request + * parameter + */ + public SAML2HTTPPostSimpleSignRule(SignatureTrustEngine engine, ParserPool parserPool, + KeyInfoCredentialResolver keyInfoCredResolver) { + super(engine); + parser = parserPool; + keyInfoResolver = keyInfoCredResolver; + } + + /** {@inheritDoc} */ + protected boolean ruleHandles(HttpServletRequest request, SAMLMessageContext samlMsgCtx) { + return "POST".equals(request.getMethod()); + } + + /** {@inheritDoc} */ + protected byte[] getSignedContent(HttpServletRequest request) throws SecurityPolicyException { + StringBuilder builder = new StringBuilder(); + String samlMsg; + try { + if (request.getParameter("SAMLRequest") != null) { + samlMsg = new String(Base64.decode(request.getParameter("SAMLRequest")), "UTF-8"); + builder.append("SAMLRequest=" + samlMsg); + } else if (request.getParameter("SAMLResponse") != null) { + samlMsg = new String(Base64.decode(request.getParameter("SAMLResponse")), "UTF-8"); + builder.append("SAMLResponse=" + samlMsg); + } else { + log.warn("Could not extract either a SAMLRequest or a SAMLResponse from the form control data"); + throw new SecurityPolicyException("Extract of SAMLRequest or SAMLResponse from form control data"); + } + } catch (UnsupportedEncodingException e) { + // All JVM's required to support UTF-8 + } + + if (request.getParameter("RelayState") != null) { + builder.append("&RelayState=" + request.getParameter("RelayState")); + } + + builder.append("&SigAlg=" + request.getParameter("SigAlg")); + + String constructed = builder.toString(); + if (DatatypeHelper.isEmpty(constructed)) { + log.warn("Could not construct signed content string from form control data"); + return null; + } + log.debug("Constructed signed content string for HTTP-Post-SimpleSign {}", constructed); + + try { + return constructed.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + // All JVM's required to support UTF-8 + } + return null; + } + + /** {@inheritDoc} */ + protected List getRequestCredentials(HttpServletRequest request, SAMLMessageContext samlContext) + throws SecurityPolicyException { + + String kiBase64 = request.getParameter("KeyInfo"); + if (DatatypeHelper.isEmpty(kiBase64)) { + log.debug("Form control data did not contain a KeyInfo"); + return null; + } else { + log.debug("Found a KeyInfo in form control data, extracting validation credentials"); + } + + Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory() + .getUnmarshaller(KeyInfo.DEFAULT_ELEMENT_NAME); + if (unmarshaller == null) { + throw new SecurityPolicyException("Could not obtain a KeyInfo unmarshaller"); + } + + ByteArrayInputStream is = new ByteArrayInputStream(Base64.decode(kiBase64)); + KeyInfo keyInfo = null; + try { + Document doc = parser.parse(is); + keyInfo = (KeyInfo) unmarshaller.unmarshall(doc.getDocumentElement()); + } catch (XMLParserException e) { + log.warn("Error parsing KeyInfo data", e); + throw new SecurityPolicyException("Error parsing KeyInfo data", e); + } catch (UnmarshallingException e) { + log.warn("Error unmarshalling KeyInfo data", e); + throw new SecurityPolicyException("Error unmarshalling KeyInfo data", e); + } + + if (keyInfo == null) { + log.warn("Could not successfully extract KeyInfo object from the form control data"); + return null; + } + + List credentials = new ArrayList(); + CriteriaSet criteriaSet = new CriteriaSet(new KeyInfoCriteria(keyInfo)); + try { + for (Credential cred : keyInfoResolver.resolve(criteriaSet)) { + credentials.add(cred); + } + } catch (SecurityException e) { + log.warn("Error resolving credentials from KeyInfo", e); + throw new SecurityPolicyException("Error resolving credentials from KeyInfo", e); + } + + return credentials; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2HTTPRedirectDeflateSignatureRule.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2HTTPRedirectDeflateSignatureRule.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/SAML2HTTPRedirectDeflateSignatureRule.java 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,130 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.binding.security; + +import java.io.UnsupportedEncodingException; + +import javax.servlet.http.HttpServletRequest; + +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.common.binding.security.BaseSAMLSimpleSignatureSecurityPolicyRule; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.opensaml.xml.signature.SignatureTrustEngine; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Security policy which evaluates simple "blob" signatures according to the SAML 2 HTTP-Redirect DEFLATE binding. + */ +public class SAML2HTTPRedirectDeflateSignatureRule extends BaseSAMLSimpleSignatureSecurityPolicyRule { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(SAML2HTTPRedirectDeflateSignatureRule.class); + + /** + * Constructor. + * + * @param engine the trust engine to use + */ + public SAML2HTTPRedirectDeflateSignatureRule(SignatureTrustEngine engine) { + super(engine); + } + + /** {@inheritDoc} */ + protected boolean ruleHandles(HttpServletRequest request, SAMLMessageContext samlMsgCtx) + throws SecurityPolicyException { + return "GET".equals(request.getMethod()); + } + + /** {@inheritDoc} */ + protected byte[] getSignedContent(HttpServletRequest request) throws SecurityPolicyException { + // We need the raw non-URL-decoded query string param values for HTTP-Redirect DEFLATE simple signature + // validation. + // We have to construct a string containing the signature input by accessing the + // request directly. We can't use the decoded parameters because we need the raw + // data and URL-encoding isn't canonical. + String queryString = request.getQueryString(); + log.debug("Constructing signed content string from URL query string {}", queryString); + + String constructed = buildSignedContentString(queryString); + if (DatatypeHelper.isEmpty(constructed)) { + log.warn("Could not extract signed content string from query string"); + return null; + } + log.debug("Constructed signed content string for HTTP-Redirect DEFLATE {}", constructed); + + try { + return constructed.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + // JVM is required to support UTF-8 + } + return null; + } + + /** + * Extract the raw request parameters and build a string representation of the content that was signed. + * + * @param queryString the raw HTTP query string from the request + * @return a string representation of the signed content + * @throws SecurityPolicyException thrown if there is an error during request processing + */ + private String buildSignedContentString(String queryString) throws SecurityPolicyException { + StringBuilder builder = new StringBuilder(); + + // One of these two is mandatory + if (!appendParameter(builder, queryString, "SAMLRequest")) { + if (!appendParameter(builder, queryString, "SAMLResponse")) { + log.warn("Could not extract either a SAMLRequest or a SAMLResponse from the query string"); + throw new SecurityPolicyException("Extract of SAMLRequest or SAMLResponse from query string failed"); + } + } + // This is optional + appendParameter(builder, queryString, "RelayState"); + // This is mandatory, but has already been checked in superclass + appendParameter(builder, queryString, "SigAlg"); + + return builder.toString(); + } + + /** + * Find the raw query string parameter indicated and append it to the string builder. + * + * The appended value will be in the form 'paramName=paramValue' (minus the quotes). + * + * @param builder string builder to which to append the parameter + * @param queryString the URL query string containing parameters + * @param paramName the name of the parameter to append + * @return true if parameter was found, false otherwise + */ + private boolean appendParameter(StringBuilder builder, String queryString, String paramName) { + String rawParam = HTTPTransportUtils.getRawQueryStringParameter(queryString, paramName); + if (rawParam == null) { + return false; + } + + if (builder.length() > 0) { + builder.append('&'); + } + + builder.append(rawParam); + + return true; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/binding/security/package.html 17 Aug 2012 15:03:42 -0000 1.1 @@ -0,0 +1,6 @@ + + +Classes responsible for performing transport-related and basic message +validation of decoded SAML 2 messages. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/CacheableSAMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/CacheableSAMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/CacheableSAMLObject.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * A functional interface for SAMLElements that provide cache duration information. + * + */ +public interface CacheableSAMLObject extends SAMLObject{ + + /** "cacheDuration" attribute name */ + public final static String CACHE_DURATION_ATTRIB_NAME = "cacheDuration"; + + /** "cacheDuration" attribute's QName */ + public final static QName CACHE_DURATION_ATTRIB_QNAME = new QName(SAMLConstants.SAML20MD_NS, CACHE_DURATION_ATTRIB_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the maximum time, in milliseconds, that this descriptor should be cached. + * + * @return the maximum time that this descriptor should be cached + */ + public Long getCacheDuration(); + + /** + * Sets the maximum time, in milliseconds, that this descriptor should be cached. + * + * @param duration the maximum time that this descriptor should be cached + */ + public void setCacheDuration(Long duration); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/Extensions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/Extensions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/Extensions.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common; + +import org.opensaml.common.SAMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SAML 2.0 Extensions + */ +public interface Extensions extends SAMLObject, ElementExtensibleXMLObject { + + /** Local name, no namespace */ + public final static String LOCAL_NAME = "Extensions"; +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/SAML2Helper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/SAML2Helper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/SAML2Helper.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,123 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common; + +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.xml.XMLObject; + +public class SAML2Helper { + + /** + * Checks to see if the given XMLObject is still valid. An XMLObject is valid if, and only if, itself and every + * ancestral {@link TimeBoundSAMLObject} is valid. + * + * @param xmlObject the XML object tree to check + * + * @return true of the tree is valid, false if not + */ + public static boolean isValid(XMLObject xmlObject) { + if (xmlObject instanceof TimeBoundSAMLObject) { + TimeBoundSAMLObject timeBoundObject = (TimeBoundSAMLObject) xmlObject; + if (!timeBoundObject.isValid()) { + return false; + } + } + + XMLObject parent = xmlObject.getParent(); + if (parent != null) { + return isValid(parent); + } + + return true; + } + + /** + * Gets the earliest expiration instant for a XMLObject. This method traverses the tree of SAMLObject rooted at the + * given object and calculates the earliest expiration as the earliest of the following two items: + *
    + *
  • the earliest validUntil time on a {@link TimeBoundSAMLObject}
  • + *
  • the shortest duration on a {@link CacheableSAMLObject} added to the current time
  • + *
+ * + * @param xmlObject the XML object tree to get the earliest expiration time from + * + * @return the earliest expiration time + */ + public static DateTime getEarliestExpiration(XMLObject xmlObject) { + DateTime now = new DateTime(); + return getEarliestExpiration(xmlObject, null, now); + } + + /** + * Gets the earliest expiration instant within a metadata tree. + * + * @param xmlObject the metadata + * @param earliestExpiration the earliest expiration instant + * @param now when this method was called + * + * @return the earliest expiration instant within a metadata tree + */ + public static DateTime getEarliestExpiration(XMLObject xmlObject, DateTime earliestExpiration, DateTime now) { + + // expiration time for a specific element + DateTime elementExpirationTime; + + // Test duration based times + if (xmlObject instanceof CacheableSAMLObject) { + CacheableSAMLObject cacheInfo = (CacheableSAMLObject) xmlObject; + + if (cacheInfo.getCacheDuration() != null && cacheInfo.getCacheDuration().longValue() > 0) { + elementExpirationTime = now.plus(cacheInfo.getCacheDuration().longValue()); + if (earliestExpiration == null) { + earliestExpiration = elementExpirationTime; + } else { + if (elementExpirationTime != null && elementExpirationTime.isBefore(earliestExpiration)) { + earliestExpiration = elementExpirationTime; + } + } + } + } + + // Test instant based times + if (xmlObject instanceof TimeBoundSAMLObject) { + TimeBoundSAMLObject timeBoundObject = (TimeBoundSAMLObject) xmlObject; + elementExpirationTime = timeBoundObject.getValidUntil(); + if (earliestExpiration == null) { + earliestExpiration = elementExpirationTime; + } else { + if (elementExpirationTime != null && elementExpirationTime.isBefore(earliestExpiration)) { + earliestExpiration = elementExpirationTime; + } + } + } + + // Inspect children + List children = xmlObject.getOrderedChildren(); + if (children != null) { + for (XMLObject child : xmlObject.getOrderedChildren()) { + if (child != null) { + earliestExpiration = getEarliestExpiration(child, earliestExpiration, now); + } + } + } + + return earliestExpiration; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/TimeBoundSAMLObject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/TimeBoundSAMLObject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/TimeBoundSAMLObject.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * A functional interface for SAMLElements that are bounded with a + * "validUntil" attribute. + */ +public interface TimeBoundSAMLObject extends SAMLObject{ + + /** "validUntil" attribute's local name */ + public final static String VALID_UNTIL_ATTRIB_NAME = "validUntil"; + + /** "validUntil" attribute's QName */ + public final static QName VALID_UNTIL_ATTRIB_QNAME = new QName(SAMLConstants.SAML20MD_NS, VALID_UNTIL_ATTRIB_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Checks to see if the current time is past the validUntil time. + * + * @return true of this descriptor is still valid otherwise false + */ + public boolean isValid(); + + /** + * Gets the date until which this descriptor is valid. + * + * @return the date until which this descriptor is valid + */ + public DateTime getValidUntil(); + + /** + * Sets the date until which this descriptor is valid. + * + * @param validUntil the date until which this descriptor is valid + */ + public void setValidUntil(DateTime validUntil); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/package.html 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,14 @@ + + +Interfaces for elements and attribtues used in multiple SAML 2.0 specification. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsBuilder.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; + +/** + * Builder of {@link org.opensaml.saml2.common.impl.ExtensionsImpl} objects. + */ +public class ExtensionsBuilder extends AbstractSAMLObjectBuilder { + + /** + * {@inheritDoc} + */ + public Extensions buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, Extensions.LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** + * {@inheritDoc} + */ + public Extensions buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ExtensionsImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsImpl.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Implementation of {@link org.opensaml.saml2.common.Extensions} + */ +public class ExtensionsImpl extends AbstractSAMLObject implements Extensions { + + /** "any" children */ + private final IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected ExtensionsImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** + * {@inheritDoc} + */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return Collections.unmodifiableList(unknownChildren); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsMarshaller.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common.impl; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectMarshaller; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.common.Extensions} objects. + */ +public class ExtensionsMarshaller extends AbstractXMLObjectMarshaller { + + /** + * Constructor + */ + public ExtensionsMarshaller() { + super(); + } + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + // no attributes + } + + /** + * {@inheritDoc} + */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + // no content + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/ExtensionsUnmarshaller.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.common.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; + +public class ExtensionsUnmarshaller extends AbstractXMLObjectUnmarshaller { + + /** Logger. */ + private final Logger log = LoggerFactory.getLogger(AbstractSAMLObjectUnmarshaller.class); + + /** Constructor. */ + public ExtensionsUnmarshaller() { + super(); + } + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + Extensions extensions = (Extensions) parentXMLObject; + + extensions.getUnknownXMLObjects().add(childXMLObject); + } + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + log.debug("Ignorning unknown attribute {}", attribute.getLocalName()); + } + + /** + * {@inheritDoc} + */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + log.debug("Ignoring element content {}", elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/common/impl/package.html 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,14 @@ + + +Implementations of elements and attribtues used in multiple SAML 2.0 specification. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Action.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Action.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Action.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,128 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Action. + */ +public interface Action extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Action"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Name of the Namespace attribute. */ + public static final String NAMEPSACE_ATTRIB_NAME = "Namespace"; + + /** Read/Write/Execute/Delete/Control action namespace. */ + public static final String RWEDC_NS_URI = "urn:oasis:names:tc:SAML:1.0:action:rwedc"; + + /** Read/Write/Execute/Delete/Control negation action namespace. */ + public static final String RWEDC_NEGATION_NS_URI = "urn:oasis:names:tc:SAML:1.0:action:rwedc-negation"; + + /** Get/Head/Put/Post action namespace. */ + public static final String GHPP_NS_URI = "urn:oasis:names:tc:SAML:1.0:action:ghpp"; + + /** UNIX file permission action namespace. */ + public static final String UNIX_NS_URI = "urn:oasis:names:tc:SAML:1.0:action:unix"; + + /** Read action. */ + public static final String READ_ACTION = "Read"; + + /** Write action. */ + public static final String WRITE_ACTION = "Write"; + + /** Execute action. */ + public static final String EXECUTE_ACTION = "Execute"; + + /** Delete action. */ + public static final String DELETE_ACTION = "Delete"; + + /** Control action. */ + public static final String CONTROL_ACTION = "Control"; + + /** Negated Read action. */ + public static final String NEG_READ_ACTION = "~Read"; + + /** Negated Write action. */ + public static final String NEG_WRITE_ACTION = "~Write"; + + /** Negated Execute action. */ + public static final String NEG_EXECUTE_ACTION = "~Execute"; + + /** Negated Delete action. */ + public static final String NEG_DELETE_ACTION = "~Delete"; + + /** Negated Control action. */ + public static final String NEG_CONTROL_ACTION = "~Control"; + + /** HTTP GET action. */ + public static final String HTTP_GET_ACTION = "GET"; + + /** HTTP HEAD action. */ + public static final String HTTP_HEAD_ACTION = "HEAD"; + + /** HTTP PUT action. */ + public static final String HTTP_PUT_ACTION = "PUT"; + + /** HTTP POST action. */ + public static final String HTTP_POST_ACTION = "POST"; + + /** + * Gets the namespace scope of the specified action. + * + * @return the namespace scope of the specified action + */ + public String getNamespace(); + + /** + * Sets the namespace scope of the specified action. + * + * @param newNamespace the namespace scope of the specified action + */ + public void setNamespace(String newNamespace); + + /** + * Gets the URI of the action to be performed. + * + * @return the URI of the action to be performed + */ + public String getAction(); + + /** + * Sets the URI of the action to be performed. + * + * @param newAction the URI of the action to be performed + */ + public void setAction(String newAction); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Advice.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Advice.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Advice.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.XMLObject; + +/** + * SAML 2.0 Core Advice. + */ +public interface Advice extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Advice"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AdviceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Gets the list of all child elements attached to this advice. + * + * @return the list of all child elements attached to this advice + */ + public List getChildren(); + + /** + * Gets the list of child elements attached to this advice that match a particular QName. + * + * @param typeOrName the QName of the child elements to return + * @return the list of matching child elements attached to this advice + */ + public List getChildren(QName typeOrName); + + /** + * Gets the list of AssertionID references used as advice. + * + * @return the list of AssertionID references used as advice + */ + public List getAssertionIDReferences(); + + /** + * Gets the list of AssertionURI references used as advice. + * + * @return the list of AssertionURI references used as advice + */ + public List getAssertionURIReferences(); + + /** + * Gets the list of Assertions used as advice. + * + * @return the list of Assertions used as advice + */ + public List getAssertions(); + + /** + * Gets the list of EncryptedAssertions used as advice. + * + * @return the list of EncryptedAssertions used as advice + */ + public List getEncryptedAssertions(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Artifact.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Artifact.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Artifact.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Artifact. + */ +public interface Artifact extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Artifact"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ArtifactType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Get artifact value. + * + * @return the artifact value + */ + public String getArtifact(); + + /** + * Set artifact value. + * + * @param newArtifact sets the new artifact value + */ + public void setArtifact(String newArtifact); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/ArtifactResolve.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/ArtifactResolve.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/ArtifactResolve.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core ArtifactResolve. + */ +public interface ArtifactResolve extends RequestAbstractType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ArtifactResolve"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ArtifactResolveType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Get Artifact child element. + * + * @return the Artifact child element + */ + public Artifact getArtifact(); + + /** + * Set Artifact child element. + * + * @param newArtifact sets the new Artifact child element + */ + public void setArtifact(Artifact newArtifact); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/ArtifactResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/ArtifactResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/ArtifactResponse.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core ArtifactResponse. + */ +public interface ArtifactResponse extends StatusResponseType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ArtifactResponse"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ArtifactResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the protocol message from the artifact response. + * + * @return protocol message from the artifact response + */ + public SAMLObject getMessage(); + + /** + * Sets the protocol message from the artifact response. + * + * @param message protocol message from the artifact response + */ + public void setMessage(SAMLObject message); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Assertion.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Assertion.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Assertion.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,190 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Assertion. + */ +public interface Assertion extends SignableSAMLObject, Evidentiary { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Assertion"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AssertionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Version attribute name. */ + public static final String VERSION_ATTRIB_NAME = "Version"; + + /** IssueInstant attribute name. */ + public static final String ISSUE_INSTANT_ATTRIB_NAME = "IssueInstant"; + + /** ID attribute name. */ + public static final String ID_ATTRIB_NAME = "ID"; + + /** + * Gets the SAML Version of this assertion. + * + * @return the SAML Version of this assertion. + */ + public SAMLVersion getVersion(); + + /** + * Sets the SAML Version of this assertion. + * + * @param newVersion the SAML Version of this assertion + */ + public void setVersion(SAMLVersion newVersion); + + /** + * Gets the issue instance of this assertion. + * + * @return the issue instance of this assertion + */ + public DateTime getIssueInstant(); + + /** + * Sets the issue instance of this assertion. + * + * @param newIssueInstance the issue instance of this assertion + */ + public void setIssueInstant(DateTime newIssueInstance); + + /** + * Sets the ID of this assertion. + * + * @return the ID of this assertion + */ + public String getID(); + + /** + * Sets the ID of this assertion. + * + * @param newID the ID of this assertion + */ + public void setID(String newID); + + /** + * Gets the Issuer of this assertion. + * + * @return the Issuer of this assertion + */ + public Issuer getIssuer(); + + /** + * Sets the Issuer of this assertion. + * + * @param newIssuer the Issuer of this assertion + */ + public void setIssuer(Issuer newIssuer); + + /** + * Gets the Subject of this assertion. + * + * @return the Subject of this assertion + */ + public Subject getSubject(); + + /** + * Sets the Subject of this assertion. + * + * @param newSubject the Subject of this assertion + */ + public void setSubject(Subject newSubject); + + /** + * Gets the Conditions placed on this assertion. + * + * @return the Conditions placed on this assertion + */ + public Conditions getConditions(); + + /** + * Sets the Conditions placed on this assertion. + * + * @param newConditions the Conditions placed on this assertion + */ + public void setConditions(Conditions newConditions); + + /** + * Gets the Advice for this assertion. + * + * @return the Advice for this assertion + */ + public Advice getAdvice(); + + /** + * Sets the Advice for this assertion. + * + * @param newAdvice the Advice for this assertion + */ + public void setAdvice(Advice newAdvice); + + /** + * Gets the list of statements attached to this assertion. + * + * @return the list of statements attached to this assertion + */ + public List getStatements(); + + /** + * Gets the list of statements attached to this assertion that match a particular QName. + * + * @param typeOrName the QName of the statements to return + * @return the list of statements attached to this assertion + */ + public List getStatements(QName typeOrName); + + /** + * Gets the list of AuthnStatements attached to this assertion. + * + * @return the list of AuthnStatements attached to this assertion + */ + public List getAuthnStatements(); + + /** + * Gets the list of AuthzDecisionStatements attached to this assertion. + * + * @return the list of AuthzDecisionStatements attached to this assertion + */ + public List getAuthzDecisionStatements(); + + /** + * Gets the list of AttributeStatement attached to this assertion. + * + * @return the list of AttributeStatement attached to this assertion + */ + public List getAttributeStatements(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionIDRef.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionIDRef.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionIDRef.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AssertionIDRef. + */ +public interface AssertionIDRef extends SAMLObject, Evidentiary { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AssertionIDRef"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Gets the ID of the assertion this references. + * + * @return the ID of the assertion this references + */ + public String getAssertionID(); + + /** + * Sets the ID of the assertion this references. + * + * @param newID the ID of the assertion this references + */ + public void setAssertionID(String newID); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionIDRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionIDRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionIDRequest.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AssertionIDRequest. + */ +public interface AssertionIDRequest extends RequestAbstractType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AssertionIDRequest"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets a list of child {@link AssertionIDRef}s. + * + * @return the list of child AssertionIDRef's + */ + public List getAssertionIDRefs(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionURIRef.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionURIRef.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AssertionURIRef.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AssertionURIRef. + */ +public interface AssertionURIRef extends SAMLObject, Evidentiary { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AssertionURIRef"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Gets the URI of the assertion this references. + * + * @return the URI of the assertion this references + */ + public String getAssertionURI(); + + /** + * Sets the URI of the assertion this references. + * + * @param newURI the URI of the assertion this references + */ + public void setAssertionURI(String newURI); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Attribute.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Attribute.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Attribute.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.XMLObject; + +/** + * SAML 2.0 Core Attribute. + */ +public interface Attribute extends SAMLObject, AttributeExtensibleXMLObject { + + /** Local name of the Attribute element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Attribute"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributeType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Name of the Name attribute. */ + public static final String NAME_ATTTRIB_NAME = "Name"; + + /** Name for the NameFormat attribute. */ + public static final String NAME_FORMAT_ATTRIB_NAME = "NameFormat"; + + /** Name of the FriendlyName attribute. */ + public static final String FRIENDLY_NAME_ATTRIB_NAME = "FriendlyName"; + + /** Unspecified attribute format ID. */ + public static final String UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"; + + /** URI reference attribute format ID. */ + public static final String URI_REFERENCE = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri"; + + /** Basic attribute format ID. */ + public static final String BASIC = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"; + + /** + * Get the name of this attribute. + * + * @return the name of this attribute + */ + public String getName(); + + /** + * Sets the name of this attribute. + * + * @param name the name of this attribute + */ + public void setName(String name); + + /** + * Get the name format of this attribute. + * + * @return the name format of this attribute + */ + public String getNameFormat(); + + /** + * Sets the name format of this attribute. + * + * @param nameFormat the name format of this attribute + */ + public void setNameFormat(String nameFormat); + + /** + * Get the friendly name of this attribute. + * + * @return the friendly name of this attribute + */ + public String getFriendlyName(); + + /** + * Sets the friendly name of this attribute. + * + * @param friendlyName the friendly name of this attribute + */ + public void setFriendlyName(String friendlyName); + + /** + * Gets the list of attribute values for this attribute. + * + * @return the list of attribute values for this attribute + */ + public List getAttributeValues(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeQuery.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 AttributeQuery. + */ +public interface AttributeQuery extends SubjectQuery { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeQuery"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributeQueryType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the Attributes of this query. + * + * @return the list of Attributes of this query + */ + public List getAttributes(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeStatement.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AttributeStatement. + */ +public interface AttributeStatement extends Statement { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeStatement"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AttributeStatementType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + + /** + * Gets the attribtues expressed in this statement. + * + * @return the attribtues expressed in this statement + */ + public List getAttributes(); + + /** + * Gets the encrypted attribtues expressed in this statement. + * + * @return the encrypted attribtues expressed in this statement + */ + public List getEncryptedAttributes(); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeValue.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeValue.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AttributeValue.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * This interface defines how the object representing a SAML 12 AttributeValue element behaves. + */ +public interface AttributeValue extends SAMLObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeValue"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Audience.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Audience.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Audience.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Audience. + */ +public interface Audience extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Audience"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AudienceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Gets the URI of the audience for the assertion. + * + * @return the URI of the audience for the assertion + */ + public String getAudienceURI(); + + /** + * Sets the URI of the audience for the assertion. + * + * @param newAudienceURI the URI of the audience for the assertion + */ + public void setAudienceURI(String newAudienceURI); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AudienceRestriction.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AudienceRestriction.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AudienceRestriction.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AudienceRestriction. + */ +public interface AudienceRestriction extends Condition { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AudienceRestriction"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AudienceRestrictionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Gets the list of audiences for the assertion. + * + * @return the list of audiences for the assertion + */ + public List getAudiences(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthenticatingAuthority.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthenticatingAuthority.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthenticatingAuthority.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AuthenticatingAuthority. + */ +public interface AuthenticatingAuthority extends SAMLObject { + + /** Local Name of AuthenticatingAuthority. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthenticatingAuthority"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Gets the URI of this Authenticating Authority. + * + * @return AuthenticatingAuthority URI + */ + public String getURI(); + + /** + * Sets the URI of this Authenticating Authority. + * + * @param newURI the URI of this Authenticating Authority + */ + public void setURI(String newURI); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContext.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,167 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** SAML 2.0 Core AuthnContext. */ +public interface AuthnContext extends SAMLObject { + + /** Local Name of AuthnContext. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnContext"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthnContextType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** URI for Internet Protocol authentication context. */ + public static final String IP_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocol"; + + /** URI for Internet Protocol Password authentication context. */ + public static final String IP_PASSWORD_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword"; + + /** URI for Kerberos authentication context. */ + public static final String KERBEROS_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:Kerberos"; + + /** URI for Mobile One Factor Unregistered authentication context. */ + public static final String MOFU_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileOneFactorUnregistered"; + + /** URI for Mobile Two Factor Unregistered authentication context. */ + public static final String MTFU = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileTwoFactorUnregistered"; + + /** URI for Mobile One Factor Contract authentication context. */ + public static final String MOFC_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileOneFactorContract"; + + /** URI for Mobile Two Factor Contract authentication context. */ + public static final String MTFC_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:MobileTwoFactorContract"; + + /** URI for Password authentication context. */ + public static final String PASSWORD_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password"; + + /** URI for Password Protected Transport authentication context. */ + public static final String PPT_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"; + + /** URI for Previous Session authentication context. */ + public static final String PREVIOUS_SESSION_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:PreviousSession"; + + /** URI for X509 Public Key authentication context. */ + public static final String X509_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:X509"; + + /** URI for PGP authentication context. */ + public static final String PGP_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:PGP"; + + /** URI for SPKI authentication context. */ + public static final String SPKI_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:SPKI"; + + /** URI for XML Digital Signature authentication context. */ + public static final String XML_DSIG_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:XMLDSig"; + + /** URI for Smart Card authentication context. */ + public static final String SMARTCARD_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:Smartcard"; + + /** URI for Smart Card PKI authentication context. */ + public static final String SMARTCARD_PKI_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:SmartcardPKI"; + + /** URI for Software PKU authentication context. */ + public static final String SOFTWARE_PKI_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:SoftwarePKI"; + + /** URI for Telephony authentication context. */ + public static final String TELEPHONY_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:Telephony"; + + /** URI for Nomadic Telephony authentication context. */ + public static final String NOMAD_TELEPHONY_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:NomadTelephony"; + + /** URI for Personalized Telephony authentication context. */ + public static final String PERSONAL_TELEPHONY_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:PersonalTelephony"; + + /** URI for Authenticated Telephony authentication context. */ + public static final String AUTHENTICATED_TELEPHONY_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:AuthenticatedTelephony"; + + /** URI for Secure Remote Password authentication context. */ + public static final String SRP_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:SecureRemotePassword"; + + /** URI for SSL/TLS Client authentication context. */ + public static final String TLS_CLIENT_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:TLSClient"; + + /** URI for Time Synchornized Token authentication context. */ + public static final String TIME_SYNC_TOKEN_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:TimeSyncToken"; + + /** URI for unspecified authentication context. */ + public static final String UNSPECIFIED_AUTHN_CTX = "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"; + + /** + * Gets the URI identifying the Context Class of this Authentication Context. + * + * @return AuthnContext AuthnContextClassRef + */ + public AuthnContextClassRef getAuthnContextClassRef(); + + /** + * Sets the URI identifying the Context Class of this Authentication Context. + * + * @param newAuthnContextClassRef the URI of this Authentication Context's Class. + */ + public void setAuthnContextClassRef(AuthnContextClassRef newAuthnContextClassRef); + + /** + * Gets Declaration of this Authentication Context. + * + * @return AuthnContext AuthnContextDecl + */ + public AuthnContextDecl getAuthContextDecl(); + + /** + * Sets the Declaration of this Authentication Context. + * + * @param newAuthnContextDecl the Declaration of this Authentication Context + */ + public void setAuthnContextDecl(AuthnContextDecl newAuthnContextDecl); + + /** + * Gets the URI of the Declaration of this Authentication Context. + * + * @return AuthnContext AuthnContextDeclRef + */ + public AuthnContextDeclRef getAuthnContextDeclRef(); + + /** + * Sets the URI of the Declaration of this Authentication Context. + * + * @param newAuthnContextDeclRef the URI of the Declaration of this Authentication Context + */ + public void setAuthnContextDeclRef(AuthnContextDeclRef newAuthnContextDeclRef); + + /** + * Gets the Authenticating Authorities of this Authentication Context. + * + * @return AuthnContext AuthenticatingAuthorities + */ + public List getAuthenticatingAuthorities(); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextClassRef.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextClassRef.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextClassRef.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AuthnContextClassRef. + */ +public interface AuthnContextClassRef extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnContextClassRef"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + + /** + * Gets the URI reference to an authentication context class. + * + * @return authentication context class reference URI + */ + public String getAuthnContextClassRef(); + + /** + * Sets the URI reference to an authentication context class. + * + * @param newAuthnContextClassRef the new AuthnContextClassRef URI + */ + public void setAuthnContextClassRef(String newAuthnContextClassRef); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextComparisonTypeEnumeration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextComparisonTypeEnumeration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextComparisonTypeEnumeration.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +/** + * A type safe enumeration of {@link org.opensaml.saml2.core.RequestedAuthnContext} comparison types. + */ +public final class AuthnContextComparisonTypeEnumeration { + + /** "exact" comparison type. */ + public static final AuthnContextComparisonTypeEnumeration EXACT = + new AuthnContextComparisonTypeEnumeration("exact"); + + /** "minimum" comparison type. */ + public static final AuthnContextComparisonTypeEnumeration MINIMUM = + new AuthnContextComparisonTypeEnumeration("minimum"); + + /** "maximum" comparison type. */ + public static final AuthnContextComparisonTypeEnumeration MAXIMUM = + new AuthnContextComparisonTypeEnumeration("maximum"); + + /** "better" comparison type. */ + public static final AuthnContextComparisonTypeEnumeration BETTER = + new AuthnContextComparisonTypeEnumeration("better"); + + /** The comparison type string. */ + private String comparisonType; + + /** + * Constructor. + * + * @param newComparisonType the comparison type string + */ + protected AuthnContextComparisonTypeEnumeration(String newComparisonType) { + this.comparisonType= newComparisonType; + } + + /** {@inheritDoc} */ + public String toString() { + return comparisonType; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextDecl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextDecl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextDecl.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSAny; + +/** + * SAML 2.0 Core AuthnContextDecl. + */ +public interface AuthnContextDecl extends SAMLObject, XSAny { + + /** Local Name of AuthnContextDecl. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnContextDecl"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextDeclRef.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextDeclRef.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnContextDeclRef.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AuthnContextDeclRef. + */ +public interface AuthnContextDeclRef extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnContextDeclRef"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + + /** + * Gets the URI reference to an authentication context declaration. + * + * @return authentication context declaration reference URI + */ + public String getAuthnContextDeclRef(); + + /** + * Sets the URI reference to an authentication context declaration. + * + * @param newAuthnContextDeclRef the new AuthnContextDeclRef URI + */ + public void setAuthnContextDeclRef(String newAuthnContextDeclRef); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnQuery.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 AuthnQuery. + */ +public interface AuthnQuery extends SubjectQuery { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnQuery"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthnQueryType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** SessionIndex attribute name. */ + public static final String SESSION_INDEX_ATTRIB_NAME = "SessionIndex"; + + /** + * Gets the SessionIndex of this request. + * + * @return the SessionIndex of this request + */ + public String getSessionIndex(); + + /** + * Sets the SessionIndex of this request. + * + * @param newSessionIndex the SessionIndex of this request + */ + public void setSessionIndex(String newSessionIndex); + + /** + * Gets the RequestedAuthnContext of this request. + * + * @return the RequestedAuthnContext of this request + */ + public RequestedAuthnContext getRequestedAuthnContext(); + + /** + * Sets the RequestedAuthnContext of this request. + * + * @param newRequestedAuthnContext the RequestedAuthnContext of this request + */ + public void setRequestedAuthnContext(RequestedAuthnContext newRequestedAuthnContext); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnRequest.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,273 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Core AuthnRequest. + */ +public interface AuthnRequest extends RequestAbstractType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnRequest"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthnRequestType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** ForceAuthn attribute name. */ + public static final String FORCE_AUTHN_ATTRIB_NAME = "ForceAuthn"; + + /** IsPassive attribute name. */ + public static final String IS_PASSIVE_ATTRIB_NAME = "IsPassive"; + + /** ProtocolBinding attribute name. */ + public static final String PROTOCOL_BINDING_ATTRIB_NAME = "ProtocolBinding"; + + /** AssertionConsumerServiceIndex attribute name. */ + public static final String ASSERTION_CONSUMER_SERVICE_INDEX_ATTRIB_NAME = "AssertionConsumerServiceIndex"; + + /** AssertionConsumerServiceURL attribute name. */ + public static final String ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME = "AssertionConsumerServiceURL"; + + /** AttributeConsumingServiceIndex attribute name. */ + public static final String ATTRIBUTE_CONSUMING_SERVICE_INDEX_ATTRIB_NAME = "AttributeConsumingServiceIndex"; + + /** ProviderName attribute name. */ + public static final String PROVIDER_NAME_ATTRIB_NAME = "ProviderName"; + + /** + * Gets whether the IdP should force the user to reauthenticate. + * + * @return whether the IdP should force the user to reauthenticate + */ + public Boolean isForceAuthn(); + + /** + * Gets whether the IdP should force the user to reauthenticate. + * + * @return whether the IdP should force the user to reauthenticate + */ + public XSBooleanValue isForceAuthnXSBoolean(); + + /** + * Sets whether the IdP should force the user to reauthenticate. Boolean values will be marshalled to either "true" + * or "false". + * + * @param newForceAuthn whether the IdP should force the user to reauthenticate + */ + public void setForceAuthn(Boolean newForceAuthn); + + /** + * Sets whether the IdP should force the user to reauthenticate. + * + * @param newForceAuthn whether the IdP should force the user to reauthenticate + */ + public void setForceAuthn(XSBooleanValue newForceAuthn); + + /** + * Gets whether the IdP should refrain from interacting with the user during the authentication process. + * + * @return whether the IdP should refrain from interacting with the user during the authentication process + */ + public Boolean isPassive(); + + /** + * Gets whether the IdP should refrain from interacting with the user during the authentication process. + * + * @return whether the IdP should refrain from interacting with the user during the authentication process + */ + public XSBooleanValue isPassiveXSBoolean(); + + /** + * Sets whether the IdP should refrain from interacting with the user during the authentication process. Boolean + * values will be marshalled to either "true" or "false". + * + * @param newIsPassive whether the IdP should refrain from interacting with the user during the authentication + * process + */ + public void setIsPassive(Boolean newIsPassive); + + /** + * Sets whether the IdP should refrain from interacting with the user during the authentication process. + * + * @param newIsPassive whether the IdP should refrain from interacting with the user during the authentication + * process + */ + public void setIsPassive(XSBooleanValue newIsPassive); + + /** + * Gets the protocol binding URI for the request. + * + * @return the value of the ProtocolBinding attribute + */ + public String getProtocolBinding(); + + /** + * Sets the protocol binding URI for the request. + * + * @param newProtocolBinding the new value of the ProtocolBinding attribute + */ + public void setProtocolBinding(String newProtocolBinding); + + /** + * Gets the index of the particular Assertion Consumer Service to which the response to this request should be + * delivered. + * + * @return the value of the AssertionConsumerServiceIndex attribute + */ + public Integer getAssertionConsumerServiceIndex(); + + /** + * Sets the index of the particular Assertion Consumer Service to which the response to this request should be + * delivered. + * + * @param newAssertionConsumerServiceIndex the new value of the AssertionConsumerServiceIndex attribute + */ + public void setAssertionConsumerServiceIndex(Integer newAssertionConsumerServiceIndex); + + /** + * Gets the URL of the particular Assertion Consumer Service to which the response to this request should be + * delivered. + * + * @return the value of the AssertionConsumerServiceURL attribute + */ + public String getAssertionConsumerServiceURL(); + + /** + * Sets the URL of the particular Assertion Consumer Service to which the response to this request should be + * delivered. + * + * @param newAssertionConsumerServiceURL the new value of the AssertionConsumerServiceURL attribute + */ + public void setAssertionConsumerServiceURL(String newAssertionConsumerServiceURL); + + /** + * Gets the index of the Attribute Consuming Service which describes the SAML attributes the requester desires or + * requires to be supplied in the Response message. + * + * + * @return the value of the AssertionConsumerServiceIndex attribute + */ + public Integer getAttributeConsumingServiceIndex(); + + /** + * + * Sets the index of the Attribute Consuming Service which describes the SAML attributes the requester desires or + * requires to be supplied in the Response message. + * + * @param newAttributeConsumingServiceIndex the new value of the AttributeConsumingServiceIndex attribute + */ + public void setAttributeConsumingServiceIndex(Integer newAttributeConsumingServiceIndex); + + /** + * Gets the human-readable name of the requester for use by the presenter's user agent or the identity provider. + * + * @return the value of the ProviderName attribute + */ + public String getProviderName(); + + /** + * Sets the human-readable name of the requester for use by the presenter's user agent or the identity provider. + * + * @param newProviderName the new value of the ProviderName attribute + */ + public void setProviderName(String newProviderName); + + /** + * Gets the {@link Subject} of the request. + * + * @return the Subject of the request + */ + public Subject getSubject(); + + /** + * Sets the {@link Subject} of the request. + * + * @param newSubject the new value of the Subject of the request + */ + public void setSubject(Subject newSubject); + + /** + * Gets the {@link NameIDPolicy} of the request. + * + * @return the NameIDPolicy of the request + */ + public NameIDPolicy getNameIDPolicy(); + + /** + * Sets the {@link NameIDPolicy} of the request. + * + * @param newNameIDPolicy the new value of the NameIDPolicy of the request + */ + public void setNameIDPolicy(NameIDPolicy newNameIDPolicy); + + /** + * Gets the {@link Conditions} of the request. + * + * @return the Conditions of the request + */ + public Conditions getConditions(); + + /** + * Sets the {@link Conditions} of the request. + * + * @param newConditions the new value of the Conditions of the request + */ + public void setConditions(Conditions newConditions); + + /** + * Gets the {@link RequestedAuthnContext} of the request. + * + * @return the RequestedAuthnContext of the request + */ + public RequestedAuthnContext getRequestedAuthnContext(); + + /** + * Sets the {@link RequestedAuthnContext} of the request. + * + * @param newRequestedAuthnContext the new value of the RequestedAuthnContext of the request + */ + public void setRequestedAuthnContext(RequestedAuthnContext newRequestedAuthnContext); + + /** + * Gets the {@link Scoping} of the request. + * + * @return the Scoping of the request + */ + public Scoping getScoping(); + + /** + * Sets the {@link Scoping} of the request. + * + * @param newScoping the new value of the Scoping of the request + */ + public void setScoping(Scoping newScoping); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthnStatement.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,122 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AuthnStatement. + */ +public interface AuthnStatement extends Statement { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnStatement"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthnStatementType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** AuthnInstant attribute name. */ + public static final String AUTHN_INSTANT_ATTRIB_NAME = "AuthnInstant"; + + /** SessionIndex attribute name. */ + public static final String SESSION_INDEX_ATTRIB_NAME = "SessionIndex"; + + /** SessionNoOnOrAfter attribute name. */ + public static final String SESSION_NOT_ON_OR_AFTER_ATTRIB_NAME = "SessionNotOnOrAfter"; + + /** + * Gets the time when the authentication took place. + * + * @return the time when the authentication took place + */ + public DateTime getAuthnInstant(); + + /** + * Sets the time when the authentication took place. + * + * @param newAuthnInstant the time when the authentication took place + */ + public void setAuthnInstant(DateTime newAuthnInstant); + + /** + * Get the session index between the principal and the authenticating authority. + * + * @return the session index between the principal and the authenticating authority + */ + public String getSessionIndex(); + + /** + * Sets the session index between the principal and the authenticating authority. + * + * @param newIndex the session index between the principal and the authenticating authority + */ + public void setSessionIndex(String newIndex); + + /** + * Get the time when the session between the principal and the SAML authority ends. + * + * @return the time when the session between the principal and the SAML authority ends + */ + public DateTime getSessionNotOnOrAfter(); + + /** + * Set the time when the session between the principal and the SAML authority ends. + * + * @param newSessionNotOnOrAfter the time when the session between the principal and the SAML authority ends + */ + public void setSessionNotOnOrAfter(DateTime newSessionNotOnOrAfter); + + /** + * Get the DNS domain and IP address of the system where the principal was authenticated. + * + * @return the DNS domain and IP address of the system where the principal was authenticated + */ + public SubjectLocality getSubjectLocality(); + + /** + * Set the DNS domain and IP address of the system where the principal was authenticated. + * + * @param newLocality the DNS domain and IP address of the system where the principal was authenticated + */ + public void setSubjectLocality(SubjectLocality newLocality); + + /** + * Gets the context used to authenticate the subject. + * + * @return the context used to authenticate the subject + */ + public AuthnContext getAuthnContext(); + + /** + * Sets the context used to authenticate the subject. + * + * @param newAuthnContext the context used to authenticate the subject + */ + public void setAuthnContext(AuthnContext newAuthnContext); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthzDecisionQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthzDecisionQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthzDecisionQuery.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 AuthzDecisionQuery. + */ +public interface AuthzDecisionQuery extends SubjectQuery { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthzDecisionQuery"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthzDecisionQueryType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Resource attribute name. */ + public static final String RESOURCE_ATTRIB_NAME = "Resource"; + + /** + * Gets the Resource attrib value of this query. + * + * @return the Resource attrib value of this query + */ + public String getResource(); + + /** + * Sets the Resource attrib value of this query. + * + * @param newResource the new Resource attrib value of this query + */ + public void setResource(String newResource); + + /** + * Gets the Actions of this query. + * + * @return the Actions of this query + */ + public List getActions(); + + /** + * Gets the Evidence of this query. + * + * @return the Evidence of this query + */ + public Evidence getEvidence(); + + /** + * Sets the Evidence of this query. + * + * @param newEvidence the new Evidence of this query + */ + public void setEvidence(Evidence newEvidence); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthzDecisionStatement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthzDecisionStatement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/AuthzDecisionStatement.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core AuthzDecisionStatement. + */ +public interface AuthzDecisionStatement extends Statement { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AuthzDecisionStatement"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "AuthzDecisionStatementType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Resource attribute name. */ + public static final String RESOURCE_ATTRIB_NAME = "Resource"; + + /** Decision attribute name. */ + public static final String DECISION_ATTRIB_NAME = "Decision"; + + /** + * Get URI of the resource to which authorization is saught. + * + * @return URI of the resource to which authorization is saught + */ + public String getResource(); + + /** + * Sets URI of the resource to which authorization is saught. + * + * @param newResourceURI URI of the resource to which authorization is saught + */ + public void setResource(String newResourceURI); + + /** + * Gets the decision of the authorization request. + * + * @return the decision of the authorization request + */ + public DecisionTypeEnumeration getDecision(); + + /** + * Sets the decision of the authorization request. + * + * @param newDecision the decision of the authorization request + */ + public void setDecision(DecisionTypeEnumeration newDecision); + + /** + * Gets the actions authorized to be performed. + * + * @return the actions authorized to be performed + */ + public List getActions(); + + /** + * Get the SAML assertion the authority relied on when making the authorization decision. + * + * @return the SAML assertion the authority relied on when making the authorization decision + */ + public Evidence getEvidence(); + + /** + * Sets the SAML assertion the authority relied on when making the authorization decision. + * + * @param newEvidence the SAML assertion the authority relied on when making the authorization decision + */ + public void setEvidence(Evidence newEvidence); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/BaseID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/BaseID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/BaseID.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core BaseID. + */ +public interface BaseID extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "BaseID"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "BaseIDAbstractType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** NameQualifier attribute name. */ + public static final String NAME_QUALIFIER_ATTRIB_NAME = "NameQualifier"; + + /** SPNameQualifier attribute name. */ + public static final String SP_NAME_QUALIFIER_ATTRIB_NAME = "SPNameQualifier"; + + /** + * Gets the NameQualifier value. + * + * @return the NameQualifier value + */ + public String getNameQualifier(); + + /** + * Sets the NameQualifier value. + * + * @param newNameQualifier the NameQualifier value + */ + public void setNameQualifier(String newNameQualifier); + + /** + * Gets the SPNameQualifier value. + * + * @return the SPNameQualifier value + */ + public String getSPNameQualifier(); + + /** + * Sets the SPNameQualifier value. + * + * @param newSPNameQualifier the SPNameQualifier value + */ + public void setSPNameQualifier(String newSPNameQualifier); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Condition.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Condition.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Condition.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Condition. + */ +public interface Condition extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Condition"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ConditionAbstractType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Conditions.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Conditions.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Conditions.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Conditions. + */ +public interface Conditions extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Conditions"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ConditionsType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** NotBefore attribute name. */ + public static final String NOT_BEFORE_ATTRIB_NAME = "NotBefore"; + + /** NotOnOrAfter attribute name. */ + public static final String NOT_ON_OR_AFTER_ATTRIB_NAME = "NotOnOrAfter"; + + /** + * Get the date/time before which the assertion is invalid. + * + * @return the date/time before which the assertion is invalid + */ + public DateTime getNotBefore(); + + /** + * Sets the date/time before which the assertion is invalid. + * + * @param newNotBefore the date/time before which the assertion is invalid + */ + public void setNotBefore(DateTime newNotBefore); + + /** + * Gets the date/time on, or after, which the assertion is invalid. + * + * @return the date/time on, or after, which the assertion is invalid + */ + public DateTime getNotOnOrAfter(); + + /** + * Sets the date/time on, or after, which the assertion is invalid. + * + * @param newNotOnOrAfter the date/time on, or after, which the assertion is invalid + */ + public void setNotOnOrAfter(DateTime newNotOnOrAfter); + + /** + * Gets all the conditions on the assertion. + * + * @return all the conditions on the assertion + */ + public List getConditions(); + + /** + * Gets the audience restriction conditions for the assertion. + * + * @return the audience restriction conditions for the assertion + */ + public List getAudienceRestrictions(); + + /** + * Gets the OneTimeUse condition for the assertion. + * + * @return the OneTimeUse condition for the assertion + */ + public OneTimeUse getOneTimeUse(); + + /** + * Gets the ProxyRestriction condition for the assertion. + * + * @return the ProxyRestriction condition for the assertion + */ + public ProxyRestriction getProxyRestriction(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/DecisionTypeEnumeration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/DecisionTypeEnumeration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/DecisionTypeEnumeration.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +/** + * A type safe enumeration of {@link org.opensaml.saml2.core.AuthzDecisionStatement} decision types. + */ +public final class DecisionTypeEnumeration { + + /** Permit decision type. */ + public static final DecisionTypeEnumeration PERMIT = new DecisionTypeEnumeration("Permit"); + + /** Deny decision type. */ + public static final DecisionTypeEnumeration DENY = new DecisionTypeEnumeration("Deny"); + + /** Indeterminate decision type. */ + public static final DecisionTypeEnumeration INDETERMINATE = new DecisionTypeEnumeration("Indeterminate"); + + /** The decision type string. */ + private String decisionType; + + /** + * Constructor. + * + * @param newDecisionType the decision type string + */ + protected DecisionTypeEnumeration(String newDecisionType) { + this.decisionType = newDecisionType; + } + + /** {@inheritDoc} */ + public String toString() { + return decisionType; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedAssertion.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedAssertion.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedAssertion.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core EncryptedAssertion. + */ +public interface EncryptedAssertion extends EncryptedElementType, Evidentiary { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "EncryptedAssertion"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedAttribute.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedAttribute.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedAttribute.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core EncryptedAttribute. + */ +public interface EncryptedAttribute extends EncryptedElementType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "EncryptedAttribute"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedElementType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedElementType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedElementType.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.encryption.EncryptedData; +import org.opensaml.xml.encryption.EncryptedKey; + +/** + * SAML 2.0 Core EncryptedElementType. + */ +public interface EncryptedElementType extends SAMLObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EncryptedElementType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + + /** + * Get the EncryptedData child element. + * + * @return the EncryptedData child element + */ + public EncryptedData getEncryptedData(); + + /** + * Set the EncryptedData child element. + * + * @param newEncryptedData the new EncryptedData child element + */ + public void setEncryptedData(EncryptedData newEncryptedData); + + /** + * A list of EncryptedKey child elements. + * + * @return a list of EncryptedKey child elements + */ + public List getEncryptedKeys(); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/EncryptedID.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core EncryptedID. + */ +public interface EncryptedID extends EncryptedElementType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "EncryptedID"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Evidence.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Evidence.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Evidence.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Evidence. + */ +public interface Evidence extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Evidence"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EvidenceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + + /** + * Gets the list of AssertionID references used as evidence. + * + * @return the list of AssertionID references used as evidence + */ + public List getAssertionIDReferences(); + + /** + * Gets the list of AssertionURI references used as evidence. + * + * @return the list of AssertionURI references used as evidence + */ + public List getAssertionURIReferences(); + + /** + * Gets the list of Assertions used as evidence. + * + * @return the list of Assertions used as evidence + */ + public List getAssertions(); + + /** + * Gets the list of EncryptedAssertions used as evidence. + * + * @return the list of EncryptedAssertions used as evidence + */ + public List getEncryptedAssertions(); + + /** + * Gets the list of all elements used as evidence. + * + * @return the list of Evidentiary objects used as evidence + */ + public List getEvidence(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Evidentiary.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Evidentiary.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Evidentiary.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core; + +import org.opensaml.common.SAMLObject; + +/** + * Marker interface for element types that can constitute evidence within a @{org.opensaml.saml2.core.Evidence} object. + */ +public interface Evidentiary extends SAMLObject { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/GetComplete.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/GetComplete.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/GetComplete.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core GetComplete. + */ +public interface GetComplete extends SAMLObject { + + /** Element Local Name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "GetComplete"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the GetComplete URI value. + * + * @return GetComplete URI + */ + public String getGetComplete(); + + /** + * Sets the GetComplete URI. + * + * @param newGetComplete the GetComplete URI + */ + public void setGetComplete(String newGetComplete); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/IDPEntry.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/IDPEntry.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/IDPEntry.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core IDPEntry. + */ +public interface IDPEntry extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "IDPEntry"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "IDPEntryType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** ProviderID attribute name. */ + public static final String PROVIDER_ID_ATTRIB_NAME = "ProviderID"; + + /** Name attribute name. */ + public static final String NAME_ATTRIB_NAME = "Name"; + + /** Loc attribute name. */ + public static final String LOC_ATTRIB_NAME = "Loc"; + + /** + * Gets ProviderID URI. + * + * @return the ProviderID URI + */ + public String getProviderID(); + + /** + * Sets the ProviderID URI. + * + * @param newProviderID the new ProviderID URI + */ + public void setProviderID(String newProviderID); + + /** + * Gets the Name value. + * + * @return the Name value + */ + public String getName(); + + /** + * Sets the Name value. + * + * @param newName the Name value + */ + public void setName(String newName); + + /** + * Gets the Loc value. + * + * @return the Loc value + */ + public String getLoc(); + + /** + * Sets the Loc value. + * + * @param newLoc the new Loc value + */ + public void setLoc(String newLoc); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/IDPList.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/IDPList.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/IDPList.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core IDPList. + */ +public interface IDPList extends SAMLObject { + + /** Element Local Name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "IDPList"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "IDPListType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the IDPEntry list. + * + * @return the IDPEntry list + */ + public List getIDPEntrys(); + + /** + * Gets the GetComplete URI. + * + * @return GetComplete URI + */ + public GetComplete getGetComplete(); + + /** + * Sets the GetComplete URI. + * + * @param newGetComplete the new GetComplete URI + */ + public void setGetComplete(GetComplete newGetComplete); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Issuer.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Issuer.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Issuer.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Issuer. + */ +public interface Issuer extends NameIDType, SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Issuer"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "IssuerType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/KeyInfoConfirmationDataType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/KeyInfoConfirmationDataType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/KeyInfoConfirmationDataType.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.XMLObject; + +/** + * SAML 2.0 Core KeyInfoConfirmationDataType. + */ +public interface KeyInfoConfirmationDataType extends SubjectConfirmationData { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "KeyInfoConfirmationDataType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Get the list of child KeyInfo elements. + * + * @return list of child KeyInfo elements + */ + public List getKeyInfos(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/LogoutRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/LogoutRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/LogoutRequest.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core LogoutRequest. + */ +public interface LogoutRequest extends RequestAbstractType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "LogoutRequest"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "LogoutRequestType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** Reason attribute name. */ + public static final String REASON_ATTRIB_NAME = "Reason"; + + /** NotOnOrAfter attribute name. */ + public static final String NOT_ON_OR_AFTER_ATTRIB_NAME = "NotOnOrAfter"; + + /** + * Get the Reason attrib value of the request. + * + * @return the Reason value of the request + */ + public String getReason(); + + /** + * Set the Reason attrib value of the request. + * + * @param newReason the new Reason value of the request + */ + public void setReason(String newReason); + + /** + * Get the NotOnOrAfter attrib value of the request. + * + * @return the NotOnOrAfter value of the request + */ + public DateTime getNotOnOrAfter(); + + /** + * Set the NotOnOrAfter attrib value of the request. + * + * @param newNotOnOrAfter the new NotOnOrAfter value of the request + */ + public void setNotOnOrAfter(DateTime newNotOnOrAfter); + + /** + * Gets the base identifier of the principal for this request. + * + * @return the base identifier of the principal for this request + */ + public BaseID getBaseID(); + + /** + * Sets the base identifier of the principal for this request. + * + * @param newBaseID the base identifier of the principal for this request + */ + public void setBaseID(BaseID newBaseID); + + /** + * Gets the name identifier of the principal for this request. + * + * @return the name identifier of the principal for this request + */ + public NameID getNameID(); + + /** + * Sets the name identifier of the principal for this request. + * + * @param newNameID the name identifier of the principal for this request + */ + public void setNameID(NameID newNameID); + + /** + * Gets the encrytped name identifier of the principal for this request. + * + * @return the encrytped name identifier of the principal for this request + */ + public EncryptedID getEncryptedID(); + + /** + * Sets the encrypted name identifier of the principal for this request. + * + * @param newEncryptedID the new encrypted name identifier of the principal for this request + */ + public void setEncryptedID(EncryptedID newEncryptedID); + + /** + * Get the list of SessionIndexes for the request. + * + * + * @return the list of SessionIndexes + */ + public List getSessionIndexes(); + + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/LogoutResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/LogoutResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/LogoutResponse.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core LogoutResponse. + */ +public interface LogoutResponse extends StatusResponseType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "LogoutResponse"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "LogoutResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** URI for User logout reason. */ + public static final String USER_LOGOUT_URI = "urn:oasis:names:tc:SAML:2.0:logout:user"; + + /** URI for Admin logout reason. */ + public static final String ADMIN_LOGOUT_URI = "urn:oasis:names:tc:SAML:2.0:logout:admin"; + + /** URI for global timeout logout reason. */ + public static final String GLOBAL_TIMEOUT_URI = "urn:oasis:names:tc:SAML:2.0:logout:global-timeout"; + + /** URI for SP timeout logout reason. */ + public static final String SP_TIMEOUT_URI = "urn:oasis:names:tc:SAML:2.0:logout:sp-timeout"; + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/ManageNameIDRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/ManageNameIDRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/ManageNameIDRequest.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,117 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + + +/** + * SAML 2.0 Core ManageNameIDRequest. + */ +public interface ManageNameIDRequest extends RequestAbstractType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ManageNameIDRequest"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ManageNameIDRequestType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** + * Get the NameID of the request. + * + * @return the NameID of the request + */ + public NameID getNameID(); + + /** + * Set the NameID of the request. + * + * @param newNameID the new NameID of the request + */ + public void setNameID(NameID newNameID); + + /** + * Get the EncryptedID of the request. + * + * @return the EncryptedID of the request + */ + public EncryptedID getEncryptedID(); + + /** + * Set the EncryptedID of the request. + * + * @param newEncryptedID the new EncryptedID of the request + */ + public void setEncryptedID(EncryptedID newEncryptedID); + + /** + * Get the NewID of the request. + * + * @return the NewID of the request + */ + public NewID getNewID(); + + /** + * Set the NewID of the request. + * + * @param newNewID the new NewID of the request + */ + public void setNewID(NewID newNewID); + + /** + * Get the NewEncryptedID of the request. + * + * @return the NewEncryptedID of the request + */ + public NewEncryptedID getNewEncryptedID(); + + /** + * Set the NewEncryptedID of the request. + * + * @param newNewEncryptedID the new NewEncryptedID of the request + */ + public void setNewEncryptedID(NewEncryptedID newNewEncryptedID); + + /** + * Get the Terminate of the request. + * + * @return the Terminate of the request + */ + public Terminate getTerminate(); + + /** + * Set the Terminate of the request. + * + * @param newTerminate the new NewID Terminate of the request + */ + public void setTerminate(Terminate newTerminate); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/ManageNameIDResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/ManageNameIDResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/ManageNameIDResponse.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core ManageNameIDResponse. + */ +public interface ManageNameIDResponse extends StatusResponseType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ManageNameIDResponse"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ManageNameIDResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/NameID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameID.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core NameID. + */ +public interface NameID extends SAMLObject, NameIDType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "NameID"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "NameIDType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDMappingRequest.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDMappingRequest.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDMappingRequest.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,104 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + + +/** + * SAML 2.0 Core NameIDMappingRequest. + */ +public interface NameIDMappingRequest extends RequestAbstractType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "NameIDMappingRequest"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "NameIDMappingRequestType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the base identifier of the principal for this request. + * + * @return the base identifier of the principal for this request + */ + public BaseID getBaseID(); + + /** + * Sets the base identifier of the principal for this request. + * + * @param newBaseID the base identifier of the principal for this request + */ + public void setBaseID(BaseID newBaseID); + + /** + * Gets the name identifier of the principal for this request. + * + * @return the name identifier of the principal for this request + */ + public NameID getNameID(); + + /** + * Sets the name identifier of the principal for this request. + * + * @param newNameID the name identifier of the principal for this request + */ + public void setNameID(NameID newNameID); + + /** + * Gets the encrypted name identifier of the principal for this request. + * + * @return the encrypted name identifier of the principal for this request + */ + public EncryptedID getEncryptedID(); + + /** + * Sets the encrypted name identifier of the principal for this request. + * + * @param newEncryptedID the new encrypted name identifier of the principal for this request + */ + public void setEncryptedID(EncryptedID newEncryptedID); + + /** + * Get the NameIDPolicy of the request. + * + * @return the NameIDPolicy of the request + */ + public NameIDPolicy getNameIDPolicy(); + + /** + * Set the NameIDPolicy of the request. + * + * @param newNameIDPolicy the new NameIDPolicy of the request + */ + public void setNameIDPolicy(NameIDPolicy newNameIDPolicy); + + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDMappingResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDMappingResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDMappingResponse.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core NameIDMappingResponse . + */ +public interface NameIDMappingResponse extends StatusResponseType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "NameIDMappingResponse"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static String TYPE_LOCAL_NAME = "NameIDMappingResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the name identifier of the principal for this response. + * + * @return the name identifier of the principal for this response + */ + public NameID getNameID(); + + /** + * Sets the name identifier of the principal for this response. + * + * @param newNameID the name identifier of the principal for this response + */ + public void setNameID(NameID newNameID); + + /** + * Gets the encrypted name identifier of the principal for this response. + * + * @return the encrypted name identifier of the principal for this response + */ + public EncryptedID getEncryptedID(); + + /** + * Sets the encrypted name identifier of the principal for this response. + * + * @param newEncryptedID the new encrypted name identifier of the principal for this response + */ + public void setEncryptedID(EncryptedID newEncryptedID); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDPolicy.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDPolicy.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDPolicy.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,110 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Core NameIDPolicy. + */ +public interface NameIDPolicy extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "NameIDPolicy"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "NameIDPolicyType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Format attribute name. */ + public static final String FORMAT_ATTRIB_NAME = "Format"; + + /** SPNameQualifier attribute name. */ + public static final String SP_NAME_QUALIFIER_ATTRIB_NAME = "SPNameQualifier"; + + /** AllowCreate attribute name. */ + public static final String ALLOW_CREATE_ATTRIB_NAME = "AllowCreate"; + + /** + * Gets the format of the NameIDPolicy. + * + * @return the format of the NameIDPolicy + */ + public String getFormat(); + + /** + * Sets the format of the NameIDPolicy + * + * @param newFormat the format of the NameIDPolicy + */ + public void setFormat(String newFormat); + + /** + * Gets the SPNameQualifier value. + * + * @return the SPNameQualifier value + */ + public String getSPNameQualifier(); + + /** + * Sets the SPNameQualifier value. + * + * @param newSPNameQualifier the SPNameQualifier value + */ + public void setSPNameQualifier(String newSPNameQualifier); + + /** + * Gets the AllowCreate value. + * + * @return the AllowCreate value + */ + public Boolean getAllowCreate(); + + /** + * Gets the AllowCreate value. + * + * @return the AllowCreate value + */ + public XSBooleanValue getAllowCreateXSBoolean(); + + /** + * Sets the AllowCreate value. Boolean values will be marshalled to either "true" or "false". + * + * @param newAllowCreate the AllowCreate value + */ + public void setAllowCreate(Boolean newAllowCreate); + + /** + * Sets the AllowCreate value. + * + * @param newAllowCreate the AllowCreate value + */ + public void setAllowCreate(XSBooleanValue newAllowCreate); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/NameIDType.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +/** + * SAML 2.0 Assertion NameID schema type. + */ +public interface NameIDType { + + /** NameQualifier attribute name. */ + public static final String NAME_QUALIFIER_ATTRIB_NAME = "NameQualifier"; + + /** SPNameQualifier attribute name. */ + public static final String SP_NAME_QUALIFIER_ATTRIB_NAME = "SPNameQualifier"; + + /** Format attribute name. */ + public static final String FORMAT_ATTRIB_NAME = "Format"; + + /** SPProviderID attribute name. */ + public static final String SPPROVIDED_ID_ATTRIB_NAME = "SPProvidedID"; + + /** URI for unspecified name format. */ + public static final String UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"; + + /** URI for email name format. */ + public static final String EMAIL = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"; + + /** URI for X509 subject name format. */ + public static final String X509_SUBJECT = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName"; + + /** URI for windows domain qualified name name format. */ + public static final String WIN_DOMAIN_QUALIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName"; + + /** URI for kerberos name format. */ + public static final String KERBEROS = "urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos"; + + /** URI for SAML entity name format. */ + public static final String ENTITY = "urn:oasis:names:tc:SAML:2.0:nameid-format:entity"; + + /** URI for persistent name format. */ + public static final String PERSISTENT = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"; + + /** URI for transient name format. */ + public static final String TRANSIENT = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"; + + /** Special URI used by NameIDPolicy to indicate a NameID should be encrypted. */ + public static final String ENCRYPTED = "urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted"; + + /** + * Gets the value of this type. + * + * @return the value of this type + */ + public String getValue(); + + /** + * Sets the value of this type. + * + * @param newValue the value of this type + */ + public void setValue(String newValue); + + /** + * Gets the NameQualifier value. + * + * @return the NameQualifier value + */ + public String getNameQualifier(); + + /** + * Sets the NameQualifier value. + * + * @param newNameQualifier the NameQualifier value + */ + public void setNameQualifier(String newNameQualifier); + + /** + * Gets the SPNameQualifier value. + * + * @return the SPNameQualifier value + */ + public String getSPNameQualifier(); + + /** + * Sets the SPNameQualifier value. + * + * @param newSPNameQualifier the SPNameQualifier value + */ + public void setSPNameQualifier(String newSPNameQualifier); + + /** + * Gets the format of the NameID. + * + * @return the format of the NameID + */ + public String getFormat(); + + /** + * Sets the format of the NameID. + * + * @param newFormat the format of the NameID + */ + public void setFormat(String newFormat); + + /** + * Gets the SPProvidedID of this NameID. + * + * @return the SPProvidedID of this NameID + */ + public String getSPProvidedID(); + + /** + * Sets the SPProvddedID of this NameID. + * + * @param newSPProvidedID the SPProvidedID of this NameID + */ + public void setSPProvidedID(String newSPProvidedID); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/NewEncryptedID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/NewEncryptedID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/NewEncryptedID.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core NewEncryptedID. + */ +public interface NewEncryptedID extends EncryptedElementType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "NewEncryptedID"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/NewID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/NewID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/NewID.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core NewID. + */ +public interface NewID extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "NewID"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Get NewID value. + * + * @return NewID value + */ + public String getNewID(); + + /** + * Set NewID value. + * + * @param newNewID the new NewID value + */ + public void setNewID(String newNewID); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/OneTimeUse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/OneTimeUse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/OneTimeUse.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core OneTimeUse. + * + */ +public interface OneTimeUse extends Condition { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "OneTimeUse"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "OneTimeUseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/ProxyRestriction.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/ProxyRestriction.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/ProxyRestriction.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core ProxyRestriction. + */ +public interface ProxyRestriction extends Condition { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ProxyRestriction"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ProxyRestrictionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Count attribute name. */ + public static final String COUNT_ATTRIB_NAME = "Count"; + + /** + * Gets the number of times the assertion may be proxied. + * + * @return the number of times the assertion may be proxied + */ + public Integer getProxyCount(); + + /** + * Sets the number of times the assertion may be proxied. + * + * @param newProxyCount the number of times the assertion may be proxied + */ + public void setProxyCount(Integer newProxyCount); + + /** + * Gets the list of audiences to whom the assertion may be proxied. + * + * @return the list of audiences to whom the assertion may be proxied + */ + public List getAudiences(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/RequestAbstractType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/RequestAbstractType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/RequestAbstractType.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,176 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; + +/** + * SAML 2.0 Core RequestAbstractType. + */ +public interface RequestAbstractType extends SignableSAMLObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestAbstractType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** ID attribute name. */ + public static final String ID_ATTRIB_NAME = "ID"; + + /** Version attribute name. */ + public static final String VERSION_ATTRIB_NAME = "Version"; + + /** IssueInstant attribute name. */ + public static final String ISSUE_INSTANT_ATTRIB_NAME = "IssueInstant"; + + /** Destination attribute name. */ + public static final String DESTINATION_ATTRIB_NAME = "Destination"; + + /** Consent attribute name. */ + public static final String CONSENT_ATTRIB_NAME = "Consent"; + + /** Unspecified consent URI. */ + public static final String UNSPECIFIED_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:unspecified"; + + /** Obtained consent URI. */ + public static final String OBTAINED_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:obtained"; + + /** Prior consent URI. */ + public static final String PRIOR_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:prior"; + + /** Implicit consent URI. */ + public static final String IMPLICIT_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:current-implicit"; + + /** Explicit consent URI. */ + public static final String EXPLICIT_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:current-explicit"; + + /** Unavailable consent URI. */ + public static final String UNAVAILABLE_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:unavailable"; + + /** Inapplicable consent URI. */ + public static final String INAPPLICABLE_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:inapplicable"; + + /** + * Gets the SAML Version of this request. + * + * @return the SAML Version of this request. + */ + public SAMLVersion getVersion(); + + /** + * Sets the SAML Version of this request. + * + * @param newVersion the SAML Version of this request + */ + public void setVersion(SAMLVersion newVersion); + + /** + * Gets the unique identifier of the request. + * + * @return the unique identifier of the request + */ + public String getID(); + + /** + * Sets the unique identifier of the request. + * + * @param newID the unique identifier of the request + */ + + public void setID(String newID); + + /** + * Gets the date/time the request was issued. + * + * @return the date/time the request was issued + */ + + public DateTime getIssueInstant(); + + /** + * Sets the date/time the request was issued. + * + * @param newIssueInstant the date/time the request was issued + */ + public void setIssueInstant(DateTime newIssueInstant); + + /** + * Gets the URI of the destination of the request. + * + * @return the URI of the destination of the request + */ + public String getDestination(); + + /** + * Sets the URI of the destination of the request. + * + * @param newDestination the URI of the destination of the request + */ + public void setDestination(String newDestination); + + /** + * Gets the consent obtained from the principal for sending this request. + * + * @return the consent obtained from the principal for sending this request + */ + public String getConsent(); + + /** + * Sets the consent obtained from the principal for sending this request. + * + * @param newConsent the new consent obtained from the principal for sending this request + */ + public void setConsent(String newConsent); + + /** + * Gets the issuer of this request. + * + * @return the issuer of this request + */ + public Issuer getIssuer(); + + /** + * Sets the issuer of this request. + * + * @param newIssuer the issuer of this request + */ + public void setIssuer(Issuer newIssuer); + + /** + * Gets the Extensions of this request. + * + * @return the Status of this request + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions of this request. + * + * @param newExtensions the Extensions of this request + */ + public void setExtensions(Extensions newExtensions); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/RequestedAuthnContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/RequestedAuthnContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/RequestedAuthnContext.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core RequestedAuthnContext. + */ +public interface RequestedAuthnContext extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RequestedAuthnContext"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** SessionIndex attribute name. */ + public static final String COMPARISON_ATTRIB_NAME = "Comparison"; + + /** + * Gets the Comparison attribute value of the requested authn context. + * + * @return the Comparison attribute value of the requested authn context + */ + public AuthnContextComparisonTypeEnumeration getComparison(); + + /** + * Sets the Comparison attribute value of the requested authn context. + * + * @param newComparison the SessionIndex of this request + */ + public void setComparison(AuthnContextComparisonTypeEnumeration newComparison); + + /** + * Gets the AuthnContextClassRefs of this request. + * + * @return the AuthnContextClassRefs of this request + */ + public List getAuthnContextClassRefs(); + + /** + * Gets the AuthnContextDeclRefs of this request. + * + * @return the AuthnContextDeclRef of this request + */ + public List getAuthnContextDeclRefs(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/RequesterID.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/RequesterID.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/RequesterID.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core RequesterID. + */ +public interface RequesterID extends SAMLObject { + + /** Element Local Name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RequesterID"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the RequesterID value. + * + * @return RequesterID value + */ + public String getRequesterID(); + + /** + * Sets the RequesterID value. + * + * @param newRequesterID the RequesterID value + */ + public void setRequesterID(String newRequesterID); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Response.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Response.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Response.java 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Response. + */ +public interface Response extends StatusResponseType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Response"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + + /** + * Return the list of Assertion child elements. + * + * @return the list of Assertion child elements + */ + public List getAssertions(); + + /** + * Return the list of EncryptedAssertion child elements. + * + * @return the list of EncryptedAssertion child elements + */ + public List getEncryptedAssertions(); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Scoping.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Scoping.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Scoping.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Scoping. + */ +public interface Scoping extends SAMLObject { + + /** Element Local Name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Scoping"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** ProxyCount attribute name. */ + public static final String PROXY_COUNT_ATTRIB_NAME = "ProxyCount"; + + /** + * Gets the ProxyCount attrib value. + * + * @return the ProxyCount attrib value + */ + public Integer getProxyCount(); + + /** + * Sets the ProxyCount attrib value. + * + * @param newProxyCount the new ProxyCount attrib value + */ + public void setProxyCount(Integer newProxyCount); + + /** + * Gets the IDPList. + * + * @return IDPList + */ + public IDPList getIDPList(); + + /** + * Sets the IDPList. + * + * @param newIDPList the new IDPList + */ + public void setIDPList(IDPList newIDPList); + + /** + * Gets the list of RequesterID's. + * + * @return list of RequesterID's + */ + public List getRequesterIDs(); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/SessionIndex.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/SessionIndex.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/SessionIndex.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core SessionIndex. + */ +public interface SessionIndex extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SessionIndex"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the session index value of the request. + * + * @return the session index value of the request + */ + public String getSessionIndex(); + + /** + * Sets the session index value of the request. + * + * @param newSessionIndex the new session index value of the request + */ + public void setSessionIndex(String newSessionIndex); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Statement.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Statement.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Statement.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Statement. This is a marker interface that all statement types must implement. + */ +public interface Statement extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Statement"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatementAbstractType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Status.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Status.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Status.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Status. + */ +public interface Status extends SAMLObject { + + /** Local Name of Status. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Status"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the Code of this Status. + * + * @return Status StatusCode + */ + public StatusCode getStatusCode(); + + /** + * Sets the Code of this Status. + * + * @param newStatusCode the Code of this Status + */ + public void setStatusCode(StatusCode newStatusCode); + + /** + * Gets the Message of this Status. + * + * @return Status StatusMessage + */ + public StatusMessage getStatusMessage(); + + /** + * Sets the Message of this Status. + * + * @param newStatusMessage the Message of this Status + */ + public void setStatusMessage(StatusMessage newStatusMessage); + + /** + * Gets the Detail of this Status. + * + * @return Status StatusDetail + */ + public StatusDetail getStatusDetail(); + + /** + * Sets the Detail of this Status. + * + * @param newStatusDetail the Detail of this Status + */ + public void setStatusDetail(StatusDetail newStatusDetail); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusCode.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusCode.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusCode.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,147 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core StatusCode. + */ +public interface StatusCode extends SAMLObject { + + /** Local Name of StatusCode. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "StatusCode"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusCodeType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local Name of the Value attribute. */ + public static final String VALUE_ATTRIB_NAME = "Value"; + + /** URI for Success status code. */ + public static final String SUCCESS_URI = "urn:oasis:names:tc:SAML:2.0:status:Success"; + + /** URI for Requester status code. */ + public static final String REQUESTER_URI = "urn:oasis:names:tc:SAML:2.0:status:Requester"; + + /** URI for Responder status code. */ + public static final String RESPONDER_URI = "urn:oasis:names:tc:SAML:2.0:status:Responder"; + + /** URI for VersionMismatch status code. */ + public static final String VERSION_MISMATCH_URI = "urn:oasis:names:tc:SAML:2.0:status:VersionMismatch"; + + /** URI for AuthnFailed status code. */ + public static final String AUTHN_FAILED_URI = "urn:oasis:names:tc:SAML:2.0:status:AuthnFailed"; + + /** URI for InvalidAttrNameOrValue status code. */ + public static final String INVALID_ATTR_NAME_VALUE_URI = "urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue"; + + /** URI for InvalidNameIDPolicy status code. */ + public static final String INVALID_NAMEID_POLICY_URI = "urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy"; + + /** URI for NoAuthnContext status code. */ + public static final String NO_AUTHN_CONTEXT_URI = "urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext"; + + /** URI for NoAvailableIDP status code. */ + public static final String NO_AVAILABLE_IDP_URI = "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP"; + + /** URI for NoPassive status code. */ + public static final String NO_PASSIVE_URI = "urn:oasis:names:tc:SAML:2.0:status:NoPassive"; + + /** URI for NoSupportedIDP status code. */ + public static final String NO_SUPPORTED_IDP_URI = "urn:oasis:names:tc:SAML:2.0:status:NoSupportedIDP"; + + /** URI for PartialLogout status code. */ + public static final String PARTIAL_LOGOUT_URI = "urn:oasis:names:tc:SAML:2.0:status:PartialLogout"; + + /** URI for ProxyCountExceeded status code. */ + public static final String PROXY_COUNT_EXCEEDED_URI = "urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded"; + + /** URI for RequestDenied status code. */ + public static final String REQUEST_DENIED_URI = "urn:oasis:names:tc:SAML:2.0:status:RequestDenied"; + + /** URI for RequestUnsupported status code. */ + public static final String REQUEST_UNSUPPORTED_URI = "urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported"; + + /** URI for RequestVersionDeprecated status code. */ + public static final String REQUEST_VERSION_DEPRECATED_URI = "urn:oasis:names:tc:SAML:2.0:status:RequestVersionDeprecated"; + + /** URI for RequestVersionTooHigh status code. */ + public static final String REQUEST_VERSION_TOO_HIGH_URI = "urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooHigh"; + + /** URI for RequestVersionTooLow status code. */ + public static final String REQUEST_VERSION_TOO_LOW_URI = "urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooLow"; + + /** URI for ResourceNotRecognized status code. */ + public static final String RESOURCE_NOT_RECOGNIZED_URI = "urn:oasis:names:tc:SAML:2.0:status:ResourceNotRecognized"; + + /** URI for TooManyResponses status code. */ + public static final String TOO_MANY_RESPONSES = "urn:oasis:names:tc:SAML:2.0:status:TooManyResponses"; + + /** URI for UnknownAttrProfile status code. */ + public static final String UNKNOWN_ATTR_PROFILE_URI = "urn:oasis:names:tc:SAML:2.0:status:UnknownAttrProfile"; + + /** URI for UnknownPrincipal status code. */ + public static final String UNKNOWN_PRINCIPAL_URI = "urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal"; + + /** URI for UnsupportedBinding status code. */ + public static final String UNSUPPORTED_BINDING_URI = "urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding"; + + /** + * Gets the Status Code of this Status Code. + * + * @return StatusCode StatusCode + */ + public StatusCode getStatusCode(); + + /** + * Sets the Status Code of this Status Code. + * + * @param newStatusCode the Status Code of this Status Code. + */ + public void setStatusCode(StatusCode newStatusCode); + + /** + * Gets the Value of this Status Code. + * + * @return StatusCode Value + */ + public String getValue(); + + /** + * Sets the Value of this Status Code. + * + * @param newValue the Value of this Status Code + */ + public void setValue(String newValue); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusDetail.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusDetail.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusDetail.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SAML 2.0 Core StatusDetail. + */ +public interface StatusDetail extends SAMLObject, ElementExtensibleXMLObject { + + /** Local Name of StatusDetail. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "StatusDetail"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusDetailType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusMessage.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusMessage.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusMessage.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core StatusMessage. + */ +public interface StatusMessage extends SAMLObject { + + /** Local Name of StatusMessage. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "StatusMessage"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the Message of this Status Message. + * + * @return StatusMessage message + */ + public String getMessage(); + + /** + * Sets the Message of this Status Message. + * + * @param newMessage the Message of this Status Message + */ + public void setMessage(String newMessage); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusResponseType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusResponseType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/StatusResponseType.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,211 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; + +/** + * SAML 2.0 Core StatusResponseType. + */ +public interface StatusResponseType extends SignableSAMLObject { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "StatusResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** ID attribute name. */ + public static final String ID_ATTRIB_NAME = "ID"; + + /** InResponseTo attribute name. */ + public static final String IN_RESPONSE_TO_ATTRIB_NAME = "InResponseTo"; + + /** Version attribute name. */ + public static final String VERSION_ATTRIB_NAME = "Version"; + + /** IssueInstant attribute name. */ + public static final String ISSUE_INSTANT_ATTRIB_NAME = "IssueInstant"; + + /** Destination attribute name. */ + public static final String DESTINATION_ATTRIB_NAME = "Destination"; + + /** Consent attribute name. */ + public static final String CONSENT_ATTRIB_NAME = "Consent"; + + /** Unspecified consent URI. */ + public static final String UNSPECIFIED_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:unspecified"; + + /** Obtained consent URI. */ + public static final String OBTAINED_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:obtained"; + + /** Prior consent URI. */ + public static final String PRIOR_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:prior"; + + /** Implicit consent URI. */ + public static final String IMPLICIT_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:current-implicit"; + + /** Explicit consent URI. */ + public static final String EXPLICIT_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:current-explicit"; + + /** Unavailable consent URI. */ + public static final String UNAVAILABLE_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:unavailable"; + + /** Inapplicable consent URI. */ + public static final String INAPPLICABLE_CONSENT = "urn:oasis:names:tc:SAML:2.0:consent:inapplicable"; + + /** + * Gets the SAML Version of this response. + * + * @return the SAML Version of this response. + */ + public SAMLVersion getVersion(); + + /** + * Sets the SAML Version of this response. + * + * @param newVersion the SAML Version of this response + */ + public void setVersion(SAMLVersion newVersion); + + /** + * Gets the unique identifier of the response. + * + * @return the unique identifier of the response + */ + public String getID(); + + /** + * Sets the unique identifier of the response. + * + * @param newID the unique identifier of the response + */ + + public void setID(String newID); + + /** + * Gets the unique request identifier for which this is a response + * + * @return the unique identifier of the originating request + */ + public String getInResponseTo(); + + /** + * Sets the unique request identifier for which this is a response + * + * @param newInResponseTo the unique identifier of the originating request + */ + + public void setInResponseTo(String newInResponseTo); + + /** + * Gets the date/time the response was issued. + * + * @return the date/time the response was issued + */ + public DateTime getIssueInstant(); + + /** + * Sets the date/time the response was issued. + * + * param newIssueInstant the date/time the response was issued + */ + public void setIssueInstant(DateTime newIssueInstant); + + /** + * Gets the URI of the destination of the response. + * + * @return the URI of the destination of the response + */ + public String getDestination(); + + /** + * Sets the URI of the destination of the response. + * + * @param newDestination the URI of the destination of the response + */ + public void setDestination(String newDestination); + + /** + * Gets the consent obtained from the principal for sending this response. + * + * @return the consent obtained from the principal for sending this response + */ + public String getConsent(); + + /** + * Sets the consent obtained from the principal for sending this response. + * + * @param newConsent the consent obtained from the principal for sending this response + */ + public void setConsent(String newConsent); + + /** + * Gets the issuer of this response. + * + * @return the issuer of this response + */ + public Issuer getIssuer(); + + /** + * Sets the issuer of this response. + * + * @param newIssuer the issuer of this response + */ + public void setIssuer(Issuer newIssuer); + + /** + * Gets the Status of this response. + * + * @return the Status of this response + */ + public Status getStatus(); + + /** + * Sets the Status of this response. + * + * @param newStatus the Status of this response + */ + public void setStatus(Status newStatus); + + /** + * Gets the Extensions of this response. + * + * @return the Status of this response + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions of this response. + * + * @param newExtensions the Extensions of this response + */ + public void setExtensions(Extensions newExtensions); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Subject.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Subject.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Subject.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Subject. + */ +public interface Subject extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Subject"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SubjectType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** + * Gets the base identifier of the principal for this request. + * + * @return the base identifier of the principal for this request + */ + public BaseID getBaseID(); + + /** + * Sets the base identifier of the principal for this request. + * + * @param newBaseID the base identifier of the principal for this request + */ + public void setBaseID(BaseID newBaseID); + + /** + * Gets the name identifier of the principal for this request. + * + * @return the name identifier of the principal for this request + */ + public NameID getNameID(); + + /** + * Sets the name identifier of the principal for this request. + * + * @param newNameID the name identifier of the principal for this request + */ + public void setNameID(NameID newNameID); + + /** + * Gets the encrypted name identifier of the principal for this request. + * + * @return the encrypted name identifier of the principal for this request + */ + public EncryptedID getEncryptedID(); + + /** + * Sets the encrypted name identifier of the principal for this request. + * + * @param newEncryptedID the new encrypted name identifier of the principal for this request + */ + public void setEncryptedID(EncryptedID newEncryptedID); + + /** + * Gets the confirmations made about this subject. + * + * @return the confirmations made about this subject + */ + public List getSubjectConfirmations(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectConfirmation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectConfirmation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectConfirmation.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,126 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core SubjectConfirmation. + */ +public interface SubjectConfirmation extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectConfirmation"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SubjectConfirmationType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Method attribute name. */ + public static final String METHOD_ATTRIB_NAME = "Method"; + + /** URI for the Holder of Key subject confirmation method, {@value}. */ + public static final String METHOD_HOLDER_OF_KEY = "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"; + + /** URI for the Sender Vouches subject confirmation method, {@value}. */ + public static final String METHOD_SENDER_VOUCHES = "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches"; + + /** URI for the Bearer subject confirmation method, {@value}. */ + public static final String METHOD_BEARER = "urn:oasis:names:tc:SAML:2.0:cm:bearer"; + + /** + * Get the method used to confirm this subject. + * + * @return the method used to confirm this subject + */ + public String getMethod(); + + /** + * Sets the method used to confirm this subject. + * + * @param newMethod the method used to confirm this subject + */ + public void setMethod(String newMethod); + + /** + * Gets the base identifier of the principal for this request. + * + * @return the base identifier of the principal for this request + */ + public BaseID getBaseID(); + + /** + * Sets the base identifier of the principal for this request. + * + * @param newBaseID the base identifier of the principal for this request + */ + public void setBaseID(BaseID newBaseID); + + /** + * Gets the name identifier of the principal for this request. + * + * @return the name identifier of the principal for this request + */ + public NameID getNameID(); + + /** + * Sets the name identifier of the principal for this request. + * + * @param newNameID the name identifier of the principal for this request + */ + public void setNameID(NameID newNameID); + + /** + * Gets the encrypted name identifier of the principal for this request. + * + * @return the encrypted name identifier of the principal for this request + */ + public EncryptedID getEncryptedID(); + + /** + * Sets the encrypted name identifier of the principal for this request. + * + * @param newEncryptedID the new encrypted name identifier of the principal for this request + */ + public void setEncryptedID(EncryptedID newEncryptedID); + + /** + * Gets the data about how this subject was confirmed or constraints on the confirmation. + * + * @return the data about how this subject was confirmed or constraints on the confirmation + */ + public SubjectConfirmationData getSubjectConfirmationData(); + + /** + * Sets the data about how this subject was confirmed or constraints on the confirmation. + * + * @param newSubjectConfirmationData the data about how this subject was confirmed or constraints on the + * confirmation + */ + public void setSubjectConfirmationData(SubjectConfirmationData newSubjectConfirmationData); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectConfirmationData.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectConfirmationData.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectConfirmationData.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,131 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SAML 2.0 Core SubjectConfirmationData. + */ +public interface SubjectConfirmationData extends SAMLObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectConfirmationData"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SubjectConfirmationDataType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** NotBefore attribute name. */ + public static final String NOT_BEFORE_ATTRIB_NAME = "NotBefore"; + + /** NotOnOrAfter attribute name. */ + public static final String NOT_ON_OR_AFTER_ATTRIB_NAME = "NotOnOrAfter"; + + /** Recipient attribute name. */ + public static final String RECIPIENT_ATTRIB_NAME = "Recipient"; + + /** InResponseTo attribute name. */ + public static final String IN_RESPONSE_TO_ATTRIB_NAME = "InResponseTo"; + + /** Address attribute name. */ + public static final String ADDRESS_ATTRIB_NAME = "Address"; + + /** + * Gets the time before which this subject is not valid. + * + * @return the time before which this subject is not valid + */ + public DateTime getNotBefore(); + + /** + * Sets the time before which this subject is not valid. + * + * @param newNotBefore the time before which this subject is not valid + */ + public void setNotBefore(DateTime newNotBefore); + + /** + * Gets the time at, or after, which this subject is not valid. + * + * @return the time at, or after, which this subject is not valid + */ + public DateTime getNotOnOrAfter(); + + /** + * Sets the time at, or after, which this subject is not valid. + * + * @param newNotOnOrAfter the time at, or after, which this subject is not valid + */ + public void setNotOnOrAfter(DateTime newNotOnOrAfter); + + /** + * Gets the recipient of this subject. + * + * @return the recipient of this subject + */ + public String getRecipient(); + + /** + * Sets the recipient of this subject. + * + * @param newRecipient the recipient of this subject + */ + public void setRecipient(String newRecipient); + + /** + * Gets the message ID this is in response to. + * + * @return the message ID this is in response to + */ + public String getInResponseTo(); + + /** + * Sets the message ID this is in response to. + * + * @param newInResponseTo the message ID this is in response to + */ + public void setInResponseTo(String newInResponseTo); + + /** + * Gets the IP address to which this information may be pressented. + * + * @return the IP address to which this information may be pressented + */ + public String getAddress(); + + /** + * Sets the IP address to which this information may be pressented. + * + * @param newAddress the IP address to which this information may be pressented + */ + public void setAddress(String newAddress); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectLocality.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectLocality.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectLocality.java 17 Aug 2012 15:03:36 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core SubjectLocality. + */ +public interface SubjectLocality extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectLocality"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SubjectLocalityType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + + /** Address attribute name. */ + public static final String ADDRESS_ATTRIB_NAME = "Address"; + + /** DNSName attribute name. */ + public static final String DNS_NAME_ATTRIB_NAME = "DNSName"; + + /** + * Gets the IP address of the system from which the subject was authenticated. + * + * @return the IP address of the system from which the subject was authenticated + */ + public String getAddress(); + + /** + * Sets the IP address of the system from which the subject was authenticated. + * + * @param newAddress the IP address of the system from which the subject was authenticated + */ + public void setAddress(String newAddress); + + /** + * Gets the DNSName of the system from which the subject was authenticated. + * + * @return the DNSName of the system from which the subject was authenticated + */ + public String getDNSName(); + + /** + * Sets the DNSName of the system from which the subject was authenticated. + * + * @param newDNSName the DNSName of the system from which the subject was authenticated + */ + public void setDNSName(String newDNSName); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectQuery.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectQuery.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/SubjectQuery.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core SubjectQuery. + */ +public interface SubjectQuery extends RequestAbstractType { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectQuery"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "SubjectQueryAbstractType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** + * Gets the Subject of this request. + * + * @return the Subject of this request + */ + public Subject getSubject(); + + /** + * Sets the Subject of this request. + * + * @param newSubject the Subject of this request + */ + public void setSubject(Subject newSubject); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/Terminate.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/Terminate.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/Terminate.java 17 Aug 2012 15:03:34 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Core Terminate + */ +public interface Terminate extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Terminate"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20P_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "TerminateType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20P_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/package.html 17 Aug 2012 15:03:35 -0000 1.1 @@ -0,0 +1,14 @@ + + +Interfaces for SAML 2.0 core specification types and elements. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDType.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.xml.XMLObject; + +/** + * Abstract implementation of {@link org.opensaml.saml2.core.NameIDType}. + */ +public class AbstractNameIDType extends AbstractSAMLObject implements NameIDType { + + /** Name of the Name ID. */ + private String name; + + /** Name Qualifier of the Name ID. */ + private String nameQualifier; + + /** SP Name Qualifier of the Name ID. */ + private String spNameQualifier; + + /** Format of the Name ID. */ + private String format; + + /** SP ProvidedID of the NameID. */ + private String spProvidedID; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AbstractNameIDType(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValue() { + return name; + } + + /** {@inheritDoc} */ + public void setValue(String newName) { + this.name = prepareForAssignment(this.name, newName); + } + + /** {@inheritDoc} */ + public String getNameQualifier() { + return nameQualifier; + } + + /** {@inheritDoc} */ + public void setNameQualifier(String newNameQualifier) { + this.nameQualifier = prepareForAssignment(this.nameQualifier, newNameQualifier); + } + + /** {@inheritDoc} */ + public String getSPNameQualifier() { + return spNameQualifier; + } + + /** {@inheritDoc} */ + public void setSPNameQualifier(String newSPNameQualifier) { + this.spNameQualifier = prepareForAssignment(this.spNameQualifier, newSPNameQualifier); + } + + /** {@inheritDoc} */ + public String getFormat() { + return format; + } + + /** {@inheritDoc} */ + public void setFormat(String newFormat) { + this.format = prepareForAssignment(this.format, newFormat); + } + + /** {@inheritDoc} */ + public String getSPProvidedID() { + return spProvidedID; + } + + /** {@inheritDoc} */ + public void setSPProvidedID(String newSPProvidedID) { + this.spProvidedID = prepareForAssignment(this.spProvidedID, newSPProvidedID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDTypeMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.NameIDType} objects. + */ +public abstract class AbstractNameIDTypeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + NameIDType nameID = (NameIDType) samlObject; + + if (nameID.getNameQualifier() != null) { + domElement.setAttributeNS(null, NameID.NAME_QUALIFIER_ATTRIB_NAME, nameID.getNameQualifier()); + } + + if (nameID.getSPNameQualifier() != null) { + domElement.setAttributeNS(null, NameID.SP_NAME_QUALIFIER_ATTRIB_NAME, nameID.getSPNameQualifier()); + } + + if (nameID.getFormat() != null) { + domElement.setAttributeNS(null, NameID.FORMAT_ATTRIB_NAME, nameID.getFormat()); + } + + if (nameID.getSPProvidedID() != null) { + domElement.setAttributeNS(null, NameID.SPPROVIDED_ID_ATTRIB_NAME, nameID.getSPProvidedID()); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + NameIDType nameID = (NameIDType) samlObject; + XMLHelper.appendTextContent(domElement, nameID.getValue()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AbstractNameIDTypeUnmarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.NameIDType} objects. + */ +public abstract class AbstractNameIDTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + NameIDType nameID = (NameIDType) samlObject; + if (attribute.getLocalName().equals(NameID.NAME_QUALIFIER_ATTRIB_NAME)) { + nameID.setNameQualifier(attribute.getValue()); + } else if (attribute.getLocalName().equals(NameID.SP_NAME_QUALIFIER_ATTRIB_NAME)) { + nameID.setSPNameQualifier(attribute.getValue()); + } else if (attribute.getLocalName().equals(NameID.FORMAT_ATTRIB_NAME)) { + nameID.setFormat(attribute.getValue()); + } else if (attribute.getLocalName().equals(NameID.SPPROVIDED_ID_ATTRIB_NAME)) { + nameID.setSPProvidedID(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + NameIDType nameID = (NameIDType) samlObject; + nameID.setValue(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionBuilder.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Action; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.ActionImpl} objects. + */ +public class ActionBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public ActionBuilder() { + + } + + /** {@inheritDoc} */ + public Action buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Action.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Action buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionImpl.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Action; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.Action}. + */ +public class ActionImpl extends AbstractSAMLObject implements Action { + + /** URI of the Namespace of this Action. */ + private String namespace; + + /** Action value. */ + private String action; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ActionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getNamespace() { + return namespace; + } + + /** {@inheritDoc} */ + public void setNamespace(String newNamespace) { + this.namespace = prepareForAssignment(this.namespace, newNamespace); + } + + /** {@inheritDoc} */ + public String getAction() { + return action; + } + + /** {@inheritDoc} */ + public void setAction(String newAction) { + this.action = prepareForAssignment(this.action, newAction); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionMarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.Action; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Action}. + */ +public class ActionMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + Action action = (Action) samlObject; + + if (action.getNamespace() != null) { + domElement.setAttributeNS(null, Action.NAMEPSACE_ATTRIB_NAME, action.getNamespace()); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Action action = (Action) samlObject; + XMLHelper.appendTextContent(domElement, action.getAction()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ActionUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Action; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Action}. + */ +public class ActionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Action action = (Action) samlObject; + + if (attribute.getLocalName().equals(Action.NAMEPSACE_ATTRIB_NAME)) { + action.setNamespace(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Action action = (Action) samlObject; + action.setAction(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceBuilder.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Advice; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AdviceImpl} objects. + */ +public class AdviceBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AdviceBuilder() { + } + + /** {@inheritDoc} */ + public Advice buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Advice.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Advice buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AdviceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceImpl.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Advice; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.saml2.core.AssertionURIRef; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.Advice}. + */ +public class AdviceImpl extends AbstractSAMLObject implements Advice { + + /** Children. */ + private final IndexedXMLObjectChildrenList indexedChildren; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AdviceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + indexedChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getChildren() { + return indexedChildren; + } + + /** {@inheritDoc} */ + public List getChildren(QName typeOrName) { + return (List) indexedChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getAssertionIDReferences() { + return (List) indexedChildren.subList(AssertionIDRef.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getAssertionURIReferences() { + return (List) indexedChildren.subList(AssertionURIRef.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getAssertions() { + return (List) indexedChildren.subList(Assertion.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getEncryptedAssertions() { + return (List) indexedChildren.subList(EncryptedAssertion.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(indexedChildren); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe marshaller for {@link org.opensaml.saml2.core.Advice}. + */ +public class AdviceMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AdviceUnmarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Advice; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Advice}. + */ +public class AdviceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + Advice advice = (Advice) parentObject; + + // This is an unbounded choice over several unrelated elements, and the wildcard element. + advice.getChildren().add(childObject); + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactBuilder.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Artifact; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.ArtifactImpl} objects. + */ +public class ArtifactBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ArtifactBuilder() { + } + + /** {@inheritDoc} */ + public Artifact buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, Artifact.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public Artifact buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ArtifactImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactImpl.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Artifact; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Artifact}. + */ +public class ArtifactImpl extends AbstractSAMLObject implements Artifact { + + /** Artifact data. */ + private String artifact; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ArtifactImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getArtifact() { + return this.artifact; + } + + /** {@inheritDoc} */ + public void setArtifact(String newArtifact) { + this.artifact = prepareForAssignment(this.artifact, newArtifact); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.Artifact; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Artifact}. + */ +public class ArtifactMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Artifact artifact = (Artifact) samlObject; + + if (artifact.getArtifact() != null) { + XMLHelper.appendTextContent(domElement, artifact.getArtifact()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.ArtifactResolve; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.ArtifactResolveImpl} objects. + */ +public class ArtifactResolveBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ArtifactResolveBuilder() { + + } + + /** {@inheritDoc} */ + public ArtifactResolve buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, ArtifactResolve.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public ArtifactResolve buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ArtifactResolveImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveImpl.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.Artifact; +import org.opensaml.saml2.core.ArtifactResolve; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.ArtifactResolve}. + */ +public class ArtifactResolveImpl extends RequestAbstractTypeImpl implements ArtifactResolve { + + /** Artifact child element. */ + private Artifact artifact; + + /** + * Constructor. + * + * @param namespaceURI namespace uri + * @param elementLocalName element name + * @param namespacePrefix namespace prefix + */ + protected ArtifactResolveImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Artifact getArtifact() { + return this.artifact; + } + + /** {@inheritDoc} */ + public void setArtifact(Artifact newArtifact) { + this.artifact = prepareForAssignment(this.artifact, newArtifact); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + if (artifact != null) { + children.add(artifact); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.ArtifactResolve}. + */ +public class ArtifactResolveMarshaller extends RequestAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResolveUnmarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.Artifact; +import org.opensaml.saml2.core.ArtifactResolve; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.ArtifactResolve}. + */ +public class ArtifactResolveUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + ArtifactResolve ar = (ArtifactResolve) parentSAMLObject; + + if (childSAMLObject instanceof Artifact) { + ar.setArtifact((Artifact) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.ArtifactResponse; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.ArtifactResponseImpl} objects. + */ +public class ArtifactResponseBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ArtifactResponseBuilder() { + + } + + /** {@inheritDoc} */ + public ArtifactResponse buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, ArtifactResponse.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public ArtifactResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ArtifactResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseImpl.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.core.ArtifactResponse; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.ArtifactResponse}. + */ +public class ArtifactResponseImpl extends StatusResponseTypeImpl implements ArtifactResponse { + + /** Protocol message. */ + private SAMLObject protocolMessage; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ArtifactResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public SAMLObject getMessage() { + return protocolMessage; + } + + /** {@inheritDoc} */ + public void setMessage(SAMLObject message) { + protocolMessage = prepareForAssignment(protocolMessage, message); + } + + /** + * {@inheritDoc} + */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.add(protocolMessage); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseMarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.ArtifactResponse}. + */ +public class ArtifactResponseMarshaller extends StatusResponseTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactResponseUnmarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.core.ArtifactResponse; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.Status; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.ArtifactResponse}. + */ +public class ArtifactResponseUnmarshaller extends StatusResponseTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + ArtifactResponse artifactResponse = (ArtifactResponse) parentSAMLObject; + + if (childSAMLObject instanceof Issuer) { + artifactResponse.setIssuer((Issuer) childSAMLObject); + } else if (childSAMLObject instanceof Signature) { + artifactResponse.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof Extensions) { + artifactResponse.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof Status) { + artifactResponse.setStatus((Status) childSAMLObject); + } else { + artifactResponse.setMessage((SAMLObject) childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ArtifactUnmarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Artifact; +import org.opensaml.xml.XMLObject; + +/** + * A thead-safe Unmarshaller for {@link org.opensaml.saml2.core.Artifact}. + */ +public class ArtifactUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Artifact artifact = (Artifact) samlObject; + + artifact.setArtifact(elementContent); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Assertion; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AssertionImpl} objects. + */ +public class AssertionBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AssertionBuilder() { + + } + + /** {@inheritDoc} */ + public Assertion buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Assertion.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Assertion buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AssertionIDRef; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AssertionIDRefImpl}. + */ +public class AssertionIDRefBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AssertionIDRefBuilder() { + + } + + /** {@inheritDoc} */ + public AssertionIDRef buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AssertionIDRef.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionIDRef buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionIDRefImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefImpl.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.AssertionIDRef}. + */ +public class AssertionIDRefImpl extends AbstractSAMLObject implements AssertionIDRef { + + /** ID Ref of the Assertion. */ + private String assertionID; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AssertionIDRefImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAssertionID() { + return assertionID; + } + + /** {@inheritDoc} */ + public void setAssertionID(String newIDRef) { + this.assertionID = prepareForAssignment(this.assertionID, newIDRef); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AssertionIDRef}. + */ +public class AssertionIDRefMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AssertionIDRef assertionIDRef = (AssertionIDRef) samlObject; + XMLHelper.appendTextContent(domElement, assertionIDRef.getAssertionID()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRefUnmarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.xml.XMLObject; + +/** + * A thead-safe Unmarshaller for {@link org.opensaml.saml2.core.AssertionIDRef}. + */ +public class AssertionIDRefUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AssertionIDRef assertionIDRef = (AssertionIDRef) samlObject; + assertionIDRef.setAssertionID(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AssertionIDRequest; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.AssertionIDRequestImpl}. + */ +public class AssertionIDRequestBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public AssertionIDRequestBuilder() { + } + + /** {@inheritDoc} */ + public AssertionIDRequest buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, AssertionIDRequest.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionIDRequest buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionIDRequestImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestImpl.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.saml2.core.AssertionIDRequest; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AssertionIDRequest}. + */ +public class AssertionIDRequestImpl extends RequestAbstractTypeImpl implements AssertionIDRequest { + + /** List of AssertionIDRef child elements. */ + private final XMLObjectChildrenList assertionIDRefs; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AssertionIDRequestImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + assertionIDRefs = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAssertionIDRefs() { + return assertionIDRefs; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + children.addAll(assertionIDRefs); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestMarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AssertionIDRequest}. + */ +public class AssertionIDRequestMarshaller extends RequestAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionIDRequestUnmarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.saml2.core.AssertionIDRequest; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thead-safe Unmarshaller for {@link org.opensaml.saml2.core.AssertionIDRequest}. + */ +public class AssertionIDRequestUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AssertionIDRequest idRequest = (AssertionIDRequest) parentSAMLObject; + + if (childSAMLObject instanceof AssertionIDRef) { + idRequest.getAssertionIDRefs().add((AssertionIDRef) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,213 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Advice; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.AttributeStatement; +import org.opensaml.saml2.core.AuthnStatement; +import org.opensaml.saml2.core.AuthzDecisionStatement; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.Statement; +import org.opensaml.saml2.core.Subject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.Assertion}. + */ +public class AssertionImpl extends AbstractSignableSAMLObject implements Assertion { + + /** SAML Version of the assertion. */ + private SAMLVersion version; + + /** Issue Instant of the assertion. */ + private DateTime issueInstant; + + /** ID of the assertion. */ + private String id; + + /** Issuer of the assertion. */ + private Issuer issuer; + + /** Subject of the assertion. */ + private Subject subject; + + /** Conditions of the assertion. */ + private Conditions conditions; + + /** Advice of the assertion. */ + private Advice advice; + + /** Statements of the assertion. */ + private final IndexedXMLObjectChildrenList statements; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AssertionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + version = SAMLVersion.VERSION_20; + statements = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public SAMLVersion getVersion() { + return version; + } + + /** {@inheritDoc} */ + public void setVersion(SAMLVersion newVersion) { + this.version = prepareForAssignment(this.version, newVersion); + } + + /** {@inheritDoc} */ + public DateTime getIssueInstant() { + return issueInstant; + } + + /** {@inheritDoc} */ + public void setIssueInstant(DateTime newIssueInstance) { + this.issueInstant = prepareForAssignment(this.issueInstant, newIssueInstance); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String newID) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, newID); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public Issuer getIssuer() { + return issuer; + } + + /** {@inheritDoc} */ + public void setIssuer(Issuer newIssuer) { + this.issuer = prepareForAssignment(this.issuer, newIssuer); + } + + /** {@inheritDoc} */ + public Subject getSubject() { + return subject; + } + + /** {@inheritDoc} */ + public void setSubject(Subject newSubject) { + this.subject = prepareForAssignment(this.subject, newSubject); + } + + /** {@inheritDoc} */ + public Conditions getConditions() { + return conditions; + } + + /** {@inheritDoc} */ + public void setConditions(Conditions newConditions) { + this.conditions = prepareForAssignment(this.conditions, newConditions); + } + + /** {@inheritDoc} */ + public Advice getAdvice() { + return advice; + } + + /** {@inheritDoc} */ + public void setAdvice(Advice newAdvice) { + this.advice = prepareForAssignment(this.advice, newAdvice); + } + + /** {@inheritDoc} */ + public List getStatements() { + return statements; + } + + /** {@inheritDoc} */ + public List getStatements(QName typeOrName) { + return (List) statements.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getAuthnStatements() { + QName statementQName = new QName(SAMLConstants.SAML20_NS, AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + return (List) statements.subList(statementQName); + } + + /** {@inheritDoc} */ + public List getAuthzDecisionStatements() { + QName statementQName = new QName(SAMLConstants.SAML20_NS, AuthzDecisionStatement.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + return (List) statements.subList(statementQName); + } + + /** {@inheritDoc} */ + public List getAttributeStatements() { + QName statementQName = new QName(SAMLConstants.SAML20_NS, AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + return (List) statements.subList(statementQName); + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID(){ + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(issuer); + + if(getSignature() != null){ + children.add(getSignature()); + } + + children.add(subject); + children.add(conditions); + children.add(advice); + children.addAll(statements); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionMarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Assertion}. + */ +public class AssertionMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + Assertion assertion = (Assertion) samlObject; + + if (assertion.getVersion() != null) { + domElement.setAttributeNS(null, Assertion.VERSION_ATTRIB_NAME, assertion.getVersion().toString()); + } + + if (assertion.getIssueInstant() != null) { + String issueInstantStr = Configuration.getSAMLDateFormatter().print(assertion.getIssueInstant()); + domElement.setAttributeNS(null, Assertion.ISSUE_INSTANT_ATTRIB_NAME, issueInstantStr); + } + + if (assertion.getID() != null) { + domElement.setAttributeNS(null, Assertion.ID_ATTRIB_NAME, assertion.getID()); + domElement.setIdAttributeNS(null, Assertion.ID_ATTRIB_NAME, true); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefBuilder.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AssertionURIRef; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AssertionURIRefImpl} objects. + */ +public class AssertionURIRefBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AssertionURIRefBuilder() { + + } + + /** {@inheritDoc} */ + public AssertionURIRef buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AssertionURIRef.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionURIRef buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionURIRefImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefImpl.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AssertionURIRef; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AssertionURIRef}. + */ +public class AssertionURIRefImpl extends AbstractSAMLObject implements AssertionURIRef { + + /** URI of the Assertion. */ + private String assertionURI; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AssertionURIRefImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAssertionURI() { + return assertionURI; + } + + /** {@inheritDoc} */ + public void setAssertionURI(String newAssertionURI) { + this.assertionURI = prepareForAssignment(this.assertionURI, newAssertionURI); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefMarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AssertionURIRef; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AssertionURIRef}. + */ +public class AssertionURIRefMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AssertionURIRef assertionURIRef = (AssertionURIRef) samlObject; + XMLHelper.appendTextContent(domElement, assertionURIRef.getAssertionURI()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionURIRefUnmarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AssertionURIRef; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AssertionURIRef}. + */ +public class AssertionURIRefUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AssertionURIRef assertionURIRef = (AssertionURIRef) samlObject; + assertionURIRef.setAssertionURI(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AssertionUnmarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Advice; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.Statement; +import org.opensaml.saml2.core.Subject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Assertion}. + */ +public class AssertionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + Assertion assertion = (Assertion) parentObject; + + if (childObject instanceof Issuer) { + assertion.setIssuer((Issuer) childObject); + } else if (childObject instanceof Signature) { + assertion.setSignature((Signature) childObject); + } else if (childObject instanceof Subject) { + assertion.setSubject((Subject) childObject); + } else if (childObject instanceof Conditions) { + assertion.setConditions((Conditions) childObject); + } else if (childObject instanceof Advice) { + assertion.setAdvice((Advice) childObject); + } else if (childObject instanceof Statement) { + assertion.getStatements().add((Statement) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Assertion assertion = (Assertion) samlObject; + + if (attribute.getLocalName().equals(Assertion.VERSION_ATTRIB_NAME)) { + assertion.setVersion(SAMLVersion.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(Assertion.ISSUE_INSTANT_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(Assertion.ID_ATTRIB_NAME)) { + assertion.setID(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeBuilder.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Attribute; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AttributeImpl} objects. + */ +public class AttributeBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public AttributeBuilder() { + + } + + /** {@inheritDoc} */ + public Attribute buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Attribute.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Attribute buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeImpl.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,113 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Attribute}. + */ +public class AttributeImpl extends AbstractSAMLObject implements Attribute { + + /** Name of the attribute. */ + private String name; + + /** Format of the name of the attribute. */ + private String nameFormat; + + /** Human readable name of the attribute. */ + private String friendlyName; + + /** "anyAttribute" attributes. */ + private AttributeMap unknownAttributes; + + /** List of attribute values for this attribute. */ + private final XMLObjectChildrenList attributeValues; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + attributeValues = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(String name) { + this.name = prepareForAssignment(this.name, name); + } + + /** {@inheritDoc} */ + public String getNameFormat() { + return nameFormat; + } + + /** {@inheritDoc} */ + public void setNameFormat(String nameFormat) { + this.nameFormat = prepareForAssignment(this.nameFormat, nameFormat); + } + + /** {@inheritDoc} */ + public String getFriendlyName() { + return friendlyName; + } + + /** {@inheritDoc} */ + public void setFriendlyName(String friendlyName) { + this.friendlyName = prepareForAssignment(this.friendlyName, friendlyName); + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getAttributeValues() { + return attributeValues; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(attributeValues); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.Attribute} objects. + */ +public class AttributeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + Attribute attribute = (Attribute) samlElement; + + if (attribute.getName() != null) { + domElement.setAttributeNS(null, Attribute.NAME_ATTTRIB_NAME, attribute.getName()); + } + + if (attribute.getNameFormat() != null) { + domElement.setAttributeNS(null, Attribute.NAME_FORMAT_ATTRIB_NAME, attribute.getNameFormat()); + } + + if (attribute.getFriendlyName() != null) { + domElement.setAttributeNS(null, Attribute.FRIENDLY_NAME_ATTRIB_NAME, attribute.getFriendlyName()); + } + + Attr attr; + for (Entry entry : attribute.getUnknownAttributes().entrySet()) { + attr = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attr.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attr); + if (Configuration.isIDAttribute(entry.getKey()) + || attribute.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attr.getOwnerElement().setIdAttributeNode(attr, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryBuilder.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AttributeQuery; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.AttributeQueryImpl} objects. + */ +public class AttributeQueryBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public AttributeQueryBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeQuery buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, AttributeQuery.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeQuery buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeQueryImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryImpl.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.AttributeQuery}. + */ +public class AttributeQueryImpl extends SubjectQueryImpl implements AttributeQuery { + + /** Attribute child elements. */ + private final XMLObjectChildrenList attributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + children.addAll(attributes); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryMarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AttributeQuery}. + */ +public class AttributeQueryMarshaller extends SubjectQueryMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeQueryUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AttributeQuery}. + */ +public class AttributeQueryUnmarshaller extends SubjectQueryUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AttributeQuery query = (AttributeQuery) parentSAMLObject; + + if (childSAMLObject instanceof Attribute) { + query.getAttributes().add((Attribute) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AttributeStatement; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AttributeStatementImpl} objects. + */ +public class AttributeStatementBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AttributeStatementBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeStatement buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeStatement buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeStatementImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeStatement; +import org.opensaml.saml2.core.EncryptedAttribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AttributeStatement}. + */ +public class AttributeStatementImpl extends AbstractSAMLObject implements AttributeStatement { + + /** Attributes and EncryptedAttributes in this statement. */ + private final IndexedXMLObjectChildrenList indexedChildren; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeStatementImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + indexedChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return (List) indexedChildren.subList(Attribute.DEFAULT_ELEMENT_NAME); + } + + + /** {@inheritDoc} */ + public List getEncryptedAttributes() { + return (List) indexedChildren.subList(EncryptedAttribute.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(indexedChildren); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementMarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AttributeStatement}. + */ +public class AttributeStatementMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeStatementUnmarshaller.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeStatement; +import org.opensaml.saml2.core.EncryptedAttribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AttributeStatement}. + */ +public class AttributeStatementUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + AttributeStatement attributeStatement = (AttributeStatement) parentObject; + + if (childObject instanceof Attribute) { + attributeStatement.getAttributes().add((Attribute) childObject); + } else if (childObject instanceof EncryptedAttribute) { + attributeStatement.getEncryptedAttributes().add((EncryptedAttribute) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AttributeUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Attribute} objects. + */ +public class AttributeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + + Attribute attribute = (Attribute) parentSAMLObject; + + QName childQName = childSAMLObject.getElementQName(); + if (childQName.getLocalPart().equals("AttributeValue") + && childQName.getNamespaceURI().equals(SAMLConstants.SAML20_NS)) { + attribute.getAttributeValues().add(childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + Attribute attrib = (Attribute) samlObject; + + if (attribute.getLocalName().equals(Attribute.NAME_ATTTRIB_NAME)) { + attrib.setName(attribute.getValue()); + } else if (attribute.getLocalName().equals(Attribute.NAME_FORMAT_ATTRIB_NAME)) { + attrib.setNameFormat(attribute.getValue()); + } else if (attribute.getLocalName().equals(Attribute.FRIENDLY_NAME_ATTRIB_NAME)) { + attrib.setFriendlyName(attribute.getValue()); + } else { + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + attrib.getUnknownAttributes().registerID(attribQName); + } + attrib.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceBuilder.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Audience; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AudienceImpl} objects. + */ +public class AudienceBuilder extends AbstractSAMLObjectBuilder { + + /** Construtor. */ + public AudienceBuilder() { + } + + /** {@inheritDoc} */ + public Audience buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Audience.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Audience buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AudienceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceImpl.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Audience; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Audience}. + */ +public class AudienceImpl extends AbstractSAMLObject implements Audience { + + /** URI of this Audience. */ + private String audienceURI; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AudienceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAudienceURI() { + return audienceURI; + } + + /** {@inheritDoc} */ + public void setAudienceURI(String newAudienceURI) { + this.audienceURI = prepareForAssignment(this.audienceURI, newAudienceURI); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceMarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.Audience; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.Audience} objects. + */ +public class AudienceMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Audience audience = (Audience) samlObject; + XMLHelper.appendTextContent(domElement, audience.getAudienceURI()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionBuilder.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AudienceRestriction; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AudienceRestrictionImpl} objects. + */ +public class AudienceRestrictionBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AudienceRestrictionBuilder() { + + } + + /** {@inheritDoc} */ + public AudienceRestriction buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AudienceRestriction.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AudienceRestriction buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AudienceRestrictionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Audience; +import org.opensaml.saml2.core.AudienceRestriction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.AudienceRestriction}. + */ +public class AudienceRestrictionImpl extends AbstractSAMLObject implements AudienceRestriction { + + /** List of the audiences. */ + private final XMLObjectChildrenList audience; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AudienceRestrictionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + audience = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAudiences() { + return audience; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(audience); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.AudienceRestriction} objects. + */ +public class AudienceRestrictionMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceRestrictionUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Audience; +import org.opensaml.saml2.core.AudienceRestriction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AudienceRestriction} objects. + */ +public class AudienceRestrictionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + AudienceRestriction audienceRestriction = (AudienceRestriction) parentObject; + + if (childObject instanceof Audience) { + audienceRestriction.getAudiences().add((Audience) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AudienceUnmarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Audience; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Audience} objects. + */ +public class AudienceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Audience audience = (Audience) samlObject; + audience.setAudienceURI(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityBuilder.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthenticatingAuthority; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AuthenticatingAuthorityImpl} objects. + */ +public class AuthenticatingAuthorityBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AuthenticatingAuthorityBuilder() { + + } + + /** {@inheritDoc} */ + public AuthenticatingAuthority buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AuthenticatingAuthority.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AuthenticatingAuthority buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthenticatingAuthorityImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AuthenticatingAuthority; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implemenation of {@link org.opensaml.saml2.core.AuthenticatingAuthority}. + */ +public class AuthenticatingAuthorityImpl extends AbstractSAMLObject implements AuthenticatingAuthority { + + /** URI of the Authenticating Authority. */ + private String uri; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthenticatingAuthorityImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getURI() { + return uri; + } + + /** {@inheritDoc} */ + public void setURI(String newURI) { + this.uri = prepareForAssignment(this.uri, newURI); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AuthenticatingAuthority; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthenticatingAuthority}. + */ +public class AuthenticatingAuthorityMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthenticatingAuthority authenticatingAuthority = (AuthenticatingAuthority) samlObject; + XMLHelper.appendTextContent(domElement, authenticatingAuthority.getURI()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthenticatingAuthorityUnmarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AuthenticatingAuthority; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthenticatingAuthority}. + */ +public class AuthenticatingAuthorityUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AuthenticatingAuthority authenticatingAuthority = (AuthenticatingAuthority) samlObject; + authenticatingAuthority.setURI(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnContext; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AuthnContextImpl} objects. + */ +public class AuthnContextBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AuthnContextBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnContext buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AuthnContext.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnContext buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnContextImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefBuilder.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnContextClassRef; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AuthnContextClassRefImpl} objects. + */ +public class AuthnContextClassRefBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AuthnContextClassRefBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnContextClassRef buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnContextClassRef buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnContextClassRefImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AuthnContextClassRef}. + */ +public class AuthnContextClassRefImpl extends AbstractSAMLObject implements AuthnContextClassRef { + + /** URI of the Authentication Context Class. */ + private String authnContextClassRef; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnContextClassRefImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAuthnContextClassRef() { + return authnContextClassRef; + } + + /** {@inheritDoc} */ + public void setAuthnContextClassRef(String newAuthnContextClassRef) { + this.authnContextClassRef = prepareForAssignment(this.authnContextClassRef, newAuthnContextClassRef); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthnContextClassRef}. + */ +public class AuthnContextClassRefMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthnContextClassRef authnContextClassRef = (AuthnContextClassRef) samlObject; + XMLHelper.appendTextContent(domElement, authnContextClassRef.getAuthnContextClassRef()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextClassRefUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthnContextClassRef}. + */ +public class AuthnContextClassRefUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AuthnContextClassRef authnContextClassRef = (AuthnContextClassRef) samlObject; + authnContextClassRef.setAuthnContextClassRef(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclBuilder.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnContextDecl; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AuthnContextDeclImpl} objects. + */ +public class AuthnContextDeclBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AuthnContextDeclBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnContextDecl buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AuthnContextDecl.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnContextDecl buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnContextDeclImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,92 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AuthnContextDecl; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AuthnContextDecl}. + */ +public class AuthnContextDeclImpl extends AbstractSAMLObject implements AuthnContextDecl { + + /** Child XMLObjects. */ + private IndexedXMLObjectChildrenList unknownXMLObjects; + + /** Attributes for this element. */ + private AttributeMap unknownAttributes; + + /** Text content of the element. */ + private String textContent; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnContextDeclImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + + unknownXMLObjects = new IndexedXMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getTextContent() { + return textContent; + } + + /** {@inheritDoc} */ + public void setTextContent(String newContent) { + textContent = prepareForAssignment(textContent, newContent); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownXMLObjects; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownXMLObjects.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return Collections.unmodifiableList(unknownXMLObjects); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclMarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AuthnContextDecl; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthnContextDecl}. + */ +public class AuthnContextDeclMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AuthnContextDecl authnCtxDecl = (AuthnContextDecl) xmlObject; + + Attr attribute; + for (Entry entry : authnCtxDecl.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || authnCtxDecl.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AuthnContextDecl authnCtxDecl = (AuthnContextDecl) xmlObject; + + if (authnCtxDecl.getTextContent() != null) { + XMLHelper.appendTextContent(domElement, authnCtxDecl.getTextContent()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnContextDeclRef; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AuthnContextDeclRefImpl} objects. + */ +public class AuthnContextDeclRefBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AuthnContextDeclRefBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnContextDeclRef buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AuthnContextDeclRef.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnContextDeclRef buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnContextDeclRefImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AuthnContextDeclRef}. + */ +public class AuthnContextDeclRefImpl extends AbstractSAMLObject implements AuthnContextDeclRef { + + /** URI of the Authentication Context Declaration. */ + private String authnContextDeclRef; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnContextDeclRefImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAuthnContextDeclRef() { + return authnContextDeclRef; + } + + /** {@inheritDoc} */ + public void setAuthnContextDeclRef(String newAuthnContextDeclRef) { + this.authnContextDeclRef = prepareForAssignment(this.authnContextDeclRef, newAuthnContextDeclRef); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthnContextDeclRef}. + */ +public class AuthnContextDeclRefMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthnContextDeclRef authnContextDeclRef = (AuthnContextDeclRef) samlObject; + XMLHelper.appendTextContent(domElement, authnContextDeclRef.getAuthnContextDeclRef()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclRefUnmarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthnContextDecl}. + */ +public class AuthnContextDeclRefUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AuthnContextDeclRef authnContextDeclRef = (AuthnContextDeclRef) samlObject; + authnContextDeclRef.setAuthnContextDeclRef(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextDeclUnmarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AuthnContextDecl; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthnContextDecl}. + */ +public class AuthnContextDeclUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + AuthnContextDecl authnCtcDecl = (AuthnContextDecl) parentXMLObject; + + authnCtcDecl.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AuthnContextDecl authnCtcDecl = (AuthnContextDecl) xmlObject; + + QName attribQName = XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute + .getPrefix()); + + if (attribute.isId()) { + authnCtcDecl.getUnknownAttributes().registerID(attribQName); + } + + authnCtcDecl.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + AuthnContextDecl authnCtcDecl = (AuthnContextDecl) xmlObject; + + authnCtcDecl.setTextContent(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AuthenticatingAuthority; +import org.opensaml.saml2.core.AuthnContext; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnContextDecl; +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A concrete implemenation of {@link org.opensaml.saml2.core.AuthnContext}. + */ +public class AuthnContextImpl extends AbstractSAMLObject implements AuthnContext { + + /** URI of the Context Class. */ + private AuthnContextClassRef authnContextClassRef; + + /** Declaration of the Authentication Context. */ + private AuthnContextDecl authnContextDecl; + + /** URI of the Declaration of the Authentication Context. */ + private AuthnContextDeclRef authnContextDeclRef; + + /** List of the Authenticating Authorities. */ + private final XMLObjectChildrenList authenticatingAuthority; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnContextImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + authenticatingAuthority = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AuthnContextClassRef getAuthnContextClassRef() { + return authnContextClassRef; + } + + /** {@inheritDoc} */ + public void setAuthnContextClassRef(AuthnContextClassRef newAuthnContextClassRef) { + this.authnContextClassRef = prepareForAssignment(this.authnContextClassRef, newAuthnContextClassRef); + } + + /** {@inheritDoc} */ + public AuthnContextDecl getAuthContextDecl() { + return authnContextDecl; + } + + /** {@inheritDoc} */ + public void setAuthnContextDecl(AuthnContextDecl newAuthnContextDecl) { + this.authnContextDecl = prepareForAssignment(this.authnContextDecl, newAuthnContextDecl); + } + + /** {@inheritDoc} */ + public AuthnContextDeclRef getAuthnContextDeclRef() { + return authnContextDeclRef; + } + + /** {@inheritDoc} */ + public void setAuthnContextDeclRef(AuthnContextDeclRef newAuthnContextDeclRef) { + this.authnContextDeclRef = prepareForAssignment(this.authnContextDeclRef, newAuthnContextDeclRef); + } + + /** {@inheritDoc} */ + public List getAuthenticatingAuthorities() { + return authenticatingAuthority; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(authnContextClassRef); + children.add(authnContextDecl); + children.add(authnContextDeclRef); + children.addAll(authenticatingAuthority); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthnContext}. + */ +public class AuthnContextMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnContextUnmarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AuthenticatingAuthority; +import org.opensaml.saml2.core.AuthnContext; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnContextDecl; +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthnContext}. + */ +public class AuthnContextUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + AuthnContext authnContext = (AuthnContext) parentObject; + if (childObject instanceof AuthnContextClassRef) { + authnContext.setAuthnContextClassRef((AuthnContextClassRef) childObject); + } else if (childObject instanceof AuthnContextDecl) { + authnContext.setAuthnContextDecl((AuthnContextDecl) childObject); + } else if (childObject instanceof AuthnContextDeclRef) { + authnContext.setAuthnContextDeclRef((AuthnContextDeclRef) childObject); + } else if (childObject instanceof AuthenticatingAuthority) { + authnContext.getAuthenticatingAuthorities().add((AuthenticatingAuthority) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnQuery; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.AuthnQueryImpl} objects. + */ +public class AuthnQueryBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public AuthnQueryBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnQuery buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, AuthnQuery.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnQuery buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnQueryImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryImpl.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,92 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.AuthnQuery; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.AuthnQuery}. + */ +public class AuthnQueryImpl extends SubjectQueryImpl implements AuthnQuery { + + /** SessionIndex attribute. */ + private String sessionIndex; + + /** RequestedAuthnContext child element. */ + private RequestedAuthnContext requestedAuthnContext; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getSessionIndex() { + return this.sessionIndex; + } + + /** {@inheritDoc} */ + public void setSessionIndex(String newSessionIndex) { + this.sessionIndex = prepareForAssignment(this.sessionIndex, newSessionIndex); + } + + /** {@inheritDoc} */ + public RequestedAuthnContext getRequestedAuthnContext() { + return this.requestedAuthnContext; + } + + /** {@inheritDoc} */ + public void setRequestedAuthnContext(RequestedAuthnContext newRequestedAuthnContext) { + this.requestedAuthnContext = prepareForAssignment(this.requestedAuthnContext, newRequestedAuthnContext); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + if (requestedAuthnContext != null) { + children.add(requestedAuthnContext); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.AuthnQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthnQuery}. + */ +public class AuthnQueryMarshaller extends SubjectQueryMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthnQuery query = (AuthnQuery) samlObject; + + if (query.getSessionIndex() != null) { + domElement.setAttributeNS(null, AuthnQuery.SESSION_INDEX_ATTRIB_NAME, query.getSessionIndex()); + } + + super.marshallAttributes(samlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnQueryUnmarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.AuthnQuery; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthnQuery} objects. + */ +public class AuthnQueryUnmarshaller extends SubjectQueryUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AuthnQuery query = (AuthnQuery) samlObject; + + if (attribute.getLocalName().equals(AuthnQuery.SESSION_INDEX_ATTRIB_NAME)) { + query.setSessionIndex(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AuthnQuery query = (AuthnQuery) parentSAMLObject; + + if (childSAMLObject instanceof RequestedAuthnContext) { + query.setRequestedAuthnContext((RequestedAuthnContext) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnRequest; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.AuthnRequestImpl} objects. + */ +public class AuthnRequestBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public AuthnRequestBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnRequest buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, AuthnRequest.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnRequest buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnRequestImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestImpl.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,282 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.saml2.core.Scoping; +import org.opensaml.saml2.core.Subject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AuthnRequest}. + */ +public class AuthnRequestImpl extends RequestAbstractTypeImpl implements AuthnRequest { + + /** Subject child element. */ + private Subject subject; + + /** NameIDPolicy child element. */ + private NameIDPolicy nameIDPolicy; + + /** Conditions child element. */ + private Conditions conditions; + + /** RequestedAuthnContext child element. */ + private RequestedAuthnContext requestedAuthnContext; + + /** Scoping child element. */ + private Scoping scoping; + + /** ForeceAuthn attribute. */ + private XSBooleanValue forceAuthn; + + /** IsPassive attribute. */ + private XSBooleanValue isPassive; + + /** ProtocolBinding attribute. */ + private String protocolBinding; + + /** AssertionConsumerServiceIndex attribute. */ + private Integer assertionConsumerServiceIndex; + + /** AssertionConsumerServiceURL attribute. */ + private String assertionConsumerServiceURL; + + /** AttributeConsumingServiceIndex attribute. */ + private Integer attributeConsumingServiceIndex; + + /** ProviderName attribute. */ + private String providerName; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnRequestImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Boolean isForceAuthn() { + if (forceAuthn != null) { + return forceAuthn.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isForceAuthnXSBoolean() { + return forceAuthn; + } + + /** {@inheritDoc} */ + public void setForceAuthn(Boolean newForceAuth) { + if (newForceAuth != null) { + forceAuthn = prepareForAssignment(forceAuthn, new XSBooleanValue(newForceAuth, false)); + } else { + forceAuthn = prepareForAssignment(forceAuthn, null); + } + } + + /** {@inheritDoc} */ + public void setForceAuthn(XSBooleanValue newForceAuthn) { + forceAuthn = prepareForAssignment(this.forceAuthn, newForceAuthn); + } + + /** {@inheritDoc} */ + public Boolean isPassive() { + if (isPassive != null) { + return isPassive.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isPassiveXSBoolean() { + return isPassive; + } + + /** {@inheritDoc} */ + public void setIsPassive(Boolean newIsPassive) { + if (newIsPassive != null) { + isPassive = prepareForAssignment(isPassive, new XSBooleanValue(newIsPassive, false)); + } else { + isPassive = prepareForAssignment(isPassive, null); + } + } + + /** {@inheritDoc} */ + public void setIsPassive(XSBooleanValue newIsPassive) { + this.isPassive = prepareForAssignment(this.isPassive, newIsPassive); + } + + /** {@inheritDoc} */ + public String getProtocolBinding() { + return this.protocolBinding; + } + + /** {@inheritDoc} */ + public void setProtocolBinding(String newProtocolBinding) { + this.protocolBinding = prepareForAssignment(this.protocolBinding, newProtocolBinding); + } + + /** {@inheritDoc} */ + public Integer getAssertionConsumerServiceIndex() { + return assertionConsumerServiceIndex; + } + + /** {@inheritDoc} */ + public void setAssertionConsumerServiceIndex(Integer newAssertionConsumerServiceIndex) { + this.assertionConsumerServiceIndex = prepareForAssignment(this.assertionConsumerServiceIndex, + newAssertionConsumerServiceIndex); + } + + /** {@inheritDoc} */ + public String getAssertionConsumerServiceURL() { + return this.assertionConsumerServiceURL; + } + + /** {@inheritDoc} */ + public void setAssertionConsumerServiceURL(String newAssertionConsumerServiceURL) { + this.assertionConsumerServiceURL = prepareForAssignment(this.assertionConsumerServiceURL, + newAssertionConsumerServiceURL); + } + + /** {@inheritDoc} */ + public Integer getAttributeConsumingServiceIndex() { + return this.attributeConsumingServiceIndex; + } + + /** {@inheritDoc} */ + public void setAttributeConsumingServiceIndex(Integer newAttributeConsumingServiceIndex) { + this.attributeConsumingServiceIndex = prepareForAssignment(this.attributeConsumingServiceIndex, + newAttributeConsumingServiceIndex); + } + + /** {@inheritDoc} */ + public String getProviderName() { + return this.providerName; + } + + /** {@inheritDoc} */ + public void setProviderName(String newProviderName) { + this.providerName = prepareForAssignment(this.providerName, newProviderName); + } + + /** {@inheritDoc} */ + public Subject getSubject() { + return this.subject; + } + + /** {@inheritDoc} */ + public void setSubject(Subject newSubject) { + this.subject = prepareForAssignment(this.subject, newSubject); + } + + /** {@inheritDoc} */ + public NameIDPolicy getNameIDPolicy() { + return this.nameIDPolicy; + } + + /** {@inheritDoc} */ + public void setNameIDPolicy(NameIDPolicy newNameIDPolicy) { + this.nameIDPolicy = prepareForAssignment(this.nameIDPolicy, newNameIDPolicy); + } + + /** {@inheritDoc} */ + public Conditions getConditions() { + return this.conditions; + } + + /** {@inheritDoc} */ + public void setConditions(Conditions newConditions) { + this.conditions = prepareForAssignment(this.conditions, newConditions); + } + + /** {@inheritDoc} */ + public RequestedAuthnContext getRequestedAuthnContext() { + return this.requestedAuthnContext; + } + + /** {@inheritDoc} */ + public void setRequestedAuthnContext(RequestedAuthnContext newRequestedAuthnContext) { + this.requestedAuthnContext = prepareForAssignment(this.requestedAuthnContext, newRequestedAuthnContext); + } + + /** {@inheritDoc} */ + public Scoping getScoping() { + return this.scoping; + } + + /** {@inheritDoc} */ + public void setScoping(Scoping newScoping) { + this.scoping = prepareForAssignment(this.scoping, newScoping); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + if (subject != null) { + children.add(subject); + } + + if (nameIDPolicy != null) { + children.add(nameIDPolicy); + } + + if (conditions != null) { + children.add(conditions); + } + + if (requestedAuthnContext != null) { + children.add(requestedAuthnContext); + } + + if (scoping != null) { + children.add(scoping); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthnRequest}. + */ +public class AuthnRequestMarshaller extends RequestAbstractTypeMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthnRequest req = (AuthnRequest) samlObject; + + if (req.isForceAuthnXSBoolean() != null) { + domElement.setAttributeNS(null, AuthnRequest.FORCE_AUTHN_ATTRIB_NAME, req.isForceAuthnXSBoolean() + .toString()); + } + + if (req.isPassiveXSBoolean() != null) { + domElement.setAttributeNS(null, AuthnRequest.IS_PASSIVE_ATTRIB_NAME, req.isPassiveXSBoolean().toString()); + } + + if (req.getProtocolBinding() != null) { + domElement.setAttributeNS(null, AuthnRequest.PROTOCOL_BINDING_ATTRIB_NAME, req.getProtocolBinding()); + } + + if (req.getAssertionConsumerServiceIndex() != null) { + domElement.setAttributeNS(null, AuthnRequest.ASSERTION_CONSUMER_SERVICE_INDEX_ATTRIB_NAME, req + .getAssertionConsumerServiceIndex().toString()); + } + + if (req.getAssertionConsumerServiceURL() != null) { + domElement.setAttributeNS(null, AuthnRequest.ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME, req + .getAssertionConsumerServiceURL()); + } + + if (req.getAttributeConsumingServiceIndex() != null) { + domElement.setAttributeNS(null, AuthnRequest.ATTRIBUTE_CONSUMING_SERVICE_INDEX_ATTRIB_NAME, req + .getAttributeConsumingServiceIndex().toString()); + } + + if (req.getProviderName() != null) { + domElement.setAttributeNS(null, AuthnRequest.PROVIDER_NAME_ATTRIB_NAME, req.getProviderName()); + } + + super.marshallAttributes(samlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnRequestUnmarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.saml2.core.Scoping; +import org.opensaml.saml2.core.Subject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthnRequest} objects. + */ +public class AuthnRequestUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AuthnRequest req = (AuthnRequest) samlObject; + + if (attribute.getLocalName().equals(AuthnRequest.FORCE_AUTHN_ATTRIB_NAME)) { + req.setForceAuthn(XSBooleanValue.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(AuthnRequest.IS_PASSIVE_ATTRIB_NAME)) { + req.setIsPassive(XSBooleanValue.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(AuthnRequest.PROTOCOL_BINDING_ATTRIB_NAME)) { + req.setProtocolBinding(attribute.getValue()); + } else if (attribute.getLocalName().equals(AuthnRequest.ASSERTION_CONSUMER_SERVICE_INDEX_ATTRIB_NAME)) { + req.setAssertionConsumerServiceIndex(Integer.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(AuthnRequest.ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME)) { + req.setAssertionConsumerServiceURL(attribute.getValue()); + } else if (attribute.getLocalName().equals(AuthnRequest.ATTRIBUTE_CONSUMING_SERVICE_INDEX_ATTRIB_NAME)) { + req.setAttributeConsumingServiceIndex(Integer.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(AuthnRequest.PROVIDER_NAME_ATTRIB_NAME)) { + req.setProviderName(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AuthnRequest req = (AuthnRequest) parentSAMLObject; + + if (childSAMLObject instanceof Subject) { + req.setSubject((Subject) childSAMLObject); + } else if (childSAMLObject instanceof NameIDPolicy) { + req.setNameIDPolicy((NameIDPolicy) childSAMLObject); + } else if (childSAMLObject instanceof Conditions) { + req.setConditions((Conditions) childSAMLObject); + } else if (childSAMLObject instanceof RequestedAuthnContext) { + req.setRequestedAuthnContext((RequestedAuthnContext) childSAMLObject); + } else if (childSAMLObject instanceof Scoping) { + req.setScoping((Scoping) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnStatement; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AuthnStatementImpl} objects. + */ +public class AuthnStatementBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AuthnStatementBuilder() { + } + + /** {@inheritDoc} */ + public AuthnStatement buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnStatement buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnStatementImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,125 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AuthnContext; +import org.opensaml.saml2.core.AuthnStatement; +import org.opensaml.saml2.core.SubjectLocality; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AuthnStatement}. + */ +public class AuthnStatementImpl extends AbstractSAMLObject implements AuthnStatement { + + /** Subject Locality of the Authentication Statement. */ + private SubjectLocality subjectLocality; + + /** Authentication Context of the Authentication Statement. */ + private AuthnContext authnContext; + + /** Time of the authentication. */ + private DateTime authnInstant; + + /** Index of the session. */ + private String sessionIndex; + + /** Time at which the session ends. */ + private DateTime sessionNotOnOrAfter; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnStatementImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public SubjectLocality getSubjectLocality() { + return subjectLocality; + } + + /** {@inheritDoc} */ + public void setSubjectLocality(SubjectLocality newSubjectLocality) { + this.subjectLocality = prepareForAssignment(this.subjectLocality, newSubjectLocality); + } + + /** {@inheritDoc} */ + public AuthnContext getAuthnContext() { + return authnContext; + } + + /** {@inheritDoc} */ + public void setAuthnContext(AuthnContext newAuthnContext) { + this.authnContext = prepareForAssignment(this.authnContext, newAuthnContext); + } + + /** {@inheritDoc} */ + public DateTime getAuthnInstant() { + return authnInstant; + } + + /** {@inheritDoc} */ + public void setAuthnInstant(DateTime newAuthnInstant) { + this.authnInstant = prepareForAssignment(this.authnInstant, newAuthnInstant); + } + + /** {@inheritDoc} */ + public String getSessionIndex() { + return sessionIndex; + } + + /** {@inheritDoc} */ + public void setSessionIndex(String newSessionIndex) { + this.sessionIndex = prepareForAssignment(this.sessionIndex, newSessionIndex); + } + + /** {@inheritDoc} */ + public DateTime getSessionNotOnOrAfter() { + return sessionNotOnOrAfter; + } + + /** {@inheritDoc} */ + public void setSessionNotOnOrAfter(DateTime newSessionNotOnOrAfter) { + this.sessionNotOnOrAfter = prepareForAssignment(this.sessionNotOnOrAfter, newSessionNotOnOrAfter); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(subjectLocality); + children.add(authnContext); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AuthnStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthnStatement}. + */ +public class AuthnStatementMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthnStatement authnStatement = (AuthnStatement) samlObject; + + if (authnStatement.getAuthnInstant() != null) { + String authnInstantStr = Configuration.getSAMLDateFormatter().print(authnStatement.getAuthnInstant()); + domElement.setAttributeNS(null, AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME, authnInstantStr); + } + + if (authnStatement.getSessionIndex() != null) { + domElement.setAttributeNS(null, AuthnStatement.SESSION_INDEX_ATTRIB_NAME, authnStatement.getSessionIndex()); + } + + if (authnStatement.getSessionNotOnOrAfter() != null) { + String sessionNotOnOrAfterStr = Configuration.getSAMLDateFormatter().print( + authnStatement.getSessionNotOnOrAfter()); + domElement.setAttributeNS(null, AuthnStatement.SESSION_NOT_ON_OR_AFTER_ATTRIB_NAME, sessionNotOnOrAfterStr); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthnStatementUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AuthnContext; +import org.opensaml.saml2.core.AuthnStatement; +import org.opensaml.saml2.core.SubjectLocality; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthnStatement}. + */ +public class AuthnStatementUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + AuthnStatement authnStatement = (AuthnStatement) parentObject; + if (childObject instanceof SubjectLocality) { + authnStatement.setSubjectLocality((SubjectLocality) childObject); + } else if (childObject instanceof AuthnContext) { + authnStatement.setAuthnContext((AuthnContext) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AuthnStatement authnStatement = (AuthnStatement) samlObject; + if (attribute.getLocalName().equals(AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + authnStatement.setAuthnInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(AuthnStatement.SESSION_INDEX_ATTRIB_NAME)) { + authnStatement.setSessionIndex(attribute.getValue()); + } else if (attribute.getLocalName().equals(AuthnStatement.SESSION_NOT_ON_OR_AFTER_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + authnStatement.setSessionNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthzDecisionQuery; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.AuthzDecisionQueryImpl} objects. + */ +public class AuthzDecisionQueryBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public AuthzDecisionQueryBuilder() { + + } + + /** {@inheritDoc} */ + public AuthzDecisionQuery buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, AuthzDecisionQuery.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public AuthzDecisionQuery buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthzDecisionQueryImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryImpl.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,103 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.Action; +import org.opensaml.saml2.core.AuthzDecisionQuery; +import org.opensaml.saml2.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.AuthzDecisionQuery}. + */ +public class AuthzDecisionQueryImpl extends SubjectQueryImpl implements AuthzDecisionQuery { + + /** Resource attribute value. */ + private String resource; + + /** Evidence child element. */ + private Evidence evidence; + + /** Action child elements. */ + private final XMLObjectChildrenList actions; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthzDecisionQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + actions = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getResource() { + return this.resource; + } + + /** {@inheritDoc} */ + public void setResource(String newResource) { + this.resource = prepareForAssignment(this.resource, newResource); + } + + /** {@inheritDoc} */ + public List getActions() { + return actions; + } + + /** {@inheritDoc} */ + public Evidence getEvidence() { + return this.evidence; + } + + /** {@inheritDoc} */ + public void setEvidence(Evidence newEvidence) { + this.evidence = prepareForAssignment(this.evidence, newEvidence); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + children.addAll(actions); + if (evidence != null) { + children.add(evidence); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.AuthzDecisionQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthzDecisionQuery} objects. + */ +public class AuthzDecisionQueryMarshaller extends SubjectQueryMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthzDecisionQuery query = (AuthzDecisionQuery) samlObject; + + if (query.getResource() != null) { + domElement.setAttributeNS(null, AuthzDecisionQuery.RESOURCE_ATTRIB_NAME, query.getResource()); + } + + super.marshallAttributes(samlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionQueryUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.Action; +import org.opensaml.saml2.core.AuthzDecisionQuery; +import org.opensaml.saml2.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthzDecisionQuery} objects. + */ +public class AuthzDecisionQueryUnmarshaller extends SubjectQueryUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AuthzDecisionQuery query = (AuthzDecisionQuery) samlObject; + + if (attribute.getLocalName().equals(AuthzDecisionQuery.RESOURCE_ATTRIB_NAME)) { + query.setResource(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AuthzDecisionQuery query = (AuthzDecisionQuery) parentSAMLObject; + + if (childSAMLObject instanceof Action) { + query.getActions().add((Action) childSAMLObject); + } else if (childSAMLObject instanceof Evidence) { + query.setEvidence((Evidence) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthzDecisionStatement; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.AuthzDecisionStatementImpl} objects. + */ +public class AuthzDecisionStatementBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public AuthzDecisionStatementBuilder() { + + } + + /** {@inheritDoc} */ + public AuthzDecisionStatement buildObject() { + return buildObject(SAMLConstants.SAML20_NS, AuthzDecisionStatement.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public AuthzDecisionStatement buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthzDecisionStatementImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementImpl.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Action; +import org.opensaml.saml2.core.AuthzDecisionStatement; +import org.opensaml.saml2.core.DecisionTypeEnumeration; +import org.opensaml.saml2.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.AuthzDecisionStatement}. + */ +public class AuthzDecisionStatementImpl extends AbstractSAMLObject implements AuthzDecisionStatement { + + /** URI of the resource to which authorization is sought. */ + private String resource; + + /** Decision of the authorization request. */ + private DecisionTypeEnumeration decision; + + /** Actions authorized to be performed. */ + private final XMLObjectChildrenList actions; + + /** SAML assertion the authority relied on when making the authorization decision. */ + private Evidence evidence; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthzDecisionStatementImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + actions = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getResource() { + return resource; + } + + /** {@inheritDoc} */ + public void setResource(String newResourceURI) { + this.resource = prepareForAssignment(this.resource, newResourceURI); + } + + /** {@inheritDoc} */ + public DecisionTypeEnumeration getDecision() { + return decision; + } + + /** {@inheritDoc} */ + public void setDecision(DecisionTypeEnumeration newDecision) { + this.decision = prepareForAssignment(this.decision, newDecision); + } + + /** {@inheritDoc} */ + public List getActions() { + return actions; + } + + /** {@inheritDoc} */ + public Evidence getEvidence() { + return evidence; + } + + /** {@inheritDoc} */ + public void setEvidence(Evidence newEvidence) { + this.evidence = prepareForAssignment(this.evidence, newEvidence); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(actions); + children.add(evidence); + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementMarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.AuthzDecisionStatement; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.AuthzDecisionStatement}. + */ +public class AuthzDecisionStatementMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + AuthzDecisionStatement authzDS = (AuthzDecisionStatement) samlObject; + + if (authzDS.getResource() != null) { + domElement.setAttributeNS(null, AuthzDecisionStatement.RESOURCE_ATTRIB_NAME, authzDS.getResource()); + } + + if (authzDS.getDecision() != null) { + domElement.setAttributeNS(null, AuthzDecisionStatement.DECISION_ATTRIB_NAME, authzDS.getDecision() + .toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/AuthzDecisionStatementUnmarshaller.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Action; +import org.opensaml.saml2.core.AuthzDecisionStatement; +import org.opensaml.saml2.core.DecisionTypeEnumeration; +import org.opensaml.saml2.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.AuthzDecisionStatement}. + */ +public class AuthzDecisionStatementUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + AuthzDecisionStatement authzDS = (AuthzDecisionStatement) parentObject; + + if (childObject instanceof Action) { + authzDS.getActions().add((Action) childObject); + } else if (childObject instanceof Evidence) { + authzDS.setEvidence((Evidence) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AuthzDecisionStatement authzDS = (AuthzDecisionStatement) samlObject; + + if (attribute.getLocalName().equals(AuthzDecisionStatement.RESOURCE_ATTRIB_NAME)) { + authzDS.setResource(attribute.getValue()); + } else if (attribute.getLocalName().equals(AuthzDecisionStatement.DECISION_ATTRIB_NAME)) { + String value = attribute.getValue(); + if (value.equals(DecisionTypeEnumeration.PERMIT.toString())) { + authzDS.setDecision(DecisionTypeEnumeration.PERMIT); + } else if (value.equals(DecisionTypeEnumeration.DENY.toString())) { + authzDS.setDecision(DecisionTypeEnumeration.DENY); + } else if (value.equals(DecisionTypeEnumeration.INDETERMINATE.toString())) { + authzDS.setDecision(DecisionTypeEnumeration.INDETERMINATE); + } else { + throw new UnmarshallingException("Unknown value for DecisionType '" + value + "'"); + } + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.BaseID}. + */ +public abstract class BaseIDImpl extends AbstractSAMLObject implements BaseID { + + /** Name Qualifier of BaseID. */ + private String nameQualifier; + + /** SP Name Qualifier of Base. */ + private String spNameQualfier; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected BaseIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getNameQualifier() { + return nameQualifier; + } + + /** {@inheritDoc} */ + public void setNameQualifier(String newNameQualifier) { + this.nameQualifier = prepareForAssignment(this.nameQualifier, newNameQualifier); + } + + /** {@inheritDoc} */ + public String getSPNameQualifier() { + return spNameQualfier; + } + + /** {@inheritDoc} */ + public void setSPNameQualifier(String newSPNameQualifier) { + this.spNameQualfier = prepareForAssignment(this.spNameQualfier, newSPNameQualifier); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDMarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.BaseID} objects. + */ +public abstract class BaseIDMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + BaseID baseID = (BaseID) samlObject; + if (baseID.getNameQualifier() != null) { + domElement.setAttributeNS(null, BaseID.NAME_QUALIFIER_ATTRIB_NAME, baseID.getNameQualifier()); + } + + if (baseID.getSPNameQualifier() != null) { + domElement.setAttributeNS(null, BaseID.SP_NAME_QUALIFIER_ATTRIB_NAME, baseID.getSPNameQualifier()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/BaseIDUnmarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.BaseID} objects. + */ +public abstract class BaseIDUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + BaseID baseID = (BaseID) samlObject; + if (attribute.getLocalName().equals(BaseID.NAME_QUALIFIER_ATTRIB_NAME)) { + baseID.setNameQualifier(attribute.getValue()); + } else if (attribute.getLocalName().equals(BaseID.SP_NAME_QUALIFIER_ATTRIB_NAME)) { + baseID.setSPNameQualifier(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsBuilder.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Conditions; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.ConditionsImpl} objects. + */ +public class ConditionsBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public ConditionsBuilder() { + + } + + /** {@inheritDoc} */ + public Conditions buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Conditions.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Conditions buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ConditionsImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,131 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AudienceRestriction; +import org.opensaml.saml2.core.Condition; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.OneTimeUse; +import org.opensaml.saml2.core.ProxyRestriction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Conditions}. + */ +public class ConditionsImpl extends AbstractSAMLObject implements Conditions { + + /** A Condition. */ + private final IndexedXMLObjectChildrenList conditions; + + /** Not Before conditions. */ + private DateTime notBefore; + + /** Not On Or After conditions. */ + private DateTime notOnOrAfter; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ConditionsImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + conditions = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getConditions() { + return conditions; + } + + /** {@inheritDoc} */ + public List getAudienceRestrictions() { + QName conditionQName = new QName(SAMLConstants.SAML20_NS, AudienceRestriction.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + return (List) conditions.subList(conditionQName); + } + + /** {@inheritDoc} */ + public OneTimeUse getOneTimeUse() { + QName conditionQName = new QName(SAMLConstants.SAML20_NS, OneTimeUse.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + List list = (List) conditions.subList(conditionQName); + if (list == null || list.size() == 0) { + return null; + } else { + return list.get(0); + } + } + + /** {@inheritDoc} */ + public ProxyRestriction getProxyRestriction() { + QName conditionQName = new QName(SAMLConstants.SAML20_NS, ProxyRestriction.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + List list = (List) conditions.subList(conditionQName); + if (list == null || list.size() == 0) { + return null; + } else { + return list.get(0); + } + } + + /** {@inheritDoc} */ + public DateTime getNotBefore() { + return notBefore; + } + + /** {@inheritDoc} */ + public void setNotBefore(DateTime newNotBefore) { + this.notBefore = prepareForAssignment(this.notBefore, newNotBefore); + } + + /** {@inheritDoc} */ + public DateTime getNotOnOrAfter() { + return notOnOrAfter; + } + + /** {@inheritDoc} */ + public void setNotOnOrAfter(DateTime newNotOnOrAfter) { + this.notOnOrAfter = prepareForAssignment(this.notOnOrAfter, newNotOnOrAfter); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(conditions); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Conditions} objects. + */ +public class ConditionsMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + Conditions conditions = (Conditions) samlObject; + + if (conditions.getNotBefore() != null) { + String notBeforeStr = Configuration.getSAMLDateFormatter().print(conditions.getNotBefore()); + domElement.setAttributeNS(null, Conditions.NOT_BEFORE_ATTRIB_NAME, notBeforeStr); + } + + if (conditions.getNotOnOrAfter() != null) { + String notOnOrAfterStr = Configuration.getSAMLDateFormatter().print(conditions.getNotOnOrAfter()); + domElement.setAttributeNS(null, Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME, notOnOrAfterStr); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ConditionsUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Condition; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Conditions} objects. + */ +public class ConditionsUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + Conditions conditions = (Conditions) parentObject; + + if (childObject instanceof Condition) { + conditions.getConditions().add((Condition) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Conditions conditions = (Conditions) samlObject; + + if (attribute.getLocalName().equals(Conditions.NOT_BEFORE_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + conditions.setNotBefore(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + conditions.setNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionBuilder.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.EncryptedAssertion; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.EncryptedAssertionImpl} objects. + */ +public class EncryptedAssertionBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public EncryptedAssertionBuilder() { + super(); + } + + /** {@inheritDoc} */ + public EncryptedAssertion buildObject() { + return buildObject(SAMLConstants.SAML20_NS, EncryptedAssertion.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public EncryptedAssertion buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptedAssertionImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionImpl.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.EncryptedAssertion; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.EncryptedAssertion}. + */ +public class EncryptedAssertionImpl extends EncryptedElementTypeImpl implements EncryptedAssertion { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EncryptedAssertionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionMarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.EncryptedAssertion}. + */ +public class EncryptedAssertionMarshaller extends EncryptedElementTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAssertionUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.EncryptedAssertion}. + */ +public class EncryptedAssertionUnmarshaller extends EncryptedElementTypeUnmarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeBuilder.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.EncryptedAttribute; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.EncryptedAttributeImpl} objects. + */ +public class EncryptedAttributeBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public EncryptedAttributeBuilder() { + super(); + } + + /** {@inheritDoc} */ + public EncryptedAttribute buildObject() { + return buildObject(SAMLConstants.SAML20_NS, EncryptedAttribute.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public EncryptedAttribute buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptedAttributeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.EncryptedAttribute; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.EncryptedAttribute}. + */ +public class EncryptedAttributeImpl extends EncryptedElementTypeImpl implements EncryptedAttribute { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EncryptedAttributeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.EncryptedAttribute}. + */ +public class EncryptedAttributeMarshaller extends EncryptedElementTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedAttributeUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.EncryptedAttribute}. + */ +public class EncryptedAttributeUnmarshaller extends EncryptedElementTypeUnmarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeImpl.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,86 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.EncryptedElementType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.encryption.EncryptedData; +import org.opensaml.xml.encryption.EncryptedKey; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.EncryptedElementType}. + */ +public class EncryptedElementTypeImpl extends AbstractSAMLObject implements EncryptedElementType { + + /** EncryptedData child element. */ + private EncryptedData encryptedData; + + /** EncryptedKey children. */ + private final XMLObjectChildrenList encryptedKeys; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EncryptedElementTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + encryptedKeys = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public EncryptedData getEncryptedData() { + return this.encryptedData; + } + + /** {@inheritDoc} */ + public void setEncryptedData(EncryptedData newEncryptedData) { + this.encryptedData = prepareForAssignment(this.encryptedData, newEncryptedData); + } + + /** {@inheritDoc} */ + public List getEncryptedKeys() { + return this.encryptedKeys; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (encryptedData != null) { + children.add(encryptedData); + } + + children.addAll(encryptedKeys); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeMarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.EncryptedElementType}. + */ +public class EncryptedElementTypeMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedElementTypeUnmarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.EncryptedElementType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.encryption.EncryptedData; +import org.opensaml.xml.encryption.EncryptedKey; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.EncryptedElementType}. + */ +public class EncryptedElementTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + EncryptedElementType eet = (EncryptedElementType) parentSAMLObject; + + if (childSAMLObject instanceof EncryptedData) { + eet.setEncryptedData((EncryptedData) childSAMLObject); + } else if (childSAMLObject instanceof EncryptedKey) { + eet.getEncryptedKeys().add((EncryptedKey) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDBuilder.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.EncryptedID; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.EncryptedIDImpl} objects. + */ +public class EncryptedIDBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public EncryptedIDBuilder() { + super(); + } + + /** {@inheritDoc} */ + public EncryptedID buildObject() { + return buildObject(SAMLConstants.SAML20_NS, EncryptedID.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public EncryptedID buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptedIDImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.EncryptedID; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.EncryptedID}. + */ +public class EncryptedIDImpl extends EncryptedElementTypeImpl implements EncryptedID { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EncryptedIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.EncryptedID}. + */ +public class EncryptedIDMarshaller extends EncryptedElementTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EncryptedIDUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.EncryptedID}. + */ +public class EncryptedIDUnmarshaller extends EncryptedElementTypeUnmarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Evidence; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.EvidenceImpl} objects. + */ +public class EvidenceBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public EvidenceBuilder() { + + } + + /** {@inheritDoc} */ + public Evidence buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Evidence.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Evidence buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EvidenceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceImpl.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.saml2.core.AssertionURIRef; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.Evidence; +import org.opensaml.saml2.core.Evidentiary; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.Evidence}. + */ +public class EvidenceImpl extends AbstractSAMLObject implements Evidence { + + /** Assertion of the Evidence. */ + private final IndexedXMLObjectChildrenList evidence; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EvidenceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + evidence = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getEvidence() { + return evidence; + } + + /** {@inheritDoc} */ + public List getAssertionIDReferences() { + return (List) evidence.subList(AssertionIDRef.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getAssertionURIReferences() { + return (List) evidence.subList(AssertionURIRef.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getAssertions() { + return (List) evidence.subList(Assertion.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getEncryptedAssertions() { + return (List) evidence.subList(EncryptedAssertion.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (evidence.size() == 0) { + return null; + } + + children.addAll(evidence); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Evidence}. + */ +public class EvidenceMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/EvidenceUnmarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.saml2.core.AssertionURIRef; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.Evidence; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Evidence}. + */ +public class EvidenceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + Evidence evidence = (Evidence) parentObject; + + if (childObject instanceof AssertionIDRef) { + evidence.getAssertionIDReferences().add((AssertionIDRef) childObject); + } else if (childObject instanceof AssertionURIRef) { + evidence.getAssertionURIReferences().add((AssertionURIRef) childObject); + } else if (childObject instanceof Assertion) { + evidence.getAssertions().add((Assertion) childObject); + } else if (childObject instanceof EncryptedAssertion) { + evidence.getEncryptedAssertions().add((EncryptedAssertion) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.GetComplete; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.GetCompleteImpl}. + */ +public class GetCompleteBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public GetCompleteBuilder() { + } + + /** {@inheritDoc} */ + public GetComplete buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, GetComplete.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public GetComplete buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new GetCompleteImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.GetComplete; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.GetComplete}. + */ +public class GetCompleteImpl extends AbstractSAMLObject implements GetComplete { + + /** URI element content. */ + private String getComplete; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected GetCompleteImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getGetComplete() { + return this.getComplete; + } + + /** {@inheritDoc} */ + public void setGetComplete(String newGetComplete) { + this.getComplete = prepareForAssignment(this.getComplete, newGetComplete); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.GetComplete; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.GetComplete} objects. + */ +public class GetCompleteMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + GetComplete gc = (GetComplete) samlObject; + + if (gc.getGetComplete() != null) { + XMLHelper.appendTextContent(domElement, gc.getGetComplete()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/GetCompleteUnmarshaller.java 17 Aug 2012 15:03:24 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.GetComplete; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.GetComplete} objects. + */ +public class GetCompleteUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + GetComplete gc = (GetComplete) samlObject; + + gc.setGetComplete(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryBuilder.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.IDPEntry; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.IDPEntryImpl}. + */ +public class IDPEntryBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public IDPEntryBuilder() { + } + + /** {@inheritDoc} */ + public IDPEntry buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, IDPEntry.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public IDPEntry buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IDPEntryImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.IDPEntry; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.IDPEntry}. + */ +public class IDPEntryImpl extends AbstractSAMLObject implements IDPEntry { + + /** The unique identifier of the IdP. */ + private String providerID; + + /** Human-readable name for the IdP. */ + private String name; + + /** + * URI reference representing the location of a profile-specific endpoint supporting the authentication request + * protocol. + */ + private String loc; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected IDPEntryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getProviderID() { + return this.providerID; + } + + /** {@inheritDoc} */ + public void setProviderID(String newProviderID) { + this.providerID = prepareForAssignment(this.providerID, newProviderID); + + } + + /** {@inheritDoc} */ + public String getName() { + return this.name; + } + + /** {@inheritDoc} */ + public void setName(String newName) { + this.name = prepareForAssignment(this.name, newName); + + } + + /** {@inheritDoc} */ + public String getLoc() { + return this.loc; + } + + /** {@inheritDoc} */ + public void setLoc(String newLoc) { + this.loc = prepareForAssignment(this.loc, newLoc); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.IDPEntry; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.IDPEntry} objects. + */ +public class IDPEntryMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + IDPEntry entry = (IDPEntry) samlObject; + + if (entry.getProviderID() != null) { + domElement.setAttributeNS(null, IDPEntry.PROVIDER_ID_ATTRIB_NAME, entry.getProviderID()); + } + if (entry.getName() != null) { + domElement.setAttributeNS(null, IDPEntry.NAME_ATTRIB_NAME, entry.getName()); + } + if (entry.getLoc() != null) { + domElement.setAttributeNS(null, IDPEntry.LOC_ATTRIB_NAME, entry.getLoc()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPEntryUnmarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.IDPEntry; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.IDPEntry} objects. + */ +public class IDPEntryUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + IDPEntry entry = (IDPEntry) samlObject; + + if (attribute.getLocalName().equals(IDPEntry.PROVIDER_ID_ATTRIB_NAME)) { + entry.setProviderID(attribute.getValue()); + } else if (attribute.getLocalName().equals(IDPEntry.NAME_ATTRIB_NAME)) { + entry.setName(attribute.getValue()); + } else if (attribute.getLocalName().equals(IDPEntry.LOC_ATTRIB_NAME)) { + entry.setLoc(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.IDPList; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.IDPListImpl}. + */ +public class IDPListBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public IDPListBuilder() { + + } + + /** {@inheritDoc} */ + public IDPList buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, IDPList.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public IDPList buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IDPListImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListImpl.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.GetComplete; +import org.opensaml.saml2.core.IDPEntry; +import org.opensaml.saml2.core.IDPList; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.IDPList}. + */ +public class IDPListImpl extends AbstractSAMLObject implements IDPList { + + /** List of IDPEntry's. */ + private final XMLObjectChildrenList idpEntries; + + /** GetComplete child element. */ + private GetComplete getComplete; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected IDPListImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + idpEntries = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getIDPEntrys() { + return idpEntries; + } + + /** {@inheritDoc} */ + public GetComplete getGetComplete() { + return getComplete; + } + + /** {@inheritDoc} */ + public void setGetComplete(GetComplete newGetComplete) { + this.getComplete = prepareForAssignment(this.getComplete, newGetComplete); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.addAll(idpEntries); + children.add(getComplete); + if (children.size() > 0) { + return Collections.unmodifiableList(children); + } else { + return null; + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListMarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.IDPList} objects. + */ +public class IDPListMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IDPListUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.GetComplete; +import org.opensaml.saml2.core.IDPEntry; +import org.opensaml.saml2.core.IDPList; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.IDPList} objects. + */ +public class IDPListUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + IDPList list = (IDPList) parentSAMLObject; + + if (childSAMLObject instanceof IDPEntry) { + list.getIDPEntrys().add((IDPEntry) childSAMLObject); + } else if (childSAMLObject instanceof GetComplete) { + list.setGetComplete((GetComplete) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Issuer; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.IssuerImpl} objects. + */ +public class IssuerBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public IssuerBuilder() { + } + + /** {@inheritDoc} */ + public Issuer buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Issuer.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Issuer buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IssuerImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerImpl.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.Issuer; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.Issuer}. + */ +public class IssuerImpl extends AbstractNameIDType implements Issuer { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected IssuerImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerMarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,26 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Issuer}. + */ +public class IssuerMarshaller extends AbstractNameIDTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/IssuerUnmarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Issuer}. + */ +public class IssuerUnmarshaller extends AbstractNameIDTypeUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/KeyInfoConfirmationDataTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/KeyInfoConfirmationDataTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/KeyInfoConfirmationDataTypeBuilder.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.KeyInfoConfirmationDataType; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.KeyInfoConfirmationDataTypeImpl} objects. + */ +public class KeyInfoConfirmationDataTypeBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public KeyInfoConfirmationDataTypeBuilder() { + } + + /** {@inheritDoc} */ + public KeyInfoConfirmationDataType buildObject() { + return buildObject(SAMLConstants.SAML20_NS, KeyInfoConfirmationDataType.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX, KeyInfoConfirmationDataType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public KeyInfoConfirmationDataType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeyInfoConfirmationDataTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/KeyInfoConfirmationDataTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/KeyInfoConfirmationDataTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/KeyInfoConfirmationDataTypeImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.saml2.core.KeyInfoConfirmationDataType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.signature.KeyInfo; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.SubjectConfirmationData}. + */ +public class KeyInfoConfirmationDataTypeImpl extends SubjectConfirmationDataImpl + implements KeyInfoConfirmationDataType { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected KeyInfoConfirmationDataTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getKeyInfos() { + return getUnknownXMLObjects(KeyInfo.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestBuilder.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.LogoutRequest; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.LogoutRequestImpl}. + */ +public class LogoutRequestBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public LogoutRequestBuilder() { + } + + /** {@inheritDoc} */ + public LogoutRequest buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, LogoutRequest.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public LogoutRequest buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new LogoutRequestImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestImpl.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,152 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.LogoutRequest; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.SessionIndex; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.LogoutRequest}. + */ +public class LogoutRequestImpl extends RequestAbstractTypeImpl implements LogoutRequest { + + /** Reason attribute. */ + private String reason; + + /** NotOnOrAfter attribute. */ + private DateTime notOnOrAfter; + + /** BaseID child element. */ + private BaseID baseID; + + /** NameID child element. */ + private NameID nameID; + + /** EncryptedID child element. */ + private EncryptedID encryptedID; + + + /** SessionIndex child elements. */ + private final XMLObjectChildrenList sessionIndexes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected LogoutRequestImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + sessionIndexes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getReason() { + return this.reason; + } + + /** {@inheritDoc} */ + public void setReason(String newReason) { + this.reason = prepareForAssignment(this.reason, newReason); + } + + /** {@inheritDoc} */ + public DateTime getNotOnOrAfter() { + return this.notOnOrAfter; + } + + /** {@inheritDoc} */ + public void setNotOnOrAfter(DateTime newNotOnOrAfter) { + this.notOnOrAfter = prepareForAssignment(this.notOnOrAfter, newNotOnOrAfter); + } + + /** {@inheritDoc} */ + public BaseID getBaseID() { + return baseID; + } + + /** {@inheritDoc} */ + public void setBaseID(BaseID newBaseID) { + baseID = prepareForAssignment(baseID, newBaseID); + } + + /** {@inheritDoc} */ + public NameID getNameID() { + return nameID; + } + + /** {@inheritDoc} */ + public void setNameID(NameID newNameID) { + nameID = prepareForAssignment(nameID, newNameID); + } + + /** {@inheritDoc} */ + public EncryptedID getEncryptedID() { + return this.encryptedID; + } + + /** {@inheritDoc} */ + public void setEncryptedID(EncryptedID newEncryptedID) { + this.encryptedID = prepareForAssignment(this.encryptedID, newEncryptedID); + } + + /** {@inheritDoc} */ + public List getSessionIndexes() { + return sessionIndexes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + if (baseID != null) { + children.add(baseID); + } + + if (nameID != null) { + children.add(nameID); + } + + if (encryptedID != null) { + children.add(encryptedID); + } + + children.addAll(sessionIndexes); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.saml2.core.LogoutRequest; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.LogoutRequest}. + */ +public class LogoutRequestMarshaller extends RequestAbstractTypeMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + LogoutRequest req = (LogoutRequest) samlObject; + + if (req.getReason() != null) { + domElement.setAttributeNS(null, LogoutRequest.REASON_ATTRIB_NAME, req.getReason()); + } + + if (req.getNotOnOrAfter() != null) { + String noaStr = Configuration.getSAMLDateFormatter().print(req.getNotOnOrAfter()); + domElement.setAttributeNS(null, LogoutRequest.NOT_ON_OR_AFTER_ATTRIB_NAME, noaStr); + } + + super.marshallAttributes(samlObject, domElement); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutRequestUnmarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.LogoutRequest; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.SessionIndex; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.LogoutRequest} objects. + */ +public class LogoutRequestUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + LogoutRequest req = (LogoutRequest) samlObject; + + if (attribute.getLocalName().equals(LogoutRequest.REASON_ATTRIB_NAME)) { + req.setReason(attribute.getValue()); + } else if (attribute.getLocalName().equals(LogoutRequest.NOT_ON_OR_AFTER_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + req.setNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + LogoutRequest req = (LogoutRequest) parentSAMLObject; + + if (childSAMLObject instanceof BaseID) { + req.setBaseID((BaseID) childSAMLObject); + } else if (childSAMLObject instanceof NameID) { + req.setNameID((NameID) childSAMLObject); + } else if (childSAMLObject instanceof EncryptedID) { + req.setEncryptedID((EncryptedID) childSAMLObject); + } else if (childSAMLObject instanceof SessionIndex) { + req.getSessionIndexes().add((SessionIndex) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.LogoutResponse; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.LogoutResponseImpl}. + */ +public class LogoutResponseBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public LogoutResponseBuilder() { + } + + /** {@inheritDoc} */ + public LogoutResponse buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, LogoutResponse.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public LogoutResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new LogoutResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.LogoutResponse; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.LogoutResponse}. + */ +public class LogoutResponseImpl extends StatusResponseTypeImpl implements LogoutResponse { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected LogoutResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.LogoutResponse} objects. + */ +public class LogoutResponseMarshaller extends StatusResponseTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/LogoutResponseUnmarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.LogoutResponse} objects. + */ +public class LogoutResponseUnmarshaller extends StatusResponseTypeUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestBuilder.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.ManageNameIDRequest; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.ManageNameIDRequestImpl} objects. + */ +public class ManageNameIDRequestBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ManageNameIDRequestBuilder() { + + } + + /** {@inheritDoc} */ + public ManageNameIDRequest buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, ManageNameIDRequest.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public ManageNameIDRequest buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ManageNameIDRequestImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestImpl.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,146 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.ManageNameIDRequest; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NewEncryptedID; +import org.opensaml.saml2.core.NewID; +import org.opensaml.saml2.core.Terminate; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.ManageNameIDRequest}. + */ +public class ManageNameIDRequestImpl extends RequestAbstractTypeImpl implements ManageNameIDRequest { + + /** NameID child element. */ + private NameID nameID; + + /** EncryptedID child element. */ + private EncryptedID encryptedID; + + /** NewID child element. */ + private NewID newID; + + /** NameID child element. */ + private NewEncryptedID newEncryptedID; + + /** Terminate child element. */ + private Terminate terminate; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ManageNameIDRequestImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public NameID getNameID() { + return this.nameID; + } + + /** {@inheritDoc} */ + public void setNameID(NameID newNameID) { + this.nameID = prepareForAssignment(this.nameID, newNameID); + } + + /** {@inheritDoc} */ + public EncryptedID getEncryptedID() { + return this.encryptedID; + } + + /** {@inheritDoc} */ + public void setEncryptedID(EncryptedID newEncID) { + this.encryptedID = prepareForAssignment(this.encryptedID, newEncID); + } + + /** {@inheritDoc} */ + public NewID getNewID() { + return this.newID; + } + + /** {@inheritDoc} */ + public void setNewID(NewID newNewID) { + this.newID = prepareForAssignment(this.newID, newNewID); + } + + /** {@inheritDoc} */ + public NewEncryptedID getNewEncryptedID() { + return this.newEncryptedID; + } + + /** {@inheritDoc} */ + public void setNewEncryptedID(NewEncryptedID newNewEncryptedID) { + this.newEncryptedID = prepareForAssignment(this.newEncryptedID, newNewEncryptedID); + } + + /** {@inheritDoc} */ + public Terminate getTerminate() { + return this.terminate; + } + + /** {@inheritDoc} */ + public void setTerminate(Terminate newTerminate) { + this.terminate = prepareForAssignment(this.terminate, newTerminate); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + if (nameID != null) { + children.add(nameID); + } + if (encryptedID != null) { + children.add(encryptedID); + } + if (newID != null) { + children.add(newID); + } + if (newEncryptedID != null) { + children.add(newEncryptedID); + } + if (terminate != null) { + children.add(terminate); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.ManageNameIDRequest} objects. + */ +public class ManageNameIDRequestMarshaller extends RequestAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDRequestUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.ManageNameIDRequest; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NewEncryptedID; +import org.opensaml.saml2.core.NewID; +import org.opensaml.saml2.core.Terminate; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.ManageNameIDRequest} objects. + */ +public class ManageNameIDRequestUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + ManageNameIDRequest req = (ManageNameIDRequest) parentSAMLObject; + + if (childSAMLObject instanceof NameID) { + req.setNameID((NameID) childSAMLObject); + } else if (childSAMLObject instanceof EncryptedID) { + req.setEncryptedID((EncryptedID) childSAMLObject); + } else if (childSAMLObject instanceof NewID) { + req.setNewID((NewID) childSAMLObject); + } else if (childSAMLObject instanceof NewEncryptedID) { + req.setNewEncryptedID((NewEncryptedID) childSAMLObject); + } else if (childSAMLObject instanceof Terminate) { + req.setTerminate((Terminate) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.ManageNameIDResponse; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.ManageNameIDResponseImpl} objects. + */ +public class ManageNameIDResponseBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ManageNameIDResponseBuilder() { + + } + + /** {@inheritDoc} */ + public ManageNameIDResponse buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, ManageNameIDResponse.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public ManageNameIDResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ManageNameIDResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.ManageNameIDResponse; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.ManageNameIDResponseImpl} objects. + */ +public class ManageNameIDResponseImpl extends StatusResponseTypeImpl implements ManageNameIDResponse { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ManageNameIDResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.ManageNameIDResponse} objects. + */ +public class ManageNameIDResponseMarshaller extends StatusResponseTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ManageNameIDResponseUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.ManageNameIDResponse} objects. + */ +public class ManageNameIDResponseUnmarshaller extends StatusResponseTypeUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDBuilder.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NameID; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.NameIDImpl} objects. + */ +public class NameIDBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public NameIDBuilder() { + + } + + /** {@inheritDoc} */ + public NameID buildObject() { + return buildObject(SAMLConstants.SAML20_NS, NameID.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public NameID buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NameIDImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.NameID; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.NameID}. + */ +public class NameIDImpl extends AbstractNameIDType implements NameID { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected NameIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NameIDMappingRequest; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.NameIDMappingRequestImpl}. + */ +public class NameIDMappingRequestBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public NameIDMappingRequestBuilder() { + + } + + /** {@inheritDoc} */ + public NameIDMappingRequest buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, NameIDMappingRequest.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public NameIDMappingRequest buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NameIDMappingRequestImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestImpl.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDMappingRequest; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.NameIDMappingRequest}. + */ +public class NameIDMappingRequestImpl extends RequestAbstractTypeImpl implements NameIDMappingRequest { + + /** BaseID child element. */ + private BaseID baseID; + + /** NameID child element. */ + private NameID nameID; + + /** EncryptedID child element. */ + private EncryptedID encryptedID; + + /** NameIDPolicy child element. */ + private NameIDPolicy nameIDPolicy; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected NameIDMappingRequestImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public BaseID getBaseID() { + return baseID; + } + + /** {@inheritDoc} */ + public void setBaseID(BaseID newBaseID) { + baseID = prepareForAssignment(baseID, newBaseID); + } + + /** {@inheritDoc} */ + public NameID getNameID() { + return nameID; + } + + /** {@inheritDoc} */ + public void setNameID(NameID newNameID) { + nameID = prepareForAssignment(nameID, newNameID); + } + + /** {@inheritDoc} */ + public EncryptedID getEncryptedID() { + return this.encryptedID; + } + + /** {@inheritDoc} */ + public void setEncryptedID(EncryptedID newEncryptedID) { + this.encryptedID = prepareForAssignment(this.encryptedID, newEncryptedID); + } + + /** {@inheritDoc} */ + public NameIDPolicy getNameIDPolicy() { + return this.nameIDPolicy; + } + + /** {@inheritDoc} */ + public void setNameIDPolicy(NameIDPolicy newNameIDPolicy) { + this.nameIDPolicy = prepareForAssignment(this.nameIDPolicy, newNameIDPolicy); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + if (baseID != null) { + children.add(baseID); + } + + if (nameID != null) { + children.add(nameID); + } + + if (encryptedID != null) { + children.add(encryptedID); + } + + if (nameIDPolicy != null) { + children.add(nameIDPolicy); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.NameIDMappingRequest}. + */ +public class NameIDMappingRequestMarshaller extends RequestAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingRequestUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDMappingRequest; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.NameIDMappingRequest} objects. + */ +public class NameIDMappingRequestUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + NameIDMappingRequest req = (NameIDMappingRequest) parentSAMLObject; + + if (childSAMLObject instanceof BaseID) { + req.setBaseID((BaseID) childSAMLObject); + } else if (childSAMLObject instanceof NameID) { + req.setNameID((NameID) childSAMLObject); + } else if (childSAMLObject instanceof EncryptedID) { + req.setEncryptedID((EncryptedID) childSAMLObject); + } else if (childSAMLObject instanceof NameIDPolicy) { + req.setNameIDPolicy((NameIDPolicy) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseBuilder.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NameIDMappingResponse; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.NameIDMappingResponseImpl}. + */ +public class NameIDMappingResponseBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public NameIDMappingResponseBuilder() { + + } + + /** {@inheritDoc} */ + public NameIDMappingResponse buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, NameIDMappingResponse.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public NameIDMappingResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NameIDMappingResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseImpl.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDMappingResponse; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.NameIDMappingResponse}. + */ +public class NameIDMappingResponseImpl extends StatusResponseTypeImpl implements NameIDMappingResponse { + + /** NameID child element. */ + private NameID nameID; + + /** EncryptedID child element. */ + private EncryptedID encryptedID; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected NameIDMappingResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public NameID getNameID() { + return this.nameID; + } + + /** {@inheritDoc} */ + public void setNameID(NameID newNameID) { + this.nameID = prepareForAssignment(this.nameID, newNameID); + } + + /** {@inheritDoc} */ + public EncryptedID getEncryptedID() { + return this.encryptedID; + } + + /** {@inheritDoc} */ + public void setEncryptedID(EncryptedID newEncryptedID) { + this.encryptedID = prepareForAssignment(this.encryptedID, newEncryptedID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + if (nameID != null) { + children.add(nameID); + } + + if (encryptedID != null) { + children.add(encryptedID); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseMarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.NameIDMappingResponse} objects. + */ +public class NameIDMappingResponseMarshaller extends StatusResponseTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMappingResponseUnmarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDMappingResponse; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.core.NameIDMappingResponse} objects. + */ +public class NameIDMappingResponseUnmarshaller extends StatusResponseTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + NameIDMappingResponse resp = (NameIDMappingResponse) parentSAMLObject; + + if (childSAMLObject instanceof NameID) { + resp.setNameID((NameID) childSAMLObject); + } else if (childSAMLObject instanceof EncryptedID) { + resp.setEncryptedID((EncryptedID) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.NameID} objects. + */ +public class NameIDMarshaller extends AbstractNameIDTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyBuilder.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NameIDPolicy; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.NameIDPolicyImpl}. + */ +public class NameIDPolicyBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public NameIDPolicyBuilder() { + } + + /** {@inheritDoc} */ + public NameIDPolicy buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, NameIDPolicy.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public NameIDPolicy buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NameIDPolicyImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.NameIDPolicy}. + */ +public class NameIDPolicyImpl extends AbstractSAMLObject implements NameIDPolicy { + + /** NameID Format URI. */ + private String format; + + /** NameID Format URI. */ + private String spNameQualifier; + + /** NameID Format URI. */ + private XSBooleanValue allowCreate; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected NameIDPolicyImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getFormat() { + return format; + } + + /** {@inheritDoc} */ + public void setFormat(String newFormat) { + format = prepareForAssignment(format, newFormat); + + } + + /** {@inheritDoc} */ + public String getSPNameQualifier() { + return spNameQualifier; + } + + /** {@inheritDoc} */ + public void setSPNameQualifier(String newSPNameQualifier) { + spNameQualifier = prepareForAssignment(spNameQualifier, newSPNameQualifier); + + } + + /** {@inheritDoc} */ + public Boolean getAllowCreate(){ + if(allowCreate != null){ + return allowCreate.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue getAllowCreateXSBoolean() { + return allowCreate; + } + + /** {@inheritDoc} */ + public void setAllowCreate(Boolean newAllowCreate){ + if(newAllowCreate != null){ + allowCreate = prepareForAssignment(allowCreate, new XSBooleanValue(newAllowCreate, false)); + }else{ + allowCreate = prepareForAssignment(allowCreate, null); + } + } + + /** {@inheritDoc} */ + public void setAllowCreate(XSBooleanValue newAllowCreate) { + allowCreate = prepareForAssignment(allowCreate, newAllowCreate); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyMarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.NameIDPolicy} objects. + */ +public class NameIDPolicyMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + NameIDPolicy policy = (NameIDPolicy) samlObject; + + if (policy.getFormat() != null) { + domElement.setAttributeNS(null, NameIDPolicy.FORMAT_ATTRIB_NAME, policy.getFormat()); + } + + if (policy.getSPNameQualifier() != null) { + domElement.setAttributeNS(null, NameIDPolicy.SP_NAME_QUALIFIER_ATTRIB_NAME, policy.getSPNameQualifier()); + } + + if (policy.getAllowCreateXSBoolean() != null) { + domElement.setAttributeNS(null, NameIDPolicy.ALLOW_CREATE_ATTRIB_NAME, policy.getAllowCreateXSBoolean() + .toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDPolicyUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.NameIDPolicy} objects. + */ +public class NameIDPolicyUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + NameIDPolicy policy = (NameIDPolicy) samlObject; + + if (attribute.getLocalName().equals(NameIDPolicy.FORMAT_ATTRIB_NAME)) { + policy.setFormat(attribute.getValue()); + } + if (attribute.getLocalName().equals(NameIDPolicy.SP_NAME_QUALIFIER_ATTRIB_NAME)) { + policy.setSPNameQualifier(attribute.getValue()); + } + if (attribute.getLocalName().equals(NameIDPolicy.ALLOW_CREATE_ATTRIB_NAME)) { + policy.setAllowCreate(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NameIDUnmarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,26 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.NameID} objects. + */ +public class NameIDUnmarshaller extends AbstractNameIDTypeUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NewEncryptedID; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.NewEncryptedIDImpl} objects. + */ +public class NewEncryptedIDBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public NewEncryptedIDBuilder() { + super(); + } + + /** {@inheritDoc} */ + public NewEncryptedID buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, NewEncryptedID.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public NewEncryptedID buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NewEncryptedIDImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.NewEncryptedID; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.NewEncryptedID}. + */ +public class NewEncryptedIDImpl extends EncryptedElementTypeImpl implements NewEncryptedID { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected NewEncryptedIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.EncryptedID}. + */ +public class NewEncryptedIDMarshaller extends EncryptedElementTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewEncryptedIDUnmarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.NewEncryptedID}. + */ +public class NewEncryptedIDUnmarshaller extends EncryptedElementTypeUnmarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDBuilder.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.NewID; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.NewIDImpl} objects. + */ +public class NewIDBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public NewIDBuilder() { + } + + /** {@inheritDoc} */ + public NewID buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, NewID.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public NewID buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NewIDImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDImpl.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.NewID; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.NewID}. + */ +public class NewIDImpl extends AbstractSAMLObject implements NewID { + + /** The new NameID. */ + private String newID; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected NewIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getNewID() { + return newID; + } + + /** {@inheritDoc} */ + public void setNewID(String newNewID) { + this.newID = prepareForAssignment(this.newID, newNewID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDMarshaller.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.NewID; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.NewID} objects. + */ +public class NewIDMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + NewID newID = (NewID) samlObject; + + if (newID.getNewID() != null) { + XMLHelper.appendTextContent(domElement, newID.getNewID()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/NewIDUnmarshaller.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.NewID; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.NewID} objects. + */ +public class NewIDUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + NewID newID = (NewID) samlObject; + + newID.setNewID(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseBuilder.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.OneTimeUse; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.OneTimeUseImpl} objects. + */ +public class OneTimeUseBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public OneTimeUseBuilder() { + + } + + /** {@inheritDoc} */ + public OneTimeUse buildObject() { + return buildObject(SAMLConstants.SAML20_NS, OneTimeUse.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public OneTimeUse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new OneTimeUseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseImpl.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.OneTimeUse; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.OneTimeUse}. + */ +public class OneTimeUseImpl extends AbstractSAMLObject implements OneTimeUse { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected OneTimeUseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.OneTimeUse} objects. + */ +public class OneTimeUseMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/OneTimeUseUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.OneTimeUse} objects. + */ +public class OneTimeUseUnmarshaller extends AbstractSAMLObjectUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.ProxyRestriction; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.ProxyRestrictionImpl} objects. + */ +public class ProxyRestrictionBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public ProxyRestrictionBuilder() { + } + + /** {@inheritDoc} */ + public ProxyRestriction buildObject() { + return buildObject(SAMLConstants.SAML20_NS, ProxyRestriction.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public ProxyRestriction buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ProxyRestrictionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Audience; +import org.opensaml.saml2.core.ProxyRestriction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.ProxyRestriction}. + */ +public class ProxyRestrictionImpl extends AbstractSAMLObject implements ProxyRestriction { + + /** Audiences of the Restriction. */ + private final XMLObjectChildrenList audiences; + + /** Count of the Restriction. */ + private Integer proxyCount; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ProxyRestrictionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + audiences = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAudiences() { + return audiences; + } + + /** {@inheritDoc} */ + public Integer getProxyCount() { + return proxyCount; + } + + /** {@inheritDoc} */ + public void setProxyCount(Integer newProxyCount) { + if (newProxyCount >= 0) { + this.proxyCount = prepareForAssignment(this.proxyCount, newProxyCount); + } else { + throw new IllegalArgumentException("Count must be a non-negative integer."); + } + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(audiences); + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionMarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.ProxyRestriction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.ProxyRestriction} objects. + */ +public class ProxyRestrictionMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + ProxyRestriction proxyRestriction = (ProxyRestriction) samlObject; + if (proxyRestriction.getProxyCount() != null) { + domElement.setAttributeNS(null, ProxyRestriction.COUNT_ATTRIB_NAME, Integer.toString(proxyRestriction + .getProxyCount())); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ProxyRestrictionUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Audience; +import org.opensaml.saml2.core.ProxyRestriction; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.ProxyRestriction} objects. + */ +public class ProxyRestrictionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + ProxyRestriction proxyRestriction = (ProxyRestriction) parentObject; + + if (childObject instanceof Audience) { + proxyRestriction.getAudiences().add((Audience) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + ProxyRestriction proxyRestriction = (ProxyRestriction) samlObject; + + if (attribute.getLocalName().equals(ProxyRestriction.COUNT_ATTRIB_NAME)) { + proxyRestriction.setProxyCount(Integer.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeImpl.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,171 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.RequestAbstractType}. + */ +public abstract class RequestAbstractTypeImpl extends AbstractSignableSAMLObject implements RequestAbstractType { + + /** SAML Version of the request. */ + private SAMLVersion version; + + /** Unique identifier of the request. */ + private String id; + + /** Date/time request was issued. */ + private DateTime issueInstant; + + /** URI of the request destination. */ + private String destination; + + /** URI of the SAML user consent type. */ + private String consent; + + /** URI of the SAML user consent type. */ + private Issuer issuer; + + /** Extensions child element. */ + private Extensions extensions; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RequestAbstractTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + version = SAMLVersion.VERSION_20; + } + + /** {@inheritDoc} */ + public SAMLVersion getVersion() { + return version; + } + + /** {@inheritDoc} */ + public void setVersion(SAMLVersion newVersion) { + this.version = prepareForAssignment(this.version, newVersion); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String newID) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, newID); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public DateTime getIssueInstant() { + return issueInstant; + } + + /** {@inheritDoc} */ + public void setIssueInstant(DateTime newIssueInstant) { + this.issueInstant = prepareForAssignment(this.issueInstant, newIssueInstant); + } + + /** {@inheritDoc} */ + public String getDestination() { + return destination; + } + + /** {@inheritDoc} */ + public void setDestination(String newDestination) { + this.destination = prepareForAssignment(this.destination, newDestination); + } + + /** {@inheritDoc} */ + public String getConsent() { + return consent; + } + + /** {@inheritDoc} */ + public void setConsent(String newConsent) { + this.consent = prepareForAssignment(this.consent, newConsent); + } + + /** {@inheritDoc} */ + public Issuer getIssuer() { + return issuer; + } + + /** {@inheritDoc} */ + public void setIssuer(Issuer newIssuer) { + this.issuer = prepareForAssignment(this.issuer, newIssuer); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return this.extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions newExtensions) { + this.extensions = prepareForAssignment(this.extensions, newExtensions); + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID() { + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (issuer != null) { + children.add(issuer); + } + if (getSignature() != null) { + children.add(getSignature()); + } + if (extensions != null) { + children.add(extensions); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.RequestAbstractType} objects. + */ +public abstract class RequestAbstractTypeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + RequestAbstractType req = (RequestAbstractType) samlObject; + + if (req.getVersion() != null) { + domElement.setAttributeNS(null, RequestAbstractType.VERSION_ATTRIB_NAME, req.getVersion().toString()); + } + + if (req.getID() != null) { + domElement.setAttributeNS(null, RequestAbstractType.ID_ATTRIB_NAME, req.getID()); + domElement.setIdAttributeNS(null, RequestAbstractType.ID_ATTRIB_NAME, true); + } + + if (req.getVersion() != null) { + domElement.setAttributeNS(null, RequestAbstractType.VERSION_ATTRIB_NAME, req.getVersion().toString()); + } + + if (req.getIssueInstant() != null) { + String iiStr = Configuration.getSAMLDateFormatter().print(req.getIssueInstant()); + domElement.setAttributeNS(null, RequestAbstractType.ISSUE_INSTANT_ATTRIB_NAME, iiStr); + } + + if (req.getDestination() != null) { + domElement.setAttributeNS(null, RequestAbstractType.DESTINATION_ATTRIB_NAME, req.getDestination()); + } + + if (req.getConsent() != null) { + domElement.setAttributeNS(null, RequestAbstractType.CONSENT_ATTRIB_NAME, req.getConsent()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestAbstractTypeUnmarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.RequestAbstractType} objects. + */ +public abstract class RequestAbstractTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + RequestAbstractType req = (RequestAbstractType) samlObject; + + if (attribute.getLocalName().equals(RequestAbstractType.VERSION_ATTRIB_NAME)) { + req.setVersion(SAMLVersion.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(RequestAbstractType.ID_ATTRIB_NAME)) { + req.setID(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (attribute.getLocalName().equals(RequestAbstractType.ISSUE_INSTANT_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + req.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(RequestAbstractType.DESTINATION_ATTRIB_NAME)) { + req.setDestination(attribute.getValue()); + } else if (attribute.getLocalName().equals(RequestAbstractType.CONSENT_ATTRIB_NAME)) { + req.setConsent(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + RequestAbstractType req = (RequestAbstractType) parentSAMLObject; + + if (childSAMLObject instanceof Issuer) { + req.setIssuer((Issuer) childSAMLObject); + } else if (childSAMLObject instanceof Signature) { + req.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof Extensions) { + req.setExtensions((Extensions) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.RequestedAuthnContext; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.RequestedAuthnContextImpl} objects. + */ +public class RequestedAuthnContextBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public RequestedAuthnContextBuilder() { + } + + /** {@inheritDoc} */ + public RequestedAuthnContext buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, RequestedAuthnContext.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public RequestedAuthnContext buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedAuthnContextImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextImpl.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,96 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.RequestedAuthnContext}. + */ +public class RequestedAuthnContextImpl extends AbstractSAMLObject implements RequestedAuthnContext { + + /** AuthnContextClassRef child elements. */ + private final XMLObjectChildrenList authnContextClassRefs; + + /** AuthnContextDeclRef child elements. */ + private final XMLObjectChildrenList authnContextDeclRefs; + + /** Comparison attribute. */ + private AuthnContextComparisonTypeEnumeration comparison; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RequestedAuthnContextImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + authnContextClassRefs = new XMLObjectChildrenList(this); + authnContextDeclRefs = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AuthnContextComparisonTypeEnumeration getComparison() { + return this.comparison; + } + + /** {@inheritDoc} */ + public void setComparison(AuthnContextComparisonTypeEnumeration newComparison) { + this.comparison = prepareForAssignment(this.comparison, newComparison); + } + + /** {@inheritDoc} */ + public List getAuthnContextClassRefs() { + return this.authnContextClassRefs; + } + + /** {@inheritDoc} */ + public List getAuthnContextDeclRefs() { + return this.authnContextDeclRefs; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(authnContextClassRefs); + children.addAll(authnContextDeclRefs); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.RequestedAuthnContext} objects. + */ +public class RequestedAuthnContextMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + RequestedAuthnContext rac = (RequestedAuthnContext) samlObject; + + if (rac.getComparison() != null) { + domElement.setAttributeNS(null, RequestedAuthnContext.COMPARISON_ATTRIB_NAME, rac.getComparison() + .toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequestedAuthnContextUnmarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.RequestedAuthnContext} objects. + */ +public class RequestedAuthnContextUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + RequestedAuthnContext rac = (RequestedAuthnContext) samlObject; + + if (attribute.getLocalName().equals(RequestedAuthnContext.COMPARISON_ATTRIB_NAME)) { + if ("exact".equals(attribute.getValue())) { + rac.setComparison(AuthnContextComparisonTypeEnumeration.EXACT); + } else if ("minimum".equals(attribute.getValue())) { + rac.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); + } else if ("maximum".equals(attribute.getValue())) { + rac.setComparison(AuthnContextComparisonTypeEnumeration.MAXIMUM); + } else if ("better".equals(attribute.getValue())) { + rac.setComparison(AuthnContextComparisonTypeEnumeration.BETTER); + } else { + throw new UnmarshallingException("Saw an invalid value for Comparison attribute: " + + attribute.getValue()); + } + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + RequestedAuthnContext rac = (RequestedAuthnContext) parentSAMLObject; + if (childSAMLObject instanceof AuthnContextClassRef) { + rac.getAuthnContextClassRefs().add((AuthnContextClassRef) childSAMLObject); + } else if (childSAMLObject instanceof AuthnContextDeclRef) { + rac.getAuthnContextDeclRefs().add((AuthnContextDeclRef) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDBuilder.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.RequesterID; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.RequesterIDImpl}. + */ +public class RequesterIDBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public RequesterIDBuilder() { + } + + /** {@inheritDoc} */ + public RequesterID buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, RequesterID.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public RequesterID buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequesterIDImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDImpl.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.RequesterID; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.RequesterID}. + */ +public class RequesterIDImpl extends AbstractSAMLObject implements RequesterID { + + /** ID of the requester. */ + private String requesterID; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RequesterIDImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getRequesterID() { + return this.requesterID; + } + + /** {@inheritDoc} */ + public void setRequesterID(String newRequesterID) { + this.requesterID = prepareForAssignment(this.requesterID, newRequesterID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDMarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.RequesterID; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.RequesterID} objects. + */ +public class RequesterIDMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + RequesterID reqID = (RequesterID) samlObject; + + if (reqID.getRequesterID() != null) { + XMLHelper.appendTextContent(domElement, reqID.getRequesterID()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/RequesterIDUnmarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.RequesterID; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.RequesterID} objects. + */ +public class RequesterIDUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + RequesterID reqID = (RequesterID) samlObject; + + reqID.setRequesterID(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseBuilder.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Response; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.ResponseImpl}. + */ +public class ResponseBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ResponseBuilder() { + + } + + /** {@inheritDoc} */ + public Response buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, Response.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public Response buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseImpl.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.Response; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Response}. + */ +public class ResponseImpl extends StatusResponseTypeImpl implements Response { + + /** Assertion child elements. */ + private final IndexedXMLObjectChildrenList indexedChildren; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + indexedChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAssertions() { + return (List) indexedChildren.subList(Assertion.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getEncryptedAssertions() { + return (List) indexedChildren.subList(EncryptedAssertion.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + + children.addAll(indexedChildren); + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.Response} objects. + */ +public class ResponseMarshaller extends StatusResponseTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ResponseUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.Response; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Response} objects. + */ +public class ResponseUnmarshaller extends StatusResponseTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Response resp = (Response) parentSAMLObject; + + if (childSAMLObject instanceof Assertion) { + resp.getAssertions().add((Assertion) childSAMLObject); + } else if (childSAMLObject instanceof EncryptedAssertion) { + resp.getEncryptedAssertions().add((EncryptedAssertion) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingBuilder.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Scoping; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.ScopingImpl}. + */ +public class ScopingBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ScopingBuilder() { + } + + /** {@inheritDoc} */ + public Scoping buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, Scoping.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public Scoping buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ScopingImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingImpl.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,103 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.IDPList; +import org.opensaml.saml2.core.RequesterID; +import org.opensaml.saml2.core.Scoping; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Scoping}. + */ +public class ScopingImpl extends AbstractSAMLObject implements Scoping { + + /** IDPList child element. */ + private IDPList idpList; + + /** List of RequesterID child elements. */ + private final XMLObjectChildrenList requesterIDs; + + /** ProxyCount attribute. */ + private Integer proxyCount; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ScopingImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + requesterIDs = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Integer getProxyCount() { + return this.proxyCount; + } + + /** {@inheritDoc} */ + public void setProxyCount(Integer newProxyCount) { + this.proxyCount = prepareForAssignment(this.proxyCount, newProxyCount); + } + + /** {@inheritDoc} */ + public IDPList getIDPList() { + return idpList; + } + + /** {@inheritDoc} */ + public void setIDPList(IDPList newIDPList) { + this.idpList = prepareForAssignment(this.idpList, newIDPList); + + } + + /** {@inheritDoc} */ + public List getRequesterIDs() { + return requesterIDs; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (idpList != null) { + children.add(idpList); + } + + children.addAll(requesterIDs); + + if (children.size() > 0) { + return Collections.unmodifiableList(children); + } else { + return null; + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingMarshaller.java 17 Aug 2012 15:03:17 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.Scoping; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.Scoping} objects. + */ +public class ScopingMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + Scoping scoping = (Scoping) samlObject; + + if (scoping.getProxyCount() != null) { + domElement.setAttributeNS(null, Scoping.PROXY_COUNT_ATTRIB_NAME, scoping.getProxyCount().toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/ScopingUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.IDPList; +import org.opensaml.saml2.core.RequesterID; +import org.opensaml.saml2.core.Scoping; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Scoping} objects. + */ +public class ScopingUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Scoping scoping = (Scoping) samlObject; + + if (attribute.getLocalName().equals(Scoping.PROXY_COUNT_ATTRIB_NAME)) { + scoping.setProxyCount(Integer.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Scoping scoping = (Scoping) parentSAMLObject; + if (childSAMLObject instanceof IDPList) { + scoping.setIDPList((IDPList) childSAMLObject); + } else if (childSAMLObject instanceof RequesterID) { + scoping.getRequesterIDs().add((RequesterID) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexBuilder.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.SessionIndex; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.SessionIndexImpl} objects. + */ +public class SessionIndexBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public SessionIndexBuilder() { + } + + /** {@inheritDoc} */ + public SessionIndex buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, SessionIndex.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public SessionIndex buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SessionIndexImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.SessionIndex; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.SessionIndex}. + */ +public class SessionIndexImpl extends AbstractSAMLObject implements SessionIndex { + + /** The session index value. */ + private String sessionIndex; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SessionIndexImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getSessionIndex() { + return this.sessionIndex; + } + + /** {@inheritDoc} */ + public void setSessionIndex(String newSessionIndex) { + this.sessionIndex = prepareForAssignment(this.sessionIndex, newSessionIndex); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.SessionIndex; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.SessionIndex} objects. + */ +public class SessionIndexMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + SessionIndex si = (SessionIndex) samlObject; + + if (si.getSessionIndex() != null) { + XMLHelper.appendTextContent(domElement, si.getSessionIndex()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SessionIndexUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.SessionIndex; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.SessionIndex} objects. + */ +public class SessionIndexUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + SessionIndex si = (SessionIndex) samlObject; + + si.setSessionIndex(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Status; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.StatusImpl}. + */ +public class StatusBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public StatusBuilder() { + + } + + /** {@inheritDoc} */ + public Status buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, Status.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public Status buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeBuilder.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.StatusCode; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.StatusCodeImpl}. + */ +public class StatusCodeBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + * + */ + public StatusCodeBuilder() { + } + + /** {@inheritDoc} */ + public StatusCode buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, StatusCode.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public StatusCode buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusCodeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeImpl.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.StatusCode}. + */ +public class StatusCodeImpl extends AbstractSAMLObject implements StatusCode { + + /** Value attribute URI. */ + private String value; + + /** Nested secondary StatusCode child element. */ + private StatusCode childStatusCode; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusCodeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public StatusCode getStatusCode() { + return childStatusCode; + } + + /** {@inheritDoc} */ + public void setStatusCode(StatusCode newStatusCode) { + this.childStatusCode = prepareForAssignment(this.childStatusCode, newStatusCode); + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + this.value = prepareForAssignment(this.value, newValue); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + if (childStatusCode != null) { + ArrayList children = new ArrayList(); + children.add(childStatusCode); + return Collections.unmodifiableList(children); + } else { + return null; + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.StatusCode} objects. + */ +public class StatusCodeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + StatusCode statusCode = (StatusCode) samlObject; + + if (statusCode.getValue() != null) { + domElement.setAttributeNS(null, StatusCode.VALUE_ATTRIB_NAME, statusCode.getValue()); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusCodeUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.StatusCode} objects. + */ +public class StatusCodeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + StatusCode statusCode = (StatusCode) samlObject; + + if (attribute.getLocalName().equals(StatusCode.VALUE_ATTRIB_NAME)) { + statusCode.setValue(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + StatusCode statusCode = (StatusCode) parentSAMLObject; + + if (childSAMLObject instanceof StatusCode) { + statusCode.setStatusCode((StatusCode) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailBuilder.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.StatusDetail; + +public class StatusDetailBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public StatusDetailBuilder() { + + } + + /** + * {@inheritDoc} + */ + public StatusDetail buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, StatusDetail.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** + * {@inheritDoc} + */ + public StatusDetail buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusDetailImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailImpl.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.StatusDetail; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.StatusDetail}. + */ +public class StatusDetailImpl extends AbstractSAMLObject implements StatusDetail { + + /** child "any" elements. */ + private final IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusDetailImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** + * {@inheritDoc} + */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** + * {@inheritDoc} + */ + public List getOrderedChildren() { + return Collections.unmodifiableList(unknownChildren); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailMarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.StatusDetail} objects. + */ +public class StatusDetailMarshaller extends AbstractSAMLObjectMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusDetailUnmarshaller.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.StatusDetail; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.StatusDetail} objects. + */ +public class StatusDetailUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + StatusDetail statusDetail = (StatusDetail) parentSAMLObject; + + statusDetail.getUnknownXMLObjects().add(childSAMLObject); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusImpl.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,104 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Status; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.core.StatusDetail; +import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Status}. + */ +public class StatusImpl extends AbstractSAMLObject implements Status { + + /** StatusCode element. */ + private StatusCode statusCode; + + /** StatusMessage element. */ + private StatusMessage statusMessage; + + /** StatusDetail element. */ + private StatusDetail statusDetail; + + /** + * Constructor. + * + * @param namespaceURI namespace uri + * @param elementLocalName element name + * @param namespacePrefix namespace prefix + */ + protected StatusImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public StatusCode getStatusCode() { + return this.statusCode; + } + + /** {@inheritDoc} */ + public void setStatusCode(StatusCode newStatusCode) { + this.statusCode = prepareForAssignment(this.statusCode, newStatusCode); + + } + + /** {@inheritDoc} */ + public StatusMessage getStatusMessage() { + return this.statusMessage; + } + + /** {@inheritDoc} */ + public void setStatusMessage(StatusMessage newStatusMessage) { + this.statusMessage = prepareForAssignment(this.getStatusMessage(), newStatusMessage); + } + + /** {@inheritDoc} */ + public StatusDetail getStatusDetail() { + return this.statusDetail; + } + + /** {@inheritDoc} */ + public void setStatusDetail(StatusDetail newStatusDetail) { + this.statusDetail = prepareForAssignment(this.statusDetail, newStatusDetail); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(statusCode); + if (statusMessage != null) { + children.add(statusMessage); + } + if (statusDetail != null) { + children.add(statusDetail); + } + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.Status} objects. + */ +public class StatusMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageBuilder.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.StatusMessage; + +/** + * Builder of {@link org.opensaml.saml2.core.impl.StatusMessageImpl}. + */ +public class StatusMessageBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + * + */ + public StatusMessageBuilder() { + } + + /** {@inheritDoc} */ + public StatusMessage buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, StatusMessage.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public StatusMessage buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusMessageImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageImpl.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.StatusMessage}. + */ +public class StatusMessageImpl extends AbstractSAMLObject implements StatusMessage { + + /** The message string. */ + private String message; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusMessageImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getMessage() { + return this.message; + } + + /** {@inheritDoc} */ + public void setMessage(String newMessage) { + this.message = prepareForAssignment(this.message, newMessage); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No children for this element + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageMarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.StatusMessage} objects. + */ +public class StatusMessageMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + StatusMessage message = (StatusMessage) samlObject; + + if (message.getMessage() != null) { + XMLHelper.appendTextContent(domElement, message.getMessage()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusMessageUnmarshaller.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.StatusMessage} objects. + * + */ +public class StatusMessageUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + StatusMessage message = (StatusMessage) samlObject; + + message.setMessage(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeImpl.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,197 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.Status; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.StatusResponseType}. + */ +public abstract class StatusResponseTypeImpl extends AbstractSignableSAMLObject implements StatusResponseType { + + /** SAML Version attribute. */ + private SAMLVersion version; + + /** ID attribute. */ + private String id; + + /** InResponseTo attribute. */ + private String inResponseTo; + + /** IssueInstant attribute. */ + private DateTime issueInstant; + + /** Destination attribute. */ + private String destination; + + /** Consent attribute. */ + private String consent; + + /** Issuer child element. */ + private Issuer issuer; + + /** Extensions child element. */ + private Extensions extensions; + + /** Status child element. */ + private Status status; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusResponseTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + version = SAMLVersion.VERSION_20; + } + + /** {@inheritDoc} */ + public SAMLVersion getVersion() { + return version; + } + + /** {@inheritDoc} */ + public void setVersion(SAMLVersion newVersion) { + this.version = prepareForAssignment(this.version, newVersion); + } + + /** {@inheritDoc} */ + public String getID() { + return this.id; + } + + /** {@inheritDoc} */ + public void setID(String newID) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, newID); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public String getInResponseTo() { + return this.inResponseTo; + } + + /** {@inheritDoc} */ + public void setInResponseTo(String newInResponseTo) { + this.inResponseTo = prepareForAssignment(this.inResponseTo, newInResponseTo); + } + + /** {@inheritDoc} */ + public DateTime getIssueInstant() { + return this.issueInstant; + } + + /** {@inheritDoc} */ + public void setIssueInstant(DateTime newIssueInstant) { + this.issueInstant = prepareForAssignment(this.issueInstant, newIssueInstant); + } + + /** {@inheritDoc} */ + public String getDestination() { + return this.destination; + } + + /** {@inheritDoc} */ + public void setDestination(String newDestination) { + this.destination = prepareForAssignment(this.destination, newDestination); + } + + /** {@inheritDoc} */ + public String getConsent() { + return this.consent; + } + + /** {@inheritDoc} */ + public void setConsent(String newConsent) { + this.consent = prepareForAssignment(this.consent, newConsent); + } + + /** {@inheritDoc} */ + public Issuer getIssuer() { + return this.issuer; + } + + /** {@inheritDoc} */ + public void setIssuer(Issuer newIssuer) { + this.issuer = prepareForAssignment(this.issuer, newIssuer); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return this.extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions newExtensions) { + this.extensions = prepareForAssignment(this.extensions, newExtensions); + } + + /** {@inheritDoc} */ + public Status getStatus() { + return this.status; + } + + /** {@inheritDoc} */ + public void setStatus(Status newStatus) { + this.status = prepareForAssignment(this.status, newStatus); + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID(){ + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (issuer != null){ + children.add(issuer); + } + if(getSignature() != null){ + children.add(getSignature()); + } + if (extensions != null){ + children.add(extensions); + } + if (status != null){ + children.add(status); + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeMarshaller.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.StatusResponseType} objects. + */ +public abstract class StatusResponseTypeMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + StatusResponseType sr = (StatusResponseType) samlObject; + + if (sr.getVersion() != null) { + domElement.setAttributeNS(null, StatusResponseType.VERSION_ATTRIB_NAME, sr.getVersion().toString()); + } + + if (sr.getID() != null) { + domElement.setAttributeNS(null, StatusResponseType.ID_ATTRIB_NAME, sr.getID()); + domElement.setIdAttributeNS(null, StatusResponseType.ID_ATTRIB_NAME, true); + } + + if (sr.getInResponseTo() != null) { + domElement.setAttributeNS(null, StatusResponseType.IN_RESPONSE_TO_ATTRIB_NAME, sr.getInResponseTo()); + } + + if (sr.getVersion() != null) { + domElement.setAttributeNS(null, StatusResponseType.VERSION_ATTRIB_NAME, sr.getVersion().toString()); + } + + if (sr.getIssueInstant() != null) { + String iiStr = Configuration.getSAMLDateFormatter().print(sr.getIssueInstant()); + domElement.setAttributeNS(null, StatusResponseType.ISSUE_INSTANT_ATTRIB_NAME, iiStr); + } + + if (sr.getDestination() != null) { + domElement.setAttributeNS(null, StatusResponseType.DESTINATION_ATTRIB_NAME, sr.getDestination()); + } + + if (sr.getConsent() != null) { + domElement.setAttributeNS(null, StatusResponseType.CONSENT_ATTRIB_NAME, sr.getConsent()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusResponseTypeUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.SAMLVersion; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.Status; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.StatusResponseType} objects. + */ +public abstract class StatusResponseTypeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + StatusResponseType sr = (StatusResponseType) samlObject; + + if (attribute.getLocalName().equals(StatusResponseType.VERSION_ATTRIB_NAME)) { + sr.setVersion(SAMLVersion.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(StatusResponseType.ID_ATTRIB_NAME)) { + sr.setID(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (attribute.getLocalName().equals(StatusResponseType.IN_RESPONSE_TO_ATTRIB_NAME)) { + sr.setInResponseTo(attribute.getValue()); + } else if (attribute.getLocalName().equals(StatusResponseType.ISSUE_INSTANT_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + sr.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(StatusResponseType.DESTINATION_ATTRIB_NAME)) { + sr.setDestination(attribute.getValue()); + } else if (attribute.getLocalName().equals(StatusResponseType.CONSENT_ATTRIB_NAME)) { + sr.setConsent(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + StatusResponseType sr = (StatusResponseType) parentSAMLObject; + + if (childSAMLObject instanceof Issuer) { + sr.setIssuer((Issuer) childSAMLObject); + } else if (childSAMLObject instanceof Signature) { + sr.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof Extensions) { + sr.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof Status) { + sr.setStatus((Status) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/StatusUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.Status; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.core.StatusDetail; +import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Status} objects. + */ +public class StatusUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Status status = (Status) parentSAMLObject; + + if (childSAMLObject instanceof StatusCode) { + status.setStatusCode((StatusCode) childSAMLObject); + } else if (childSAMLObject instanceof StatusMessage) { + status.setStatusMessage((StatusMessage) childSAMLObject); + } else if (childSAMLObject instanceof StatusDetail) { + status.setStatusDetail((StatusDetail) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectBuilder.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Subject; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.SubjectImpl} objects. + */ +public class SubjectBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public SubjectBuilder() { + + } + + /** {@inheritDoc} */ + public Subject buildObject() { + return buildObject(SAMLConstants.SAML20_NS, Subject.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public Subject buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationBuilder.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.SubjectConfirmation; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.SubjectConfirmationImpl} objects. + */ +public class SubjectConfirmationBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public SubjectConfirmationBuilder() { + + } + + /** {@inheritDoc} */ + public SubjectConfirmation buildObject() { + return buildObject(SAMLConstants.SAML20_NS, SubjectConfirmation.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public SubjectConfirmation buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectConfirmationImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataBuilder.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.SubjectConfirmationData; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.SubjectConfirmationDataImpl} objects. + */ +public class SubjectConfirmationDataBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public SubjectConfirmationDataBuilder() { + + } + + /** {@inheritDoc} */ + public SubjectConfirmationData buildObject() { + return buildObject(SAMLConstants.SAML20_NS, SubjectConfirmationData.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public SubjectConfirmationData buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectConfirmationDataImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataImpl.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,148 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.SubjectConfirmationData}. + */ +public class SubjectConfirmationDataImpl extends AbstractSAMLObject implements SubjectConfirmationData { + + /** NotBefore of the Confirmation Data. */ + private DateTime notBefore; + + /** NotOnOrAfter of the Confirmation Data. */ + private DateTime notOnOrAfter; + + /** Recipient of the Confirmation Data. */ + private String recipient; + + /** InResponseTo of the Confirmation Data. */ + private String inResponseTo; + + /** Address of the Confirmation Data. */ + private String address; + + /** "anyAttribute" attributes. */ + private final AttributeMap unknownAttributes; + + /** "any" children. */ + private final IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectConfirmationDataImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public DateTime getNotBefore() { + return notBefore; + } + + /** {@inheritDoc} */ + public void setNotBefore(DateTime newNotBefore) { + this.notBefore = prepareForAssignment(this.notBefore, newNotBefore); + } + + /** {@inheritDoc} */ + public DateTime getNotOnOrAfter() { + return notOnOrAfter; + } + + /** {@inheritDoc} */ + public void setNotOnOrAfter(DateTime newNotOnOrAfter) { + this.notOnOrAfter = prepareForAssignment(this.notOnOrAfter, newNotOnOrAfter); + } + + /** {@inheritDoc} */ + public String getRecipient() { + return recipient; + } + + /** {@inheritDoc} */ + public void setRecipient(String newRecipient) { + this.recipient = prepareForAssignment(this.recipient, newRecipient); + } + + /** {@inheritDoc} */ + public String getInResponseTo() { + return inResponseTo; + } + + /** {@inheritDoc} */ + public void setInResponseTo(String newInResponseTo) { + this.inResponseTo = prepareForAssignment(this.inResponseTo, newInResponseTo); + } + + /** {@inheritDoc} */ + public String getAddress() { + return address; + } + + /** {@inheritDoc} */ + public void setAddress(String newAddress) { + this.address = prepareForAssignment(this.address, newAddress); + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** + * {@inheritDoc} + */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return Collections.unmodifiableList(unknownChildren); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataMarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.SubjectConfirmationData} objects. + */ +public class SubjectConfirmationDataMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + SubjectConfirmationData subjectCD = (SubjectConfirmationData) samlObject; + + if (subjectCD.getNotBefore() != null) { + String notBeforeStr = Configuration.getSAMLDateFormatter().print(subjectCD.getNotBefore()); + domElement.setAttributeNS(null, SubjectConfirmationData.NOT_BEFORE_ATTRIB_NAME, notBeforeStr); + } + + if (subjectCD.getNotOnOrAfter() != null) { + String notOnOrAfterStr = Configuration.getSAMLDateFormatter().print(subjectCD.getNotOnOrAfter()); + domElement.setAttributeNS(null, SubjectConfirmationData.NOT_ON_OR_AFTER_ATTRIB_NAME, notOnOrAfterStr); + } + + if (subjectCD.getRecipient() != null) { + domElement.setAttributeNS(null, SubjectConfirmationData.RECIPIENT_ATTRIB_NAME, subjectCD.getRecipient()); + } + + if (subjectCD.getInResponseTo() != null) { + domElement.setAttributeNS(null, SubjectConfirmationData.IN_RESPONSE_TO_ATTRIB_NAME, subjectCD + .getInResponseTo()); + } + + if (subjectCD.getAddress() != null) { + domElement.setAttributeNS(null, SubjectConfirmationData.ADDRESS_ATTRIB_NAME, subjectCD.getAddress()); + } + + Attr attribute; + for (Entry entry : subjectCD.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || subjectCD.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationDataUnmarshaller.java 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.SubjectConfirmationData} objects. + */ +public class SubjectConfirmationDataUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + SubjectConfirmationData subjectCD = (SubjectConfirmationData) parentSAMLObject; + + subjectCD.getUnknownXMLObjects().add(childSAMLObject); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + SubjectConfirmationData subjectCD = (SubjectConfirmationData) samlObject; + + if (attribute.getLocalName().equals(SubjectConfirmationData.NOT_BEFORE_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + subjectCD.setNotBefore(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(SubjectConfirmationData.NOT_ON_OR_AFTER_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + subjectCD.setNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(SubjectConfirmationData.RECIPIENT_ATTRIB_NAME)) { + subjectCD.setRecipient(attribute.getValue()); + } else if (attribute.getLocalName().equals(SubjectConfirmationData.IN_RESPONSE_TO_ATTRIB_NAME)) { + subjectCD.setInResponseTo(attribute.getValue()); + } else if (attribute.getLocalName().equals(SubjectConfirmationData.ADDRESS_ATTRIB_NAME)) { + subjectCD.setAddress(attribute.getValue()); + } else { + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + subjectCD.getUnknownAttributes().registerID(attribQName); + } + subjectCD.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationImpl.java 17 Aug 2012 15:03:16 -0000 1.1 @@ -0,0 +1,134 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.SubjectConfirmation}. + */ +public class SubjectConfirmationImpl extends AbstractSAMLObject implements SubjectConfirmation { + + /** BaseID child element. */ + private BaseID baseID; + + /** NameID child element. */ + private NameID nameID; + + /** EncryptedID child element. */ + private EncryptedID encryptedID; + + /** SubjectConfirmationData of the Confirmation. */ + private SubjectConfirmationData subjectConfirmationData; + + /** Method of the Confirmation. */ + private String method; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectConfirmationImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public BaseID getBaseID() { + return baseID; + } + + /** {@inheritDoc} */ + public void setBaseID(BaseID newBaseID) { + baseID = prepareForAssignment(baseID, newBaseID); + } + + /** {@inheritDoc} */ + public NameID getNameID() { + return nameID; + } + + /** {@inheritDoc} */ + public void setNameID(NameID newNameID) { + nameID = prepareForAssignment(nameID, newNameID); + } + + /** {@inheritDoc} */ + public EncryptedID getEncryptedID() { + return this.encryptedID; + } + + /** {@inheritDoc} */ + public void setEncryptedID(EncryptedID newEncryptedID) { + this.encryptedID = prepareForAssignment(this.encryptedID, newEncryptedID); + } + + /** {@inheritDoc} */ + public SubjectConfirmationData getSubjectConfirmationData() { + return subjectConfirmationData; + } + + /** {@inheritDoc} */ + public void setSubjectConfirmationData(SubjectConfirmationData newSubjectConfirmationData) { + this.subjectConfirmationData = prepareForAssignment(this.subjectConfirmationData, newSubjectConfirmationData); + + } + + /** {@inheritDoc} */ + public String getMethod() { + return method; + } + + /** {@inheritDoc} */ + public void setMethod(String newMethod) { + this.method = prepareForAssignment(this.method, newMethod); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (baseID != null) { + children.add(baseID); + } + + if (nameID != null) { + children.add(nameID); + } + + if (encryptedID != null) { + children.add(encryptedID); + } + + children.add(subjectConfirmationData); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.SubjectConfirmation} objects. + */ +public class SubjectConfirmationMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + SubjectConfirmation subjectConfirmation = (SubjectConfirmation) samlObject; + + if (subjectConfirmation.getMethod() != null) { + domElement.setAttributeNS(null, SubjectConfirmation.METHOD_ATTRIB_NAME, subjectConfirmation.getMethod()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectConfirmationUnmarshaller.java 17 Aug 2012 15:03:23 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.SubjectConfirmation} objects. + */ +public class SubjectConfirmationUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + SubjectConfirmation subjectConfirmation = (SubjectConfirmation) parentObject; + + if (childObject instanceof BaseID) { + subjectConfirmation.setBaseID((BaseID) childObject); + } else if (childObject instanceof NameID) { + subjectConfirmation.setNameID((NameID) childObject); + } else if (childObject instanceof EncryptedID) { + subjectConfirmation.setEncryptedID((EncryptedID) childObject); + } else if (childObject instanceof SubjectConfirmationData) { + subjectConfirmation.setSubjectConfirmationData((SubjectConfirmationData) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + SubjectConfirmation subjectConfirmation = (SubjectConfirmation) samlObject; + + if (attribute.getLocalName().equals(SubjectConfirmation.METHOD_ATTRIB_NAME)) { + subjectConfirmation.setMethod(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectImpl.java 17 Aug 2012 15:03:22 -0000 1.1 @@ -0,0 +1,117 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.Subject; +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Subject}. + */ +public class SubjectImpl extends AbstractSAMLObject implements Subject { + + /** BaseID child element. */ + private BaseID baseID; + + /** NameID child element. */ + private NameID nameID; + + /** EncryptedID child element. */ + private EncryptedID encryptedID; + + /** Subject Confirmations of the Subject. */ + private final XMLObjectChildrenList subjectConfirmations; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + subjectConfirmations = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public BaseID getBaseID() { + return baseID; + } + + /** {@inheritDoc} */ + public void setBaseID(BaseID newBaseID) { + baseID = prepareForAssignment(baseID, newBaseID); + } + + /** {@inheritDoc} */ + public NameID getNameID() { + return nameID; + } + + /** {@inheritDoc} */ + public void setNameID(NameID newNameID) { + nameID = prepareForAssignment(nameID, newNameID); + } + + /** {@inheritDoc} */ + public EncryptedID getEncryptedID() { + return this.encryptedID; + } + + /** {@inheritDoc} */ + public void setEncryptedID(EncryptedID newEncryptedID) { + this.encryptedID = prepareForAssignment(this.encryptedID, newEncryptedID); + } + + /** {@inheritDoc} */ + public List getSubjectConfirmations() { + return subjectConfirmations; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (baseID != null) { + children.add(baseID); + } + + if (nameID != null) { + children.add(nameID); + } + + if (encryptedID != null) { + children.add(encryptedID); + } + + children.addAll(subjectConfirmations); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityBuilder.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.SubjectLocality; + +/** + * Builder for {@link org.opensaml.saml2.core.impl.SubjectLocalityImpl} objects. + */ +public class SubjectLocalityBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public SubjectLocalityBuilder() { + + } + + /** {@inheritDoc} */ + public SubjectLocality buildObject() { + return buildObject(SAMLConstants.SAML20_NS, SubjectLocality.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20_PREFIX); + } + + /** {@inheritDoc} */ + public SubjectLocality buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectLocalityImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityImpl.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.SubjectLocality; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.core.SubjectLocality}. + */ +public class SubjectLocalityImpl extends AbstractSAMLObject implements SubjectLocality { + + /** The Address of the assertion. */ + private String address; + + /** The DNS Name of the assertion. */ + private String dnsName; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectLocalityImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAddress() { + return address; + } + + /** {@inheritDoc} */ + public void setAddress(String newAddress) { + this.address = prepareForAssignment(this.address, newAddress); + } + + /** {@inheritDoc} */ + public String getDNSName() { + return dnsName; + } + + /** {@inheritDoc} */ + public void setDNSName(String newDNSName) { + this.dnsName = prepareForAssignment(this.dnsName, newDNSName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.core.SubjectLocality; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaler for {@link org.opensaml.saml2.core.SubjectLocality}. + */ +public class SubjectLocalityMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + SubjectLocality subjectLocality = (SubjectLocality) samlObject; + if (subjectLocality.getAddress() != null) { + domElement.setAttributeNS(null, SubjectLocality.ADDRESS_ATTRIB_NAME, subjectLocality.getAddress()); + } + + if (subjectLocality.getDNSName() != null) { + domElement.setAttributeNS(null, SubjectLocality.DNS_NAME_ATTRIB_NAME, subjectLocality.getDNSName()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectLocalityUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.SubjectLocality; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.SubjectLocality}. + */ +public class SubjectLocalityUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + SubjectLocality subjectLocality = (SubjectLocality) samlObject; + + if (attribute.getLocalName().equals(SubjectLocality.ADDRESS_ATTRIB_NAME)) { + subjectLocality.setAddress(attribute.getValue()); + } else if (attribute.getLocalName().equals(SubjectLocality.DNS_NAME_ATTRIB_NAME)) { + subjectLocality.setDNSName(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectMarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Subject} objects. + */ +public class SubjectMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryImpl.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.core.Subject; +import org.opensaml.saml2.core.SubjectQuery; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.SubjectQuery}. + */ +public abstract class SubjectQueryImpl extends RequestAbstractTypeImpl implements SubjectQuery { + + /** Subject child element. */ + private Subject subject; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectQueryImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Subject getSubject() { + return this.subject; + } + + /** + * {@inheritDoc} + */ + public void setSubject(Subject newSubject) { + this.subject = prepareForAssignment(this.subject, newSubject); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (super.getOrderedChildren() != null) { + children.addAll(super.getOrderedChildren()); + } + if (subject != null) { + children.add(subject); + } + + if (children.size() == 0) { + return null; + } + + return Collections.unmodifiableList(children); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryMarshaller.java 17 Aug 2012 15:03:21 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.core.SubjectQuery}. + */ +public abstract class SubjectQueryMarshaller extends RequestAbstractTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectQueryUnmarshaller.java 17 Aug 2012 15:03:15 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.saml2.core.Subject; +import org.opensaml.saml2.core.SubjectQuery; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.SubjectQuery}. + */ +public abstract class SubjectQueryUnmarshaller extends RequestAbstractTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + SubjectQuery sq = (SubjectQuery) parentSAMLObject; + + if (childSAMLObject instanceof Subject) { + sq.setSubject((Subject) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/SubjectUnmarshaller.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.Subject; +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Subject} objects. + */ +public class SubjectUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + Subject subject = (Subject) parentObject; + + if (childObject instanceof BaseID) { + subject.setBaseID((BaseID) childObject); + } else if (childObject instanceof NameID) { + subject.setNameID((NameID) childObject); + } else if (childObject instanceof EncryptedID) { + subject.setEncryptedID((EncryptedID) childObject); + } else if (childObject instanceof SubjectConfirmation) { + subject.getSubjectConfirmations().add((SubjectConfirmation) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateBuilder.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Terminate; + +/** + * A Builder for {@link org.opensaml.saml2.core.impl.TerminateImpl} objects. + */ +public class TerminateBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public TerminateBuilder() { + } + + /** {@inheritDoc} */ + public Terminate buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, Terminate.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); + } + + /** {@inheritDoc} */ + public Terminate buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new TerminateImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateImpl.java 17 Aug 2012 15:03:19 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.Terminate; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.core.Terminate}. + */ +public class TerminateImpl extends AbstractSAMLObject implements Terminate { + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected TerminateImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateMarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.core.Terminate} objects. + */ +public class TerminateMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/TerminateUnmarshaller.java 17 Aug 2012 15:03:18 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.core.Terminate} objects. + */ +public class TerminateUnmarshaller extends AbstractSAMLObjectUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/impl/package.html 17 Aug 2012 15:03:20 -0000 1.1 @@ -0,0 +1,14 @@ + + +Implementations of SAML 2.0 core specification types and elements. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ActionSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ActionSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ActionSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Action; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Action} for Schema compliance. + */ +public class ActionSchemaValidator implements Validator { + + /** Constructor */ + public ActionSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Action action) throws ValidationException { + validateAction(action); + validateNamespace(action); + } + + /** + * Checks that the Action label is present. + * @param action + * @throws ValidationException + */ + protected void validateAction(Action action) throws ValidationException { + if (DatatypeHelper.isEmpty(action.getAction())) { + throw new ValidationException("Action label must be specified."); + } + } + + /** + * Checks that the Namespace attribute is present. + * + * @param action + * @throws ValidationException + */ + protected void validateNamespace(Action action) throws ValidationException { + if (DatatypeHelper.isEmpty(action.getNamespace())) { + throw new ValidationException("Namespace is required attribute."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactResolveSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactResolveSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactResolveSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.ArtifactResolve; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.ArtifactResolve} for Schema compliance. + */ +public class ArtifactResolveSchemaValidator extends RequestAbstractTypeSchemaValidator { + + /** + * Constructor + * + */ + public ArtifactResolveSchemaValidator() { + super(); + + } + + /** {@inheritDoc} */ + public void validate(ArtifactResolve artifactResolve) throws ValidationException { + super.validate(artifactResolve); + validateArtifact(artifactResolve); + } + + /** + * Validates the Artifact child element. + * + * @param ar + * @throws ValidationException + */ + protected void validateArtifact(ArtifactResolve ar) throws ValidationException { + if (ar.getArtifact() == null) { + throw new ValidationException("An Artifact is required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactResponseSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactResponseSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactResponseSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.ArtifactResponse; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.ArtifactResponse} for Schema compliance. + */ +public class ArtifactResponseSchemaValidator extends StatusResponseTypeSchemaValidator { + + /** + * Constructor + * + */ + public ArtifactResponseSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(ArtifactResponse response) throws ValidationException { + super.validate(response); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ArtifactSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + + +import org.opensaml.saml2.core.Artifact; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Artifact} for Schema compliance. + */ +public class ArtifactSchemaValidator implements Validator { + + /** + * Constructor. + */ + public ArtifactSchemaValidator() { + } + + /** {@inheritDoc} */ + public void validate(Artifact artifact) throws ValidationException { + validateArtifact(artifact); + } + + /** + * Test that Artifact element content is not empty. + * + * @param artifact artifact to validate + * @throws ValidationException if invalid + */ + protected void validateArtifact(Artifact artifact) throws ValidationException { + if (DatatypeHelper.isEmpty(artifact.getArtifact())) { + throw new ValidationException("Artifact must contain a value"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionIDRefSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionIDRefSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionIDRefSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AssertionIDRef; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AssertionIDRef} for Schema compliance. + */ +public class AssertionIDRefSchemaValidator implements Validator { + + /** Constructor */ + public AssertionIDRefSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AssertionIDRef assertionIDRef) throws ValidationException { + validateIDRef(assertionIDRef); + } + + /** + * Checks that the ID Reference is present. + * + * @param assertionIDRef + * @throws ValidationException + */ + protected void validateIDRef(AssertionIDRef assertionIDRef) throws ValidationException { + if (DatatypeHelper.isEmpty(assertionIDRef.getAssertionID())) { + throw new ValidationException("IDRef is required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionIDRequestSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionIDRequestSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionIDRequestSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AssertionIDRequest; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.AssertionIDRequest} for Schema compliance. + */ +public class AssertionIDRequestSchemaValidator extends RequestAbstractTypeSchemaValidator { + + /** + * Constructor. + */ + public AssertionIDRequestSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(AssertionIDRequest request) throws ValidationException { + super.validate(request); + validateAssertionIDRefs(request); + } + + /** + * Validate the AssertionIDRef child elements. + * + * @param request request to validate + * @throws ValidationException if invalid + */ + protected void validateAssertionIDRefs(AssertionIDRequest request) throws ValidationException { + if (request.getAssertionIDRefs().size() < 1) { + throw new ValidationException("Request must contain at least one AssertionIDRef"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Assertion; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Assertion} for Schema compliance. + */ +public class AssertionSchemaValidator implements Validator { + + /** Constructor */ + public AssertionSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Assertion assertion) throws ValidationException { + validateIssuer(assertion); + validateVersion(assertion); + validateID(assertion); + validateIssueInstant(assertion); + } + + /** + * Checks that Issuer element is present. + * + * @param assertion + * @throws ValidationException + */ + protected void validateIssuer(Assertion assertion) throws ValidationException { + if (assertion.getIssuer() == null) { + throw new ValidationException("Issuer is required element"); + } + } + + /** + * Checks that the Version attribute is present. + * + * @param assertion + * @throws ValidationException + */ + protected void validateVersion(Assertion assertion) throws ValidationException { + if (assertion.getVersion() == null) { + throw new ValidationException("Version is required attribute"); + } + } + + /** + * Checks that the ID attribute is present. + * + * @param assertion + * @throws ValidationException + */ + protected void validateID(Assertion assertion) throws ValidationException { + if (DatatypeHelper.isEmpty(assertion.getID())) { + throw new ValidationException("ID is required attribute"); + } + } + + /** + * Checks that the IssueInstant attribute is present. + * + * @param assertion + * @throws ValidationException + */ + protected void validateIssueInstant(Assertion assertion) throws ValidationException { + if (assertion.getIssueInstant() == null) { + throw new ValidationException("IssueInstant is required attribute"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionSpecValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Assertion; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Assertion} for Spec compliance. + */ +public class AssertionSpecValidator implements Validator { + + /** Constructor */ + public AssertionSpecValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Assertion assertion) throws ValidationException { + validateSubject(assertion); + } + + /** + * Checks that the Subject element is present when required. + * + * @param assertion + * @throws ValidationException + */ + protected void validateSubject(Assertion assertion) throws ValidationException { + if ((assertion.getStatements() == null || assertion.getStatements().size() == 0) + && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().size() == 0) + && (assertion.getAttributeStatements() == null || assertion.getAttributeStatements().size() == 0) + && (assertion.getAuthzDecisionStatements() == null || assertion.getAuthzDecisionStatements().size() == 0) + && assertion.getSubject() == null) { + throw new ValidationException("Subject is required when Statements are absent"); + } + + if (assertion.getAuthnStatements().size() > 0 && assertion.getSubject() == null) { + throw new ValidationException("Assertions containing AuthnStatements require a Subject"); + } + if (assertion.getAuthzDecisionStatements().size() > 0 && assertion.getSubject() == null) { + throw new ValidationException("Assertions containing AuthzDecisionStatements require a Subject"); + } + if (assertion.getAttributeStatements().size() > 0 && assertion.getSubject() == null) { + throw new ValidationException("Assertions containing AttributeStatements require a Subject"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionURIRefSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionURIRefSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AssertionURIRefSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AssertionURIRef; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AssertionURIRef} for Schema compliance. + */ +public class AssertionURIRefSchemaValidator implements Validator { + + /** Constructor */ + public AssertionURIRefSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AssertionURIRef assertionURIRef) throws ValidationException { + validateURIRef(assertionURIRef); + } + + /** + * Checks that the URI reference is present. + * + * @param assertionURIRef + * @throws ValidationException + */ + protected void validateURIRef(AssertionURIRef assertionURIRef) throws ValidationException { + if (DatatypeHelper.isEmpty(assertionURIRef.getAssertionURI())) { + throw new ValidationException("AssertionURI required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeQuerySchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import java.util.HashSet; +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeQuery; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.Pair; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.AttributeQuery} for Schema compliance. + */ +public class AttributeQuerySchemaValidator extends SubjectQuerySchemaValidator { + + /** + * Constructor. + */ + public AttributeQuerySchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(AttributeQuery query) throws ValidationException { + super.validate(query); + validateUniqueAttributeIdentifiers(query); + } + + /** + * Checks that all the attributes have a unique Name/NameFormat pair. + * + * @param query the attribute query to validate + * + * @throws ValidationException thrown if more than on Name/NameFormat pair is found in the list of attributes in + * this query + */ + protected void validateUniqueAttributeIdentifiers(AttributeQuery query) throws ValidationException { + List attributes = query.getAttributes(); + + HashSet> encounteredNames = new HashSet>(); + String attributeName; + String attributeNameFormat; + for (Attribute attribute : attributes) { + attributeName = attribute.getName(); + attributeNameFormat = attribute.getNameFormat(); + if (DatatypeHelper.isEmpty(attributeNameFormat)) { + // SAML 2 core, sec. 2.7.3.1, if no format is specified, + // unspecified is in effect. This avoids bug in processing null value. + attributeNameFormat = Attribute.UNSPECIFIED; + } + + Pair pair = new Pair(attributeName, attributeNameFormat); + if (encounteredNames.contains(pair)) { + throw new ValidationException( + "Attribute query contains more than one attribute with the same Name and NameFormat"); + } else { + encounteredNames.add(pair); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Attribute} for Schema compliance. + */ +public class AttributeSchemaValidator implements Validator { + + /** Constructor */ + public AttributeSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Attribute attribute) throws ValidationException { + validateName(attribute); + } + + /** + * Checks that the Name attribute is present. + * + * @param attribute + * @throws ValidationException + */ + protected void validateName(Attribute attribute) throws ValidationException { + if (DatatypeHelper.isEmpty(attribute.getName())) { + throw new ValidationException("Name is required attribute"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeStatementSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeStatementSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AttributeStatementSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AttributeStatement; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AttributeStatement} for Schema compliance. + */ +public class AttributeStatementSchemaValidator implements Validator { + + /** Constructor */ + public AttributeStatementSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AttributeStatement attributeStatement) throws ValidationException { + validateAttributes(attributeStatement); + } + + /** + * Checks that at least one Attribute is present. + * + * @param attributeStatement + * @throws ValidationException + */ + protected void validateAttributes(AttributeStatement attributeStatement) throws ValidationException { + if (attributeStatement.getAttributes() == null || attributeStatement.getAttributes().size() == 0) { + throw new ValidationException("Must contain one or more attributes"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AudienceRestrictionSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AudienceRestrictionSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AudienceRestrictionSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AudienceRestriction; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AudienceRestriction} for Schema compliance. + */ +public class AudienceRestrictionSchemaValidator implements Validator { + + /** Constructor */ + public AudienceRestrictionSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AudienceRestriction audienceRestriction) throws ValidationException { + validateAudiences(audienceRestriction); + } + + /** + * Checks that at least one Audience is present. + * + * @param audienceRestriction + * @throws ValidationException + */ + protected void validateAudiences(AudienceRestriction audienceRestriction) throws ValidationException { + if (audienceRestriction.getAudiences() == null || audienceRestriction.getAudiences().size() == 0) { + throw new ValidationException("Must contain one or more Audiences"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AudienceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AudienceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AudienceSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Audience; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Audience} for Schema compliance. + */ +public class AudienceSchemaValidator implements Validator { + + /** Constructor */ + public AudienceSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Audience audience) throws ValidationException { + validateAudienceURI(audience); + } + + /** + * Checks that the AudienceURI is present. + * + * @param audience + * @throws ValidationException + */ + protected void validateAudienceURI(Audience audience) throws ValidationException { + if (DatatypeHelper.isEmpty(audience.getAudienceURI())) { + throw new ValidationException("AudienceURI required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthenticatingAuthoritySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthenticatingAuthoritySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthenticatingAuthoritySchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthenticatingAuthority; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AuthenticatingAuthority} for Schema compliance. + */ +public class AuthenticatingAuthoritySchemaValidator implements Validator { + + /** Constructor */ + public AuthenticatingAuthoritySchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AuthenticatingAuthority authenAuthority) throws ValidationException { + validateURI(authenAuthority); + } + + /** + * Checks that the URI is present. + * + * @param authenAuthority + * @throws ValidationException + */ + protected void validateURI(AuthenticatingAuthority authenAuthority) throws ValidationException { + if (DatatypeHelper.isEmpty(authenAuthority.getURI())) { + throw new ValidationException("URI required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextClassRefSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextClassRefSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextClassRefSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AuthnContextClassRef} for Schema compliance. + */ +public class AuthnContextClassRefSchemaValidator implements Validator { + + /** Constructor */ + public AuthnContextClassRefSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AuthnContextClassRef authnContextClassRef) throws ValidationException { + validateClassRef(authnContextClassRef); + } + + /** + * Checks that the AuthnContextClassRef is present. + * + * @param authnCCR + * @throws ValidationException + */ + protected void validateClassRef(AuthnContextClassRef authnCCR) throws ValidationException { + if (DatatypeHelper.isEmpty(authnCCR.getAuthnContextClassRef())) { + throw new ValidationException("AuthnContextClassRef required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextDeclRefSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextDeclRefSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextDeclRefSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthnContextDeclRef; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AuthnContextDeclRef} for Schema compliance. + */ +public class AuthnContextDeclRefSchemaValidator implements Validator { + + /** Constructor */ + public AuthnContextDeclRefSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AuthnContextDeclRef authnCDR) throws ValidationException { + validateDeclRef(authnCDR); + } + + /** + * Checks that the Declaration Reference is present. + * + * @param authnCDR + * @throws ValidationException + */ + protected void validateDeclRef(AuthnContextDeclRef authnCDR) throws ValidationException { + if (DatatypeHelper.isEmpty(authnCDR.getAuthnContextDeclRef())) { + throw new ValidationException("AuthnContextDeclRef required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextDeclSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextDeclSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnContextDeclSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthnContextDecl; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AuthnContextDecl} for Schema compliance. + */ +public class AuthnContextDeclSchemaValidator implements Validator { + + /** Constructor. */ + public AuthnContextDeclSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AuthnContextDecl authnCD) throws ValidationException { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnQuerySchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthnQuery; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.AuthnQuery} for Schema compliance. + */ +public class AuthnQuerySchemaValidator extends SubjectQuerySchemaValidator { + + /** + * Constructor + * + */ + public AuthnQuerySchemaValidator() { + } + + /** {@inheritDoc} */ + public void validate(AuthnQuery query) throws ValidationException { + super.validate(query); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnRequestSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnRequestSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnRequestSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.AuthnRequest} for Schema compliance. + */ +public class AuthnRequestSchemaValidator extends RequestAbstractTypeSchemaValidator{ + + /** + * Constructor + * + */ + public AuthnRequestSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(AuthnRequest request) throws ValidationException { + super.validate(request); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnStatementSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnStatementSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthnStatementSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthnStatement; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AuthnStatement} for Schema compliance. + */ +public class AuthnStatementSchemaValidator implements Validator { + + /** Constructor */ + public AuthnStatementSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AuthnStatement authnStatement) throws ValidationException { + validateAuthnInstant(authnStatement); + validateAuthnContext(authnStatement); + } + + /** + * Checks that the AuthnInstant attribute is present. + * + * @param authnStatement + * @throws ValidationException + */ + protected void validateAuthnInstant(AuthnStatement authnStatement) throws ValidationException { + if (authnStatement.getAuthnInstant() == null) { + throw new ValidationException("AuthnInstant required"); + } + } + + /** + * Checks that the AuthnContext element is present. + * + * @param authnStatement + * @throws ValidationException + */ + protected void validateAuthnContext(AuthnStatement authnStatement) throws ValidationException { + if (authnStatement.getAuthnContext() == null) { + throw new ValidationException("AuthnContext required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthzDecisionQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthzDecisionQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthzDecisionQuerySchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthzDecisionQuery; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.AuthzDecisionQuery} for Schema compliance. + */ +public class AuthzDecisionQuerySchemaValidator extends SubjectQuerySchemaValidator { + + /** + * Constructor + * + */ + public AuthzDecisionQuerySchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(AuthzDecisionQuery query) throws ValidationException { + super.validate(query); + validateActions(query); + validateResource(query); + } + + /** + * Validate the Action child elements + * + * @param query + * @throws ValidationException + */ + protected void validateActions(AuthzDecisionQuery query) throws ValidationException { + if (query.getActions().size() < 1) { + throw new ValidationException("A minimum of one Action child element is required"); + } + } + + /** + * Validate the Resource attribute + * + * @param query + * @throws ValidationException + */ + protected void validateResource(AuthzDecisionQuery query) throws ValidationException { + if (DatatypeHelper.isEmpty(query.getResource())) { + throw new ValidationException("Resource attribute is required"); + } + } + + + + + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthzDecisionStatementSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthzDecisionStatementSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/AuthzDecisionStatementSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.AuthzDecisionStatement; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.AuthzDecisionStatement} for Schema compliance. + */ +public class AuthzDecisionStatementSchemaValidator implements Validator { + + /** Constructor */ + public AuthzDecisionStatementSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AuthzDecisionStatement authzDS) throws ValidationException { + validateResource(authzDS); + validateDecision(authzDS); + validateActions(authzDS); + } + + /** + * Checks that the Resource attribute is present. + * + * @param authzDS + * @throws ValidationException + */ + protected void validateResource(AuthzDecisionStatement authzDS) throws ValidationException { + if (DatatypeHelper.isEmpty(authzDS.getResource())) { + throw new ValidationException("Resource required"); + } + } + + /** + * Checks that the Decision attribute is present. + * + * @param authzDS + * @throws ValidationException + */ + protected void validateDecision(AuthzDecisionStatement authzDS) throws ValidationException { + if (authzDS.getDecision() == null) { + throw new ValidationException("Decision required"); + } + } + + /** + * Checks that one or more Action is present. + * + * @param authzDS + * @throws ValidationException + */ + protected void validateActions(AuthzDecisionStatement authzDS) throws ValidationException { + if (authzDS.getActions() == null || authzDS.getActions().size() < 1) { + throw new ValidationException("One or more Actions required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ConditionsSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ConditionsSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ConditionsSpecValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.OneTimeUse; +import org.opensaml.saml2.core.ProxyRestriction; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks the {@link org.opensaml.saml2.core.Conditions} for Spec compliance. + */ +public class ConditionsSpecValidator implements Validator { + + /** Constructor */ + public ConditionsSpecValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Conditions conditions) throws ValidationException { + validateOneTimeUseCondition(conditions); + validateProxyRestrictionCondition(conditions); + } + + /** + * Checks that there is at most one OneTimeUse condition. + * + * @param conditions + * @throws ValidationException + */ + protected void validateOneTimeUseCondition(Conditions conditions) throws ValidationException { + int oneTimeUseCount = 0; + for (int i = 0; i < conditions.getConditions().size(); i++) { + if (conditions.getConditions().get(i) instanceof OneTimeUse) { + oneTimeUseCount++; + } + } + + if (oneTimeUseCount > 1) { + throw new ValidationException("At most one instance of OneTimeUse allowed"); + } + } + + protected void validateProxyRestrictionCondition(Conditions conditions) throws ValidationException { + int proxyRestrictionCount = 0; + for (int i = 0; i < conditions.getConditions().size(); i++) { + if (conditions.getConditions().get(i) instanceof ProxyRestriction) { + proxyRestrictionCount++; + } + } + + if (proxyRestrictionCount > 1) { + throw new ValidationException("At most one instance of ProxyRestriction allowed"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/EvidenceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/EvidenceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/EvidenceSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Evidence; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Evidence} for Schema compliance. + */ +public class EvidenceSchemaValidator implements Validator { + + /** Constructor */ + public EvidenceSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Evidence evidence) throws ValidationException { + validateAssertions(evidence); + } + + /** + * Checks that at least one Assertion, Assertion ID Reference, or Assertion URI Reference is present. + * + * @param evidence + * @throws ValidationException + */ + protected void validateAssertions(Evidence evidence) throws ValidationException { + if (evidence.getEvidence() == null || evidence.getEvidence().size() == 0) { + throw new ValidationException( + "Must contain at least one AssertionIDReference, AssertionURIReference, or Assertion"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/GetCompleteSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/GetCompleteSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/GetCompleteSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.GetComplete; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.GetComplete} for Schema compliance. + */ +public class GetCompleteSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public GetCompleteSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(GetComplete gc) throws ValidationException { + validateGetComplete(gc); + } + + /** + * Validate the GetComplete element content. + * + * @param gc + * @throws ValidationException + */ + protected void validateGetComplete(GetComplete gc) throws ValidationException { + if (DatatypeHelper.isEmpty(gc.getGetComplete())) { + throw new ValidationException("GetComplete element must be non-empty"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IDPEntrySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IDPEntrySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IDPEntrySchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.IDPEntry; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.IDPEntry} for Schema compliance. + */ +public class IDPEntrySchemaValidator implements Validator { + + /** + * Constructor + * + */ + public IDPEntrySchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(IDPEntry entry) throws ValidationException { + validateProviderID(entry); + } + + /** + * Validates ProviderID attribute + * + * @param entry + * @throws ValidationException + */ + protected void validateProviderID(IDPEntry entry) throws ValidationException { + if (DatatypeHelper.isEmpty(entry.getProviderID())) { + throw new ValidationException("ProviderID attribute is required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IDPListSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IDPListSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IDPListSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.IDPList; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.IDPList} for Schema compliance. + */ +public class IDPListSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public IDPListSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(IDPList list) throws ValidationException { + validateIDPEntries(list); + } + + /** + * Validates IDPEntry child elements. + * + * @param list + * @throws ValidationException + */ + protected void validateIDPEntries(IDPList list) throws ValidationException { + if (list.getIDPEntrys().size() < 1) { + throw new ValidationException("IDPList must contain at least one IDPEntry"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IssuerSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IssuerSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/IssuerSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Issuer; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Issuer} for Schema compliance. + */ +public class IssuerSchemaValidator implements Validator { + + /** Constructor */ + public IssuerSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Issuer issuer) throws ValidationException { + validateName(issuer); + } + + /** + * Checks that Issuer name is present. + * + * @param issuer + * @throws ValidationException + */ + protected void validateName(Issuer issuer) throws ValidationException { + if (DatatypeHelper.isEmpty(issuer.getValue())) { + throw new ValidationException("Issuer name required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/LogoutRequestSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/LogoutRequestSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/LogoutRequestSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.LogoutRequest; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.LogoutRequest} for Schema compliance. + */ +public class LogoutRequestSchemaValidator extends RequestAbstractTypeSchemaValidator { + + /** + * Constructor. + * + */ + public LogoutRequestSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(LogoutRequest request) throws ValidationException { + super.validate(request); + validateIdentifiers(request); + } + + /** + * Validate the Identifier child types (BaseID, NameID, EncryptedID). + * + * @param request the request being processed + * @throws ValidationException thrown if the identifiers present are not valid + */ + protected void validateIdentifiers(LogoutRequest request) throws ValidationException { + int idCount = 0; + + if (request.getBaseID() != null) { + idCount++; + } + if (request.getNameID() != null) { + idCount++; + } + if (request.getEncryptedID() != null) { + idCount++; + } + + if (idCount != 1) { + throw new ValidationException("LogoutRequest must contain exactly one of: BaseID, NameID, EncryptedID"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/LogoutResponseSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/LogoutResponseSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/LogoutResponseSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.LogoutResponse; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.LogoutRequest} for Schema compliance. + */ +public class LogoutResponseSchemaValidator extends StatusResponseTypeSchemaValidator { + + /** + * Constructor + * + */ + public LogoutResponseSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(LogoutResponse response) throws ValidationException { + super.validate(response); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ManageNameIDRequestSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ManageNameIDRequestSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ManageNameIDRequestSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.ManageNameIDRequest; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.ManageNameIDRequest} for Schema compliance. + */ +public class ManageNameIDRequestSchemaValidator extends RequestAbstractTypeSchemaValidator { + + /** + * Constructor + * + */ + public ManageNameIDRequestSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(ManageNameIDRequest request) throws ValidationException { + super.validate(request); + validateNameID(request); + validateNewIDAndTerminate(request); + } + + /** + * Validates NameID/EncryptedID child element + * + * @param request + * @throws ValidationException + */ + protected void validateNameID(ManageNameIDRequest request) throws ValidationException { + int idCount = 0; + + if (request.getNameID() != null) { + idCount++; + } + if (request.getEncryptedID() != null) { + idCount++; + } + + if (idCount != 1) { + throw new ValidationException("ManageNameIDRequest must contain exactly one of: NameID, EncryptedID"); + } + } + + /** + * Validates NewID/NewEncryptedID child element + * + * @param request + * @throws ValidationException + */ + protected void validateNewIDAndTerminate(ManageNameIDRequest request) throws ValidationException { + int count = 0; + + if (request.getNewID() != null) { + count++; + } + if (request.getNewEncryptedID() != null) { + count++; + } + if (request.getTerminate() != null) { + count++; + } + + if (count != 1) { + throw new ValidationException("ManageNameIDRequest must contain exactly one of: NewID, NewEncryptedID, Terminate"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ManageNameIDResponseSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ManageNameIDResponseSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ManageNameIDResponseSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.ManageNameIDResponse; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.ManageNameIDResponse} for Schema compliance. + */ +public class ManageNameIDResponseSchemaValidator extends StatusResponseTypeSchemaValidator { + + /** + * Constructor + * + */ + public ManageNameIDResponseSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(ManageNameIDResponse response) throws ValidationException { + super.validate(response); + } + + // All requirements are validated in the superclasses +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDMappingRequestSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDMappingRequestSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDMappingRequestSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.NameIDMappingRequest; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.NameIDMappingRequest} for Schema compliance. + */ +public class NameIDMappingRequestSchemaValidator extends RequestAbstractTypeSchemaValidator { + + /** + * Constructor + * + */ + public NameIDMappingRequestSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(NameIDMappingRequest request) throws ValidationException { + super.validate(request); + validateIdentifiers(request); + validateNameIDPolicy(request); + } + + /** + * Validates the identifier child types (BaseID, NameID, EncryptedID). + * + * @param request + * @throws ValidationException + */ + protected void validateIdentifiers(NameIDMappingRequest request) throws ValidationException { + int idCount = 0; + + if (request.getBaseID() != null) { + idCount++; + } + if (request.getNameID() != null) { + idCount++; + } + if (request.getEncryptedID() != null) { + idCount++; + } + + if (idCount != 1) { + throw new ValidationException("NameIDMappingRequest must contain exactly one of: BaseID, NameID, EncryptedID"); + } + } + + /** + * Validates the NameIDPolicy child element. + * + * @param request + * @throws ValidationException + */ + private void validateNameIDPolicy(NameIDMappingRequest request) throws ValidationException { + if(request.getNameIDPolicy() == null) { + throw new ValidationException("NameIDPolicy is required"); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDMappingResponseSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDMappingResponseSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDMappingResponseSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.NameIDMappingResponse; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.NameIDMappingResponse} for Schema compliance. + */ +public class NameIDMappingResponseSchemaValidator extends StatusResponseTypeSchemaValidator { + + /** + * Constructor + * + */ + public NameIDMappingResponseSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(NameIDMappingResponse response) throws ValidationException { + super.validate(response); + validateIdentifiers(response); + } + + /** + * Validate the identifier child elements (NameID, EncryptedID). + * + * @param resp + * @throws ValidationException + */ + protected void validateIdentifiers(NameIDMappingResponse resp) throws ValidationException { + int idCount = 0; + + if (resp.getNameID() != null) { + idCount++; + } + if (resp.getEncryptedID() != null) { + idCount++; + } + + if (idCount != 1) { + throw new ValidationException("NameIDMappingResponse must contain exactly one of: NameID, EncryptedID"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NameIDSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.NameID; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.NameID} for Schema compliance. + */ +public class NameIDSchemaValidator implements Validator { + + /** Constructor */ + public NameIDSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(NameID nameID) throws ValidationException { + validateName(nameID); + } + + /** + * Checks that Name is present. + * + * @param nameID + * @throws ValidationException + */ + protected void validateName(NameID nameID) throws ValidationException { + if (DatatypeHelper.isEmpty(nameID.getValue())) { + throw new ValidationException("Name is required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NewIDSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NewIDSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/NewIDSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.NewID; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.NewID} for Schema compliance. + */ +public class NewIDSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public NewIDSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(NewID newid) throws ValidationException { + validateNewID(newid); + } + + /** + * Validate the element content. + * + * @param newid + * @throws ValidationException + */ + protected void validateNewID(NewID newid) throws ValidationException { + if (DatatypeHelper.isEmpty(newid.getNewID())) { + throw new ValidationException("NewID must be non-empty"); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequestAbstractTypeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequestAbstractTypeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequestAbstractTypeSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,90 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.common.SAMLVersion; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.RequestAbstractType} for Schema compliance. + * + * @param request type that will be validated + */ +public abstract class RequestAbstractTypeSchemaValidator implements + Validator { + + /** + * Constructor. + */ + public RequestAbstractTypeSchemaValidator() { + } + + /** {@inheritDoc} */ + public void validate(RequestType request) throws ValidationException { + validateID(request); + validateVersion(request); + validateIssueInstant(request); + + } + + /** + * Validates the ID attribute. + * + * @param request request to validate + * @throws ValidationException if invalid + */ + protected void validateID(RequestAbstractType request) throws ValidationException { + if (DatatypeHelper.isEmpty(request.getID())) { + throw new ValidationException("ID attribute must not be empty"); + } + } + + /** + * Validates the Version attribute. + * + * @param request request to validate + * @throws ValidationException if invalid + */ + protected void validateVersion(RequestAbstractType request) throws ValidationException { + if (request.getVersion() == null) { + throw new ValidationException("Version attribute must not be null"); + } + if (request.getVersion().toString() != SAMLVersion.VERSION_20.toString()) { + throw new ValidationException("Wrong SAML Version"); + } + } + + /** + * Validates the IsssueInstant attribute. + * + * @param request request to validate + * @throws ValidationException if invalid + */ + protected void validateIssueInstant(RequestAbstractType request) throws ValidationException { + if (request.getIssueInstant() == null) { + throw new ValidationException("IssueInstant attribute must not be null"); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequestedAuthnContextSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequestedAuthnContextSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequestedAuthnContextSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.RequestedAuthnContext} for Schema compliance. + */ +public class RequestedAuthnContextSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public RequestedAuthnContextSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(RequestedAuthnContext requestedAuthnContext) throws ValidationException { + validateChildren(requestedAuthnContext); + } + + /** + * Validates the presence and combination of child elements. + * + * @param rac + * @throws ValidationException + */ + protected void validateChildren(RequestedAuthnContext rac) throws ValidationException { + int classRefCount = rac.getAuthnContextClassRefs().size(); + int declRefCount = rac.getAuthnContextDeclRefs().size(); + + if (classRefCount == 0 && declRefCount == 0){ + throw new ValidationException("At least one of either AuthnContextClassRef or AuthnContextDeclRef is required"); + } + + if (classRefCount > 0 && declRefCount > 0) { + throw new ValidationException("AuthnContextClassRef and AuthnContextDeclRef are mutually exclusive"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequesterIDSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequesterIDSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/RequesterIDSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.RequesterID; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.RequesterID} for Schema compliance. + */ +public class RequesterIDSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public RequesterIDSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(RequesterID requesterID) throws ValidationException { + validateRequesterID(requesterID); + } + + protected void validateRequesterID(RequesterID reqid) throws ValidationException { + if (DatatypeHelper.isEmpty(reqid.getRequesterID())) { + throw new ValidationException("RequesterID element must be non-empty"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ResponseSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ResponseSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/ResponseSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Response; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.Response} for Schema compliance. + */ +public class ResponseSchemaValidator extends StatusResponseTypeSchemaValidator { + + /** + * Constructor + * + */ + public ResponseSchemaValidator() { + } + + /** {@inheritDoc} */ + public void validate(Response response) throws ValidationException { + super.validate(response); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SessionIndexSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SessionIndexSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SessionIndexSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.SessionIndex; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.SessionIndex} for Schema compliance. + */ +public class SessionIndexSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public SessionIndexSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(SessionIndex sessionIndex) throws ValidationException { + validateSessionIndex(sessionIndex); + } + + /** + * Validates the SessionIndex element content. + * + * @param si + * @throws ValidationException + */ + protected void validateSessionIndex(SessionIndex si) throws ValidationException { + if (DatatypeHelper.isEmpty(si.getSessionIndex())) { + throw new ValidationException("SessionIndex must be non-empty"); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusCodeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusCodeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusCodeSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.StatusCode} for Schema compliance. + */ +public class StatusCodeSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public StatusCodeSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(StatusCode statusCode) throws ValidationException { + validateValue(statusCode); + } + + /** + * Validates the Value attribute + * + * @param sc + * @throws ValidationException + */ + protected void validateValue(StatusCode sc) throws ValidationException { + if (DatatypeHelper.isEmpty(sc.getValue())) { + throw new ValidationException("Value attribute is required"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusMessageSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusMessageSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusMessageSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * hecks {@link org.opensaml.saml2.core.StatusMessage} for Schema compliance. + */ +public class StatusMessageSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public StatusMessageSchemaValidator() { + super(); + } + + /** {@inheritDoc} */ + public void validate(StatusMessage statusMessage) throws ValidationException { + validateMessage(statusMessage); + } + + protected void validateMessage(StatusMessage sm) throws ValidationException { + if (DatatypeHelper.isEmpty(sm.getMessage())) { + throw new ValidationException("Message element just be non-empty"); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusResponseTypeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusResponseTypeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusResponseTypeSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.common.SAMLVersion; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.StatusResponseType} for Schema compliance. + */ +public abstract class StatusResponseTypeSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public StatusResponseTypeSchemaValidator() { + } + + /** {@inheritDoc} */ + public void validate(StatusResponse response) throws ValidationException { + validateStatus(response); + validateID(response); + validateVersion(response); + validateIssueInstant(response); + + } + + /** + * Validates the Status child element. + * + * @param response + * @throws ValidationException + */ + protected void validateStatus(StatusResponse response) throws ValidationException { + if (response.getStatus() == null) + throw new ValidationException("Status is required"); + + } + + /** + * Validates the ID attribute + * + * @param response + * @throws ValidationException + */ + protected void validateID(StatusResponse response) throws ValidationException { + if (DatatypeHelper.isEmpty(response.getID())) + throw new ValidationException("ID attribute must not be empty"); + } + + /** + * Validates the Version attribute + * + * @param response + * @throws ValidationException + */ + protected void validateVersion(StatusResponse response) throws ValidationException { + if (response.getVersion() == null) + throw new ValidationException("Version attribute must not be null"); + if (response.getVersion().toString() != SAMLVersion.VERSION_20.toString()) + throw new ValidationException("Wrong SAML Version"); + } + + /** + * Validates the IsssueInstant attribute + * + * @param response + * @throws ValidationException + */ + protected void validateIssueInstant(StatusResponse response) throws ValidationException { + if (response.getIssueInstant() == null) + throw new ValidationException ("IssueInstant attribute must not be null"); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/StatusSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Status; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Status} for Schema compliance. + */ +public class StatusSchemaValidator implements Validator { + + /** + * Constructor + * + */ + public StatusSchemaValidator() { + } + + /** {@inheritDoc} */ + public void validate(Status status) throws ValidationException { + validateStatusCode(status); + + } + + protected void validateStatusCode(Status status) throws ValidationException { + if (status.getStatusCode() == null) { + throw new ValidationException("StatusCode is required"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectConfirmationSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectConfirmationSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectConfirmationSchemaValidator.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.SubjectConfirmation} for Schema compliance. + */ +public class SubjectConfirmationSchemaValidator implements Validator { + + /** Constructor */ + public SubjectConfirmationSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(SubjectConfirmation subjectConfirmation) throws ValidationException { + validateMethod(subjectConfirmation); + } + + /** + * Checks that Method is present. + * + * @param subjectConfirmation + * @throws ValidationException + */ + protected void validateMethod(SubjectConfirmation subjectConfirmation) throws ValidationException { + if (DatatypeHelper.isEmpty(subjectConfirmation.getMethod())) { + throw new ValidationException("Method required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectQuerySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectQuerySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectQuerySchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.SubjectQuery; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.core.SubjectQuery} for Schema compliance. + */ +public abstract class SubjectQuerySchemaValidator extends RequestAbstractTypeSchemaValidator { + + /** + * Constructor + * + */ + public SubjectQuerySchemaValidator() { + } + + /** {@inheritDoc} */ + public void validate(SubjectQueryType query) throws ValidationException { + super.validate(query); + validateSubject(query); + } + + /** + * Validates the Subject child element. + * + * @param query + * @throws ValidationException + */ + protected void validateSubject(SubjectQuery query) throws ValidationException { + if (query.getSubject() == null) + throw new ValidationException("Subject is required"); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/SubjectSchemaValidator.java 17 Aug 2012 15:03:30 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.core.validator; + +import org.opensaml.saml2.core.Subject; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.core.Subject} for Schema compliance. + */ +public class SubjectSchemaValidator implements Validator { + + /** Constructor */ + public SubjectSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Subject subject) throws ValidationException { + if (subject.getBaseID() == null && subject.getNameID() == null + && (subject.getSubjectConfirmations() == null || subject.getSubjectConfirmations().size() == 0)) { + throw new ValidationException("ID or SubjectConfirmation required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/core/validator/package.html 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,15 @@ + + +Validation rules for SAML 2.0 core types and elements. +

+Schema validators check to ensure that SAMLObjects adhere to the SAML 2.0 core XML schemas while spec validators ensure +the objects adhere to the additional constraints placed upon the object by the SAML 2.0 core specification. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/RelayState.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/RelayState.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/RelayState.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.xml.schema.XSString; + +/** + * SAML 2.0 ECP RelayState SOAP header. + */ +public interface RelayState extends XSString, SAMLObject, MustUnderstandBearing, ActorBearing { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RelayState"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20ECP_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20ECP_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RelayStateType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20ECP_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20ECP_PREFIX); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/Request.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/Request.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/Request.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,125 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.IDPList; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 ECP Request SOAP header. + */ +public interface Request extends SAMLObject, MustUnderstandBearing, ActorBearing { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Request"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20ECP_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20ECP_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RequestType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20ECP_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20ECP_PREFIX); + + /** ProviderName attribute name. */ + public static final String PROVIDER_NAME_ATTRIB_NAME = "ProviderName"; + + /** IsPassive attribute name. */ + public static final String IS_PASSIVE_NAME_ATTRIB_NAME = "IsPassive"; + + /** + * Get the Issuer child elemet. + * + * @return the Issuer child element + */ + public Issuer getIssuer(); + + /** + * Set the Issuer child elemet. + * + * @param newIssuer the new Issuer child element + */ + public void setIssuer(Issuer newIssuer); + + /** + * Get the IDPList child element. + * + * @return the IDPList child element + */ + public IDPList getIDPList(); + + /** + * Set the IDPList child element. + * + * @param newIDPList the new IDPList child element + */ + public void setIDPList(IDPList newIDPList); + + /** + * Get the ProviderName attribute value. + * + * @return the ProviderName attribute value + */ + public String getProviderName(); + + /** + * Set the ProviderName attribute value. + * + * @param newProviderName the new ProviderName attribute value + */ + public void setProviderName(String newProviderName); + + /** + * Get the IsPassive attribute value. + * + * @return the IsPassive attribute value + */ + public Boolean isPassive(); + + /** + * Get the IsPassive attribute value. + * + * @return the IsPassive attribute value + */ + public XSBooleanValue isPassiveXSBoolean(); + + /** + * Set the IsPassive attribute value. + * + * @param newIsPassive the new IsPassive attribute value + */ + public void setPassive(Boolean newIsPassive); + + /** + * Set the IsPassive attribute value. + * + * @param newIsPassive the new IsPassive attribute value + */ + public void setPassive(XSBooleanValue newIsPassive); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/Response.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/Response.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/Response.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; + +/** + * SAML 2.0 ECP Response SOAP header. + */ +public interface Response extends SAMLObject, MustUnderstandBearing, ActorBearing { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Response"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20ECP_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20ECP_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ResponseType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20ECP_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20ECP_PREFIX); + + /** ProviderName attribute name. */ + public static final String ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME = "AssertionConsumerServiceURL"; + + /** + * Get the AssertionConsumerServiceURL attribute value. + * + * @return the AssertionConsumerServiceURL attribute value + */ + public String getAssertionConsumerServiceURL(); + + /** + * Get the AssertionConsumerServiceURL attribute value. + * + * @param newAssertionConsumerServiceURL the new AssertionConsumerServiceURL attribute value + */ + public void setAssertionConsumerServiceURL(String newAssertionConsumerServiceURL); + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateBuilder.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.ecp.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.ecp.RelayState; + +/** + * A Builder for {@link RelayState} objects. + */ +public class RelayStateBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public RelayStateBuilder() { + + } + + /** {@inheritDoc} */ + public RelayState buildObject() { + return buildObject(SAMLConstants.SAML20ECP_NS, RelayState.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20ECP_PREFIX); + } + + /** {@inheritDoc} */ + public RelayState buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RelayStateImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateImpl.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,99 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import java.util.List; + +import org.opensaml.saml2.ecp.RelayState; +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.schema.impl.XSStringImpl; + +/** + * A concrete implementation of {@link RelayState}. + */ +public class RelayStateImpl extends XSStringImpl implements RelayState { + + /** soap11:actor attribute. */ + private String soap11Actor; + + /** soap11:mustUnderstand. */ + private XSBooleanValue soap11MustUnderstand; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RelayStateImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Boolean isSOAP11MustUnderstand() { + if (soap11MustUnderstand != null) { + return soap11MustUnderstand.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isSOAP11MustUnderstandXSBoolean() { + return soap11MustUnderstand; + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(Boolean newMustUnderstand) { + if (newMustUnderstand != null) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, + new XSBooleanValue(newMustUnderstand, true)); + } else { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, null); + } + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(XSBooleanValue newMustUnderstand) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, newMustUnderstand); + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public String getSOAP11Actor() { + return soap11Actor; + } + + /** {@inheritDoc} */ + public void setSOAP11Actor(String newActor) { + soap11Actor = prepareForAssignment(soap11Actor, newActor); + manageQualifiedAttributeNamespace(ActorBearing.SOAP11_ACTOR_ATTR_NAME, soap11Actor != null); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateMarshaller.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import org.opensaml.saml2.ecp.RelayState; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.impl.XSStringMarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link RelayState}. + */ +public class RelayStateMarshaller extends XSStringMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + RelayState relayState = (RelayState) xmlObject; + + if (relayState.isSOAP11MustUnderstandXSBoolean() != null) { + XMLHelper.marshallAttribute(RelayState.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + relayState.isSOAP11MustUnderstandXSBoolean().toString(), domElement, false); + } + if (relayState.getSOAP11Actor() != null) { + XMLHelper.marshallAttribute(RelayState.SOAP11_ACTOR_ATTR_NAME, + relayState.getSOAP11Actor(), domElement, false); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RelayStateUnmarshaller.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.ecp.RelayState; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.schema.impl.XSStringUnmarshaller; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link RelayState}. + */ +public class RelayStateUnmarshaller extends XSStringUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + RelayState relayState = (RelayState) xmlObject; + + QName attrName = XMLHelper.getNodeQName(attribute); + if (RelayState.SOAP11_MUST_UNDERSTAND_ATTR_NAME.equals(attrName)) { + relayState.setSOAP11MustUnderstand(XSBooleanValue.valueOf(attribute.getValue())); + } else if (RelayState.SOAP11_ACTOR_ATTR_NAME.equals(attrName)) { + relayState.setSOAP11Actor(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestBuilder.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.ecp.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.ecp.Request; + +/** + * A Builder for {@link Request} objects. + */ +public class RequestBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public RequestBuilder() { + + } + + /** {@inheritDoc} */ + public Request buildObject() { + return buildObject(SAMLConstants.SAML20ECP_NS, Request.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20ECP_PREFIX); + } + + /** {@inheritDoc} */ + public Request buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestImpl.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,180 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.core.IDPList; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.ecp.Request; +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * A concrete implementation of {@link Request}. + */ +public class RequestImpl extends AbstractSAMLObject implements Request { + + /** IDPList child element. */ + private IDPList idpList; + + /** Issuer child element. */ + private Issuer issuer; + + /** ProviderName attribute. */ + private String providerName; + + /** IsPassive attribute value. */ + private XSBooleanValue isPassive; + + /** soap11:actor attribute. */ + private String soap11Actor; + + /** soap11:mustUnderstand. */ + private XSBooleanValue soap11MustUnderstand; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RequestImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public IDPList getIDPList() { + return idpList; + } + + /** {@inheritDoc} */ + public void setIDPList(IDPList newIDPList) { + idpList = prepareForAssignment(idpList, newIDPList); + } + + /** {@inheritDoc} */ + public Issuer getIssuer() { + return issuer; + } + + /** {@inheritDoc} */ + public void setIssuer(Issuer newIssuer) { + issuer = prepareForAssignment(issuer, newIssuer); + } + + /** {@inheritDoc} */ + public String getProviderName() { + return providerName; + } + + /** {@inheritDoc} */ + public void setProviderName(String newProviderName) { + providerName = prepareForAssignment(providerName, newProviderName); + } + + /** {@inheritDoc} */ + public Boolean isPassive() { + if (isPassive != null) { + return isPassive.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isPassiveXSBoolean() { + return isPassive; + } + + /** {@inheritDoc} */ + public void setPassive(Boolean newIsPassive) { + if (newIsPassive != null) { + isPassive = prepareForAssignment(isPassive, new XSBooleanValue(newIsPassive, false)); + } else { + isPassive = prepareForAssignment(isPassive, null); + } + } + + /** {@inheritDoc} */ + public void setPassive(XSBooleanValue newIsPassive) { + this.isPassive = prepareForAssignment(this.isPassive, newIsPassive); + } + + /** {@inheritDoc} */ + public Boolean isSOAP11MustUnderstand() { + if (soap11MustUnderstand != null) { + return soap11MustUnderstand.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isSOAP11MustUnderstandXSBoolean() { + return soap11MustUnderstand; + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(Boolean newMustUnderstand) { + if (newMustUnderstand != null) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, + new XSBooleanValue(newMustUnderstand, true)); + } else { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, null); + } + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(XSBooleanValue newMustUnderstand) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, newMustUnderstand); + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public String getSOAP11Actor() { + return soap11Actor; + } + + /** {@inheritDoc} */ + public void setSOAP11Actor(String newActor) { + soap11Actor = prepareForAssignment(soap11Actor, newActor); + manageQualifiedAttributeNamespace(ActorBearing.SOAP11_ACTOR_ATTR_NAME, soap11Actor != null); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (issuer!=null) { + children.add(issuer); + } + if (idpList!=null) { + children.add(idpList); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestMarshaller.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.ecp.Request; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link Request}. + */ +public class RequestMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Request request = (Request) xmlObject; + + if (request.getProviderName() != null) { + domElement.setAttributeNS(null, Request.PROVIDER_NAME_ATTRIB_NAME, request.getProviderName()); + } + if (request.isPassiveXSBoolean() != null) { + domElement.setAttributeNS(null, Request.IS_PASSIVE_NAME_ATTRIB_NAME, + request.isPassiveXSBoolean().toString()); + } + if (request.isSOAP11MustUnderstandXSBoolean() != null) { + XMLHelper.marshallAttribute(Request.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + request.isSOAP11MustUnderstandXSBoolean().toString(), domElement, false); + } + if (request.getSOAP11Actor() != null) { + XMLHelper.marshallAttribute(Request.SOAP11_ACTOR_ATTR_NAME, + request.getSOAP11Actor(), domElement, false); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/RequestUnmarshaller.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.core.IDPList; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.ecp.Request; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link Request}. + */ +public class RequestUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Request request = (Request) samlObject; + + QName attrName = XMLHelper.getNodeQName(attribute); + if (Request.SOAP11_MUST_UNDERSTAND_ATTR_NAME.equals(attrName)) { + request.setSOAP11MustUnderstand(XSBooleanValue.valueOf(attribute.getValue())); + } else if (Request.SOAP11_ACTOR_ATTR_NAME.equals(attrName)) { + request.setSOAP11Actor(attribute.getValue()); + } else if (Request.IS_PASSIVE_NAME_ATTRIB_NAME.equals(attribute.getLocalName())) { + request.setPassive(XSBooleanValue.valueOf(attribute.getValue())); + } else if (Request.PROVIDER_NAME_ATTRIB_NAME.equals(attribute.getLocalName())) { + request.setProviderName(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Request request = (Request) parentSAMLObject; + + if (childSAMLObject instanceof Issuer) { + request.setIssuer((Issuer) childSAMLObject); + } else if (childSAMLObject instanceof IDPList) { + request.setIDPList((IDPList) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseBuilder.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.ecp.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.ecp.Response; + +/** + * A Builder for {@link Response} objects. + */ +public class ResponseBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public ResponseBuilder() { + + } + + /** {@inheritDoc} */ + public Response buildObject() { + return buildObject(SAMLConstants.SAML20ECP_NS, Response.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20ECP_PREFIX); + } + + /** {@inheritDoc} */ + public Response buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseImpl.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.ecp.Response; +import org.opensaml.ws.soap.soap11.ActorBearing; +import org.opensaml.ws.soap.soap11.MustUnderstandBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * A concrete implementation of {@link Response}. + */ +public class ResponseImpl extends AbstractSAMLObject implements Response { + + /** soap11:actor attribute. */ + private String soap11Actor; + + /** soap11:mustUnderstand. */ + private XSBooleanValue soap11MustUnderstand; + + /** The AssertionConsumerServiceURL attribute value. */ + private String acsURL; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAssertionConsumerServiceURL() { + return acsURL; + } + + /** {@inheritDoc} */ + public void setAssertionConsumerServiceURL(String newAssertionConsumerServiceURL) { + acsURL = prepareForAssignment(acsURL, newAssertionConsumerServiceURL); + } + + /** {@inheritDoc} */ + public Boolean isSOAP11MustUnderstand() { + if (soap11MustUnderstand != null) { + return soap11MustUnderstand.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isSOAP11MustUnderstandXSBoolean() { + return soap11MustUnderstand; + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(Boolean newMustUnderstand) { + if (newMustUnderstand != null) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, + new XSBooleanValue(newMustUnderstand, true)); + } else { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, null); + } + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public void setSOAP11MustUnderstand(XSBooleanValue newMustUnderstand) { + soap11MustUnderstand = prepareForAssignment(soap11MustUnderstand, newMustUnderstand); + manageQualifiedAttributeNamespace(MustUnderstandBearing.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + soap11MustUnderstand != null); + } + + /** {@inheritDoc} */ + public String getSOAP11Actor() { + return soap11Actor; + } + + /** {@inheritDoc} */ + public void setSOAP11Actor(String newActor) { + soap11Actor = prepareForAssignment(soap11Actor, newActor); + manageQualifiedAttributeNamespace(ActorBearing.SOAP11_ACTOR_ATTR_NAME, soap11Actor != null); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseMarshaller.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.ecp.Response; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for instances of {@link Response}. + */ +public class ResponseMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Response response = (Response) xmlObject; + + if (response.getAssertionConsumerServiceURL() != null) { + domElement.setAttributeNS(null, Response.ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME, + response.getAssertionConsumerServiceURL()); + } + if (response.isSOAP11MustUnderstandXSBoolean() != null) { + XMLHelper.marshallAttribute(Response.SOAP11_MUST_UNDERSTAND_ATTR_NAME, + response.isSOAP11MustUnderstandXSBoolean().toString(), domElement, false); + } + if (response.getSOAP11Actor() != null) { + XMLHelper.marshallAttribute(Response.SOAP11_ACTOR_ATTR_NAME, + response.getSOAP11Actor(), domElement, false); + } + } + + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/ecp/impl/ResponseUnmarshaller.java 17 Aug 2012 15:03:37 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.ecp.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.ecp.Response; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for instances of {@link Response}. + */ +public class ResponseUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Response response = (Response) samlObject; + + QName attrName = XMLHelper.getNodeQName(attribute); + if (Response.SOAP11_MUST_UNDERSTAND_ATTR_NAME.equals(attrName)) { + response.setSOAP11MustUnderstand(XSBooleanValue.valueOf(attribute.getValue())); + } else if (Response.SOAP11_ACTOR_ATTR_NAME.equals(attrName)) { + response.setSOAP11Actor(attribute.getValue()); + } else if (Response.ASSERTION_CONSUMER_SERVICE_URL_ATTRIB_NAME.equals(attribute.getLocalName())) { + response.setAssertionConsumerServiceURL(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/Decrypter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/encryption/Decrypter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/Decrypter.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,154 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.encryption; + +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.EncryptedAttribute; +import org.opensaml.saml2.core.EncryptedElementType; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NewEncryptedID; +import org.opensaml.saml2.core.NewID; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.encryption.DecryptionException; +import org.opensaml.xml.encryption.EncryptedKeyResolver; +import org.opensaml.xml.security.keyinfo.KeyInfoCredentialResolver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class which implements SAML2-specific options for {@link EncryptedElementType} objects. + * + *

+ * For information on other parameters and options, and general XML Encryption issues, + * see {@link org.opensaml.xml.encryption.Decrypter}. + *

+ */ +public class Decrypter extends org.opensaml.xml.encryption.Decrypter { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(Decrypter.class); + + /** + * Constructor. + * + * @param newResolver resolver for data encryption keys. + * @param newKEKResolver resolver for key encryption keys. + * @param newEncKeyResolver resolver for EncryptedKey elements + */ + public Decrypter(KeyInfoCredentialResolver newResolver, KeyInfoCredentialResolver newKEKResolver, + EncryptedKeyResolver newEncKeyResolver) { + super(newResolver, newKEKResolver, newEncKeyResolver); + } + + /** + * Decrypt the specified EncryptedAssertion. + * + * @param encryptedAssertion the EncryptedAssertion to decrypt + * @return an Assertion + * @throws DecryptionException thrown when decryption generates an error + */ + public Assertion decrypt(EncryptedAssertion encryptedAssertion) throws DecryptionException { + SAMLObject samlObject = decryptData(encryptedAssertion); + if (! (samlObject instanceof Assertion)) { + throw new DecryptionException("Decrypted SAMLObject was not an instance of Assertion"); + } + return (Assertion) samlObject; + } + + /** + * Decrypt the specified EncryptedAttribute. + * + * @param encryptedAttribute the EncryptedAttribute to decrypt + * @return an Attribute + * @throws DecryptionException thrown when decryption generates an error + */ + public Attribute decrypt(EncryptedAttribute encryptedAttribute) throws DecryptionException { + SAMLObject samlObject = decryptData(encryptedAttribute); + if (! (samlObject instanceof Attribute)) { + throw new DecryptionException("Decrypted SAMLObject was not an instance of Attribute"); + } + return (Attribute) samlObject; + } + + /** + * Decrypt the specified EncryptedID. + * + *

+ * Note that an EncryptedID can contain a NameID, an Assertion + * or a BaseID. It is up to the caller to determine the type of + * the resulting SAMLObject. + *

+ * + * @param encryptedID the EncryptedID to decrypt + * @return an XMLObject + * @throws DecryptionException thrown when decryption generates an error + */ + public SAMLObject decrypt(EncryptedID encryptedID) throws DecryptionException { + return decryptData(encryptedID); + } + + + /** + * Decrypt the specified NewEncryptedID. + * + * @param newEncryptedID the NewEncryptedID to decrypt + * @return a NewID + * @throws DecryptionException thrown when decryption generates an error + */ + public NewID decrypt(NewEncryptedID newEncryptedID) throws DecryptionException { + SAMLObject samlObject = decryptData(newEncryptedID); + if (! (samlObject instanceof NewID)) { + throw new DecryptionException("Decrypted SAMLObject was not an instance of NewID"); + } + return (NewID) samlObject; + } + + /** + * Decrypt the specified instance of EncryptedElementType, and return it as an instance + * of the specified QName. + * + * + * @param encElement the EncryptedElementType to decrypt + * @return the decrypted SAMLObject + * @throws DecryptionException thrown when decryption generates an error + */ + private SAMLObject decryptData(EncryptedElementType encElement) throws DecryptionException { + + if (encElement.getEncryptedData() == null) { + throw new DecryptionException("Element had no EncryptedData child"); + } + + XMLObject xmlObject = null; + try { + xmlObject = decryptData(encElement.getEncryptedData(), isRootInNewDocument()); + } catch (DecryptionException e) { + log.error("SAML Decrypter encountered an error decrypting element content", e); + throw e; + } + + if (! (xmlObject instanceof SAMLObject)) { + throw new DecryptionException("Decrypted XMLObject was not an instance of SAMLObject"); + } + + return (SAMLObject) xmlObject; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/EncryptedElementTypeEncryptedKeyResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/encryption/EncryptedElementTypeEncryptedKeyResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/EncryptedElementTypeEncryptedKeyResolver.java 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.encryption; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.saml2.core.EncryptedElementType; +import org.opensaml.xml.encryption.AbstractEncryptedKeyResolver; +import org.opensaml.xml.encryption.EncryptedData; +import org.opensaml.xml.encryption.EncryptedKey; +import org.opensaml.xml.encryption.EncryptedKeyResolver; + +/** + * An implementation of {@link EncryptedKeyResolver} which resolves {@link EncryptedKey} + * elements which appear as immediate children of the {@link EncryptedElementType} which + * is the parent of the {@link EncryptedData} context. + */ +public class EncryptedElementTypeEncryptedKeyResolver extends AbstractEncryptedKeyResolver { + + /** {@inheritDoc} */ + public Iterable resolve(EncryptedData encryptedData) { + List resolvedEncKeys = new ArrayList(); + + if (! (encryptedData.getParent() instanceof EncryptedElementType) ) { + return resolvedEncKeys; + } + + EncryptedElementType encElementType = (EncryptedElementType) encryptedData.getParent(); + + for (EncryptedKey encKey : encElementType.getEncryptedKeys()) { + if (matchRecipient(encKey.getRecipient())) { + resolvedEncKeys.add(encKey); + } + } + + return resolvedEncKeys; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/Encrypter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/encryption/Encrypter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/Encrypter.java 17 Aug 2012 15:03:44 -0000 1.1 @@ -0,0 +1,530 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.encryption; + +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.common.IdentifierGenerator; +import org.opensaml.common.impl.SecureRandomIdentifierGenerator; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.BaseID; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.EncryptedAttribute; +import org.opensaml.saml2.core.EncryptedElementType; +import org.opensaml.saml2.core.EncryptedID; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NewEncryptedID; +import org.opensaml.saml2.core.NewID; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.XMLObjectBuilderFactory; +import org.opensaml.xml.encryption.CarriedKeyName; +import org.opensaml.xml.encryption.DataReference; +import org.opensaml.xml.encryption.EncryptedData; +import org.opensaml.xml.encryption.EncryptedKey; +import org.opensaml.xml.encryption.EncryptionConstants; +import org.opensaml.xml.encryption.EncryptionException; +import org.opensaml.xml.encryption.EncryptionParameters; +import org.opensaml.xml.encryption.KeyEncryptionParameters; +import org.opensaml.xml.encryption.ReferenceList; +import org.opensaml.xml.encryption.XMLEncryptionBuilder; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; +import org.opensaml.xml.signature.KeyInfo; +import org.opensaml.xml.signature.KeyName; +import org.opensaml.xml.signature.RetrievalMethod; +import org.opensaml.xml.signature.XMLSignatureBuilder; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * Encrypter for SAML 2 SAMLObjects which has specific options for generating instances of subtypes of + * {@link EncryptedElementType}. + * + *

+ * Overloaded methods are provided for encrypting various SAML 2 elements to their corresponding + * encrypted element variant of {@link EncryptedElementType}. + *

+ * + *

+ * Support is also provided for differing placement options for any associated EncryptedKeys that may + * be generated. The options are: + *

    + *
  • INLINE: EncryptedKeys will placed inside the KeyInfo element of the EncryptedData element
  • + *
  • PEER: EncryptedKeys will be placed as peer elements of the EncryptedData inside the + * EncryptedElementType element
  • + *
+ * The default placement is PEER. + *

+ * + *

+ * The EncryptedKey forward and back referencing behavior associated with these key placement options + * is intended to be consistent with the guidelines detailed in SAML 2 Errata E43. See that document + * for further information. + *

+ * + *

+ * For information on other parameters and options, and general XML Encryption issues, + * see {@link org.opensaml.xml.encryption.Encrypter}. + *

+ * + */ +public class Encrypter extends org.opensaml.xml.encryption.Encrypter { + + /** + * Options for where to place the resulting EncryptedKey elements with respect + * to the associated EncryptedData element. + */ + public enum KeyPlacement { + /** Place the EncryptedKey element(s) as a peer to the EncryptedData inside the EncryptedElementType. */ + PEER, + + /** Place the EncryptedKey element(s) within the KeyInfo of the EncryptedData. */ + INLINE + } + + /** Factory for building XMLObject instances. */ + private XMLObjectBuilderFactory builderFactory; + + /** Builder for KeyInfo objects. */ + private XMLSignatureBuilder keyInfoBuilder; + + /** Builder for DataReference objects. */ + private XMLEncryptionBuilder dataReferenceBuilder; + + /** Builder for ReferenceList objects. */ + private XMLEncryptionBuilder referenceListBuilder; + + /** Builder for RetrievalMethod objects. */ + private XMLSignatureBuilder retrievalMethodBuilder; + + /** Builder for KeyName objects. */ + private XMLSignatureBuilder keyNameBuilder; + + /** Builder for CarriedKeyName objects. */ + private XMLEncryptionBuilder carriedKeyNameBuilder; + + /** Generator for XML ID attribute values. */ + private IdentifierGenerator idGenerator; + + /** The parameters to use for encrypting the data. */ + private EncryptionParameters encParams; + + /** The parameters to use for encrypting (wrapping) the data encryption key. */ + private List kekParamsList; + + /** The option for where to place the generated EncryptedKey elements. */ + private KeyPlacement keyPlacement; + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(Encrypter.class); + + + /** + * Constructor. + * + * @param dataEncParams the data encryption parameters + * @param keyEncParams the key encryption parameters + */ + public Encrypter(EncryptionParameters dataEncParams, List keyEncParams) { + super(); + + this.encParams = dataEncParams; + this.kekParamsList = keyEncParams; + + init(); + } + + /** + * Constructor. + * + * @param dataEncParams the data encryption parameters + * @param keyEncParam the key encryption parameter + */ + public Encrypter(EncryptionParameters dataEncParams, KeyEncryptionParameters keyEncParam) { + super(); + + List keks = new ArrayList(); + keks.add(keyEncParam); + + this.encParams = dataEncParams; + this.kekParamsList = keks; + + init(); + } + + /** + * Constructor. + * + * @param dataEncParams the data encryption parameters + */ + public Encrypter(EncryptionParameters dataEncParams) { + super(); + + List keks = new ArrayList(); + + this.encParams = dataEncParams; + this.kekParamsList = keks; + + init(); + } + + /** + * Helper method for constructors. + */ + private void init() { + builderFactory = Configuration.getBuilderFactory(); + keyInfoBuilder = + (XMLSignatureBuilder) builderFactory.getBuilder(KeyInfo.DEFAULT_ELEMENT_NAME); + dataReferenceBuilder = + (XMLEncryptionBuilder) builderFactory.getBuilder(DataReference.DEFAULT_ELEMENT_NAME); + referenceListBuilder = + (XMLEncryptionBuilder) builderFactory.getBuilder(ReferenceList.DEFAULT_ELEMENT_NAME); + retrievalMethodBuilder = + (XMLSignatureBuilder) builderFactory.getBuilder(RetrievalMethod.DEFAULT_ELEMENT_NAME); + keyNameBuilder = + (XMLSignatureBuilder) builderFactory.getBuilder(KeyName.DEFAULT_ELEMENT_NAME); + carriedKeyNameBuilder = + (XMLEncryptionBuilder) builderFactory.getBuilder(CarriedKeyName.DEFAULT_ELEMENT_NAME); + + try{ + idGenerator = new SecureRandomIdentifierGenerator(); + }catch(NoSuchAlgorithmException e){ + log.error("JVM does not support SHA1PRNG random number generation algorithm."); + } + + keyPlacement = KeyPlacement.PEER; + } + + /** + * Set the generator to use when creating XML ID attribute values. + * + * @param newIDGenerator the new IdentifierGenerator to use + */ + public void setIDGenerator(IdentifierGenerator newIDGenerator) { + this.idGenerator = newIDGenerator; + } + + /** + * Get the current key placement option. + * + * @return returns the key placement option. + */ + public KeyPlacement getKeyPlacement() { + return this.keyPlacement; + } + + /** + * Set the key placement option. + * + * @param newKeyPlacement The new key placement option to set + */ + public void setKeyPlacement(KeyPlacement newKeyPlacement) { + this.keyPlacement = newKeyPlacement; + } + + /** + * Encrypt the specified Assertion. + * + * @param assertion the Assertion to encrypt + * @return an EncryptedAssertion + * @throws EncryptionException thrown when encryption generates an error + */ + public EncryptedAssertion encrypt(Assertion assertion) throws EncryptionException { + return (EncryptedAssertion) encrypt(assertion, EncryptedAssertion.DEFAULT_ELEMENT_NAME); + } + + /** + * Encrypt the specified Assertion, treating as an identifier and returning + * an EncryptedID. + * + * @param assertion the Assertion to encrypt + * @return an EncryptedID + * @throws EncryptionException thrown when encryption generates an error + */ + public EncryptedID encryptAsID(Assertion assertion) throws EncryptionException { + return (EncryptedID) encrypt(assertion, EncryptedID.DEFAULT_ELEMENT_NAME); + } + + /** + * Encrypt the specified Attribute. + * + * @param attribute the Attribute to encrypt + * @return an EncryptedAttribute + * @throws EncryptionException thrown when encryption generates an error + */ + public EncryptedAttribute encrypt(Attribute attribute) throws EncryptionException { + return (EncryptedAttribute) encrypt(attribute, EncryptedAttribute.DEFAULT_ELEMENT_NAME); + } + + /** + * Encrypt the specified NameID. + * + * @param nameID the NameID to encrypt + * @return an EncryptedID + * @throws EncryptionException thrown when encryption generates an error + */ + public EncryptedID encrypt(NameID nameID) throws EncryptionException { + return (EncryptedID) encrypt(nameID, EncryptedID.DEFAULT_ELEMENT_NAME); + } + + /** + * Encrypt the specified BaseID. + * + * @param baseID the BaseID to encrypt + * @return an EncryptedID + * @throws EncryptionException thrown when encryption generates an error + */ + public EncryptedID encrypt(BaseID baseID) throws EncryptionException { + return (EncryptedID) encrypt(baseID, EncryptedID.DEFAULT_ELEMENT_NAME); + } + + /** + * Encrypt the specified NewID. + * + * @param newID the NewID to encrypt + * @return a NewEncryptedID + * @throws EncryptionException thrown when encryption generates an error + */ + public NewEncryptedID encrypt(NewID newID) throws EncryptionException { + return (NewEncryptedID) encrypt(newID, NewEncryptedID.DEFAULT_ELEMENT_NAME); + } + + /** + * Encrypt the specified XMLObject, and return it as an instance of the specified QName, + * which should be one of the types derived from {@link org.opensaml.saml2.core.EncryptedElementType}. + * + * @param xmlObject the XMLObject to encrypt + * @param encElementName the QName of the specialization of EncryptedElementType to return + * @return a specialization of {@link org.opensaml.saml2.core.EncryptedElementType} + * @throws EncryptionException thrown when encryption generates an error + */ + private EncryptedElementType encrypt(XMLObject xmlObject, QName encElementName) throws EncryptionException { + + checkParams(encParams, kekParamsList); + + EncryptedElementType encElement = + (EncryptedElementType) builderFactory.getBuilder(encElementName).buildObject(encElementName); + + // Marshall the containing element, we will need its Document context to pass + // to the key encryption method + checkAndMarshall(encElement); + Document ownerDocument = encElement.getDOM().getOwnerDocument(); + + String encryptionAlgorithmURI = encParams.getAlgorithm(); + Key encryptionKey = SecurityHelper.extractEncryptionKey(encParams.getEncryptionCredential()); + if (encryptionKey == null) { + encryptionKey = generateEncryptionKey(encryptionAlgorithmURI); + } + + EncryptedData encryptedData = encryptElement(xmlObject, encryptionKey, encryptionAlgorithmURI, false); + if (encParams.getKeyInfoGenerator() != null) { + KeyInfoGenerator generator = encParams.getKeyInfoGenerator(); + log.debug("Dynamically generating KeyInfo from Credential for EncryptedData using generator: {}", + generator.getClass().getName()); + try { + encryptedData.setKeyInfo( generator.generate(encParams.getEncryptionCredential()) ); + } catch (SecurityException e) { + throw new EncryptionException("Error generating EncryptedData KeyInfo", e); + } + } + + List encryptedKeys = new ArrayList(); + if (kekParamsList != null && ! kekParamsList.isEmpty()) { + encryptedKeys.addAll( encryptKey(encryptionKey, kekParamsList, ownerDocument) ); + } + + return processElements(encElement, encryptedData, encryptedKeys); + } + + /** + * Handle post-processing of generated EncryptedData and EncryptedKey(s) and storage in the appropriate + * EncryptedElementType instance. + * + * @param encElement the EncryptedElementType instance which will hold the encrypted data and keys + * @param encData the EncryptedData object + * @param encKeys the list of EncryptedKey objects + * @return the processed EncryptedElementType instance + * + * @throws EncryptionException thrown when processing encounters an error + */ + protected EncryptedElementType processElements(EncryptedElementType encElement, + EncryptedData encData, List encKeys) throws EncryptionException { + // First ensure certain elements/attributes are non-null, common to all cases. + if (encData.getID() == null) { + encData.setID(idGenerator.generateIdentifier()); + } + + // If not doing key wrapping, just return the encrypted element + if (encKeys.isEmpty()) { + encElement.setEncryptedData(encData); + return encElement; + } + + if (encData.getKeyInfo() == null) { + encData.setKeyInfo(keyInfoBuilder.buildObject()); + } + + for (EncryptedKey encKey : encKeys) { + if (encKey.getID() == null) { + encKey.setID(idGenerator.generateIdentifier()); + } + } + + switch (keyPlacement) { + case INLINE: + return placeKeysInline(encElement, encData, encKeys); + case PEER: + return placeKeysAsPeers(encElement, encData, encKeys); + default: + //Shouldn't be able to get here, but just in case... + throw new EncryptionException("Unsupported key placement option was specified: " + keyPlacement); + } + } + + /** + * Place the EncryptedKey elements inside the KeyInfo element within the EncryptedData element. + * + * Although operationally trivial, this method is provided so that subclasses may + * override or augment as desired. + * + * @param encElement the EncryptedElementType instance which will hold the encrypted data and keys + * @param encData the EncryptedData object + * @param encKeys the list of EncryptedKey objects + * @return the processed EncryptedElementType instance + */ + protected EncryptedElementType placeKeysInline(EncryptedElementType encElement, + EncryptedData encData, List encKeys) { + + log.debug("Placing EncryptedKey elements inline inside EncryptedData"); + + encData.getKeyInfo().getEncryptedKeys().addAll(encKeys); + encElement.setEncryptedData(encData); + return encElement; + } + + /** + * Store the specified EncryptedData and EncryptedKey(s) in the specified instance of EncryptedElementType + * as peer elements, following SAML 2 Errata E43 guidelines for forward and back referencing between the + * EncryptedData and EncryptedKey(s). + * + * @param encElement a specialization of EncryptedElementType to store the encrypted data and keys + * @param encData the EncryptedData to store + * @param encKeys the EncryptedKey(s) to store + * @return the resulting specialization of EncryptedElementType + */ + protected EncryptedElementType placeKeysAsPeers(EncryptedElementType encElement, + EncryptedData encData, List encKeys) { + + log.debug("Placing EncryptedKey elements as peers of EncryptedData in EncryptedElementType"); + + for (EncryptedKey encKey : encKeys) { + if (encKey.getReferenceList() == null) { + encKey.setReferenceList(referenceListBuilder.buildObject()); + } + } + + // If there is only 1 EncryptedKey we have a simple forward reference (RetrievalMethod) + // and back reference (ReferenceList/DataReference) requirement. + // Multiple "multicast" keys use back reference + CarriedKeyName + if (encKeys.size() == 1) { + linkSinglePeerKey(encData, encKeys.get(0)); + } else if (encKeys.size() > 1) { + linkMultiplePeerKeys(encData, encKeys); + } + + encElement.setEncryptedData(encData); + encElement.getEncryptedKeys().addAll(encKeys); + + return encElement; + } + + /** + * Link a single EncryptedKey to the EncryptedData according to guidelines in SAML Errata E43. + * + * @param encData the EncryptedData + * @param encKey the EncryptedKey + */ + protected void linkSinglePeerKey(EncryptedData encData, EncryptedKey encKey) { + log.debug("Linking single peer EncryptedKey with RetrievalMethod and DataReference"); + // Forward reference from EncryptedData to the EncryptedKey + RetrievalMethod rm = retrievalMethodBuilder.buildObject(); + rm.setURI("#" + encKey.getID()); + rm.setType(EncryptionConstants.TYPE_ENCRYPTED_KEY); + encData.getKeyInfo().getRetrievalMethods().add(rm); + + // Back reference from the EncryptedKey to the EncryptedData + DataReference dr = dataReferenceBuilder.buildObject(); + dr.setURI("#" + encData.getID()); + encKey.getReferenceList().getDataReferences().add(dr); + } + + /** + * Link multiple "multicast" EncryptedKeys to the EncryptedData according + * to guidelines in SAML Errata E43. + * + * @param encData the EncryptedData + * @param encKeys the list of EncryptedKeys + */ + protected void linkMultiplePeerKeys(EncryptedData encData, List encKeys) { + log.debug("Linking multiple peer EncryptedKeys with CarriedKeyName and DataReference"); + // Get the name of the data encryption key + List dataEncKeyNames = encData.getKeyInfo().getKeyNames(); + String carriedKeyNameValue; + if (dataEncKeyNames.size() == 0 || DatatypeHelper.isEmpty(dataEncKeyNames.get(0).getValue()) ) { + // If there isn't one, autogenerate a random key name. + String keyNameValue = idGenerator.generateIdentifier(); + log.debug("EncryptedData encryption key had no KeyName, generated one for use in CarriedKeyName: {}", + keyNameValue); + + KeyName keyName = dataEncKeyNames.get(0); + if (keyName == null) { + keyName = keyNameBuilder.buildObject(); + dataEncKeyNames.add(keyName); + } + keyName.setValue(keyNameValue); + carriedKeyNameValue = keyNameValue; + } else { + carriedKeyNameValue = dataEncKeyNames.get(0).getValue(); + } + + // Set carried key name of the multicast key in each EncryptedKey + for (EncryptedKey encKey : encKeys) { + if (encKey.getCarriedKeyName() == null) { + encKey.setCarriedKeyName(carriedKeyNameBuilder.buildObject()); + } + encKey.getCarriedKeyName().setValue(carriedKeyNameValue); + + // Back reference from the EncryptedKeys to the EncryptedData + DataReference dr = dataReferenceBuilder.buildObject(); + dr.setURI("#" + encData.getID()); + encKey.getReferenceList().getDataReferences().add(dr); + + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/encryption/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/encryption/package.html 17 Aug 2012 15:03:43 -0000 1.1 @@ -0,0 +1,5 @@ + + +Classes for encrypting and decrypting SAML. + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AdditionalMetadataLocation.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AdditionalMetadataLocation.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AdditionalMetadataLocation.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata AdditionalMetadataLocation + */ +public interface AdditionalMetadataLocation extends SAMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AdditionalMetadataLocation"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AdditionalMetadataLocationType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** "affiliationOwnerID" attribute's local name */ + public final static String NAMESPACE_ATTRIB_NAME = "namespace"; + + /** + * Gets the location URI. + * + * @return the location URI + */ + public String getLocationURI(); + + /** + * Sets the location URI. + * + * @param locationURI the location URI + */ + public void setLocationURI(String locationURI); + + /** + * Gets the namespace URI. + * + * @return the namespace URI + */ + public String getNamespaceURI(); + + /** + * Sets the namespace URI. + * + * @param namespaceURI the namespace URI + */ + public void setNamespaceURI(String namespaceURI); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AffiliateMember.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AffiliateMember.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AffiliateMember.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata AffiliateMember + */ +public interface AffiliateMember extends SAMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AffiliateMember"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "entityIDType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the member's entity ID. + * + * @return the member's ID + */ + public String getID(); + + /** + * Sets the member's entity ID. + * + * @param memberID the member's ID + * + * @throws IllegalArgumentException thrown if the ID is over 1024 characters long + */ + public void setID(String memberID) throws IllegalArgumentException; +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AffiliationDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AffiliationDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AffiliationDescriptor.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * SAML 2.0 Metadata AffiliationDescriptorType + */ +public interface AffiliationDescriptor extends SignableSAMLObject, TimeBoundSAMLObject, CacheableSAMLObject, + AttributeExtensibleXMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AffiliationDescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AffiliationDescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** "affiliationOwnerID" attribute's local name */ + public final static String OWNER_ID_ATTRIB_NAME = "affiliationOwnerID"; + + /** ID attribute's local name */ + public final static String ID_ATTRIB_NAME = "ID"; + + /** + * Gets the ID of the owner of this affiliation. The owner may, or may not, be a memeber of the affiliation. + * + * @return the ID of the owner of this affiliation + */ + public String getOwnerID(); + + /** + * Gets the ID of this Descriptor. + * + * @return the ID of this Descriptor + */ + public String getID(); + + /** + * Gets the Extensions child of this object. + * + * @return the Extensions child of this object + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions child of this object. + * + * @param extensions the Extensions child of this object + * + * @throws IllegalArgumentException thrown if the given extensions Object is already a child of another SAMLObject + */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException; + + /** + * Sets the ID of the owner of this affiliation. + * + * @param ownerID the ID of the owner of this affiliation + */ + public void setOwnerID(String ownerID); + + /** + * Sets the ID of this descriptor. + * + * @param newID the ID of this descriptor + */ + public void setID(String newID); + + /** + * Gets a list of the members of this affiliation. + * + * @return a list of affiliate members + */ + public List getMembers(); + + /** + * Gets an immutable list of KeyDescriptors for this affiliation. + * + * @return list of {@link KeyDescriptor}s for this affiliation + */ + public List getKeyDescriptors(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ArtifactResolutionService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ArtifactResolutionService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ArtifactResolutionService.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata ArtifactResolutionService + */ +public interface ArtifactResolutionService extends IndexedEndpoint { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "ArtifactResolutionService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AssertionConsumerService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AssertionConsumerService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AssertionConsumerService.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata AssertionConsumerService + */ +public interface AssertionConsumerService extends IndexedEndpoint { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AssertionConsumerService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AssertionIDRequestService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AssertionIDRequestService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AssertionIDRequestService.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + + +/** + * SAML 2.0 Metadata AssertionIDRequestService + */ +public interface AssertionIDRequestService extends Endpoint { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AssertionIDRequestService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeAuthorityDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeAuthorityDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeAuthorityDescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Attribute; + +/** + * SAML 2.0 Metadata AttributeAuthorityDescriptor + */ +public interface AttributeAuthorityDescriptor extends SAMLObject, RoleDescriptor { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeAuthorityDescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AttributeAuthorityDescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets a list of attribute service {@link Endpoint}s for this authority. + * + * @return list of attributes services + */ + public List getAttributeServices(); + + /** + * Gets a list of Assertion ID request services. + * + * @return list of Assertion ID request services + */ + public List getAssertionIDRequestServices(); + + /** + * Gets a list of NameID formats supported by this authority. + * + * @return list of NameID formats supported by this authority + */ + public List getNameIDFormats(); + + /** + * Gets a list of Attribute profiles supported by this authority. + * + * @return list of Attribute profiles supported by this authority + */ + public List getAttributeProfiles(); + + /** + * Gets the list of attribute available from this authority. + * + * @return list of attribute available from this authority + */ + public List getAttributes(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeConsumingService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeConsumingService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeConsumingService.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,116 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Metadata AttributeAuthorityDescriptor + */ +public interface AttributeConsumingService extends SAMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeConsumingService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AttributeConsumingServiceType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** "index" attribute's local name */ + public final static String INDEX_ATTRIB_NAME = "index"; + + /** "isDefault" attribute's local name */ + public final static String IS_DEFAULT_ATTRIB_NAME = "isDefault"; + + /** + * Gets the index for this service. + * + * @return the index for this service + */ + public int getIndex(); + + /** + * Sets the index for this service. + * + * @param index the index for this service + */ + public void setIndex(int index); + + /** + * Checks if this is the default service for the service provider. + * + * @return true if this is the default service, false if not + */ + public Boolean isDefault(); + + /** + * Checks if this is the default service for the service provider. + * + * @return true if this is the default service, false if not + */ + public XSBooleanValue isDefaultXSBoolean(); + + /** + * Sets if this is the default service for the service provider. Boolean values will be marshalled to either "true" + * or "false". + * + * @param newIsDefault true if this is the default service, false if not + */ + public void setIsDefault(Boolean newIsDefault); + + /** + * Sets if this is the default service for the service provider. + * + * @param newIsDefault true if this is the default service, false if not + */ + public void setIsDefault(XSBooleanValue newIsDefault); + + /** + * Gets the list of names this service has. + * + * @return list of names this service has + */ + public List getNames(); + + /** + * Gets the descriptions for this service. + * + * @return descriptions for this service + */ + public List getDescriptions(); + + /** + * Gets the attributes this service requests. + * + * @return attributes this service requests + */ + public List getRequestAttributes(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeProfile.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeProfile.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeProfile.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata AttributeProfile + */ +public interface AttributeProfile extends SAMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeProfile"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AttributeProfileType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the URI of this attribute profile. + * + * @return the URI of this attribute profile + */ + public String getProfileURI(); + + /** + * Sets the URI of this attribute profile. + * + * @param profileURI the URI of this attribute profile + */ + public void setProfileURI(String profileURI); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AttributeService.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + + +/** + * SAML 2.0 Metadata AttributeService + */ +public interface AttributeService extends Endpoint { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthnAuthorityDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthnAuthorityDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthnAuthorityDescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata AuthnAuthorityDescriptor + */ +public interface AuthnAuthorityDescriptor extends SAMLObject, RoleDescriptor { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnAuthorityDescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "AuthnAuthorityDescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the list of authentication query services for this authority. + * + * @return list of authentication query services + */ + public List getAuthnQueryServices(); + + /** + * Gets the list of assertion ID request services for this authority. + * + * @return assertion ID request services for this authority + */ + public List getAssertionIDRequestServices(); + + /** + * Gets the list of supported name ID formats for this authority. + * + * @return supported name ID formats for this authority + */ + public List getNameIDFormats(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthnQueryService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthnQueryService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthnQueryService.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + + +/** + * SAML 2.0 Metadata AuthnQueryService + */ +public interface AuthnQueryService extends Endpoint { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthnQueryService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthzService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthzService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/AuthzService.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata AuthzService + */ +public interface AuthzService extends Endpoint { + + /** Default element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "AuthzService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Company.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Company.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Company.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata Company + */ +public interface Company extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Company"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "CompanyType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the name of the company. + * + * @return the name of the company + */ + public String getName(); + + /** + * Sets the name of the company. + * + * @param newName the name of the company + */ + public void setName(String newName); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ContactPerson.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ContactPerson.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ContactPerson.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,133 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * SAML 2.0 Metadata ContactPerson + */ +public interface ContactPerson extends SAMLObject, AttributeExtensibleXMLObject{ + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "ContactPerson"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "ContactPersonType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** "contactType" attribute's local name */ + public final static String CONTACT_TYPE_ATTRIB_NAME = "contactType"; + + /** + * Gets the type of contact this person. + * + * @return the type of contact this person + */ + public ContactPersonTypeEnumeration getType(); + + /** + * Sets the type of contact this person. + * + * @param type the type of contact this person + */ + public void setType(ContactPersonTypeEnumeration type); + + /** + * Gets the Extensions child of this object. + * + * @return the Extensions child of this object + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions child of this object. + * + * @param extensions the Extensions child of this object + * + * @throws IllegalArgumentException thrown if the given extensions Object is already a child of another SAMLObject + */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException; + + /** + * Gets the company this contact person is associated with. + * + * @return the company this contact person is associated with + */ + public Company getCompany(); + + /** + * Sets the company this contact person is associated with. + * + * @param company the company this contact person is associated with + */ + public void setCompany(Company company); + + /** + * Gets the given name for this person. + * + * @return the given name for this person + */ + public GivenName getGivenName(); + + /** + * Sets the given name for this person. + * + * @param name the given name for this person + */ + public void setGivenName(GivenName name); + + /** + * Gets the surname for this person. + * + * @return the surname for this person + */ + public SurName getSurName(); + + /** + * Sets the surname for this person. + * @param name the surname for this person + */ + public void setSurName(SurName name); + + /** + * Gets a list of email addresses for this person. + * + * @return list of email addresses for this person + */ + public List getEmailAddresses(); + + /** + * Gets an immutable list of telephone numbers for this person. + * + * @return list of telephone numbers for this person + */ + public List getTelephoneNumbers(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ContactPersonTypeEnumeration.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ContactPersonTypeEnumeration.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ContactPersonTypeEnumeration.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +/** + * A type safe enumeration of contact types used by {@link org.opensaml.saml2.metadata.ContactPerson}. + */ +public final class ContactPersonTypeEnumeration { + + /** "technical" contact type */ + public static final ContactPersonTypeEnumeration TECHNICAL = new ContactPersonTypeEnumeration("technical"); + + /** "support" contact type */ + public static final ContactPersonTypeEnumeration SUPPORT = new ContactPersonTypeEnumeration("support"); + + /** "administrative" contact type */ + public static final ContactPersonTypeEnumeration ADMINISTRATIVE = new ContactPersonTypeEnumeration("administrative"); + + /** "billing" contact type */ + public static final ContactPersonTypeEnumeration BILLING = new ContactPersonTypeEnumeration("billing"); + + /** "other" contact type */ + public static final ContactPersonTypeEnumeration OTHER = new ContactPersonTypeEnumeration("other"); + + /** the contact type */ + private String type; + + /** + * Constructor + * + * @param type the contact type + */ + protected ContactPersonTypeEnumeration(String type) { + this.type = type; + } + + /** + * Gets the contact type as a string. + * + * @return the contact type + */ + public String toString() { + return type; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EmailAddress.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EmailAddress.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EmailAddress.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata EmailAddress + */ +public interface EmailAddress extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "EmailAddress"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "EmailAddressType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the email address. + * + * @return the email address + */ + public String getAddress(); + + /** + * Sets the email address. + * + * @param address email address + */ + public void setAddress(String address); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EncryptionMethod.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EncryptionMethod.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EncryptionMethod.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata EncryptionMethod. + */ +public interface EncryptionMethod extends org.opensaml.xml.encryption.EncryptionMethod, SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "EncryptionMethod"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Endpoint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Endpoint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Endpoint.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** + * SAML 2.0 Metadata Endpoint data type interface + */ +public interface Endpoint extends SAMLObject, ElementExtensibleXMLObject, AttributeExtensibleXMLObject{ + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Endpoint"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "EndpointType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** "Binding" attribute name */ + public final static String BINDING_ATTRIB_NAME = "Binding"; + + /** "Location" attribute name */ + public final static String LOCATION_ATTRIB_NAME = "Location"; + + /** "ResponseLocation" attribute name */ + public final static String RESPONSE_LOCATION_ATTRIB_NAME = "ResponseLocation"; + + /** + * Gets the URI identifier for the binding supported by this Endpoint. + * + * @return the URI identifier for the binding supported by this Endpoint + */ + public String getBinding(); + + /** + * Sets the URI identifier for the binding supported by this Endpoint. + * + * @param binding the URI identifier for the binding supported by this Endpoint + */ + public void setBinding(String binding); + + /** + * Gets the URI, usually a URL, for the location of this Endpoint. + * + * @return the location of this Endpoint + */ + public String getLocation(); + + /** + * Sets the URI, usually a URL, for the location of this Endpoint. + * + * @param location the location of this Endpoint + */ + public void setLocation(String location); + + /** + * Gets the URI, usually a URL, responses should be sent to this for this Endpoint. + * + * @return the URI responses should be sent to this for this Endpoint + */ + public String getResponseLocation(); + + /** + * Sets the URI, usually a URL, responses should be sent to this for this Endpoint. + * + * @param location the URI responses should be sent to this for this Endpoint + */ + public void setResponseLocation(String location); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EntitiesDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EntitiesDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EntitiesDescriptor.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,115 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; + +/** + * SAML 2.0 Metadata EntitiesDescriptor. + * + * @author Chad La Joie + */ +public interface EntitiesDescriptor extends SignableSAMLObject, TimeBoundSAMLObject, CacheableSAMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "EntitiesDescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "EntitiesDescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Element QName, no prefix */ + public final static QName ELEMENT_QNAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME); + + /** "ID" attribute name */ + public final static String ID_ATTRIB_NAME = "ID"; + + /** "Name" attribute name */ + public final static String NAME_ATTRIB_NAME = "Name"; + + /** + * Gets the name of this entity group. + * + * @return the name of this entity group + */ + public String getName(); + + /** + * Sets the name of this entity group. + * + * @param name the name of this entity group + */ + public void setName(String name); + + /** + * Gets the ID of this entity group. + * + * @return the id of this entity group + */ + public String getID(); + + /** + * Sets the ID of this entity group. + * + * @param newID the ID of this entity group + */ + public void setID(String newID); + + /** + * Gets the Extensions child of this object. + * + * @return the Extensions child of this object + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions child of this object. + * + * @param extensions the Extensions child of this object + * + * @throws IllegalArgumentException thrown if the given extensions Object is already a child of another SAMLObject + */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException; + + /** + * Gets a list of child {@link EntitiesDescriptor}s. + * + * @return list of descriptors + */ + public List getEntitiesDescriptors(); + + /** + * Gets a list of child {@link EntityDescriptor}s. + * + * @return list of child descriptors + */ + public List getEntityDescriptors(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EntityDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EntityDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/EntityDescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,209 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * SAML 2.0 Metadata EntityDescriptor + */ +public interface EntityDescriptor extends SignableSAMLObject, TimeBoundSAMLObject, CacheableSAMLObject, + AttributeExtensibleXMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "EntityDescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "EntityDescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Element QName, no prefix */ + public final static QName ELEMENT_QNAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME); + + /** "ID" attribute name */ + public final static String ID_ATTRIB_NAME = "ID"; + + /** "Name" attribute name */ + public final static String ENTITY_ID_ATTRIB_NAME = "entityID"; + + /** + * Gets the entity ID for this entity descriptor. + * + * @return the entity ID for this entity descriptor + */ + public String getEntityID(); + + /** + * Sets the entity ID for this entity descriptor. + * + * @param id the entity ID for this entity descriptor + */ + public void setEntityID(String id); + + /** + * Gets the ID for this entity descriptor. + * + * @return the ID for this entity descriptor + */ + public String getID(); + + /** + * Sets the ID for this entity descriptor. + * + * @param newID the ID for this entity descriptor + */ + public void setID(String newID); + + /** + * Gets the Extensions child of this object. + * + * @return the Extensions child of this object + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions child of this object. + * + * @param extensions the Extensions child of this object + * + * @throws IllegalArgumentException thrown if the given extensions Object is already a child of another SAMLObject + */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException; + + /** + * Gets all the role descriptors for this entity descriptor. + * + * @return the role descriptors for this entity descriptor + */ + public List getRoleDescriptors(); + + /** + * Gets all the role descriptors for this entity descriptor that match the supplied QName parameter. + * + * @param typeOrName the name of the role + * + * @return the role descriptors for this entity descriptor + */ + public List getRoleDescriptors(QName typeOrName); + + /** + * Gets all the role descriptors for this entity that support the given protocol. + * + * @param typeOrName the name of the role + * @param supportedProtocol the supported protocol + * + * @return the list of role descriptors that support the given protocol + */ + public List getRoleDescriptors(QName typeOrName, String supportedProtocol); + + /** + * Gets the first {@link IDPSSODescriptor} role descriptor for this entity that supports the given protocol. + * + * @return the {@link IDPSSODescriptor} role descriptor + */ + public IDPSSODescriptor getIDPSSODescriptor(String supportedProtocol); + + /** + * Gets the first {@link SPSSODescriptor} role descriptor for this entity that supports the given protocol. + * + * @return the {@link SPSSODescriptor} role descriptor + */ + public SPSSODescriptor getSPSSODescriptor(String supportedProtocol); + + /** + * Gets the first {@link AuthnAuthorityDescriptor} role descriptor for this entity that supports the given protocol. + * + * @return the {@link AuthnAuthorityDescriptor} role descriptor + */ + public AuthnAuthorityDescriptor getAuthnAuthorityDescriptor(String supportedProtocol); + + /** + * Gets the first {@link AttributeAuthorityDescriptor} role descriptor for this entity that supports the given protocol. + * + * @return the {@link AttributeAuthorityDescriptor} role descriptor + */ + public AttributeAuthorityDescriptor getAttributeAuthorityDescriptor(String supportedProtocol); + + /** + * Gets the first {@link PDPDescriptor} role descriptor for this entity that supports the given protocol. + * + * @return the {@link PDPDescriptor} role descriptor + */ + public PDPDescriptor getPDPDescriptor(String supportedProtocol); + + /** + * Gets the affiliation descriptor for this entity. + * + * @return the affiliation descriptor for this entity + */ + public AffiliationDescriptor getAffiliationDescriptor(); + + /** + * Sets the affiliation descriptor for this entity. + * + * @param descriptor the affiliation descriptor for this entity + * + * @throws IllegalArgumentException thrown if the descriptor is owned by another entity or if this entity already + * has one or more role descriptors associated with it + */ + public void setAffiliationDescriptor(AffiliationDescriptor descriptor) throws IllegalArgumentException; + + /** + * Gets the organization for this entity. + * + * @return the organization for this entity + */ + public Organization getOrganization(); + + /** + * Sets the organization for this entity. + * + * @param organization the organization for this entity + * + * @throws IllegalArgumentException thrown if this organization belongs to another entity + */ + public void setOrganization(Organization organization) throws IllegalArgumentException; + + /** + * Get the contact people for this entity. + * + * @return the contact people for this entity + */ + public List getContactPersons(); + + /** + * Gets the additional metadata locations for this entity. + * + * @return the additional metadata locations for this entity + */ + public List getAdditionalMetadataLocations(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/GivenName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/GivenName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/GivenName.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata GivenName + */ +public interface GivenName extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "GivenName"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the name. + * + * @return the name + */ + public String getName(); + + /** + * Sets the name. + * + * @param newName the name + */ + public void setName(String newName); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/IDPSSODescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/IDPSSODescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/IDPSSODescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,113 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Metadata IDPSSODescriptorType + */ +public interface IDPSSODescriptor extends SSODescriptor { + + /** Local name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "IDPSSODescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "IDPSSODescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** "WantAuthnRequestSigned" attribute name */ + public final static String WANT_AUTHN_REQ_SIGNED_ATTRIB_NAME = "WantAuthnRequestsSigned"; + + /** + * Checks if the IDP SSO service wants authentication requests signed. + * + * @return true is signing is desired, false if not + */ + public Boolean getWantAuthnRequestsSigned(); + + /** + * Checks if the IDP SSO service wants authentication requests signed. + * + * @return true is signing is desired, false if not + */ + public XSBooleanValue getWantAuthnRequestsSignedXSBoolean(); + + /** + * Sets whether the IDP SSO service wants authentication requests signed. Boolean values will be marshalled to + * either "true" or "false". + * + * @param newWantSigned true if request should be signed, false if not + */ + public void setWantAuthnRequestsSigned(Boolean newWantSigned); + + /** + * Sets whether the IDP SSO service wants authentication requests signed. + * + * @param newWantSigned true if request should be signed, false if not + */ + public void setWantAuthnRequestsSigned(XSBooleanValue newWantSigned); + + /** + * Gets the list of single sign on services for this IDP. + * + * @return list of single sign on services + */ + public List getSingleSignOnServices(); + + /** + * Gets the list of NameID mapping services for this service. + * + * @return the list of NameID mapping services for this service + */ + public List getNameIDMappingServices(); + + /** + * Gets the list of assertion ID request services. + * + * @return assertion ID request services + */ + public List getAssertionIDRequestServices(); + + /** + * Gets the list of attribute profiles supported by this IdP. + * + * @return attribute profiles supported by this IdP + */ + public List getAttributeProfiles(); + + /** + * Gets the list of attributes supported by this IdP. + * + * @return attributes supported by this IdP + */ + public List getAttributes(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/IndexedEndpoint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/IndexedEndpoint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/IndexedEndpoint.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,92 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Metadata IndexedEndpoint. + */ +public interface IndexedEndpoint extends Endpoint { + + /** Local name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "IndexedEndpoint"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "IndexedEndpointType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** index attribute name. */ + public static final String INDEX_ATTRIB_NAME = "index"; + + /** isDeault attribute name. */ + public static final String IS_DEFAULT_ATTRIB_NAME = "isDefault"; + + /** + * Gets the index of the endpoint. + * + * @return index of the endpoint + */ + public Integer getIndex(); + + /** + * Sets the index of the endpoint. + * + * @param index index of the endpoint + */ + public void setIndex(Integer index); + + /** + * Gets whether this is the default endpoint in a list. + * + * @return whether this is the default endpoint in a list + */ + public Boolean isDefault(); + + /** + * Gets whether this is the default endpoint in a list. + * + * @return whether this is the default endpoint in a list + */ + public XSBooleanValue isDefaultXSBoolean(); + + /** + * Sets whether this is the default endpoint in a list. Boolean values will be marshalled to either "true" or + * "false". + * + * @param newIsDefault whether this is the default endpoint in a list + */ + public void setIsDefault(Boolean newIsDefault); + + /** + * Sets whether this is the default endpoint in a list. + * + * @param newIsDefault whether this is the default endpoint in a list + */ + public void setIsDefault(XSBooleanValue newIsDefault); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/KeyDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/KeyDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/KeyDescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.signature.KeyInfo; + +public interface KeyDescriptor extends SAMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "KeyDescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "KeyDescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** "use" attribute's local name */ + public final static String USE_ATTRIB_NAME = "use"; + + /** + * Gets the use of this key. + * + * @return the use of this key + */ + public UsageType getUse(); + + /** + * Sets the use of this key. + * + * @param newType the use of this key + */ + public void setUse(UsageType newType); + + /** + * Gets information about the key, including the key itself. + * + * @return information about the key, including the key itself + */ + public KeyInfo getKeyInfo(); + + /** + * Sets information about the key, including the key itself. + * + * @param newKeyInfo information about the key, including the key itself + */ + public void setKeyInfo(KeyInfo newKeyInfo); + + /** + * Gets the encryption methods that are supported by the entity. + * + * @return the encryption methods that are supported by the entity + */ + public List getEncryptionMethods(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/LocalizedString.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/LocalizedString.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/LocalizedString.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,113 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +/** + * Localized String with the language associated with it. + */ +public class LocalizedString { + + /** Localized string. */ + private String localizedString; + + /** Language of the localized string. */ + private String language; + + /** Constructor. */ + public LocalizedString() { + + } + + /** + * Constructor. + * + * @param localString the localized string + * @param language the language of the string + */ + public LocalizedString(String localString, String language) { + localizedString = localString; + this.language = language; + } + + /** + * Gets the localized string. + * + * @return the localized string + */ + public String getLocalString() { + return localizedString; + } + + /** + * Sets the localized string. + * + * @param newString the localized string + */ + public void setLocalizedString(String newString) { + localizedString = newString; + } + + /** + * Gets the language of the string. + * + * @return the language of the string + */ + public String getLanguage() { + return language; + } + + /** + * Sets the language of the string. + * + * @param newLanguage the language of the string + */ + public void setLanguage(String newLanguage) { + language = newLanguage; + } + + /** + * {@inheritDoc} + */ + public int hashCode() { + int hash = 1; + hash = hash * 31 + language.hashCode(); + hash = hash * 31 + localizedString.hashCode(); + return hash; + } + + /** + * Determines if two LocalizedStrings are equal, that is, if both thier localized string and language have + * case-sentivite equality. + * + * @param obj the object this object is compared with + * + * @return true if the objects are equal, false if not + */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (obj instanceof LocalizedString) { + LocalizedString otherLString = (LocalizedString) obj; + return localizedString.equals(otherLString.getLocalString()) && language.equals(otherLString.getLanguage()); + } + + return false; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ManageNameIDService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ManageNameIDService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ManageNameIDService.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata ManageNameIDService + */ +public interface ManageNameIDService extends Endpoint { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "ManageNameIDService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/NameIDFormat.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/NameIDFormat.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/NameIDFormat.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata NameIDFormat + */ +public interface NameIDFormat extends SAMLObject { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "NameIDFormat"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "NameIDFormatType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the format of the NameID. + * + * @return the format of the NameID + */ + public String getFormat(); + + /** + * Sets the format of the NameID. + * + * @param format the format of the NameID + */ + public void setFormat(String format); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/NameIDMappingService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/NameIDMappingService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/NameIDMappingService.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata NameIDMappingService + */ +public interface NameIDMappingService extends Endpoint { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME="NameIDMappingService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Organization.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Organization.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/Organization.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * SAML 2.0 Metadata Organization + */ +public interface Organization extends SAMLObject, AttributeExtensibleXMLObject{ + + /** Local name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "Organization"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "OrganizationType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the Extensions child of this object. + * + * @return the Extensions child of this object + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions child of this object. + * + * @param extensions the Extensions child of this object + * + * @throws IllegalArgumentException thrown if the given extensions Object is already a child of another SAMLObject + */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException; + + /** + * Gets the list of names for this organization. + * + * @return names for this organization + */ + public List getOrganizationNames(); + + /** + * Gets a list of diaplay names for this organization. + * + * @return list of names + */ + public List getDisplayNames(); + + /** + * Gets a list of URLs for this organization. + * + * @return list of URLs for this organization + */ + public List getURLs(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationDisplayName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationDisplayName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationDisplayName.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata OrganizationDisplayName + */ +public interface OrganizationDisplayName extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "OrganizationDisplayName"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "localizedNameType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Language attribute name */ + public final static String LANG_ATTRIB_NAME = "lang"; + + /** + * Gets the name of the organization. + * + * @return the name of the organization + */ + public LocalizedString getName(); + + /** + * Sets the organization name. + * + * @param newName organization name + */ + public void setName(LocalizedString newName); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationName.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata OrganizationName + */ +public interface OrganizationName extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "OrganizationName"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "localizedNameType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Language attribute name */ + public final static String LANG_ATTRIB_NAME = "lang"; + + /** + * Gets the name of the organization. + * + * @return the name of the organization + */ + public LocalizedString getName(); + + /** + * Sets the organization name. + * + * @param newName organization name + */ + public void setName(LocalizedString newName); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationURL.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationURL.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/OrganizationURL.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata OrganizationURL + */ +public interface OrganizationURL extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "OrganizationURL"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "localizedURIType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Language attribute name */ + public final static String LANG_ATTRIB_NAME = "lang"; + + /** + * Gets the URL of the organization. + * + * @return the URL of the organization + */ + public LocalizedString getURL(); + + /** + * Sets the organization URL. + * + * @param newURL organization URL + */ + public void setURL(LocalizedString newURL); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/PDPDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/PDPDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/PDPDescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata PDPDescriptor. + */ +public interface PDPDescriptor extends RoleDescriptor { + + /** Local name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "PDPDescriptor"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "PDPDescriptorType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets an list of authz services for this service. + * + * @return list of authz services for this service + */ + public List getAuthzServices(); + + /** + * Gets the list of assertion ID request services for this PDP. + * + * @return list of assertion ID request services for this PDP + */ + public List getAssertionIDRequestServices(); + + /** + * Gets the list of NameID formats this service supports. + * + * @return NameID formats this service supports + */ + public List getNameIDFormats(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/RequestedAttribute.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/RequestedAttribute.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/RequestedAttribute.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Metadata RequestedAttribute + * + */ +public interface RequestedAttribute extends Attribute { + + /** Local name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "RequestedAttribute"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "RequestedAttributeType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** "isRequired" attribute's local name */ + public final static String IS_REQUIRED_ATTRIB_NAME = "isRequired"; + + /** + * Checks to see if this requested attribute is also required. + * + * @return true if this attribute is required + */ + public Boolean isRequired(); + + /** + * Checks to see if this requested attribute is also required. + * + * @return true if this attribute is required + */ + public XSBooleanValue isRequiredXSBoolean(); + + /** + * Sets if this requested attribute is also required. Boolean values will be marshalled to either "true" or "false". + * + * @param newIsRequire true if this attribute is required + */ + public void setIsRequired(Boolean newIsRequire); + + /** + * Sets if this requested attribute is also required. + * + * @param newIsRequire true if this attribute is required + */ + public void setIsRequired(XSBooleanValue newIsRequire); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/RoleDescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/RoleDescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/RoleDescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,191 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.Collection; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.xml.AttributeExtensibleXMLObject; + +/** + * SAML 2.0 Metadata RoleDescriptor. + */ +public interface RoleDescriptor extends SignableSAMLObject, TimeBoundSAMLObject, CacheableSAMLObject, + AttributeExtensibleXMLObject { + + /** Element name, no namespace. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RoleDescriptor"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "RoleDescriptorType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** "ID" attribute's local name. */ + public static final String ID_ATTRIB_NAME = "ID"; + + /** "protocolEnumeration" attribute's local name. */ + public static final String PROTOCOL_ENUMERATION_ATTRIB_NAME = "protocolSupportEnumeration"; + + /** "errorURL" attribute's local name. */ + public static final String ERROR_URL_ATTRIB_NAME = "errorURL"; + + /** + * Gets the ID of this role descriptor. + * + * @return the ID of this role descriptor + */ + public String getID(); + + /** + * Sets the ID of this role descriptor. + * + * @param newID the ID of this role descriptor + */ + public void setID(String newID); + + /** + * Gets an immutable list of protocol URIs supported by this role. + * + * @return list of protocol URIs supported by this role + */ + public List getSupportedProtocols(); + + /** + * Chckes to see if the given protocol is supported by this role. + * + * @param protocol the protocol + * + * @return true if the protocol is supported, false if not + */ + public boolean isSupportedProtocol(String protocol); + + /** + * Adds a protocol to the list of supported protocols for this role. + * + * @param protocol the protocol + */ + public void addSupportedProtocol(String protocol); + + /** + * Removes a protocol to the list of supported protocols for this role. + * + * @param protocol the protocol + */ + public void removeSupportedProtocol(String protocol); + + /** + * Removes a list of protocols to the list of supported protocols for this role. + * + * @param protocols the protocol + */ + public void removeSupportedProtocols(Collection protocols); + + /** + * Removes all the supported protocols from this role. + * + */ + public void removeAllSupportedProtocols(); + + /** + * Gets the URI users should be sent to in the event of an error. + * + * @return the URI users should be sent to in the event of an error + */ + public String getErrorURL(); + + /** + * Sets the URI users should be sent to in the event of an error. + * + * @param errorURL the URI users should be sent to in the event of an error + */ + public void setErrorURL(String errorURL); + + /** + * Gets the Extensions child of this object. + * + * @return the Extensions child of this object + */ + public Extensions getExtensions(); + + /** + * Sets the Extensions child of this object. + * + * @param extensions the Extensions child of this object + * + * @throws IllegalArgumentException thrown if the given extensions Object is already a child of another SAMLObject + */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException; + + /** + * Gets the key descriptors for this role. + * + * @return the key descriptors for this role + */ + public List getKeyDescriptors(); + + /** + * Gets the organization responsible for this role. + * + * @return the organization responsible for this role + */ + public Organization getOrganization(); + + /** + * Sets the organization responsible for this role. + * + * @param organization the organization responsible for this role + * + * @throws IllegalArgumentException thrown if the given organization is owned by another element + */ + public void setOrganization(Organization organization) throws IllegalArgumentException; + + /** + * Gets an immutable list of {@link ContactPerson}s for this role. + * + * @return list of {@link ContactPerson}s for this role + */ + public List getContactPersons(); + + /** + * Gets a read-only list of endpoints for this role. + * + * @return immutable list of endpoints for this role + */ + public List getEndpoints(); + + /** + * Gets a read-only list of endpoints for this role for the given type. + * + * @param type the type of endpoints to retrieve + * + * @return immutable list of endpoints for this role + */ + public List getEndpoints(QName type); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SPSSODescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SPSSODescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SPSSODescriptor.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,153 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.support.SAML2MetadataHelper; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * SAML 2.0 Metadata SPSSODescriptorType + */ +public interface SPSSODescriptor extends SSODescriptor { + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SPSSODescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "SPSSODescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + + /** "AuthnRequestsSigned" attribute's local name */ + public final static String AUTH_REQUESTS_SIGNED_ATTRIB_NAME = "AuthnRequestsSigned"; + + /** "WantAssertionsSigned" attribute's local name */ + public final static String WANT_ASSERTIONS_SIGNED_ATTRIB_NAME = "WantAssertionsSigned"; + + /** + * Gets whether this service signs AuthN requests. + * + * @return true of this service signs requests, false if not + */ + public Boolean isAuthnRequestsSigned(); + + /** + * Gets whether this service signs AuthN requests. + * + * @return true of this service signs requests, false if not + */ + public XSBooleanValue isAuthnRequestsSignedXSBoolean(); + + /** + * Sets whether this service signs AuthN requests. Boolean values will be marshalled to either "true" or "false". + * + * @param newIsSigned true of this service signs requests, false if not + */ + public void setAuthnRequestsSigned(Boolean newIsSigned); + + /** + * Sets whether this service signs AuthN requests. + * + * @param newIsSigned true of this service signs requests, false if not + */ + public void setAuthnRequestsSigned(XSBooleanValue newIsSigned); + + /** + * Gets whether this service wants assertions signed. + * + * @return true if this service wants assertions signed, false if not + */ + public Boolean getWantAssertionsSigned(); + + /** + * Gets whether this service wants assertions signed. + * + * @return true if this service wants assertions signed, false if not + */ + public XSBooleanValue getWantAssertionsSignedXSBoolean(); + + /** + * Sets whether this service wants assertions signed. Boolean values will be marshalled to either "true" or "false". + * + * @param newWantAssestionSigned true if this service wants assertions signed, false if not + */ + public void setWantAssertionsSigned(Boolean newWantAssestionSigned); + + /** + * Sets whether this service wants assertions signed. + * + * @param newWantAssestionSigned true if this service wants assertions signed, false if not + */ + public void setWantAssertionsSigned(XSBooleanValue newWantAssestionSigned); + + /** + * Gets an list of assertion consumer service {@link Endpoint}s for this service. + * + * @return list of assertion consumer service {@link Endpoint}s for this service + */ + public List getAssertionConsumerServices(); + + /** + * Gets the default assertion consumer service. + * + *

+ * The selection algorithm used is: + *

    + *
  1. Select the first service with an explicit isDefault=true
  2. + *
  3. Select the first service with no explicit isDefault
  4. + *
  5. Select the first service
  6. + *
+ *

+ * + * @return default assertion consumer service (or null if there are no assertion consumer services defined) + */ + public AssertionConsumerService getDefaultAssertionConsumerService(); + + /** + * Gets an list of attribute consuming service descriptors for this service. + * + * @return list of attribute consuming service descriptors for this service + */ + public List getAttributeConsumingServices(); + + /** + * Gets the default attribute consuming service. + * + *

+ * The selection algorithm used is: + *

    + *
  1. Select the first service with an explicit isDefault=true
  2. + *
  3. Select the first service with no explicit isDefault
  4. + *
  5. Select the first service
  6. + *
+ *

+ * + * @return default attribute consuming service (or null if there are no attribute consuming services defined) + */ + public AttributeConsumingService getDefaultAttributeConsumingService(); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SSODescriptor.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SSODescriptor.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SSODescriptor.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,107 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.support.SAML2MetadataHelper; + + +/** + * SAML 2.0 Metadata SSODescriptor + */ +public interface SSODescriptor extends RoleDescriptor { + + /** Element name, no namespace */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SSODescriptor"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "SSODescriptorType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets a list of artifact resolution services for this service. + * + * @return list of artifact resolution services for this service + */ + public List getArtifactResolutionServices(); + + /** + * Gets the default artifact resolution service. + * + *

+ * The selection algorithm used is: + *

    + *
  1. Select the first service with an explicit isDefault=true
  2. + *
  3. Select the first service with no explicit isDefault
  4. + *
  5. Select the first service
  6. + *
+ *

+ * + * @return default artifact resolution service (or null if there are no artifact resolution services defined) + * + */ + public ArtifactResolutionService getDefaultArtifactResolutionService(); + + /** + * Gets the default artifact resolution service. + * + *

+ * The selection algorithm used is: + *

    + *
  1. Select the first service with an explicit isDefault=true
  2. + *
  3. Select the first service with no explicit isDefault
  4. + *
  5. Select the first service
  6. + *
+ *

+ * + * @return default artifact resolution service (or null if there are no artifact resolution services defined) + * + * @deprecated replacement {@link #getDefaultArtifactResolutionService()} + */ + public ArtifactResolutionService getDefaultArtificateResolutionService(); + + /** + * Gets a list of single logout services for this service. + * + * @return list of single logout services for this service + */ + public List getSingleLogoutServices(); + + /** + * Gets a list of manage NameId services for this service. + * + * @return list of manage NameId services for this service + */ + public List getManageNameIDServices(); + + /** + * Gets the list of NameID formats this service supports. + * + * @return NameID formats this service supports + */ + public List getNameIDFormats(); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ServiceDescription.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ServiceDescription.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ServiceDescription.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata ServiceDescription + */ +public interface ServiceDescription extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "ServiceDescription"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "localizedNameType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Language attribute name */ + public final static String LANG_ATTRIB_NAME = "lang"; + + /** + * Gets the description of the service. + * + * @return the description of the service + */ + public LocalizedString getDescription(); + + /** + * Sets the description of the service. + * + * @param newDescription the description of the service + */ + public void setDescription(LocalizedString newDescription); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ServiceName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ServiceName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/ServiceName.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata ServiceName + */ +public interface ServiceName extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "ServiceName"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Local name of the XSI type */ + public final static String TYPE_LOCAL_NAME = "localizedNameType"; + + /** QName of the XSI type */ + public final static QName TYPE_NAME = new QName(SAMLConstants.SAML20MD_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** Language attribute name */ + public final static String LANG_ATTRIB_NAME = "lang"; + + /** + * Gets the name of the service. + * + * @return the name of the service + */ + public LocalizedString getName(); + + /** + * Sets the service name. + * + * @param newName service name + */ + public void setName(LocalizedString newName); +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SingleLogoutService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SingleLogoutService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SingleLogoutService.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata SingleLogoutService + */ +public interface SingleLogoutService extends Endpoint { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SingleLogoutService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SingleSignOnService.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SingleSignOnService.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SingleSignOnService.java 17 Aug 2012 15:03:33 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata SingleSignOnService + */ +public interface SingleSignOnService extends Endpoint { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SingleSignOnService"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SurName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SurName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/SurName.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata SurName + */ +public interface SurName extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "SurName"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the name. + * + * @return the name + */ + public String getName(); + + /** + * Sets the name. + * + * @param newName the name + */ + public void setName(String newName); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/TelephoneNumber.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/TelephoneNumber.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/TelephoneNumber.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; + +/** + * SAML 2.0 Metadata TelephoneNumber + */ +public interface TelephoneNumber extends SAMLObject { + + /** Element local name */ + public final static String DEFAULT_ELEMENT_LOCAL_NAME = "TelephoneNumber"; + + /** Default element name */ + public final static QName DEFAULT_ELEMENT_NAME = new QName(SAMLConstants.SAML20MD_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + + /** + * Gets the telephone number. + * + * @return the telephone number + */ + public String getNumber(); + + /** + * Sets the telephone number. + * + * @param newNumber the telephone number + */ + public void setNumber(String newNumber); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/package.html 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,14 @@ + + +Interfaces for SAML 2.0 metadata specification types and elements. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationBuilder.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AdditionalMetadataLocation; + +/** + * A builder for {@link org.opensaml.saml2.metadata.impl.AdditionalMetadataLocationImpl} objects. + */ +public class AdditionalMetadataLocationBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AdditionalMetadataLocationBuilder() { + + } + + /** {@inheritDoc} */ + public AdditionalMetadataLocation buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AdditionalMetadataLocation.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AdditionalMetadataLocation buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AdditionalMetadataLocationImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.AdditionalMetadataLocation; +import org.opensaml.xml.XMLObject; + +/** + * Concreate implementation of {@link org.opensaml.saml2.metadata.AdditionalMetadataLocation} + */ +public class AdditionalMetadataLocationImpl extends AbstractSAMLObject implements AdditionalMetadataLocation { + + /** The metadata location */ + private String location; + + /** Namespace scope of the root metadata element at the location */ + private String namespace; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AdditionalMetadataLocationImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getLocationURI() { + return location; + } + + /** {@inheritDoc} */ + public void setLocationURI(String locationURI) { + location = prepareForAssignment(location, locationURI); + } + + /** {@inheritDoc} */ + public String getNamespaceURI() { + return namespace; + } + + /** {@inheritDoc} */ + public void setNamespaceURI(String namespaceURI) { + namespace = prepareForAssignment(namespace, namespaceURI); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No children for this element + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.AdditionalMetadataLocation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe marshaller for {@link org.opensaml.saml2.metadata.AdditionalMetadataLocation} objects. + */ +public class AdditionalMetadataLocationMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AdditionalMetadataLocation aml = (AdditionalMetadataLocation) samlElement; + + if (aml.getNamespaceURI() != null) { + domElement.setAttributeNS(null, AdditionalMetadataLocation.NAMESPACE_ATTRIB_NAME, aml.getNamespaceURI()); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + super.marshallElementContent(samlObject, domElement); + + AdditionalMetadataLocation aml = (AdditionalMetadataLocation) samlObject; + if (aml.getLocationURI() != null) { + domElement.appendChild(domElement.getOwnerDocument().createTextNode(aml.getLocationURI())); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AdditionalMetadataLocationUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.AdditionalMetadataLocation; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.AdditionalMetadataLocation} objects. + */ +public class AdditionalMetadataLocationUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(AdditionalMetadataLocation.NAMESPACE_ATTRIB_NAME)) { + AdditionalMetadataLocation aml = (AdditionalMetadataLocation) samlObject; + aml.setNamespaceURI(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AdditionalMetadataLocation aml = (AdditionalMetadataLocation) samlObject; + aml.setLocationURI(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberBuilder.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AffiliateMember; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AffiliateMemberImpl}s. + */ +public class AffiliateMemberBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AffiliateMemberBuilder() { + + } + + /** {@inheritDoc} */ + public AffiliateMember buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AffiliateMember.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AffiliateMember buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AffiliateMemberImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.AffiliateMember; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.AffiliateMember}. + */ +public class AffiliateMemberImpl extends AbstractSAMLObject implements AffiliateMember { + + /** ID of this member */ + private String id; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AffiliateMemberImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String newID) throws IllegalArgumentException { + if (newID != null && newID.length() > 1024) { + throw new IllegalArgumentException("Member ID can not exceed 1024 characters in length"); + } + + id = prepareForAssignment(id, newID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // No children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.AffiliateMember; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.metadata.AffiliateMember} objects. + */ +public class AffiliateMemberMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + super.marshallElementContent(samlObject, domElement); + + AffiliateMember member = (AffiliateMember) samlObject; + if (member.getID() != null) { + domElement.appendChild(domElement.getOwnerDocument().createTextNode(member.getID())); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliateMemberUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.AffiliateMember; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.AffiliateMember}s. + */ +public class AffiliateMemberUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + AffiliateMember member = (AffiliateMember) samlObject; + member.setID(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorBuilder.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AffiliationDescriptor; + +/** + * A builder for {@link org.opensaml.saml2.metadata.impl.AffiliationDescriptorImpl} objects. + */ +public class AffiliationDescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AffiliationDescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public AffiliationDescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AffiliationDescriptor.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AffiliationDescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AffiliationDescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,177 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.AffiliateMember; +import org.opensaml.saml2.metadata.AffiliationDescriptor; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.AffiliationDescriptor}. + */ +public class AffiliationDescriptorImpl extends AbstractSignableSAMLObject implements AffiliationDescriptor { + + /** ID of the owner of this affiliation */ + private String ownerID; + + /** ID attribute*/ + private String id; + + /** validUntil attribute */ + private DateTime validUntil; + + /** cacheDurection attribute */ + private Long cacheDuration; + + /** Extensions child */ + private Extensions extensions; + + /** "anyAttribute" attributes */ + private final AttributeMap unknownAttributes; + + /** Members of this affiliation */ + private final XMLObjectChildrenList members; + + /** Key descriptors for this role */ + private final XMLObjectChildrenList keyDescriptors; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AffiliationDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + members = new XMLObjectChildrenList(this); + keyDescriptors = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getOwnerID() { + return ownerID; + } + + /** {@inheritDoc} */ + public void setOwnerID(String newOwnerID) { + if (newOwnerID != null && newOwnerID.length() > 1024) { + throw new IllegalArgumentException("Owner ID can not exceed 1024 characters in length"); + } + ownerID = prepareForAssignment(ownerID, newOwnerID); + } + + public String getID() { + return id; + } + + public void setID(String newID) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, newID); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public boolean isValid() { + return validUntil.isBeforeNow(); + } + + /** {@inheritDoc} */ + public DateTime getValidUntil() { + return validUntil; + } + + /** {@inheritDoc} */ + public void setValidUntil(DateTime validUntil) { + this.validUntil = prepareForAssignment(this.validUntil, validUntil); + } + + /** {@inheritDoc} */ + public Long getCacheDuration() { + return cacheDuration; + } + + /** {@inheritDoc} */ + public void setCacheDuration(Long duration) { + cacheDuration = prepareForAssignment(cacheDuration, duration); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException { + this.extensions = prepareForAssignment(this.extensions, extensions); + } + + /** {@inheritDoc} */ + public List getMembers() { + return members; + } + + /** {@inheritDoc} */ + public List getKeyDescriptors() { + return keyDescriptors; + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID(){ + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(getSignature() != null){ + children.add(getSignature()); + } + + children.add(getExtensions()); + + children.addAll(getMembers()); + + children.addAll(getKeyDescriptors()); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.AffiliationDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AffiliationDescriptor} objects. + */ +public class AffiliationDescriptorMarshaller extends AbstractSAMLObjectMarshaller { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(AffiliationDescriptorMarshaller.class); + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AffiliationDescriptor descriptor = (AffiliationDescriptor) samlElement; + + // Set affiliationOwnerID + if (descriptor.getOwnerID() != null) { + domElement.setAttributeNS(null, AffiliationDescriptor.OWNER_ID_ATTRIB_NAME, descriptor.getOwnerID()); + } + + // Set ID + if (descriptor.getID() != null) { + domElement.setAttributeNS(null, AffiliationDescriptor.ID_ATTRIB_NAME, descriptor.getID()); + domElement.setIdAttributeNS(null, AffiliationDescriptor.ID_ATTRIB_NAME, true); + } + + // Set the validUntil attribute + if (descriptor.getValidUntil() != null) { + log.debug("Writting validUntil attribute to AffiliationDescriptor DOM element"); + String validUntilStr = Configuration.getSAMLDateFormatter().print(descriptor.getValidUntil()); + domElement.setAttributeNS(null, TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME, validUntilStr); + } + + // Set the cacheDuration attribute + if (descriptor.getCacheDuration() != null) { + log.debug("Writting cacheDuration attribute to AffiliationDescriptor DOM element"); + String cacheDuration = XMLHelper.longToDuration(descriptor.getCacheDuration()); + domElement.setAttributeNS(null, CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME, cacheDuration); + } + + Attr attribute; + for (Entry entry : descriptor.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || descriptor.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AffiliationDescriptorUnmarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.AffiliateMember; +import org.opensaml.saml2.metadata.AffiliationDescriptor; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.AffiliationDescriptor}s. + */ +public class AffiliationDescriptorUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AffiliationDescriptor descriptor = (AffiliationDescriptor) parentSAMLObject; + + if (childSAMLObject instanceof Extensions) { + descriptor.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof Signature) { + descriptor.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof AffiliateMember) { + descriptor.getMembers().add((AffiliateMember) childSAMLObject); + } else if (childSAMLObject instanceof KeyDescriptor) { + descriptor.getKeyDescriptors().add((KeyDescriptor) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AffiliationDescriptor descriptor = (AffiliationDescriptor) samlObject; + + if (attribute.getLocalName().equals(AffiliationDescriptor.OWNER_ID_ATTRIB_NAME)) { + descriptor.setOwnerID(attribute.getValue()); + } else if (attribute.getLocalName().equals(AffiliationDescriptor.ID_ATTRIB_NAME)) { + descriptor.setID(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + descriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) { + descriptor.setCacheDuration(XMLHelper.durationToLong(attribute.getValue())); + } else { + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + descriptor.getUnknownAttributes().registerID(attribQName); + } + descriptor.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceBuilder.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.ArtifactResolutionService; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.ArtifactResolutionServiceImpl} + */ +public class ArtifactResolutionServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ArtifactResolutionServiceBuilder() { + + } + + /** {@inheritDoc} */ + public ArtifactResolutionService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, ArtifactResolutionService.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public ArtifactResolutionService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ArtifactResolutionServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceImpl.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.ArtifactResolutionService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.ArtifactResolutionService} + */ +public class ArtifactResolutionServiceImpl extends IndexedEndpointImpl implements ArtifactResolutionService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected ArtifactResolutionServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceMarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.ArtifactResolutionService} objects. + */ +public class ArtifactResolutionServiceMarshaller extends IndexedEndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ArtifactResolutionServiceUnmarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.ArtifactResolutionService} objects. + */ +public class ArtifactResolutionServiceUnmarshaller extends IndexedEndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceBuilder.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AssertionConsumerService; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AssertionConsumerServiceImpl} objects. + */ +public class AssertionConsumerServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AssertionConsumerServiceBuilder() { + + } + + /** {@inheritDoc} */ + public AssertionConsumerService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AssertionConsumerService.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionConsumerService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionConsumerServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AssertionConsumerService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.AssertionConsumerService} + */ +public class AssertionConsumerServiceImpl extends IndexedEndpointImpl implements AssertionConsumerService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AssertionConsumerServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceMarshaller.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AssertionConsumerService} objects. + */ +public class AssertionConsumerServiceMarshaller extends IndexedEndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionConsumerServiceUnmarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.AssertionConsumerService} objects. + */ +public class AssertionConsumerServiceUnmarshaller extends IndexedEndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceBuilder.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AssertionIDRequestService; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AssertionIDRequestServiceImpl} + */ +public class AssertionIDRequestServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AssertionIDRequestServiceBuilder() { + + } + + /** {@inheritDoc} */ + public AssertionIDRequestService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AssertionIDRequestService.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AssertionIDRequestService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AssertionIDRequestServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AssertionIDRequestService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.AssertionIDRequestService} + */ +public class AssertionIDRequestServiceImpl extends EndpointImpl implements AssertionIDRequestService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AssertionIDRequestServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceMarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AssertionIDRequestService}s. + */ +public class AssertionIDRequestServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AssertionIDRequestServiceUnmarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.AssertionIDRequestService}s. + */ +public class AssertionIDRequestServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorBuilder.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AttributeAuthorityDescriptorImpl}s. + */ +public class AttributeAuthorityDescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeAuthorityDescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeAuthorityDescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AttributeAuthorityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeAuthorityDescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeAuthorityDescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor; +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.saml2.metadata.AttributeService; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.metadata.AttributeAuthorityDescriptor}. + */ +public class AttributeAuthorityDescriptorImpl extends RoleDescriptorImpl implements AttributeAuthorityDescriptor { + + /** Attribte query endpoints. */ + private final XMLObjectChildrenList attributeServices; + + /** Assertion request endpoints. */ + private final XMLObjectChildrenList assertionIDRequestServices; + + /** Supported NameID formats. */ + private final XMLObjectChildrenList nameFormats; + + /** Supported attribute profiles. */ + private final XMLObjectChildrenList attributeProfiles; + + /** Supported attribute. */ + private final XMLObjectChildrenList attributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeAuthorityDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeServices = new XMLObjectChildrenList(this); + assertionIDRequestServices = new XMLObjectChildrenList(this); + attributeProfiles = new XMLObjectChildrenList(this); + nameFormats = new XMLObjectChildrenList(this); + attributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributeServices() { + return attributeServices; + } + + /** {@inheritDoc} */ + public List getAssertionIDRequestServices() { + return assertionIDRequestServices; + } + + /** {@inheritDoc} */ + public List getNameIDFormats() { + return nameFormats; + } + + /** {@inheritDoc} */ + public List getAttributeProfiles() { + return attributeProfiles; + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } + + /** {@inheritDoc} */ + public List getEndpoints() { + List endpoints = new ArrayList(); + endpoints.addAll(attributeServices); + endpoints.addAll(assertionIDRequestServices); + return Collections.unmodifiableList(endpoints); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + if(type.equals(AttributeService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(attributeServices)); + }else if(type.equals(AssertionIDRequestService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(assertionIDRequestServices)); + } + + return null; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(attributeServices); + children.addAll(assertionIDRequestServices); + children.addAll(nameFormats); + children.addAll(attributeProfiles); + children.addAll(attributes); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AttributeAuthorityDescriptor}s. + */ +public class AttributeAuthorityDescriptorMarshaller extends RoleDescriptorMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeAuthorityDescriptorUnmarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor; +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.saml2.metadata.AttributeService; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread safe unmarshaller for {@link org.opensaml.saml2.metadata.AttributeAuthorityDescriptor}s. + */ +public class AttributeAuthorityDescriptorUnmarshaller extends RoleDescriptorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentElement, XMLObject childElement) throws UnmarshallingException { + AttributeAuthorityDescriptor descriptor = (AttributeAuthorityDescriptor) parentElement; + + if (childElement instanceof AttributeService) { + descriptor.getAttributeServices().add((AttributeService) childElement); + } else if (childElement instanceof AssertionIDRequestService) { + descriptor.getAssertionIDRequestServices().add((AssertionIDRequestService) childElement); + } else if (childElement instanceof NameIDFormat) { + descriptor.getNameIDFormats().add((NameIDFormat) childElement); + } else if (childElement instanceof AttributeProfile) { + descriptor.getAttributeProfiles().add((AttributeProfile) childElement); + } else if (childElement instanceof Attribute) { + descriptor.getAttributes().add((Attribute) childElement); + } else { + super.processChildElement(parentElement, childElement); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceBuilder.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AttributeConsumingService; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.AttributeConsumingServiceImpl}. + */ +public class AttributeConsumingServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeConsumingServiceBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeConsumingService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AttributeConsumingService.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeConsumingService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeConsumingServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,137 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.ServiceDescription; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.AttributeConsumingService}. + */ +public class AttributeConsumingServiceImpl extends AbstractSAMLObject implements AttributeConsumingService { + + /** Index of this service */ + private int index; + + /** isDefault attribute of this service */ + private XSBooleanValue isDefault; + + /** ServiceName children */ + private final XMLObjectChildrenList serviceNames; + + /** ServiceDescription children */ + private final XMLObjectChildrenList serviceDescriptions; + + /** RequestedAttribute children */ + private final XMLObjectChildrenList requestAttributes; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AttributeConsumingServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + serviceNames = new XMLObjectChildrenList(this); + serviceDescriptions = new XMLObjectChildrenList(this); + requestAttributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public int getIndex() { + return index; + } + + /** {@inheritDoc} */ + public void setIndex(int index) { + if (this.index != index) { + releaseThisandParentDOM(); + this.index = index; + } + } + + /** {@inheritDoc} */ + public Boolean isDefault(){ + if(isDefault != null){ + return isDefault.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isDefaultXSBoolean() { + return isDefault; + } + + /** {@inheritDoc} */ + public void setIsDefault(Boolean newIsDefault){ + if(newIsDefault != null){ + isDefault = prepareForAssignment(isDefault, new XSBooleanValue(newIsDefault, false)); + }else{ + isDefault = prepareForAssignment(isDefault, null); + } + } + + /** {@inheritDoc} */ + public void setIsDefault(XSBooleanValue newIsDefault) { + isDefault = prepareForAssignment(isDefault, newIsDefault); + } + + /** {@inheritDoc} */ + public List getNames() { + return serviceNames; + } + + /** {@inheritDoc} */ + public List getDescriptions() { + return serviceDescriptions; + } + + /** {@inheritDoc} */ + public List getRequestAttributes() { + return requestAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(serviceNames); + children.addAll(serviceDescriptions); + children.addAll(requestAttributes); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AttributeConsumingService} objects. + */ +public class AttributeConsumingServiceMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + AttributeConsumingService service = (AttributeConsumingService) samlObject; + + domElement.setAttributeNS(null, AttributeConsumingService.INDEX_ATTRIB_NAME, Integer.toString(service + .getIndex())); + + if (service.isDefaultXSBoolean() != null) { + domElement.setAttributeNS(null, AttributeConsumingService.IS_DEFAULT_ATTRIB_NAME, service + .isDefaultXSBoolean().toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeConsumingServiceUnmarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.ServiceDescription; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.AttributeConsumingService} objects. + */ +public class AttributeConsumingServiceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AttributeConsumingService service = (AttributeConsumingService) parentSAMLObject; + + if (childSAMLObject instanceof ServiceName) { + service.getNames().add((ServiceName) childSAMLObject); + } else if (childSAMLObject instanceof ServiceDescription) { + service.getDescriptions().add((ServiceDescription) childSAMLObject); + } else if (childSAMLObject instanceof RequestedAttribute) { + service.getRequestAttributes().add((RequestedAttribute) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + AttributeConsumingService service = (AttributeConsumingService) samlObject; + + if (attribute.getLocalName().equals(AttributeConsumingService.INDEX_ATTRIB_NAME)) { + service.setIndex(Integer.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(AttributeConsumingService.IS_DEFAULT_ATTRIB_NAME)) { + service.setIsDefault(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileBuilder.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AttributeProfile; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AttributeProfileImpl}s + */ +public class AttributeProfileBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeProfileBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeProfile buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AttributeProfile.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeProfile buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeProfileImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileImpl.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.xml.XMLObject; + +/** + * A concrete implementation of {@link org.opensaml.saml2.metadata.AttributeProfile} + */ +public class AttributeProfileImpl extends AbstractSAMLObject implements AttributeProfile { + + /** Profile URI */ + private String profileURI; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AttributeProfileImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getProfileURI() { + return profileURI; + } + + /** {@inheritDoc} */ + public void setProfileURI(String profileURI) { + this.profileURI = prepareForAssignment(this.profileURI, profileURI); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; // No Children + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AttributeProfile} objects. + */ +public class AttributeProfileMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + AttributeProfile profile = (AttributeProfile) samlObject; + if (profile.getProfileURI() != null) { + XMLHelper.appendTextContent(domElement, profile.getProfileURI()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeProfileUnmarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.xml.XMLObject; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.AttributeProfile} objects. + */ +public class AttributeProfileUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + ((AttributeProfile) samlObject).setProfileURI(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceBuilder.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AttributeService; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AttributeServiceImpl}. + */ +public class AttributeServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AttributeServiceBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AttributeService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AttributeService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AttributeService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.AttributeService}. + */ +public class AttributeServiceImpl extends EndpointImpl implements AttributeService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AttributeServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceMarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AttributeService} objects. + */ +public class AttributeServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AttributeServiceUnmarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.AttributeService} objects. + */ +public class AttributeServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorBuilder.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor; + +/** + * A builder for {@link org.opensaml.saml2.metadata.impl.AuthnAuthorityDescriptorImpl} objects. + */ +public class AuthnAuthorityDescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthnAuthorityDescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnAuthorityDescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AuthnAuthorityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnAuthorityDescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnAuthorityDescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,107 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor; +import org.opensaml.saml2.metadata.AuthnQueryService; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concreate implementation of {@link org.opensaml.saml2.metadata.AuthnAuthorityDescriptor} + */ +public class AuthnAuthorityDescriptorImpl extends RoleDescriptorImpl implements AuthnAuthorityDescriptor { + + /** AuthnQueryService endpoints. */ + private final XMLObjectChildrenList authnQueryServices; + + /** AuthnQueryService endpoints. */ + private final XMLObjectChildrenList assertionIDRequestServices; + + /** NameID formats supported by this descriptor. */ + private final XMLObjectChildrenList nameIDFormats; + + /** + * Constructor . + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnAuthorityDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + authnQueryServices = new XMLObjectChildrenList(this); + assertionIDRequestServices = new XMLObjectChildrenList(this); + nameIDFormats = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAuthnQueryServices() { + return authnQueryServices; + } + + /** {@inheritDoc} */ + public List getAssertionIDRequestServices() { + return assertionIDRequestServices; + } + + /** {@inheritDoc} */ + public List getNameIDFormats() { + return nameIDFormats; + } + + /** {@inheritDoc} */ + public List getEndpoints() { + List endpoints = new ArrayList(); + endpoints.addAll(authnQueryServices); + endpoints.addAll(assertionIDRequestServices); + return Collections.unmodifiableList(endpoints); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + if(type.equals(AuthnQueryService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(authnQueryServices)); + }else if(type.equals(AssertionIDRequestService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(assertionIDRequestServices)); + } + + return null; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(authnQueryServices); + children.addAll(assertionIDRequestServices); + children.addAll(nameIDFormats); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AuthnAuthorityDescriptor} objects. + */ +public class AuthnAuthorityDescriptorMarshaller extends RoleDescriptorMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnAuthorityDescriptorUnmarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor; +import org.opensaml.saml2.metadata.AuthnQueryService; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.AuthnAuthorityDescriptor} objects. + */ +public class AuthnAuthorityDescriptorUnmarshaller extends RoleDescriptorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentElement, XMLObject childElement) throws UnmarshallingException { + AuthnAuthorityDescriptor descriptor = (AuthnAuthorityDescriptor) parentElement; + + if (childElement instanceof AuthnQueryService) { + descriptor.getAuthnQueryServices().add((AuthnQueryService) childElement); + } else if (childElement instanceof AssertionIDRequestService) { + descriptor.getAssertionIDRequestServices().add((AssertionIDRequestService) childElement); + } else if (childElement instanceof NameIDFormat) { + descriptor.getNameIDFormats().add((NameIDFormat) childElement); + } else { + super.processChildElement(parentElement, childElement); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceBuilder.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AuthnQueryService; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AuthnQueryServiceImpl}. + */ +public class AuthnQueryServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthnQueryServiceBuilder() { + + } + + /** {@inheritDoc} */ + public AuthnQueryService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AuthnQueryService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AuthnQueryService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnQueryServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceImpl.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AuthnQueryService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.AuthnQueryService} + */ +public class AuthnQueryServiceImpl extends EndpointImpl implements AuthnQueryService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AuthnQueryServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceMarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AuthnQueryService} objects. + */ +public class AuthnQueryServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthnQueryServiceUnmarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.AuthnQueryService} objects. + */ +public class AuthnQueryServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceBuilder.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AuthzService; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.AuthzServiceImpl}. + */ +public class AuthzServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public AuthzServiceBuilder() { + + } + + /** {@inheritDoc} */ + public AuthzService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, AuthzService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public AuthzService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthzServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AuthzService; + +/** + * Concrete implmentation of {@link org.opensaml.saml2.metadata.AuthzService}. + */ +public class AuthzServiceImpl extends EndpointImpl implements AuthzService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected AuthzServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceMarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.AuthzService} objects. + */ +public class AuthzServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/AuthzServiceUnmarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.AuthzService} objects. + */ +public class AuthzServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyBuilder.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.Company; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.CompanyImpl} + */ +public class CompanyBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public CompanyBuilder() { + + } + + /** {@inheritDoc} */ + public Company buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, Company.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public Company buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new CompanyImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.Company; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.Company}. + */ +public class CompanyImpl extends AbstractSAMLObject implements Company { + + /** Company name */ + private String companyName; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected CompanyImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getName() { + return companyName; + } + + /** {@inheritDoc} */ + public void setName(String newName) { + companyName = prepareForAssignment(companyName, newName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.Company; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.Company} objects. + */ +public class CompanyMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Company company = (Company) samlObject; + + if (company.getName() != null) { + XMLHelper.appendTextContent(domElement, company.getName()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/CompanyUnmarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.Company; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.Company} objects. + */ +public class CompanyUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Company company = (Company) samlObject; + + company.setName(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonBuilder.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.ContactPerson; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.ContactPersonImpl} + */ +public class ContactPersonBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ContactPersonBuilder() { + + } + + /** {@inheritDoc} */ + public ContactPerson buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, ContactPerson.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public ContactPerson buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ContactPersonImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,163 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.Company; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.ContactPersonTypeEnumeration; +import org.opensaml.saml2.metadata.EmailAddress; +import org.opensaml.saml2.metadata.GivenName; +import org.opensaml.saml2.metadata.SurName; +import org.opensaml.saml2.metadata.TelephoneNumber; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.ContactPerson} + */ +public class ContactPersonImpl extends AbstractSAMLObject implements ContactPerson { + + /** Contact person type */ + private ContactPersonTypeEnumeration type; + + /** Extensions child object */ + private Extensions extensions; + + /** Company child element */ + private Company company; + + /** GivenName child objectobject */ + private GivenName givenName; + + /** SurName child object */ + private SurName surName; + + /** "anyAttribute" attributes */ + private final AttributeMap unknownAttributes; + + /** Child email address */ + private final XMLObjectChildrenList emailAddresses; + + /** Child telephone numbers */ + private final XMLObjectChildrenList telephoneNumbers; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected ContactPersonImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + emailAddresses = new XMLObjectChildrenList(this); + telephoneNumbers = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public ContactPersonTypeEnumeration getType() { + return type; + } + + /** {@inheritDoc} */ + public void setType(ContactPersonTypeEnumeration type) { + this.type = prepareForAssignment(this.type, type); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException { + this.extensions = prepareForAssignment(this.extensions, extensions); + } + + /** {@inheritDoc} */ + public Company getCompany() { + return company; + } + + /** {@inheritDoc} */ + public void setCompany(Company company) { + this.company = prepareForAssignment(this.company, company); + } + + /** {@inheritDoc} */ + public GivenName getGivenName() { + return givenName; + } + + /** {@inheritDoc} */ + public void setGivenName(GivenName name) { + givenName = prepareForAssignment(givenName, name); + } + + /** {@inheritDoc} */ + public SurName getSurName() { + return surName; + } + + /** {@inheritDoc} */ + public void setSurName(SurName name) { + surName = prepareForAssignment(surName, name); + } + + /** {@inheritDoc} */ + public List getEmailAddresses() { + return emailAddresses; + } + + /** {@inheritDoc} */ + public List getTelephoneNumbers() { + return telephoneNumbers; + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(extensions); + children.add(company); + children.add(givenName); + children.add(surName); + children.addAll(emailAddresses); + children.addAll(telephoneNumbers); + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonMarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe marshaller for {@link org.opensaml.saml2.metadata.ContactPerson} objects. + */ +public class ContactPersonMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + ContactPerson person = (ContactPerson) samlObject; + + if (person.getType() != null) { + domElement.setAttributeNS(null, ContactPerson.CONTACT_TYPE_ATTRIB_NAME, person.getType().toString()); + } + + Attr attribute; + for (Entry entry : person.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || person.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ContactPersonUnmarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.Company; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.ContactPersonTypeEnumeration; +import org.opensaml.saml2.metadata.EmailAddress; +import org.opensaml.saml2.metadata.GivenName; +import org.opensaml.saml2.metadata.SurName; +import org.opensaml.saml2.metadata.TelephoneNumber; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.ContactPerson} objects. + */ +public class ContactPersonUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + ContactPerson person = (ContactPerson) parentSAMLObject; + + if (childSAMLObject instanceof Extensions) { + person.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof Company) { + person.setCompany((Company) childSAMLObject); + } else if (childSAMLObject instanceof GivenName) { + person.setGivenName((GivenName) childSAMLObject); + } else if (childSAMLObject instanceof SurName) { + person.setSurName((SurName) childSAMLObject); + } else if (childSAMLObject instanceof EmailAddress) { + person.getEmailAddresses().add((EmailAddress) childSAMLObject); + } else if (childSAMLObject instanceof TelephoneNumber) { + person.getTelephoneNumbers().add((TelephoneNumber) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + ContactPerson person = (ContactPerson) samlObject; + + if (attribute.getLocalName().equals(ContactPerson.CONTACT_TYPE_ATTRIB_NAME)) { + if (ContactPersonTypeEnumeration.TECHNICAL.toString().equals(attribute.getValue())) { + person.setType(ContactPersonTypeEnumeration.TECHNICAL); + } else if (ContactPersonTypeEnumeration.SUPPORT.toString().equals(attribute.getValue())) { + person.setType(ContactPersonTypeEnumeration.SUPPORT); + } else if (ContactPersonTypeEnumeration.ADMINISTRATIVE.toString().equals(attribute.getValue())) { + person.setType(ContactPersonTypeEnumeration.ADMINISTRATIVE); + } else if (ContactPersonTypeEnumeration.BILLING.toString().equals(attribute.getValue())) { + person.setType(ContactPersonTypeEnumeration.BILLING); + } else if (ContactPersonTypeEnumeration.OTHER.toString().equals(attribute.getValue())) { + person.setType(ContactPersonTypeEnumeration.OTHER); + } else { + super.processAttribute(samlObject, attribute); + } + } else { + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + person.getUnknownAttributes().registerID(attribQName); + } + person.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressBuilder.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.EmailAddress; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.EmailAddressImpl} + */ +public class EmailAddressBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public EmailAddressBuilder() { + + } + + /** {@inheritDoc} */ + public EmailAddress buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, EmailAddress.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public EmailAddress buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EmailAddressImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressImpl.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.EmailAddress; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.EmailAddress} + */ +public class EmailAddressImpl extends AbstractSAMLObject implements EmailAddress { + + /** The email address */ + private String address; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected EmailAddressImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAddress() { + return address; + } + + /** {@inheritDoc} */ + public void setAddress(String address) { + this.address = prepareForAssignment(this.address, address); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.EmailAddress; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.EmailAddress} objects. + */ +public class EmailAddressMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + EmailAddress address = (EmailAddress) samlObject; + + if (address.getAddress() != null) { + XMLHelper.appendTextContent(domElement, address.getAddress()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EmailAddressUnmarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.EmailAddress; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.EmailAddress} objects. + */ +public class EmailAddressUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + EmailAddress address = (EmailAddress) samlObject; + + address.setAddress(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodBuilder.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.SAMLObjectBuilder; +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.EncryptionMethod; + +/** + * Builder of {@link org.opensaml.saml2.metadata.EncryptionMethod}. + */ +public class EncryptionMethodBuilder extends AbstractSAMLObjectBuilder + implements SAMLObjectBuilder { + + /** + * Constructor. + * + */ + public EncryptionMethodBuilder() { + } + + /** {@inheritDoc} */ + public EncryptionMethod buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EncryptionMethodImpl(namespaceURI, localName, namespacePrefix); + } + + /** {@inheritDoc} */ + public EncryptionMethod buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, EncryptionMethod.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MD_PREFIX); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.EncryptionMethod; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.EncryptionMethod}. + */ +public class EncryptionMethodImpl extends org.opensaml.xml.encryption.impl.EncryptionMethodImpl implements EncryptionMethod { + + /** + * Constructor. + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected EncryptionMethodImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodMarshaller.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,26 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.EncryptionMethod} objects. + */ +public class EncryptionMethodMarshaller extends org.opensaml.xml.encryption.impl.EncryptionMethodMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EncryptionMethodUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.EncryptionMethod} objects. + */ +public class EncryptionMethodUnmarshaller extends org.opensaml.xml.encryption.impl.EncryptionMethodUnmarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointImpl.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * A concrete implementation of {@link org.opensaml.saml2.metadata.Endpoint} + */ +public abstract class EndpointImpl extends AbstractSAMLObject implements Endpoint { + + /** Binding URI */ + private String bindingId; + + /** Endpoint location URI */ + private String location; + + /** Response location URI */ + private String responseLocation; + + /** "anyAttribute" attributes */ + private final AttributeMap unknownAttributes; + + /** child "any" elements */ + private final IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EndpointImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getBinding() { + return bindingId; + } + + /** {@inheritDoc} */ + public void setBinding(String binding) { + bindingId = prepareForAssignment(bindingId, binding); + } + + /** {@inheritDoc} */ + public String getLocation() { + return location; + } + + /** {@inheritDoc} */ + public void setLocation(String location) { + this.location = prepareForAssignment(this.location, location); + } + + /** {@inheritDoc} */ + public String getResponseLocation() { + return responseLocation; + } + + /** {@inheritDoc} */ + public void setResponseLocation(String location) { + responseLocation = prepareForAssignment(responseLocation, location); + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** + * {@inheritDoc} + */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } + + /** + * {@inheritDoc} + */ + public List getOrderedChildren() { + return Collections.unmodifiableList(unknownChildren); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointMarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.Endpoint} objects. + */ +public class EndpointMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + public void marshallAttributes(XMLObject samlElement, Element domElement) { + Endpoint endpoint = (Endpoint) samlElement; + + if (endpoint.getBinding() != null) { + domElement.setAttributeNS(null, Endpoint.BINDING_ATTRIB_NAME, endpoint.getBinding().toString()); + } + if (endpoint.getLocation() != null) { + domElement.setAttributeNS(null, Endpoint.LOCATION_ATTRIB_NAME, endpoint.getLocation().toString()); + } + + if (endpoint.getResponseLocation() != null) { + domElement.setAttributeNS(null, Endpoint.RESPONSE_LOCATION_ATTRIB_NAME, endpoint.getResponseLocation() + .toString()); + } + + Attr attribute; + for (Entry entry : endpoint.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || endpoint.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EndpointUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.saml2.metadata.Endpoint} objects. + */ +public class EndpointUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Endpoint endpoint = (Endpoint) samlObject; + + if (attribute.getLocalName().equals(Endpoint.BINDING_ATTRIB_NAME)) { + endpoint.setBinding(attribute.getValue()); + } else if (attribute.getLocalName().equals(Endpoint.LOCATION_ATTRIB_NAME)) { + endpoint.setLocation(attribute.getValue()); + } else if (attribute.getLocalName().equals(Endpoint.RESPONSE_LOCATION_ATTRIB_NAME)) { + endpoint.setResponseLocation(attribute.getValue()); + } else { + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + endpoint.getUnknownAttributes().registerID(attribQName); + } + endpoint.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Endpoint endpoint = (Endpoint) parentSAMLObject; + + endpoint.getUnknownXMLObjects().add(childSAMLObject); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorBuilder.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.EntitiesDescriptor; + +/** + * A builder of {@link org.opensaml.saml2.metadata.impl.EntitiesDescriptorImpl} objects. + */ +public class EntitiesDescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public EntitiesDescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public EntitiesDescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, EntitiesDescriptor.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public EntitiesDescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EntitiesDescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,158 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.SAMLObject; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.EntitiesDescriptor}. + */ +public class EntitiesDescriptorImpl extends AbstractSignableSAMLObject implements EntitiesDescriptor { + + /** Name of this descriptor group. */ + private String name; + + /** ID attribute. */ + private String id; + + /** validUntil attribute. */ + private DateTime validUntil; + + /** cacheDurection attribute. */ + private Long cacheDuration; + + /** Extensions child. */ + private Extensions extensions; + + /** Ordered set of child Entity/Entities Descriptors. */ + private final IndexedXMLObjectChildrenList orderedDescriptors; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EntitiesDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + orderedDescriptors = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(String newName) { + this.name = prepareForAssignment(this.name, newName); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String newID) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, newID); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public boolean isValid() { + if (null == validUntil) { + return true; + } + + DateTime now = new DateTime(); + return now.isBefore(validUntil); + } + + /** {@inheritDoc} */ + public DateTime getValidUntil() { + return validUntil; + } + + /** {@inheritDoc} */ + public void setValidUntil(DateTime newValidUntil) { + validUntil = prepareForAssignment(validUntil, newValidUntil); + } + + /** {@inheritDoc} */ + public Long getCacheDuration() { + return cacheDuration; + } + + /** {@inheritDoc} */ + public void setCacheDuration(Long duration) { + cacheDuration = prepareForAssignment(cacheDuration, duration); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions newExtensions) { + extensions = prepareForAssignment(extensions, newExtensions); + } + + /** {@inheritDoc} */ + public List getEntitiesDescriptors() { + return (List) orderedDescriptors.subList(EntitiesDescriptor.ELEMENT_QNAME); + } + + /** {@inheritDoc} */ + public List getEntityDescriptors() { + return (List) orderedDescriptors.subList(EntityDescriptor.ELEMENT_QNAME); + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID(){ + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(getSignature() != null){ + children.add(getSignature()); + } + + children.add(getExtensions()); + children.addAll(orderedDescriptors); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorMarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.EntitiesDescriptor} objects. + */ +public class EntitiesDescriptorMarshaller extends AbstractSAMLObjectMarshaller { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(EntitiesDescriptorMarshaller.class); + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) { + + EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) samlElement; + + // Set the ID attribute + if (entitiesDescriptor.getID() != null) { + log.debug("Writing ID attribute to EntitiesDescriptor DOM element."); + domElement.setAttributeNS(null, EntitiesDescriptor.ID_ATTRIB_NAME, entitiesDescriptor.getID()); + domElement.setIdAttributeNS(null, EntitiesDescriptor.ID_ATTRIB_NAME, true); + } + + // Set the validUntil attribute + if (entitiesDescriptor.getValidUntil() != null) { + log.debug("Writting validUntil attribute to EntitiesDescriptor DOM element"); + String validUntilStr = Configuration.getSAMLDateFormatter().print(entitiesDescriptor.getValidUntil()); + domElement.setAttributeNS(null, TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME, validUntilStr); + } + + // Set the cacheDuration attribute + if (entitiesDescriptor.getCacheDuration() != null) { + log.debug("Writting cacheDuration attribute to EntitiesDescriptor DOM element"); + String cacheDuration = XMLHelper.longToDuration(entitiesDescriptor.getCacheDuration()); + domElement.setAttributeNS(null, CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME, cacheDuration); + } + + // Set the Name attribute + if (entitiesDescriptor.getName() != null) { + log.debug("Writting Name attribute to EntitiesDescriptor DOM element"); + domElement.setAttributeNS(null, EntitiesDescriptor.NAME_ATTRIB_NAME, entitiesDescriptor.getName()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntitiesDescriptorUnmarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.EntitiesDescriptor} objects. + */ +public class EntitiesDescriptorUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) parentSAMLObject; + + if (childSAMLObject instanceof Extensions) { + entitiesDescriptor.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof EntitiesDescriptor) { + entitiesDescriptor.getEntitiesDescriptors().add((EntitiesDescriptor) childSAMLObject); + } else if (childSAMLObject instanceof EntityDescriptor) { + entitiesDescriptor.getEntityDescriptors().add((EntityDescriptor) childSAMLObject); + } else if (childSAMLObject instanceof Signature) { + entitiesDescriptor.setSignature((Signature) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) samlObject; + + if (attribute.getLocalName().equals(EntitiesDescriptor.ID_ATTRIB_NAME)) { + entitiesDescriptor.setID(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + entitiesDescriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) { + entitiesDescriptor.setCacheDuration(new Long(XMLHelper.durationToLong(attribute.getValue()))); + } else if (attribute.getLocalName().equals(EntitiesDescriptor.NAME_ATTRIB_NAME)) { + entitiesDescriptor.setName(attribute.getValue()); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorBuilder.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.EntityDescriptor; + +/** + * An Builder for EntityDescriptor elements. + */ +public class EntityDescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public EntityDescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public EntityDescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public EntityDescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EntityDescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorImpl.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,295 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.AdditionalMetadataLocation; +import org.opensaml.saml2.metadata.AffiliationDescriptor; +import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor; +import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.PDPDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concretate implementation of {@link org.opensaml.saml2.metadata.EntitiesDescriptor}. + */ +public class EntityDescriptorImpl extends AbstractSignableSAMLObject implements EntityDescriptor { + + /** Entity ID of this Entity. */ + private String entityID; + + /** ID attribute. */ + private String id; + + /** validUntil attribute. */ + private DateTime validUntil; + + /** cacheDurection attribute. */ + private Long cacheDuration; + + /** Extensions child. */ + private Extensions extensions; + + /** Role descriptors for this entity. */ + private final IndexedXMLObjectChildrenList roleDescriptors; + + /** Affiliatition descriptor for this entity. */ + private AffiliationDescriptor affiliationDescriptor; + + /** Organization the administers this entity. */ + private Organization organization; + + /** Contact persons for this entity. */ + private final XMLObjectChildrenList contactPersons; + + /** Additional metadata locations for this entity. */ + private final XMLObjectChildrenList additionalMetadata; + + /** "anyAttribute" attributes. */ + private final AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EntityDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + roleDescriptors = new IndexedXMLObjectChildrenList(this); + contactPersons = new XMLObjectChildrenList(this); + additionalMetadata = new XMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public String getEntityID() { + return entityID; + } + + /** {@inheritDoc} */ + public void setEntityID(String newId) { + if (newId != null && newId.length() > 1024) { + throw new IllegalArgumentException("Entity ID can not exceed 1024 characters in length"); + } + entityID = prepareForAssignment(entityID, newId); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String newID) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, newID); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public boolean isValid() { + if (null == validUntil) { + return true; + } + + DateTime now = new DateTime(); + return now.isBefore(validUntil); + } + + /** {@inheritDoc} */ + public DateTime getValidUntil() { + return validUntil; + } + + /** {@inheritDoc} */ + public void setValidUntil(DateTime newValidUntil) { + validUntil = prepareForAssignment(validUntil, newValidUntil); + } + + /** {@inheritDoc} */ + public Long getCacheDuration() { + return cacheDuration; + } + + /** {@inheritDoc} */ + public void setCacheDuration(Long duration) { + cacheDuration = prepareForAssignment(cacheDuration, duration); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions newExtensions) { + extensions = prepareForAssignment(extensions, newExtensions); + } + + /** {@inheritDoc} */ + public List getRoleDescriptors() { + return roleDescriptors; + } + + /** {@inheritDoc} */ + public List getRoleDescriptors(QName typeOrName) { + return (List) roleDescriptors.subList(typeOrName); + } + + /** {@inheritDoc} */ + public List getRoleDescriptors(QName type, String supportedProtocol) { + ArrayList supportingRoleDescriptors = new ArrayList(); + for (RoleDescriptor descriptor : roleDescriptors.subList(type)) { + if (descriptor.isSupportedProtocol(supportedProtocol)) { + supportingRoleDescriptors.add(descriptor); + } + } + + return supportingRoleDescriptors; + } + + /** {@inheritDoc} */ + public IDPSSODescriptor getIDPSSODescriptor(String supportedProtocol) { + List descriptors = getRoleDescriptors(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, supportedProtocol); + if (descriptors.size() > 0) { + return (IDPSSODescriptor) descriptors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public SPSSODescriptor getSPSSODescriptor(String supportedProtocol) { + List descriptors = getRoleDescriptors(SPSSODescriptor.DEFAULT_ELEMENT_NAME, supportedProtocol); + if (descriptors.size() > 0) { + return (SPSSODescriptor) descriptors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public AuthnAuthorityDescriptor getAuthnAuthorityDescriptor(String supportedProtocol) { + List descriptors = getRoleDescriptors(AuthnAuthorityDescriptor.DEFAULT_ELEMENT_NAME, + supportedProtocol); + if (descriptors.size() > 0) { + return (AuthnAuthorityDescriptor) descriptors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public AttributeAuthorityDescriptor getAttributeAuthorityDescriptor(String supportedProtocol) { + List descriptors = getRoleDescriptors(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME, + supportedProtocol); + if (descriptors.size() > 0) { + return (AttributeAuthorityDescriptor) descriptors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public PDPDescriptor getPDPDescriptor(String supportedProtocol) { + List descriptors = getRoleDescriptors(PDPDescriptor.DEFAULT_ELEMENT_NAME, supportedProtocol); + if (descriptors.size() > 0) { + return (PDPDescriptor) descriptors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public AffiliationDescriptor getAffiliationDescriptor() { + return affiliationDescriptor; + } + + /** {@inheritDoc} */ + public void setAffiliationDescriptor(AffiliationDescriptor descriptor) { + affiliationDescriptor = prepareForAssignment(affiliationDescriptor, descriptor); + } + + /** {@inheritDoc} */ + public Organization getOrganization() { + return organization; + } + + /** {@inheritDoc} */ + public void setOrganization(Organization newOrganization) { + organization = prepareForAssignment(organization, newOrganization); + } + + /** {@inheritDoc} */ + public List getContactPersons() { + return contactPersons; + } + + /** {@inheritDoc} */ + public List getAdditionalMetadataLocations() { + return additionalMetadata; + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID() { + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (getSignature() != null) { + children.add(getSignature()); + } + children.add(getExtensions()); + children.addAll(roleDescriptors); + children.add(getAffiliationDescriptor()); + children.add(getOrganization()); + children.addAll(contactPersons); + children.addAll(additionalMetadata); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.EntityDescriptor} objects. + */ +public class EntityDescriptorMarshaller extends AbstractSAMLObjectMarshaller { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(EntityDescriptorMarshaller.class); + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) { + EntityDescriptor entityDescriptor = (EntityDescriptor) samlElement; + + // Set the entityID attribute + if (entityDescriptor.getEntityID() != null) { + domElement.setAttributeNS(null, EntityDescriptor.ENTITY_ID_ATTRIB_NAME, entityDescriptor.getEntityID()); + } + + // Set the ID attribute + if (entityDescriptor.getID() != null) { + domElement.setAttributeNS(null, EntityDescriptor.ID_ATTRIB_NAME, entityDescriptor.getID()); + domElement.setIdAttributeNS(null, EntityDescriptor.ID_ATTRIB_NAME, true); + } + + // Set the validUntil attribute + if (entityDescriptor.getValidUntil() != null) { + log.debug("Writting validUntil attribute to EntityDescriptor DOM element"); + String validUntilStr = Configuration.getSAMLDateFormatter().print(entityDescriptor.getValidUntil()); + domElement.setAttributeNS(null, TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME, validUntilStr); + } + + // Set the cacheDuration attribute + if (entityDescriptor.getCacheDuration() != null) { + log.debug("Writting cacheDuration attribute to EntityDescriptor DOM element"); + String cacheDuration = XMLHelper.longToDuration(entityDescriptor.getCacheDuration()); + domElement.setAttributeNS(null, CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME, cacheDuration); + } + + Attr attribute; + for (Entry entry : entityDescriptor.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || entityDescriptor.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/EntityDescriptorUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,92 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.AdditionalMetadataLocation; +import org.opensaml.saml2.metadata.AffiliationDescriptor; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.EntityDescriptor}s. + */ +public class EntityDescriptorUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + EntityDescriptor entityDescriptor = (EntityDescriptor) parentSAMLObject; + + if (childSAMLObject instanceof Extensions) { + entityDescriptor.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof Signature) { + entityDescriptor.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof RoleDescriptor) { + entityDescriptor.getRoleDescriptors().add((RoleDescriptor) childSAMLObject); + } else if (childSAMLObject instanceof AffiliationDescriptor) { + entityDescriptor.setAffiliationDescriptor((AffiliationDescriptor) childSAMLObject); + } else if (childSAMLObject instanceof Organization) { + entityDescriptor.setOrganization((Organization) childSAMLObject); + } else if (childSAMLObject instanceof ContactPerson) { + entityDescriptor.getContactPersons().add((ContactPerson) childSAMLObject); + } else if (childSAMLObject instanceof AdditionalMetadataLocation) { + entityDescriptor.getAdditionalMetadataLocations().add((AdditionalMetadataLocation) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + EntityDescriptor entityDescriptor = (EntityDescriptor) samlObject; + + if (attribute.getLocalName().equals(EntityDescriptor.ENTITY_ID_ATTRIB_NAME)) { + entityDescriptor.setEntityID(attribute.getValue()); + } else if (attribute.getLocalName().equals(EntityDescriptor.ID_ATTRIB_NAME)) { + entityDescriptor.setID(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + entityDescriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) { + entityDescriptor.setCacheDuration(XMLHelper.durationToLong(attribute.getValue())); + } else { + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + entityDescriptor.getUnknownAttributes().registerID(attribQName); + } + entityDescriptor.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameBuilder.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.GivenName; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.GivenNameImpl} + */ +public class GivenNameBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public GivenNameBuilder() { + + } + + /** {@inheritDoc} */ + public GivenName buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, GivenName.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public GivenName buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new GivenNameImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameImpl.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.GivenName; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.GivenName}. + */ +public class GivenNameImpl extends AbstractSAMLObject implements GivenName { + + /** Given name (first name) */ + private String name; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected GivenNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(String newName) { + name = prepareForAssignment(name, newName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.GivenName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.GivenName} objects. + */ +public class GivenNameMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + GivenName name = (GivenName) samlObject; + + if (name.getName() != null) { + XMLHelper.appendTextContent(domElement, name.getName()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/GivenNameUnmarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.GivenName; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.GivenName} objects. + */ +public class GivenNameUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + GivenName name = (GivenName) samlObject; + + name.setName(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorBuilder.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.IDPSSODescriptor; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.IDPSSODescriptorImpl} + */ +public class IDPSSODescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public IDPSSODescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public IDPSSODescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, IDPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public IDPSSODescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IDPSSODescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorImpl.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,169 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.NameIDMappingService; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.IDPSSODescriptor}. + */ +public class IDPSSODescriptorImpl extends SSODescriptorImpl implements IDPSSODescriptor { + + /** wantAuthnRequestSigned attribute. */ + private XSBooleanValue wantAuthnRequestsSigned; + + /** SingleSignOn services for this entity. */ + private final XMLObjectChildrenList singleSignOnServices; + + /** NameID mapping services for this entity. */ + private final XMLObjectChildrenList nameIDMappingServices; + + /** AssertionID request services for this entity. */ + private final XMLObjectChildrenList assertionIDRequestServices; + + /** Attribute profiles supported by this entity. */ + private final XMLObjectChildrenList attributeProfiles; + + /** Attributes accepted by this entity. */ + private final XMLObjectChildrenList attributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected IDPSSODescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + singleSignOnServices = new XMLObjectChildrenList(this); + nameIDMappingServices = new XMLObjectChildrenList(this); + assertionIDRequestServices = new XMLObjectChildrenList(this); + attributeProfiles = new XMLObjectChildrenList(this); + attributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Boolean getWantAuthnRequestsSigned(){ + if(wantAuthnRequestsSigned != null){ + return wantAuthnRequestsSigned.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue getWantAuthnRequestsSignedXSBoolean() { + return wantAuthnRequestsSigned; + } + + /** {@inheritDoc} */ + public void setWantAuthnRequestsSigned(Boolean newWantSigned){ + if(newWantSigned != null){ + wantAuthnRequestsSigned = prepareForAssignment(wantAuthnRequestsSigned, new XSBooleanValue(newWantSigned, false)); + }else{ + wantAuthnRequestsSigned = prepareForAssignment(wantAuthnRequestsSigned, null); + } + } + + /** {@inheritDoc} */ + public void setWantAuthnRequestsSigned(XSBooleanValue wantSigned) { + wantAuthnRequestsSigned = prepareForAssignment(wantAuthnRequestsSigned, wantSigned); + } + + /** {@inheritDoc} */ + public List getSingleSignOnServices() { + return singleSignOnServices; + } + + /** {@inheritDoc} */ + public List getNameIDMappingServices() { + return nameIDMappingServices; + } + + /** {@inheritDoc} */ + public List getAssertionIDRequestServices() { + return assertionIDRequestServices; + } + + /** {@inheritDoc} */ + public List getAttributeProfiles() { + return attributeProfiles; + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } + + /** {@inheritDoc} */ + public List getEndpoints() { + List endpoints = new ArrayList(); + endpoints.addAll(super.getEndpoints()); + endpoints.addAll(singleSignOnServices); + endpoints.addAll(nameIDMappingServices); + endpoints.addAll(assertionIDRequestServices); + return Collections.unmodifiableList(endpoints); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + if(type.equals(SingleSignOnService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(singleSignOnServices)); + }else if(type.equals(NameIDMappingService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(nameIDMappingServices)); + }else if(type.equals(AssertionIDRequestService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(assertionIDRequestServices)); + }else{ + return super.getEndpoints(type); + } + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(singleSignOnServices); + children.addAll(nameIDMappingServices); + children.addAll(assertionIDRequestServices); + children.addAll(attributeProfiles); + children.addAll(attributes); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.IDPSSODescriptor} objects. + */ +public class IDPSSODescriptorMarshaller extends SSODescriptorMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + IDPSSODescriptor descriptor = (IDPSSODescriptor) samlObject; + + if (descriptor.getWantAuthnRequestsSignedXSBoolean() != null) { + domElement.setAttributeNS(null, IDPSSODescriptor.WANT_AUTHN_REQ_SIGNED_ATTRIB_NAME, descriptor + .getWantAuthnRequestsSignedXSBoolean().toString()); + } + + super.marshallAttributes(samlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IDPSSODescriptorUnmarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.NameIDMappingService; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.SSODescriptor} objects. + */ +public class IDPSSODescriptorUnmarshaller extends SSODescriptorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + IDPSSODescriptor descriptor = (IDPSSODescriptor) parentObject; + + if (childObject instanceof SingleSignOnService) { + descriptor.getSingleSignOnServices().add((SingleSignOnService) childObject); + } else if (childObject instanceof NameIDMappingService) { + descriptor.getNameIDMappingServices().add((NameIDMappingService) childObject); + } else if (childObject instanceof AssertionIDRequestService) { + descriptor.getAssertionIDRequestServices().add((AssertionIDRequestService) childObject); + } else if (childObject instanceof AttributeProfile) { + descriptor.getAttributeProfiles().add((AttributeProfile) childObject); + } else if (childObject instanceof Attribute) { + descriptor.getAttributes().add((Attribute) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + IDPSSODescriptor descriptor = (IDPSSODescriptor) samlObject; + + if (attribute.getLocalName().equals(IDPSSODescriptor.WANT_AUTHN_REQ_SIGNED_ATTRIB_NAME)) { + descriptor.setWantAuthnRequestsSigned(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointImpl.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.IndexedEndpoint} + */ +public abstract class IndexedEndpointImpl extends EndpointImpl implements IndexedEndpoint { + + /** Index of this endpoint */ + private Integer index; + + /** isDefault attribute */ + private XSBooleanValue isDefault; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected IndexedEndpointImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Integer getIndex() { + return index; + } + + /** {@inheritDoc} */ + public void setIndex(Integer index) { + this.index = prepareForAssignment(this.index, index); + } + + /** {@inheritDoc} */ + public Boolean isDefault() { + if (isDefault == null) { + return Boolean.FALSE; + } + return isDefault.getValue(); + } + + /** {@inheritDoc} */ + public XSBooleanValue isDefaultXSBoolean() { + return isDefault; + } + + /** {@inheritDoc} */ + public void setIsDefault(Boolean newIsDefault){ + if(newIsDefault != null){ + isDefault = prepareForAssignment(isDefault, new XSBooleanValue(newIsDefault, false)); + }else{ + isDefault = prepareForAssignment(isDefault, null); + } + } + + /** {@inheritDoc} */ + public void setIsDefault(XSBooleanValue isDefault) { + this.isDefault = prepareForAssignment(this.isDefault, isDefault); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.opensaml.xml.XMLObject; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.IndexedEndpoint} objects. + */ +public class IndexedEndpointMarshaller extends EndpointMarshaller { + + /** {@inheritDoc} */ + public void marshallAttributes(XMLObject samlObject, Element domElement) { + IndexedEndpoint iEndpoint = (IndexedEndpoint) samlObject; + + if (iEndpoint.getIndex() != null) { + domElement.setAttributeNS(null, IndexedEndpoint.INDEX_ATTRIB_NAME, iEndpoint.getIndex().toString()); + } + + if (iEndpoint.isDefaultXSBoolean() != null) { + domElement.setAttributeNS(null, IndexedEndpoint.IS_DEFAULT_ATTRIB_NAME, iEndpoint.isDefaultXSBoolean() + .toString()); + } + + super.marshallAttributes(samlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/IndexedEndpointUnmarshaller.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.saml2.metadata.IndexedEndpoint} objects. + */ +public class IndexedEndpointUnmarshaller extends EndpointUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + IndexedEndpoint iEndpoint = (IndexedEndpoint) samlObject; + + if (attribute.getLocalName().equals(IndexedEndpoint.INDEX_ATTRIB_NAME)) { + iEndpoint.setIndex(Integer.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(IndexedEndpoint.IS_DEFAULT_ATTRIB_NAME)) { + iEndpoint.setIsDefault(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorBuilder.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.KeyDescriptor; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.KeyDescriptorImpl} objects. + */ +public class KeyDescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** {@inheritDoc} */ + public KeyDescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, KeyDescriptor.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public KeyDescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new KeyDescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.EncryptionMethod; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.signature.KeyInfo; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.KeyDescriptor}. + */ +public class KeyDescriptorImpl extends AbstractSAMLObject implements KeyDescriptor { + + /** Key usage type. */ + private UsageType keyUseType; + + /** Key information. */ + private KeyInfo keyInfo; + + /** Encryption methods supported by the entity. */ + private final XMLObjectChildrenList encryptionMethods; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected KeyDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + encryptionMethods = new XMLObjectChildrenList(this); + keyUseType = UsageType.UNSPECIFIED; + } + + /** {@inheritDoc} */ + public UsageType getUse() { + return keyUseType; + } + + /** {@inheritDoc} */ + public void setUse(UsageType newType) { + if (newType != null) { + keyUseType = prepareForAssignment(keyUseType, newType); + } else { + keyUseType = prepareForAssignment(keyUseType, UsageType.UNSPECIFIED); + } + } + + /** {@inheritDoc} */ + public KeyInfo getKeyInfo() { + return keyInfo; + } + + /** {@inheritDoc} */ + public void setKeyInfo(KeyInfo newKeyInfo) { + keyInfo = prepareForAssignment(keyInfo, newKeyInfo); + } + + /** {@inheritDoc} */ + public List getEncryptionMethods() { + return encryptionMethods; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(keyInfo); + children.addAll(encryptionMethods); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorMarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.credential.UsageType; +import org.w3c.dom.Element; + +/** + * A thread-safe marshaller for {@link org.opensaml.saml2.metadata.KeyDescriptor}s. + */ +public class KeyDescriptorMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + KeyDescriptor keyDescriptor = (KeyDescriptor) xmlObject; + + if (keyDescriptor.getUse() != null) { + UsageType use = keyDescriptor.getUse(); + // UsageType enum contains more values than are allowed by SAML 2 schema + if (use.equals(UsageType.SIGNING) || use.equals(UsageType.ENCRYPTION)) { + domElement.setAttribute(KeyDescriptor.USE_ATTRIB_NAME, use.toString().toLowerCase()); + } else if (use.equals(UsageType.UNSPECIFIED)) { + // emit nothing for unspecified - this is semantically equivalent to non-existent attribute + } else { + // Just in case values are unknowingly added to UsageType in the future... + throw new MarshallingException("KeyDescriptor had illegal value for use attribute: " + use.toString()); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/KeyDescriptorUnmarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.EncryptionMethod; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.signature.KeyInfo; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.saml2.metadata.KeyDescriptor}s. + */ +public class KeyDescriptorUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + KeyDescriptor keyDescriptor = (KeyDescriptor) parentSAMLObject; + + if (childSAMLObject instanceof KeyInfo) { + keyDescriptor.setKeyInfo((KeyInfo) childSAMLObject); + } else if (childSAMLObject instanceof EncryptionMethod) { + keyDescriptor.getEncryptionMethods().add((EncryptionMethod) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + KeyDescriptor keyDescriptor = (KeyDescriptor) samlObject; + + if (attribute.getName().equals(KeyDescriptor.USE_ATTRIB_NAME)) { + try { + UsageType usageType = UsageType.valueOf(UsageType.class, attribute.getValue().toUpperCase()); + // Only allow the enum values specified in the schema. + if (usageType != UsageType.SIGNING && usageType != UsageType.ENCRYPTION) { + throw new UnmarshallingException("Invalid key usage type: " + attribute.getValue()); + } + keyDescriptor.setUse(usageType); + } catch (IllegalArgumentException e) { + throw new UnmarshallingException("Invalid key usage type: " + attribute.getValue()); + } + } + + super.processAttribute(samlObject, attribute); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceBuilder.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.ManageNameIDService; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.ManageNameIDServiceImpl}. + */ +public class ManageNameIDServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ManageNameIDServiceBuilder() { + + } + + /** {@inheritDoc} */ + public ManageNameIDService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, ManageNameIDService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public ManageNameIDService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ManageNameIDServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.ManageNameIDService; + +/** + * Concrete implenentation of {@link org.opensaml.saml2.metadata.ManageNameIDService}. + */ +public class ManageNameIDServiceImpl extends EndpointImpl implements ManageNameIDService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected ManageNameIDServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.ManageNameIDService} objects. + */ +public class ManageNameIDServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ManageNameIDServiceUnmarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.ManageNameIDService} objects. + */ +public class ManageNameIDServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatBuilder.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.NameIDFormat; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.NameIDFormatImpl} + */ +public class NameIDFormatBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public NameIDFormatBuilder() { + + } + + /** {@inheritDoc} */ + public NameIDFormat buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, NameIDFormat.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public NameIDFormat buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NameIDFormatImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatImpl.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.NameIDFormat}. + */ +public class NameIDFormatImpl extends AbstractSAMLObject implements NameIDFormat { + + /** NameID format */ + private String format; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected NameIDFormatImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getFormat() { + return format; + } + + /** {@inheritDoc} */ + public void setFormat(String format) { + this.format = prepareForAssignment(this.format, format); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.NameIDFormat} objects. + */ +public class NameIDFormatMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + NameIDFormat format = (NameIDFormat) samlObject; + + if (format.getFormat() != null) { + XMLHelper.appendTextContent(domElement, format.getFormat()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDFormatUnmarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.NameIDFormat} objects. + */ +public class NameIDFormatUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + NameIDFormat format = (NameIDFormat) samlObject; + + format.setFormat(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceBuilder.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.NameIDMappingService; + +/** + * Builder of (@link org.opensaml.saml2.metadata.impl.NameIDMappingServiceImpl}. + */ +public class NameIDMappingServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public NameIDMappingServiceBuilder() { + + } + + /** {@inheritDoc} */ + public NameIDMappingService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, NameIDMappingService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public NameIDMappingService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new NameIDMappingServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceImpl.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.NameIDMappingService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.NameIDMappingService}. + */ +public class NameIDMappingServiceImpl extends EndpointImpl implements NameIDMappingService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected NameIDMappingServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.NameIDMappingService} objects. + */ +public class NameIDMappingServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/NameIDMappingServiceUnmarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.NameIDMappingService} objects. + */ +public class NameIDMappingServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationBuilder.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.Organization; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.OrganizationImpl} + */ +public class OrganizationBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public OrganizationBuilder() { + + } + + /** {@inheritDoc} */ + public Organization buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, Organization.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public Organization buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new OrganizationImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameBuilder.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.OrganizationDisplayName; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.OrganizationDisplayNameImpl} + */ +public class OrganizationDisplayNameBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public OrganizationDisplayNameBuilder() { + + } + + /** {@inheritDoc} */ + public OrganizationDisplayName buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, OrganizationDisplayName.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public OrganizationDisplayName buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new OrganizationDisplayNameImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameImpl.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.OrganizationDisplayName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.OrganizationDisplayName} + */ +public class OrganizationDisplayNameImpl extends AbstractSAMLObject implements OrganizationDisplayName { + + /** Organization name */ + private LocalizedString name; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected OrganizationDisplayNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(LocalizedString newName) { + name = prepareForAssignment(name, newName); + boolean hasXMLLang = false; + if (name != null && !DatatypeHelper.isEmpty(name.getLanguage())) { + hasXMLLang = true; + } + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasXMLLang); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameMarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.OrganizationDisplayName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.OrganizationDisplayName} objects. + */ +public class OrganizationDisplayNameMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + OrganizationDisplayName name = (OrganizationDisplayName) samlObject; + + if (name.getName() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + OrganizationDisplayName.LANG_ATTRIB_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(name.getName().getLanguage()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + OrganizationDisplayName name = (OrganizationDisplayName) samlObject; + + if (name.getName() != null) { + XMLHelper.appendTextContent(domElement, name.getName().getLocalString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationDisplayNameUnmarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.OrganizationDisplayName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.saml2.metadata.OrganizationDisplayName} objects. + */ +public class OrganizationDisplayNameUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + QName attribName = XMLHelper.getNodeQName(attribute); + if (LangBearing.XML_LANG_ATTR_NAME.equals(attribName)) { + OrganizationDisplayName name = (OrganizationDisplayName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLanguage(attribute.getValue()); + name.setName(nameStr); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + OrganizationDisplayName name = (OrganizationDisplayName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLocalizedString(elementContent); + name.setName(nameStr); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationImpl.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,115 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.OrganizationDisplayName; +import org.opensaml.saml2.metadata.OrganizationName; +import org.opensaml.saml2.metadata.OrganizationURL; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.Organization} + */ +public class OrganizationImpl extends AbstractSAMLObject implements Organization { + + /** element extensions */ + private Extensions extensions; + + /** OrganizationName children */ + private final XMLObjectChildrenList names; + + /** OrganizationDisplayName children */ + private final XMLObjectChildrenList displayNames; + + /** OrganizationURL children */ + private final XMLObjectChildrenList urls; + + /** "anyAttribute" attributes */ + private final AttributeMap unknownAttributes; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected OrganizationImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + names = new XMLObjectChildrenList(this); + displayNames = new XMLObjectChildrenList(this); + urls = new XMLObjectChildrenList(this); + unknownAttributes = new AttributeMap(this); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException { + this.extensions = prepareForAssignment(this.extensions, extensions); + } + + /** {@inheritDoc} */ + public List getOrganizationNames() { + return names; + } + + /** {@inheritDoc} */ + public List getDisplayNames() { + return displayNames; + } + + /** {@inheritDoc} */ + public List getURLs() { + return urls; + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.add(extensions); + children.addAll(names); + children.addAll(displayNames); + children.addAll(urls); + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationMarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.xml.Configuration; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.Organization} objects. + */ +public class OrganizationMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + Organization org = (Organization) xmlObject; + + Attr attribute; + for (Entry entry : org.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) || org.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameBuilder.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.OrganizationName; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.OrganizationNameImpl} + */ +public class OrganizationNameBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public OrganizationNameBuilder() { + + } + + /** {@inheritDoc} */ + public OrganizationName buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, OrganizationName.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public OrganizationName buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new OrganizationNameImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameImpl.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.OrganizationName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.OrganizationName} + */ +public class OrganizationNameImpl extends AbstractSAMLObject implements OrganizationName { + + /** Organization name */ + private LocalizedString name; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected OrganizationNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(LocalizedString newName) { + name = prepareForAssignment(name, newName); + boolean hasXMLLang = false; + if (name != null && !DatatypeHelper.isEmpty(name.getLanguage())) { + hasXMLLang = true; + } + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasXMLLang); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.OrganizationName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.OrganizationName} objects. + */ +public class OrganizationNameMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + OrganizationName name = (OrganizationName) samlObject; + + if (name.getName() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + OrganizationName.LANG_ATTRIB_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(name.getName().getLanguage()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + OrganizationName name = (OrganizationName) samlObject; + + if (name.getName() != null) { + XMLHelper.appendTextContent(domElement, name.getName().getLocalString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationNameUnmarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.OrganizationName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.OrganizationName} objects. + */ +public class OrganizationNameUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + QName attribName = XMLHelper.getNodeQName(attribute); + if (LangBearing.XML_LANG_ATTR_NAME.equals(attribName)) { + OrganizationName name = (OrganizationName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLanguage(attribute.getValue()); + name.setName(nameStr); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + OrganizationName name = (OrganizationName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLocalizedString(elementContent); + name.setName(nameStr); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLBuilder.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.OrganizationURL; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.OrganizationURLImpl} + */ +public class OrganizationURLBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public OrganizationURLBuilder() { + + } + + /** {@inheritDoc} */ + public OrganizationURL buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, OrganizationURL.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public OrganizationURL buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new OrganizationURLImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLImpl.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.OrganizationURL; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.OrganizationURL} + */ +public class OrganizationURLImpl extends AbstractSAMLObject implements OrganizationURL { + + /** Organization URL */ + private LocalizedString url; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected OrganizationURLImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getURL() { + return url; + } + + /** {@inheritDoc} */ + public void setURL(LocalizedString newURL) { + url = prepareForAssignment(url, newURL); + boolean hasXMLLang = false; + if (url != null && !DatatypeHelper.isEmpty(url.getLanguage())) { + hasXMLLang = true; + } + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasXMLLang); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLMarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.OrganizationURL; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.OrganizationURL} objects. + */ +public class OrganizationURLMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + OrganizationURL url = (OrganizationURL) samlObject; + + if (url.getURL() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + OrganizationURL.LANG_ATTRIB_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(url.getURL().getLanguage()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + OrganizationURL url = (OrganizationURL) samlObject; + + if (url.getURL() != null) { + XMLHelper.appendTextContent(domElement, url.getURL().getLocalString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationURLUnmarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.OrganizationURL; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.OrganizationURL} objects. + */ +public class OrganizationURLUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + QName attribName = XMLHelper.getNodeQName(attribute); + if (LangBearing.XML_LANG_ATTR_NAME.equals(attribName)) { + OrganizationURL url = (OrganizationURL) samlObject; + + LocalizedString urlStr = url.getURL(); + if (urlStr == null) { + urlStr = new LocalizedString(); + } + + urlStr.setLanguage(attribute.getValue()); + url.setURL(urlStr); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + OrganizationURL url = (OrganizationURL) samlObject; + + LocalizedString urlStr = url.getURL(); + if (urlStr == null) { + urlStr = new LocalizedString(); + } + + urlStr.setLocalizedString(elementContent); + url.setURL(urlStr); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/OrganizationUnmarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.OrganizationDisplayName; +import org.opensaml.saml2.metadata.OrganizationName; +import org.opensaml.saml2.metadata.OrganizationURL; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.Organization} objects. + */ +public class OrganizationUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + Organization org = (Organization) parentSAMLObject; + + if (childSAMLObject instanceof Extensions) { + org.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof OrganizationName) { + org.getOrganizationNames().add((OrganizationName) childSAMLObject); + } else if (childSAMLObject instanceof OrganizationDisplayName) { + org.getDisplayNames().add((OrganizationDisplayName) childSAMLObject); + } else if (childSAMLObject instanceof OrganizationURL) { + org.getURLs().add((OrganizationURL) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Organization org = (Organization) samlObject; + + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + org.getUnknownAttributes().registerID(attribQName); + } + org.getUnknownAttributes().put(attribQName, attribute.getValue()); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorBuilder.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.PDPDescriptor; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.PDPDescriptorImpl} + */ +public class PDPDescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public PDPDescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public PDPDescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, PDPDescriptor.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public PDPDescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PDPDescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AuthzService; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.PDPDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.PDPDescriptor}. + */ +public class PDPDescriptorImpl extends RoleDescriptorImpl implements PDPDescriptor { + + /** AuthzService children. */ + private final XMLObjectChildrenList authzServices; + + /** AssertionIDRequestService children. */ + private final XMLObjectChildrenList assertionIDRequestServices; + + /** NameIDFormat children. */ + private final XMLObjectChildrenList nameIDFormats; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected PDPDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + authzServices = new XMLObjectChildrenList(this); + assertionIDRequestServices = new XMLObjectChildrenList(this); + nameIDFormats = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAuthzServices() { + return authzServices; + } + + /** {@inheritDoc} */ + public List getAssertionIDRequestServices() { + return assertionIDRequestServices; + } + + /** {@inheritDoc} */ + public List getNameIDFormats() { + return nameIDFormats; + } + + /** {@inheritDoc} */ + public List getEndpoints() { + List endpoints = new ArrayList(); + endpoints.addAll(authzServices); + endpoints.addAll(assertionIDRequestServices); + return Collections.unmodifiableList(endpoints); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + if(type.equals(AuthzService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(authzServices)); + }else if(type.equals(AssertionIDRequestService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(assertionIDRequestServices)); + } + + return null; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(authzServices); + children.addAll(assertionIDRequestServices); + children.addAll(nameIDFormats); + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.PDPDescriptor} objects. + */ +public class PDPDescriptorMarshaller extends RoleDescriptorMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/PDPDescriptorUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AssertionIDRequestService; +import org.opensaml.saml2.metadata.AuthzService; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.PDPDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.PDPDescriptor} objects. + */ +public class PDPDescriptorUnmarshaller extends RoleDescriptorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + PDPDescriptor descriptor = (PDPDescriptor) parentSAMLObject; + + if (childSAMLObject instanceof AuthzService) { + descriptor.getAuthzServices().add((AuthzService) childSAMLObject); + } else if (childSAMLObject instanceof AssertionIDRequestService) { + descriptor.getAssertionIDRequestServices().add((AssertionIDRequestService) childSAMLObject); + } else if (childSAMLObject instanceof NameIDFormat) { + descriptor.getNameIDFormats().add((NameIDFormat) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeBuilder.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.RequestedAttribute; + +/** + * Builder for {@link org.opensaml.saml2.metadata.impl.RequestedAttributeImpl}. + */ +public class RequestedAttributeBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor */ + public RequestedAttributeBuilder() { + + } + + /** {@inheritDoc} */ + public RequestedAttribute buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, RequestedAttribute.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public RequestedAttribute buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestedAttributeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeImpl.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.saml2.core.impl.AttributeImpl; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.RequestedAttribute} + */ +public class RequestedAttributeImpl extends AttributeImpl implements RequestedAttribute { + + /** isRequired attribute */ + private XSBooleanValue isRequired; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected RequestedAttributeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public Boolean isRequired(){ + if(isRequired != null){ + return isRequired.getValue(); + } + + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isRequiredXSBoolean() { + return isRequired; + } + + /** {@inheritDoc} */ + public void setIsRequired(Boolean newIsRequired){ + if(newIsRequired != null){ + isRequired = prepareForAssignment(isRequired, new XSBooleanValue(newIsRequired, false)); + }else{ + isRequired = prepareForAssignment(isRequired, null); + } + } + + /** {@inheritDoc} */ + public void setIsRequired(XSBooleanValue newIsRequired) { + isRequired = prepareForAssignment(isRequired, newIsRequired); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeMarshaller.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.core.impl.AttributeMarshaller; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread-safe Marshaller for {@link org.opensaml.saml2.metadata.RequestedAttribute} objects. + */ +public class RequestedAttributeMarshaller extends AttributeMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + RequestedAttribute requestedAttribute = (RequestedAttribute) samlObject; + + if (requestedAttribute.isRequiredXSBoolean() != null) { + domElement.setAttributeNS(null, RequestedAttribute.IS_REQUIRED_ATTRIB_NAME, requestedAttribute + .isRequiredXSBoolean().toString()); + } + + super.marshallAttributes(samlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RequestedAttributeUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.core.impl.AttributeUnmarshaller; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.RequestedAttribute} objects. + */ +public class RequestedAttributeUnmarshaller extends AttributeUnmarshaller { + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + RequestedAttribute requestedAttribute = (RequestedAttribute) samlObject; + if (attribute.getLocalName().equals(RequestedAttribute.IS_REQUIRED_ATTRIB_NAME)) { + requestedAttribute.setIsRequired(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorImpl.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,241 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.AbstractSignableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.LazyList; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link org.opensaml.saml2.metadata.RoleDescriptor}. */ +public abstract class RoleDescriptorImpl extends AbstractSignableSAMLObject implements RoleDescriptor { + + /** ID attribute. */ + private String id; + + /** validUntil attribute. */ + private DateTime validUntil; + + /** cacheDurection attribute. */ + private Long cacheDuration; + + /** Set of supported protocols. */ + private final List supportedProtocols; + + /** Error URL. */ + private String errorURL; + + /** Extensions child. */ + private Extensions extensions; + + /** Organization administering this role. */ + private Organization organization; + + /** "anyAttribute" attributes. */ + private final AttributeMap unknownAttributes; + + /** Contact persons for this role. */ + private final XMLObjectChildrenList contactPersons; + + /** Key descriptors for this role. */ + private final XMLObjectChildrenList keyDescriptors; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RoleDescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + supportedProtocols = new LazyList(); + contactPersons = new XMLObjectChildrenList(this); + keyDescriptors = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getID() { + return id; + } + + /** {@inheritDoc} */ + public void setID(String newID) { + String oldID = this.id; + this.id = prepareForAssignment(this.id, newID); + registerOwnID(oldID, this.id); + } + + /** {@inheritDoc} */ + public boolean isValid() { + if (validUntil != null) { + return validUntil.isBeforeNow(); + } else { + return true; + } + } + + /** {@inheritDoc} */ + public DateTime getValidUntil() { + return validUntil; + } + + /** {@inheritDoc} */ + public void setValidUntil(DateTime validUntil) { + this.validUntil = prepareForAssignment(this.validUntil, validUntil); + } + + /** {@inheritDoc} */ + public Long getCacheDuration() { + return cacheDuration; + } + + /** {@inheritDoc} */ + public void setCacheDuration(Long duration) { + cacheDuration = prepareForAssignment(cacheDuration, duration); + } + + /** {@inheritDoc} */ + public List getSupportedProtocols() { + return Collections.unmodifiableList(supportedProtocols); + } + + /** {@inheritDoc} */ + public boolean isSupportedProtocol(String protocol) { + return supportedProtocols.contains(protocol); + } + + /** {@inheritDoc} */ + public void addSupportedProtocol(String protocol) { + protocol = DatatypeHelper.safeTrimOrNullString(protocol); + if (protocol != null && !supportedProtocols.contains(protocol)) { + releaseThisandParentDOM(); + supportedProtocols.add(protocol); + } + } + + /** {@inheritDoc} */ + public void removeSupportedProtocol(String protocol) { + protocol = DatatypeHelper.safeTrimOrNullString(protocol); + if (protocol != null && supportedProtocols.contains(protocol)) { + releaseThisandParentDOM(); + supportedProtocols.remove(protocol); + } + } + + /** {@inheritDoc} */ + public void removeSupportedProtocols(Collection protocols) { + for (String protocol : protocols) { + removeSupportedProtocol(protocol); + } + } + + /** {@inheritDoc} */ + public void removeAllSupportedProtocols() { + for (String protocol : supportedProtocols) { + removeSupportedProtocol(protocol); + } + } + + /** {@inheritDoc} */ + public String getErrorURL() { + return errorURL; + } + + /** {@inheritDoc} */ + public void setErrorURL(String errorURL) { + + this.errorURL = prepareForAssignment(this.errorURL, errorURL); + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return extensions; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions extensions) throws IllegalArgumentException { + this.extensions = prepareForAssignment(this.extensions, extensions); + } + + /** {@inheritDoc} */ + public Organization getOrganization() { + return organization; + } + + /** {@inheritDoc} */ + public void setOrganization(Organization organization) throws IllegalArgumentException { + this.organization = prepareForAssignment(this.organization, organization); + } + + /** {@inheritDoc} */ + public List getContactPersons() { + return contactPersons; + } + + /** {@inheritDoc} */ + public List getKeyDescriptors() { + return keyDescriptors; + } + + /** + * {@inheritDoc} + */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID() { + return id; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (getSignature() != null) { + children.add(getSignature()); + } + + if (extensions != null) { + children.add(getExtensions()); + } + children.addAll(getKeyDescriptors()); + if (organization != null) { + children.add(getOrganization()); + } + children.addAll(getContactPersons()); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,102 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.RoleDescriptor} objects. + */ +public abstract class RoleDescriptorMarshaller extends AbstractSAMLObjectMarshaller { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(RoleDescriptorMarshaller.class); + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + RoleDescriptor roleDescriptor = (RoleDescriptor) samlElement; + + // Set the ID attribute + if (roleDescriptor.getID() != null) { + log.trace("Writing ID attribute to RoleDescriptor DOM element"); + domElement.setAttributeNS(null, RoleDescriptor.ID_ATTRIB_NAME, roleDescriptor.getID()); + domElement.setIdAttributeNS(null, RoleDescriptor.ID_ATTRIB_NAME, true); + } + + // Set the validUntil attribute + if (roleDescriptor.getValidUntil() != null) { + log.trace("Writting validUntil attribute to RoleDescriptor DOM element"); + String validUntilStr = Configuration.getSAMLDateFormatter().print(roleDescriptor.getValidUntil()); + domElement.setAttributeNS(null, TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME, validUntilStr); + } + + // Set the cacheDuration attribute + if (roleDescriptor.getCacheDuration() != null) { + log.trace("Writting cacheDuration attribute to EntitiesDescriptor DOM element"); + String cacheDuration = XMLHelper.longToDuration(roleDescriptor.getCacheDuration()); + domElement.setAttributeNS(null, CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME, cacheDuration); + } + + // Set the protocolSupportEnumeration attribute + List supportedProtocols = roleDescriptor.getSupportedProtocols(); + if (supportedProtocols != null && supportedProtocols.size() > 0) { + log.trace("Writting protocolSupportEnumberation attribute to RoleDescriptor DOM element"); + + StringBuilder builder = new StringBuilder(); + for (String protocol : supportedProtocols) { + builder.append(protocol); + builder.append(" "); + } + + domElement.setAttributeNS(null, RoleDescriptor.PROTOCOL_ENUMERATION_ATTRIB_NAME, builder.toString().trim()); + } + + // Set errorURL attribute + if (roleDescriptor.getErrorURL() != null) { + log.trace("Writting errorURL attribute to RoleDescriptor DOM element"); + domElement.setAttributeNS(null, RoleDescriptor.ERROR_URL_ATTRIB_NAME, roleDescriptor.getErrorURL()); + } + + Attr attribute; + for (Entry entry : roleDescriptor.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || roleDescriptor.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/RoleDescriptorUnmarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.StringTokenizer; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.common.CacheableSAMLObject; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.common.TimeBoundSAMLObject; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.RoleDescriptor} objects. + */ +public abstract class RoleDescriptorUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + RoleDescriptor roleDescriptor = (RoleDescriptor) parentSAMLObject; + + if (childSAMLObject instanceof Extensions) { + roleDescriptor.setExtensions((Extensions) childSAMLObject); + } else if (childSAMLObject instanceof Signature) { + roleDescriptor.setSignature((Signature) childSAMLObject); + } else if (childSAMLObject instanceof KeyDescriptor) { + roleDescriptor.getKeyDescriptors().add((KeyDescriptor) childSAMLObject); + } else if (childSAMLObject instanceof Organization) { + roleDescriptor.setOrganization((Organization) childSAMLObject); + } else if (childSAMLObject instanceof ContactPerson) { + roleDescriptor.getContactPersons().add((ContactPerson) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + RoleDescriptor roleDescriptor = (RoleDescriptor) samlObject; + + if (attribute.getLocalName().equals(RoleDescriptor.ID_ATTRIB_NAME)) { + roleDescriptor.setID(attribute.getValue()); + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME) + && !DatatypeHelper.isEmpty(attribute.getValue())) { + roleDescriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); + } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) { + roleDescriptor.setCacheDuration(XMLHelper.durationToLong(attribute.getValue())); + } else if (attribute.getLocalName().equals(RoleDescriptor.PROTOCOL_ENUMERATION_ATTRIB_NAME)) { + StringTokenizer protocolTokenizer = new StringTokenizer(attribute.getValue(), " "); + while (protocolTokenizer.hasMoreTokens()) { + roleDescriptor.addSupportedProtocol(protocolTokenizer.nextToken()); + } + } else if (attribute.getLocalName().equals(RoleDescriptor.ERROR_URL_ATTRIB_NAME)) { + roleDescriptor.setErrorURL(attribute.getValue()); + } else { + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + roleDescriptor.getUnknownAttributes().registerID(attribQName); + } + roleDescriptor.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorBuilder.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.SPSSODescriptor; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.SPSSODescriptorImpl} + */ +public class SPSSODescriptorBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public SPSSODescriptorBuilder() { + + } + + /** {@inheritDoc} */ + public SPSSODescriptor buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, SPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public SPSSODescriptor buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SPSSODescriptorImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorImpl.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,173 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.support.AttributeConsumingServiceSelector; +import org.opensaml.saml2.metadata.support.SAML2MetadataHelper; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.SPSSODescriptor}. + */ +public class SPSSODescriptorImpl extends SSODescriptorImpl implements SPSSODescriptor { + + /** value for isAuthnRequestSigned attribute. */ + private XSBooleanValue authnRequestSigned; + + /** value for the want assertion signed attribute. */ + private XSBooleanValue assertionSigned; + + /** AssertionConsumerService children. */ + private final XMLObjectChildrenList assertionConsumerServices; + + /** AttributeConsumingService children. */ + private final XMLObjectChildrenList attributeConsumingServices; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SPSSODescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + assertionConsumerServices = new XMLObjectChildrenList(this); + attributeConsumingServices = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Boolean isAuthnRequestsSigned() { + if (authnRequestSigned == null) { + return Boolean.FALSE; + } + return authnRequestSigned.getValue(); + } + + /** {@inheritDoc} */ + public XSBooleanValue isAuthnRequestsSignedXSBoolean() { + return authnRequestSigned; + } + + /** {@inheritDoc} */ + public void setAuthnRequestsSigned(Boolean newIsSigned) { + if(newIsSigned != null){ + authnRequestSigned = prepareForAssignment(authnRequestSigned, new XSBooleanValue(newIsSigned, false)); + }else{ + authnRequestSigned = prepareForAssignment(authnRequestSigned, null); + } + } + + /** {@inheritDoc} */ + public void setAuthnRequestsSigned(XSBooleanValue isSigned) { + authnRequestSigned = prepareForAssignment(authnRequestSigned, isSigned); + } + + /** {@inheritDoc} */ + public Boolean getWantAssertionsSigned() { + if (assertionSigned == null) { + return Boolean.FALSE; + } + return assertionSigned.getValue(); + } + + /** {@inheritDoc} */ + public XSBooleanValue getWantAssertionsSignedXSBoolean() { + return assertionSigned; + } + + /** {@inheritDoc} */ + public void setWantAssertionsSigned(Boolean wantAssestionSigned) { + if(wantAssestionSigned != null){ + assertionSigned = prepareForAssignment(assertionSigned, new XSBooleanValue(wantAssestionSigned, false)); + }else{ + assertionSigned = prepareForAssignment(assertionSigned, null); + } + } + + /** {@inheritDoc} */ + public void setWantAssertionsSigned(XSBooleanValue wantAssestionSigned) { + this.assertionSigned = prepareForAssignment(this.assertionSigned, wantAssestionSigned); + } + + /** {@inheritDoc} */ + public List getAssertionConsumerServices() { + return assertionConsumerServices; + } + + /** {@inheritDoc} */ + public AssertionConsumerService getDefaultAssertionConsumerService() { + return SAML2MetadataHelper.getDefaultIndexedEndpoint(assertionConsumerServices); + } + + /** {@inheritDoc} */ + public List getAttributeConsumingServices() { + return attributeConsumingServices; + } + + /** {@inheritDoc} */ + public AttributeConsumingService getDefaultAttributeConsumingService(){ + AttributeConsumingServiceSelector selector = new AttributeConsumingServiceSelector(); + selector.setRoleDescriptor(this); + return selector.selectService(); + } + + /** {@inheritDoc} */ + public List getEndpoints() { + List endpoints = new ArrayList(); + endpoints.addAll(super.getEndpoints()); + endpoints.addAll(assertionConsumerServices); + return Collections.unmodifiableList(endpoints); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + if(type.equals(AssertionConsumerService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(assertionConsumerServices)); + }else{ + return super.getEndpoints(type); + } + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(assertionConsumerServices); + children.addAll(attributeConsumingServices); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.SPSSODescriptor} objects. + */ +public class SPSSODescriptorMarshaller extends SSODescriptorMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + SPSSODescriptor descriptor = (SPSSODescriptor) samlObject; + + if (descriptor.isAuthnRequestsSignedXSBoolean() != null) { + domElement.setAttributeNS(null, SPSSODescriptor.AUTH_REQUESTS_SIGNED_ATTRIB_NAME, descriptor + .isAuthnRequestsSignedXSBoolean().toString()); + } + + if (descriptor.getWantAssertionsSignedXSBoolean() != null) { + domElement.setAttributeNS(null, SPSSODescriptor.WANT_ASSERTIONS_SIGNED_ATTRIB_NAME, descriptor + .getWantAssertionsSignedXSBoolean().toString()); + } + + super.marshallAttributes(samlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SPSSODescriptorUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.SPSSODescriptor} objects. + */ +public class SPSSODescriptorUnmarshaller extends SSODescriptorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + SPSSODescriptor descriptor = (SPSSODescriptor) parentSAMLObject; + + if (childSAMLObject instanceof AssertionConsumerService) { + descriptor.getAssertionConsumerServices().add((AssertionConsumerService) childSAMLObject); + } else if (childSAMLObject instanceof AttributeConsumingService) { + descriptor.getAttributeConsumingServices().add((AttributeConsumingService) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + SPSSODescriptor descriptor = (SPSSODescriptor) samlObject; + + if (attribute.getLocalName().equals(SPSSODescriptor.AUTH_REQUESTS_SIGNED_ATTRIB_NAME)) { + descriptor.setAuthnRequestsSigned(XSBooleanValue.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(SPSSODescriptor.WANT_ASSERTIONS_SIGNED_ATTRIB_NAME)) { + descriptor.setWantAssertionsSigned(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,136 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.ArtifactResolutionService; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.saml2.metadata.ManageNameIDService; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.SSODescriptor; +import org.opensaml.saml2.metadata.SingleLogoutService; +import org.opensaml.saml2.metadata.support.SAML2MetadataHelper; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.SSODescriptor}. + */ +public abstract class SSODescriptorImpl extends RoleDescriptorImpl implements SSODescriptor { + + /** Supported artifact resolutions services. */ + private final XMLObjectChildrenList artifactResolutionServices; + + /** Logout services for this SSO entity. */ + private final XMLObjectChildrenList singleLogoutServices; + + /** Manage NameID services for this entity. */ + private final XMLObjectChildrenList manageNameIDServices; + + /** NameID formats supported by this entity. */ + private final XMLObjectChildrenList nameIDFormats; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SSODescriptorImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + artifactResolutionServices = new XMLObjectChildrenList(this); + singleLogoutServices = new XMLObjectChildrenList(this); + manageNameIDServices = new XMLObjectChildrenList(this); + nameIDFormats = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getArtifactResolutionServices() { + return artifactResolutionServices; + } + + /** {@inheritDoc} */ + public ArtifactResolutionService getDefaultArtifactResolutionService(){ + return SAML2MetadataHelper.getDefaultIndexedEndpoint(artifactResolutionServices); + } + + /** {@inheritDoc} */ + public ArtifactResolutionService getDefaultArtificateResolutionService(){ + return getDefaultArtifactResolutionService(); + } + + /** {@inheritDoc} */ + public List getSingleLogoutServices() { + return singleLogoutServices; + } + + /** {@inheritDoc} */ + public List getManageNameIDServices() { + return manageNameIDServices; + } + + /** {@inheritDoc} */ + public List getNameIDFormats() { + return nameIDFormats; + } + + /** {@inheritDoc} */ + public List getEndpoints() { + List endpoints = new ArrayList(); + endpoints.addAll(artifactResolutionServices); + endpoints.addAll(singleLogoutServices); + endpoints.addAll(manageNameIDServices); + return Collections.unmodifiableList(endpoints); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + if(type.equals(ArtifactResolutionService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(artifactResolutionServices)); + }else if(type.equals(SingleLogoutService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(singleLogoutServices)); + }else if(type.equals(ManageNameIDService.DEFAULT_ELEMENT_NAME)){ + return Collections.unmodifiableList(new ArrayList(manageNameIDServices)); + } + + return null; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(artifactResolutionServices); + children.addAll(singleLogoutServices); + children.addAll(manageNameIDServices); + children.addAll(nameIDFormats); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorMarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.SSODescriptor} objects. + */ +public abstract class SSODescriptorMarshaller extends RoleDescriptorMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SSODescriptorUnmarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.ArtifactResolutionService; +import org.opensaml.saml2.metadata.ManageNameIDService; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.SSODescriptor; +import org.opensaml.saml2.metadata.SingleLogoutService; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.SSODescriptor} objects. + */ +public abstract class SSODescriptorUnmarshaller extends RoleDescriptorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentElement, XMLObject childElement) throws UnmarshallingException { + SSODescriptor descriptor = (SSODescriptor) parentElement; + if (childElement instanceof ArtifactResolutionService) { + descriptor.getArtifactResolutionServices().add((ArtifactResolutionService) childElement); + } else if (childElement instanceof SingleLogoutService) { + descriptor.getSingleLogoutServices().add((SingleLogoutService) childElement); + } else if (childElement instanceof ManageNameIDService) { + descriptor.getManageNameIDServices().add((ManageNameIDService) childElement); + } else if (childElement instanceof NameIDFormat) { + descriptor.getNameIDFormats().add((NameIDFormat) childElement); + } else { + super.processChildElement(parentElement, childElement); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionBuilder.java 17 Aug 2012 15:03:06 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.ServiceDescription; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.ServiceDescriptionImpl} + */ +public class ServiceDescriptionBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ServiceDescriptionBuilder() { + + } + + /** {@inheritDoc} */ + public ServiceDescription buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, ServiceDescription.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public ServiceDescription buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ServiceDescriptionImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionImpl.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.ServiceDescription; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.ServiceDescription}. + */ +public class ServiceDescriptionImpl extends AbstractSAMLObject implements ServiceDescription { + + /** Service description */ + private LocalizedString description; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected ServiceDescriptionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getDescription() { + return description; + } + + /** {@inheritDoc} */ + public void setDescription(LocalizedString newDescription) { + description = prepareForAssignment(description, newDescription); + boolean hasXMLLang = false; + if (description != null && !DatatypeHelper.isEmpty(description.getLanguage())) { + hasXMLLang = true; + } + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasXMLLang); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.ServiceDescription; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.ServiceDescription} objects. + */ +public class ServiceDescriptionMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + ServiceDescription description = (ServiceDescription) samlObject; + + if (description.getDescription() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + ServiceDescription.LANG_ATTRIB_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(description.getDescription().getLanguage()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + ServiceDescription description = (ServiceDescription) samlObject; + + if (description.getDescription() != null) { + XMLHelper.appendTextContent(domElement, description.getDescription().getLocalString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceDescriptionUnmarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.ServiceDescription; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.ServiceDescription} objects. + */ +public class ServiceDescriptionUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + QName attribName = XMLHelper.getNodeQName(attribute); + if (LangBearing.XML_LANG_ATTR_NAME.equals(attribName)) { + ServiceDescription description = (ServiceDescription) samlObject; + + LocalizedString descStr = description.getDescription(); + if (descStr == null) { + descStr = new LocalizedString(); + } + + descStr.setLanguage(attribute.getValue()); + description.setDescription(descStr); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + ServiceDescription description = (ServiceDescription) samlObject; + + LocalizedString descStr = description.getDescription(); + if (descStr == null) { + descStr = new LocalizedString(); + } + + descStr.setLocalizedString(elementContent); + description.setDescription(descStr); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameBuilder.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.ServiceName; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.ServiceNameImpl} + */ +public class ServiceNameBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public ServiceNameBuilder() { + + } + + /** {@inheritDoc} */ + public ServiceName buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, ServiceName.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public ServiceName buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ServiceNameImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameImpl.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.ServiceName} + */ +public class ServiceNameImpl extends AbstractSAMLObject implements ServiceName { + + /** Service name */ + private LocalizedString name; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected ServiceNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(LocalizedString newName) { + name = prepareForAssignment(name, newName); + boolean hasXMLLang = false; + if (name != null && !DatatypeHelper.isEmpty(name.getLanguage())) { + hasXMLLang = true; + } + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasXMLLang); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameMarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.ServiceName} objects. + */ +public class ServiceNameMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + ServiceName name = (ServiceName) samlObject; + + if (name.getName() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + ServiceName.LANG_ATTRIB_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(name.getName().getLanguage()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + ServiceName name = (ServiceName) samlObject; + + if (name.getName() != null) { + XMLHelper.appendTextContent(domElement, name.getName().getLocalString()); + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/ServiceNameUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.ServiceName} objects. + */ +public class ServiceNameUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + QName attribName = XMLHelper.getNodeQName(attribute); + if (LangBearing.XML_LANG_ATTR_NAME.equals(attribName)) { + ServiceName name = (ServiceName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLanguage(attribute.getValue()); + name.setName(nameStr); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + ServiceName name = (ServiceName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLocalizedString(elementContent); + name.setName(nameStr); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceBuilder.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.SingleLogoutService; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.SingleLogoutServiceImpl}. + */ +public class SingleLogoutServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public SingleLogoutServiceBuilder() { + + } + + /** {@inheritDoc} */ + public SingleLogoutService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, SingleLogoutService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public SingleLogoutService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SingleLogoutServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceImpl.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.SingleLogoutService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.SingleLogoutService}. + */ +public class SingleLogoutServiceImpl extends EndpointImpl implements SingleLogoutService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected SingleLogoutServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceMarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.SingleLogoutService} objects. + */ +public class SingleLogoutServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleLogoutServiceUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.SingleLogoutService} objects. + */ +public class SingleLogoutServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceBuilder.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.SingleSignOnService; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.SingleSignOnServiceImpl}. + */ +public class SingleSignOnServiceBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public SingleSignOnServiceBuilder() { + + } + + /** {@inheritDoc} */ + public SingleSignOnService buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, SingleSignOnService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public SingleSignOnService buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SingleSignOnServiceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceImpl.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.saml2.metadata.SingleSignOnService; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.SingleSignOnService}. + */ +public class SingleSignOnServiceImpl extends EndpointImpl implements SingleSignOnService { + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected SingleSignOnServiceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceMarshaller.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.SingleSignOnService} objects. + */ +public class SingleSignOnServiceMarshaller extends EndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SingleSignOnServiceUnmarshaller.java 17 Aug 2012 15:03:11 -0000 1.1 @@ -0,0 +1,29 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +/** + * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.SingleSignOnService} objects. + */ +public class SingleSignOnServiceUnmarshaller extends EndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameBuilder.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.SurName; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.SurNameImpl} + */ +public class SurNameBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public SurNameBuilder() { + + } + + /** {@inheritDoc} */ + public SurName buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, SurName.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public SurName buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SurNameImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameImpl.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.SurName; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.SurName} + */ +public class SurNameImpl extends AbstractSAMLObject implements SurName { + + /** Service name */ + private String name; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected SurNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(String newName) { + name = prepareForAssignment(name, newName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameMarshaller.java 17 Aug 2012 15:03:09 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.SurName; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.SurName} objects. + */ +public class SurNameMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + SurName name = (SurName) samlObject; + + if (name.getName() != null) { + XMLHelper.appendTextContent(domElement, name.getName()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/SurNameUnmarshaller.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.SurName; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.SurName} objects. + */ +public class SurNameUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + SurName name = (SurName) samlObject; + + name.setName(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberBuilder.java 17 Aug 2012 15:03:07 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.TelephoneNumber; + +/** + * Builder of {@link org.opensaml.saml2.metadata.impl.TelephoneNumberImpl} + */ +public class TelephoneNumberBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor + */ + public TelephoneNumberBuilder() { + + } + + /** {@inheritDoc} */ + public TelephoneNumber buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, TelephoneNumber.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public TelephoneNumber buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new TelephoneNumberImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberImpl.java 17 Aug 2012 15:03:12 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.TelephoneNumber; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.saml2.metadata.TelephoneNumber} + */ +public class TelephoneNumberImpl extends AbstractSAMLObject implements TelephoneNumber { + + /** Telephone number */ + private String number; + + /** + * Constructor + * + * @param namespaceURI + * @param elementLocalName + * @param namespacePrefix + */ + protected TelephoneNumberImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getNumber() { + return number; + } + + /** {@inheritDoc} */ + public void setNumber(String newNumber) { + number = prepareForAssignment(number, newNumber); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberMarshaller.java 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.saml2.metadata.TelephoneNumber; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.saml2.metadata.TelephoneNumber} objects. + */ +public class TelephoneNumberMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + TelephoneNumber number = (TelephoneNumber) samlObject; + + if (number.getNumber() != null) { + XMLHelper.appendTextContent(domElement, number.getNumber()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/TelephoneNumberUnmarshaller.java 17 Aug 2012 15:03:10 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.saml2.metadata.TelephoneNumber; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.saml2.metadata.TelephoneNumber} objects. + */ +public class TelephoneNumberUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + TelephoneNumber number = (TelephoneNumber) samlObject; + + number.setNumber(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/impl/package.html 17 Aug 2012 15:03:08 -0000 1.1 @@ -0,0 +1,14 @@ + + +Implementations of the SAML 2.0 metadata specification types and elements. +

+ +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,644 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.common.SAML2Helper; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.parse.ParserPool; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** An abstract, base, implementation of a metadata provider. */ +public abstract class AbstractMetadataProvider extends BaseMetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(AbstractMetadataProvider.class); + + /** Whether the metadata provider has been initialized. */ + private boolean initialized; + + /** + * Whether problems during initialization should cause the provider to fail or go on without metadata. The + * assumption being that in most cases a provider will recover at some point in the future. Default: true. + */ + private boolean failFastInitialization; + + /** Cache of entity IDs to their descriptors. */ + private Map indexedDescriptors; + + /** Pool of parsers used to process XML. */ + private ParserPool parser; + + /** Constructor. */ + public AbstractMetadataProvider() { + super(); + indexedDescriptors = new ConcurrentHashMap(); + failFastInitialization = true; + initialized = false; + } + + /** {@inheritDoc} */ + public XMLObject getMetadata() throws MetadataProviderException { + if (!isInitialized()) { + throw new MetadataProviderException("Metadata provider has not been initialized"); + } + + XMLObject metadata = doGetMetadata(); + + if (metadata == null) { + log.debug("Metadata provider does not currently contain any metadata"); + } + + if (!isValid(metadata)) { + log.debug("Metadata document exists, but it is no longer valid"); + return null; + } + + return metadata; + } + + /** + * Gets the metadata currently held by the provider. This method should not check if the provider is initialized, if + * the metadata is valid, etc. All of this is done by the invoker of this method. + * + * @return the metadata currently held by this provider or null if no metadata is available + * + * @throws MetadataProviderException thrown if there is a problem retrieving the metadata + */ + protected abstract XMLObject doGetMetadata() throws MetadataProviderException; + + /** {@inheritDoc} */ + public EntitiesDescriptor getEntitiesDescriptor(String name) throws MetadataProviderException { + if (!isInitialized()) { + throw new MetadataProviderException("Metadata provider has not been initialized"); + } + + if (DatatypeHelper.isEmpty(name)) { + log.debug("EntitiesDescriptor name was null or empty, skipping search for it"); + return null; + } + + EntitiesDescriptor descriptor = doGetEntitiesDescriptor(name); + if (descriptor == null) { + log.debug("Metadata document does not contain an EntitiesDescriptor with the name {}", name); + return null; + } else if (!isValid(descriptor)) { + log.debug("Metadata document contained an EntitiesDescriptor with the name {}, but it was no longer valid", + name); + return null; + } + + return descriptor; + } + + /** + * Gets the named EntitiesDescriptor from the metadata. This method should not check if the provider is initialized, + * if arguments are null, if metadata is valid, etc. All of this is done by the invoker of this method. + * + * @param name the name of the EntitiesDescriptor, never null + * + * @return the named EntitiesDescriptor or null if no such EntitiesDescriptor exists + * + * @throws MetadataProviderException thrown if there is a problem searching for the EntitiesDescriptor + */ + protected EntitiesDescriptor doGetEntitiesDescriptor(String name) throws MetadataProviderException { + XMLObject metadata = doGetMetadata(); + if (metadata == null) { + log.debug("Metadata provider does not currently contain any metadata, unable to look for an EntitiesDescriptor with the name {}", + name); + return null; + } + + EntitiesDescriptor descriptor = null; + if (metadata instanceof EntitiesDescriptor) { + descriptor = getEntitiesDescriptorByName(name, (EntitiesDescriptor) metadata); + } + + return descriptor; + } + + /** {@inheritDoc} */ + public EntityDescriptor getEntityDescriptor(String entityID) throws MetadataProviderException { + if (!isInitialized()) { + throw new MetadataProviderException("Metadata provider has not been initialized"); + } + + if (DatatypeHelper.isEmpty(entityID)) { + log.debug("EntityDescriptor entityID was null or empty, skipping search for it"); + return null; + } + + EntityDescriptor descriptor = doGetEntityDescriptor(entityID); + if (descriptor == null) { + log.debug("Metadata document does not contain an EntityDescriptor with the ID {}", entityID); + return null; + } else if (!isValid(descriptor)) { + log.debug("Metadata document contained an EntityDescriptor with the ID {}, but it was no longer valid", + entityID); + return null; + } + + return descriptor; + } + + /** + * Gets the identified EntityDescriptor from the metadata. This method should not check if the provider is + * initialized, if arguments are null, if the metadata is valid, etc. All of this is done by the invoker of this + * method. + * + * @param entityID ID of the EntityDescriptor, never null + * + * @return the identified EntityDescriptor or null if no such EntityDescriptor exists + * + * @throws MetadataProviderException thrown if there is a problem searching for the EntityDescriptor + */ + protected EntityDescriptor doGetEntityDescriptor(String entityID) throws MetadataProviderException { + XMLObject metadata = doGetMetadata(); + if (metadata == null) { + log.debug("Metadata document was empty, unable to look for an EntityDescriptor with the ID {}", entityID); + return null; + } + + return getEntityDescriptorById(entityID, metadata); + } + + /** {@inheritDoc} */ + public List getRole(String entityID, QName roleName) throws MetadataProviderException { + if (!isInitialized()) { + throw new MetadataProviderException("Metadata provider has not been initialized"); + } + + if (DatatypeHelper.isEmpty(entityID)) { + log.debug("EntityDescriptor entityID was null or empty, skipping search for roles"); + return null; + } + + if (roleName == null) { + log.debug("Role descriptor name was null, skipping search for roles"); + return null; + } + + List roleDescriptors = doGetRole(entityID, roleName); + if (roleDescriptors == null || roleDescriptors.isEmpty()) { + log.debug("Entity descriptor {} did not contain any {} roles", entityID, roleName); + return null; + } + + Iterator roleDescItr = roleDescriptors.iterator(); + while (roleDescItr.hasNext()) { + if (!isValid(roleDescItr.next())) { + log.debug("Metadata document contained a role of type {} for entity {}, but it was invalid", roleName, + entityID); + roleDescItr.remove(); + } + } + + if (roleDescriptors.isEmpty()) { + log.debug("Entity descriptor {} did not contain any valid {} roles", entityID, roleName); + } + return roleDescriptors; + } + + /** + * Gets the identified roles from an EntityDescriptor. This method should not check if the provider is initialized, + * if arguments are null, if the roles are valid, etc. All of this is done by the invoker of this method. + * + * @param entityID ID of the entity from which to retrieve the roles, never null + * @param roleName name of the roles to search for, never null + * + * @return the modifiable list of identified roles or an empty list if no roles exists + * + * @throws MetadataProviderException thrown if there is a problem searching for the roles + */ + protected List doGetRole(String entityID, QName roleName) throws MetadataProviderException { + EntityDescriptor entity = doGetEntityDescriptor(entityID); + if (entity == null) { + log.debug("Metadata document did not contain a descriptor for entity {}", entityID); + return Collections.emptyList(); + } + + List descriptors = entity.getRoleDescriptors(roleName); + if (descriptors != null && !descriptors.isEmpty()) { + return new ArrayList(descriptors); + } + + return Collections.emptyList(); + } + + /** {@inheritDoc} */ + public RoleDescriptor getRole(String entityID, QName roleName, String supportedProtocol) + throws MetadataProviderException { + if (!isInitialized()) { + throw new MetadataProviderException("Metadata provider has not been initialized"); + } + + if (DatatypeHelper.isEmpty(entityID)) { + log.debug("EntityDescriptor entityID was null or empty, skipping search for role"); + return null; + } + + if (roleName == null) { + log.debug("Role descriptor name was null, skipping search for role"); + return null; + } + + if (DatatypeHelper.isEmpty(supportedProtocol)) { + log.debug("Supported protocol was null, skipping search for role."); + return null; + } + + RoleDescriptor role = doGetRole(entityID, roleName, supportedProtocol); + if (role == null) { + log.debug("Metadata document does not contain a role of type {} supporting protocol {} for entity {}", + new Object[] { roleName, supportedProtocol, entityID }); + return null; + } + + if (!isValid(role)) { + log + .debug( + "Metadata document contained a role of type {} supporting protocol {} for entity {}, but it was not longer valid", + new Object[] { roleName, supportedProtocol, entityID }); + return null; + } + + return role; + } + + /** + * Gets the role which supports the given protocol. + * + * @param entityID ID of the entity from which to retrieve roles, never null + * @param roleName name of the role to search for, never null + * @param supportedProtocol protocol to search for, never null + * + * @return the role supporting the protocol or null if no such role exists + * + * @throws MetadataProviderException thrown if there is a problem search for the roles + */ + protected RoleDescriptor doGetRole(String entityID, QName roleName, String supportedProtocol) + throws MetadataProviderException { + List roles = doGetRole(entityID, roleName); + if (roles == null || roles.isEmpty()) { + log.debug("Metadata document did not contain any role descriptors of type {} for entity {}", roleName, + entityID); + return null; + } + + Iterator rolesItr = roles.iterator(); + RoleDescriptor role = null; + while (rolesItr.hasNext()) { + role = rolesItr.next(); + if (role != null && role.isSupportedProtocol(supportedProtocol)) { + return role; + } + } + + return null; + } + + /** + * Gets whether this provider is initialized. + * + * @return whether this provider is initialized + */ + public boolean isInitialized() { + return initialized; + } + + /** + * Sets whether this provider is initialized. + * + * @param isInitialized whether this provider is initialized + */ + protected void setInitialized(boolean isInitialized) { + initialized = isInitialized; + } + + /** + * Gets whether problems during initialization should cause the provider to fail or go on without metadata. The + * assumption being that in most cases a provider will recover at some point in the future. + * + * @return whether problems during initialization should cause the provider to fail + */ + public boolean isFailFastInitialization() { + return failFastInitialization; + } + + /** + * Sets whether problems during initialization should cause the provider to fail or go on without metadata. The + * assumption being that in most cases a provider will recover at some point in the future. + * + * @param failFast whether problems during initialization should cause the provider to fail + */ + public void setFailFastInitialization(boolean failFast) { + if (isInitialized()) { + return; + } + + failFastInitialization = failFast; + } + + /** + * Gets the pool of parsers to use to parse XML. + * + * @return pool of parsers to use to parse XML + */ + public ParserPool getParserPool() { + return parser; + } + + /** + * Sets the pool of parsers to use to parse XML. + * + * @param pool pool of parsers to use to parse XML + */ + public void setParserPool(ParserPool pool) { + parser = pool; + } + + /** + * Initializes this metadata provider. If called after the metadata provider has already been initialized this + * method simply returns. + * + * @throws MetadataProviderException thrown if there is a problem initializing the problem and fail fast + * Initialization is enabled + */ + public synchronized void initialize() throws MetadataProviderException { + if (initialized) { + return; + } + + try { + doInitialization(); + initialized = true; + } catch (MetadataProviderException e) { + if (failFastInitialization) { + log.error("Metadata provider failed to properly initializing, halting", e); + throw e; + } else { + log.error("Metadata provider failed to properly initializing, continuing on without metadata", e); + } + } + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + initialized = false; + indexedDescriptors = Collections.emptyMap(); + parser = null; + + super.destroy(); + } + + /** + * Subclasses should override this method to perform any initialization logic necessary. Default implementation is a + * no-op. + * + * @throws MetadataProviderException thrown if there is a problem initializing the provider + */ + protected void doInitialization() throws MetadataProviderException { + + } + + /** + * Clears the entity ID to entity descriptor index. + */ + protected void clearDescriptorIndex() { + indexedDescriptors.clear(); + } + + /** + * Unmarshalls the metadata from the given stream. The stream is closed by this method and the returned metadata + * released its DOM representation. + * + * @param metadataInput the input reader to the metadata. + * + * @return the unmarshalled metadata + * + * @throws UnmarshallingException thrown if the metadata can no be unmarshalled + */ + protected XMLObject unmarshallMetadata(InputStream metadataInput) throws UnmarshallingException { + try { + log.trace("Parsing retrieved metadata into a DOM object"); + Document mdDocument = parser.parse(metadataInput); + + log.trace("Unmarshalling and caching metdata DOM"); + Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(mdDocument.getDocumentElement()); + if (unmarshaller == null) { + String msg ="No unmarshaller registered for document element " + XMLHelper + .getNodeQName(mdDocument.getDocumentElement()); + log.error(msg); + throw new UnmarshallingException(msg); + } + XMLObject metadata = unmarshaller.unmarshall(mdDocument.getDocumentElement()); + return metadata; + } catch (Exception e) { + throw new UnmarshallingException(e); + } finally { + try { + metadataInput.close(); + } catch (IOException e) { + // ignore + } + } + } + + /** + * Filters the given metadata. + * + * @param metadata the metadata to be filtered + * + * @throws FilterException thrown if there is an error filtering the metadata + */ + protected void filterMetadata(XMLObject metadata) throws FilterException { + if (getMetadataFilter() != null) { + log.debug("Applying metadata filter"); + getMetadataFilter().doFilter(metadata); + } + } + + /** + * Releases the DOM representation from the metadata object. + * + * @param metadata the metadata object + */ + protected void releaseMetadataDOM(XMLObject metadata) { + if (metadata != null) { + metadata.releaseDOM(); + metadata.releaseChildrenDOM(true); + } + } + + /** + * Gets the EntityDescriptor with the given ID from the cached metadata. + * + * @param entityID the ID of the entity to get the descriptor for + * @param metadata metadata associated with the entity + * + * @return the EntityDescriptor + */ + protected EntityDescriptor getEntityDescriptorById(String entityID, XMLObject metadata) { + EntityDescriptor descriptor = null; + + log.debug("Searching for entity descriptor with an entity ID of {}", entityID); + if (entityID != null && indexedDescriptors.containsKey(entityID)) { + descriptor = indexedDescriptors.get(entityID); + if (isValid(descriptor)) { + log.trace("Entity descriptor for the ID {} was found in index cache, returning", entityID); + return descriptor; + } else { + indexedDescriptors.remove(descriptor); + } + } + + if (metadata != null) { + if (metadata instanceof EntityDescriptor) { + log.trace("Metadata root is an entity descriptor, checking if it's the one we're looking for."); + descriptor = (EntityDescriptor) metadata; + if (!DatatypeHelper.safeEquals(descriptor.getEntityID(), entityID)) { + // skip this one, it isn't what we're looking for + descriptor = null; + } + if (!isValid(descriptor)) { + log.trace("Found entity descriptor for entity with ID {} but it is no longer valid, skipping it.", + entityID); + descriptor = null; + } + } else { + log + .trace("Metadata was an EntitiesDescriptor, checking if any of its descendant EntityDescriptor elements is the one we're looking for."); + if (metadata instanceof EntitiesDescriptor) { + descriptor = getEntityDescriptorById(entityID, (EntitiesDescriptor) metadata); + } + } + } + + if (descriptor != null) { + log.trace("Located entity descriptor, creating an index to it for faster lookups"); + indexedDescriptors.put(entityID, descriptor); + } + + return descriptor; + } + + /** + * Gets the entity descriptor with the given ID that is a descendant of the given entities descriptor. + * + * @param entityID the ID of the entity whose descriptor is to be fetched + * @param descriptor the entities descriptor + * + * @return the entity descriptor + */ + protected EntityDescriptor getEntityDescriptorById(String entityID, EntitiesDescriptor descriptor) { + log.trace("Checking to see if EntitiesDescriptor {} contains the requested descriptor", descriptor.getName()); + List entityDescriptors = descriptor.getEntityDescriptors(); + if (entityDescriptors != null && !entityDescriptors.isEmpty()) { + for (EntityDescriptor entityDescriptor : entityDescriptors) { + log.trace("Checking entity descriptor with entity ID {}", entityDescriptor.getEntityID()); + if (DatatypeHelper.safeEquals(entityDescriptor.getEntityID(), entityID) && isValid(entityDescriptor)) { + return entityDescriptor; + } + } + } + + log.trace("Checking to see if any of the child entities descriptors contains the entity descriptor requested"); + EntityDescriptor entityDescriptor; + List entitiesDescriptors = descriptor.getEntitiesDescriptors(); + if (entitiesDescriptors != null && !entitiesDescriptors.isEmpty()) { + for (EntitiesDescriptor entitiesDescriptor : descriptor.getEntitiesDescriptors()) { + entityDescriptor = getEntityDescriptorById(entityID, entitiesDescriptor); + if (entityDescriptor != null) { + // We don't need to check for validity because getEntityDescriptorById only returns a valid + // descriptor + return entityDescriptor; + } + } + } + + return null; + } + + /** + * Gets the entities descriptor with the given name. + * + * @param name name of the entities descriptor + * @param rootDescriptor the root descriptor to search in + * + * @return the EntitiesDescriptor with the given name + */ + protected EntitiesDescriptor getEntitiesDescriptorByName(String name, EntitiesDescriptor rootDescriptor) { + EntitiesDescriptor descriptor = null; + + if (DatatypeHelper.safeEquals(name, rootDescriptor.getName()) && isValid(rootDescriptor)) { + descriptor = rootDescriptor; + } else { + List childDescriptors = rootDescriptor.getEntitiesDescriptors(); + if (childDescriptors == null || childDescriptors.isEmpty()) { + return null; + } + + for (EntitiesDescriptor childDescriptor : childDescriptors) { + childDescriptor = getEntitiesDescriptorByName(name, childDescriptor); + if (childDescriptor != null) { + descriptor = childDescriptor; + } + } + } + + return descriptor; + } + + /** + * Returns whether the given descriptor is valid. If valid metadata is not required this method always returns true. + * + * @param descriptor the descriptor to check + * + * @return true if valid metadata is not required or the given descriptor is valid, false otherwise + */ + protected boolean isValid(XMLObject descriptor) { + if (descriptor == null) { + return false; + } + + if (!requireValidMetadata()) { + return true; + } + + return SAML2Helper.isValid(descriptor); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractObservableMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractObservableMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractObservableMetadataProvider.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * An observable base implementation of metadata providers. An observer that clears the descriptor index kept by + * {@link AbstractMetadataProvider} is registered during construction time. + */ +public abstract class AbstractObservableMetadataProvider extends AbstractMetadataProvider implements + ObservableMetadataProvider { + + /** List of registered observers. */ + private List observers; + + /** Constructor. */ + public AbstractObservableMetadataProvider() { + super(); + observers = new CopyOnWriteArrayList(); + observers.add(new DescriptorIndexClearingObserver()); + } + + /** {@inheritDoc} */ + public List getObservers() { + return observers; + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + observers = Collections.emptyList(); + + super.destroy(); + } + + /** + * Helper method for calling + * {@link org.opensaml.saml2.metadata.provider.ObservableMetadataProvider.Observer#onEvent(MetadataProvider)} on + * every registered Observer passing in this provider. + */ + protected void emitChangeEvent() { + synchronized (observers) { + for (Observer observer : observers) { + if (observer != null) { + observer.onEvent(this); + } + } + } + } + + /** + * Observer that clears the descriptor index of this provider. + */ + private class DescriptorIndexClearingObserver implements Observer { + + /** {@inheritDoc} */ + public void onEvent(MetadataProvider provider) { + ((AbstractMetadataProvider) provider).clearDescriptorIndex(); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractReloadingMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractReloadingMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/AbstractReloadingMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,515 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Timer; +import java.util.TimerTask; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.saml2.common.SAML2Helper; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * Base class for metadata providers that cache and periodically refresh their metadata. + * + * This metadata provider periodically checks to see if the read metadata file has changed. The delay between each + * refresh interval is calculated as follows. If no validUntil or cacheDuration is present then the + * {@link #getMaxRefreshDelay()} value is used. Otherwise, the earliest refresh interval of the metadata file is checked + * by looking for the earliest of all the validUntil attributes and cacheDuration attributes. If that refresh interval + * is larger than the max refresh delay then {@link #getMaxRefreshDelay()} is used. If that number is smaller than the + * min refresh delay then {@link #getMinRefreshDelay()} is used. Otherwise the calculated refresh delay multiplied by + * {@link #getRefreshDelayFactor()} is used. By using this factor, the provider will attempt to be refresh before the + * cache actually expires, allowing a some room for error and recovery. Assuming the factor is not exceedingly close to + * 1.0 and a min refresh delay that is not overly large, this refresh will likely occur a few times before the cache + * expires. + */ +public abstract class AbstractReloadingMetadataProvider extends AbstractObservableMetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(AbstractReloadingMetadataProvider.class); + + /** Timer used to schedule background metadata update tasks. */ + private Timer taskTimer; + + /** Whether we created our own task timer during object construction. */ + private boolean createdOwnTaskTimer; + + /** Current task to refresh metadata. */ + private RefreshMetadataTask refresMetadataTask; + + /** Factor used to compute when the next refresh interval will occur. Default value: {@value} */ + private float refreshDelayFactor = 0.75f; + + /** + * Refresh interval used when metadata does not contain any validUntil or cacheDuration information. Default value: + * * {@value} ms + */ + private long maxRefreshDelay = 14400000; + + /** Floor, in milliseconds, for the refresh interval. Default value: {@value} ms */ + private int minRefreshDelay = 300000; + + /** Time when the currently cached metadata file expires. */ + private DateTime expirationTime; + + /** Last time the metadata was updated. */ + private DateTime lastUpdate; + + /** Last time a refresh cycle occurred. */ + private DateTime lastRefresh; + + /** Next time a refresh cycle will occur. */ + private DateTime nextRefresh; + + /** Last successfully read in metadata. */ + private XMLObject cachedMetadata; + + /** Constructor. */ + protected AbstractReloadingMetadataProvider() { + taskTimer = new Timer(true); + createdOwnTaskTimer = true; + } + + /** + * Constructor. + * + * @param backgroundTaskTimer time used to schedule background refresh tasks + */ + protected AbstractReloadingMetadataProvider(Timer backgroundTaskTimer) { + if (backgroundTaskTimer == null) { + throw new IllegalArgumentException("Task timer may not be null"); + } + taskTimer = backgroundTaskTimer; + } + + /** + * Gets the time when the currently cached metadata expires. + * + * @return time when the currently cached metadata expires, or null if no metadata is cached + */ + public DateTime getExpirationTime() { + return expirationTime; + } + + /** + * Gets the time that the currently available metadata was last updated. Note, this may be different than the time + * retrieved by {@link #getLastUpdate()} is the metadata was known not to have changed during the last refresh + * cycle. + * + * @return time when the currently metadata was last update, 0 if metadata has never successfully been read in + */ + public DateTime getLastUpdate() { + return lastUpdate; + } + + /** + * Gets the time the last refresh cycle occurred. + * + * @return time the last refresh cycle occurred + */ + public DateTime getLastRefresh() { + return lastRefresh; + } + + /** + * Gets the time when the next refresh cycle will occur. + * + * @return time when the next refresh cycle will occur + */ + public DateTime getNextRefresh() { + return nextRefresh; + } + + /** + * Gets the maximum amount of time, in milliseconds, between refresh intervals. + * + * @return maximum amount of time between refresh intervals + */ + public long getMaxRefreshDelay() { + return maxRefreshDelay; + } + + /** + * Sets the maximum amount of time, in milliseconds, between refresh intervals. + * + * @param delay maximum amount of time, in milliseconds, between refresh intervals + */ + public void setMaxRefreshDelay(long delay) { + if (delay < 0) { + throw new IllegalArgumentException("Maximum refresh delay must be greater than 0"); + } + maxRefreshDelay = delay; + } + + /** + * Gets the delay factor used to compute the next refresh time. + * + * @return delay factor used to compute the next refresh time + */ + public float getRefreshDelayFactor() { + return refreshDelayFactor; + } + + /** + * Sets the delay factor used to compute the next refresh time. The delay must be between 0.0 and 1.0, exclusive. + * + * @param factor delay factor used to compute the next refresh time + */ + public void setRefreshDelayFactor(float factor) { + if (factor <= 0 || factor >= 1) { + throw new IllegalArgumentException("Refresh delay factor must be a number between 0.0 and 1.0, exclusive"); + } + + refreshDelayFactor = factor; + } + + /** + * Gets the minimum amount of time, in milliseconds, between refreshes. + * + * @return minimum amount of time, in milliseconds, between refreshes + */ + public int getMinRefreshDelay() { + return minRefreshDelay; + } + + /** + * Sets the minimum amount of time, in milliseconds, between refreshes. + * + * @param delay minimum amount of time, in milliseconds, between refreshes + */ + public void setMinRefreshDelay(int delay) { + if (delay < 0) { + throw new IllegalArgumentException("Minimum refresh delay must be greater than 0"); + } + minRefreshDelay = delay; + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + refresMetadataTask.cancel(); + + if (createdOwnTaskTimer) { + taskTimer.cancel(); + } + + expirationTime = null; + lastRefresh = null; + lastUpdate = null; + nextRefresh = null; + cachedMetadata = null; + + super.destroy(); + } + + /** {@inheritDoc} */ + protected XMLObject doGetMetadata() throws MetadataProviderException { + return cachedMetadata; + } + + /** {@inheritDoc} */ + protected void doInitialization() throws MetadataProviderException { + refresh(); + + if (minRefreshDelay > maxRefreshDelay) { + throw new MetadataProviderException("Minimum refresh delay " + minRefreshDelay + + " is greater than maximum refresh delay " + maxRefreshDelay); + } + } + + /** + * Refreshes the metadata from its source. + * + * @throws MetadataProviderException thrown is there is a problem retrieving and processing the metadata + */ + public void refresh() throws MetadataProviderException { + DateTime now = new DateTime(ISOChronology.getInstanceUTC()); + String mdId = getMetadataIdentifier(); + + log.debug("Beginning refresh of metadata from '{}'", mdId); + try { + byte[] mdBytes = fetchMetadata(); + if (mdBytes == null) { + log.debug("Metadata from '{}' has not changed since last refresh", mdId); + processCachedMetadata(mdId, now); + } else { + log.debug("Processing new metadata from '{}'", mdId); + processNewMetadata(mdId, now, mdBytes); + } + } catch (Exception e) { + log.debug("Error occurred while attempting to refresh metadata from '{}'", e); + nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(minRefreshDelay); + throw new MetadataProviderException(e); + } finally { + refresMetadataTask = new RefreshMetadataTask(); + long nextRefreshDelay = nextRefresh.getMillis() - System.currentTimeMillis(); + taskTimer.schedule(refresMetadataTask, nextRefreshDelay); + log.info("Next refresh cycle for metadata provider '{}' will occur on '{}' ('{}' local time)", + new Object[] {mdId, nextRefresh, nextRefresh.toDateTime(DateTimeZone.getDefault()),}); + lastRefresh = now; + } + } + + /** + * Gets an identifier which may be used to distinguish this metadata in logging statements. + * + * @return identifier which may be used to distinguish this metadata in logging statements + */ + protected abstract String getMetadataIdentifier(); + + /** + * Fetches metadata from a source. + * + * @return the fetched metadata, or null if the metadata is known not to have changed since the last retrieval + * + * @throws MetadataProviderException thrown if there is a problem fetching the metadata + */ + protected abstract byte[] fetchMetadata() throws MetadataProviderException; + + /** + * Unmarshalls the given metadata bytes. + * + * @param metadataBytes raw metadata bytes + * + * @return the metadata + * + * @throws MetadataProviderException thrown if the metadata can not be unmarshalled + */ + protected XMLObject unmarshallMetadata(byte[] metadataBytes) throws MetadataProviderException { + try { + return unmarshallMetadata(new ByteArrayInputStream(metadataBytes)); + } catch (UnmarshallingException e) { + String errorMsg = "Unable to unmarshall metadata"; + log.error(errorMsg, e); + throw new MetadataProviderException(errorMsg, e); + } + } + + /** + * Processes a cached metadata document in order to determine, and schedule, the next time it should be refreshed. + * + * @param metadataIdentifier identifier of the metadata source + * @param refreshStart when the current refresh cycle started + * + * @throws MetadataProviderException throw is there is a problem process the cached metadata + */ + protected void processCachedMetadata(String metadataIdentifier, DateTime refreshStart) + throws MetadataProviderException { + log.debug("Computing new expiration time for cached metadata from '{}", metadataIdentifier); + DateTime metadataExpirationTime = + SAML2Helper + .getEarliestExpiration(cachedMetadata, refreshStart.plus(getMaxRefreshDelay()), refreshStart); + + expirationTime = metadataExpirationTime; + long nextRefreshDelay = computeNextRefreshDelay(expirationTime); + nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(nextRefreshDelay); + } + + /** + * Process a new metadata document. Processing include unmarshalling and filtering metadata, determining the next + * time is should be refreshed and scheduling the next refresh cycle. + * + * @param metadataIdentifier identifier of the metadata source + * @param refreshStart when the current refresh cycle started + * @param metadataBytes raw bytes of the new metadata document + * + * @throws MetadataProviderException thrown if there is a problem unmarshalling or filtering the new metadata + */ + protected void processNewMetadata(String metadataIdentifier, DateTime refreshStart, byte[] metadataBytes) + throws MetadataProviderException { + log.debug("Unmarshalling metadata from '{}'", metadataIdentifier); + XMLObject metadata = unmarshallMetadata(metadataBytes); + + if (!isValid(metadata)) { + processPreExpiredMetadata(metadataIdentifier, refreshStart, metadataBytes, metadata); + } else { + processNonExpiredMetadata(metadataIdentifier, refreshStart, metadataBytes, metadata); + } + } + + /** + * Processes metadata that has been determined to be invalid (usually because it's already expired) at the time it + * was fetched. A metadata document is considered be invalid if its root element returns false when passed to the + * {@link #isValid(XMLObject)} method. + * + * @param metadataIdentifier identifier of the metadata source + * @param refreshStart when the current refresh cycle started + * @param metadataBytes raw bytes of the new metadata document + * @param metadata new metadata document unmarshalled + */ + protected void processPreExpiredMetadata(String metadataIdentifier, DateTime refreshStart, byte[] metadataBytes, + XMLObject metadata) { + log.warn("Entire metadata document from '{}' was expired at time of loading, existing metadata retained", + metadataIdentifier); + + lastUpdate = refreshStart; + nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(getMinRefreshDelay()); + } + + /** + * Processes metadata that has been determined to be valid at the time it was fetched. A metadata document is + * considered be valid if its root element returns true when passed to the {@link #isValid(XMLObject)} method. + * + * @param metadataIdentifier identifier of the metadata source + * @param refreshStart when the current refresh cycle started + * @param metadataBytes raw bytes of the new metadata document + * @param metadata new metadata document unmarshalled + * + * @throws MetadataProviderException thrown if there s a problem processing the metadata + */ + protected void processNonExpiredMetadata(String metadataIdentifier, DateTime refreshStart, byte[] metadataBytes, + XMLObject metadata) throws MetadataProviderException { + Document metadataDom = metadata.getDOM().getOwnerDocument(); + + log.debug("Filtering metadata from '{}'", metadataIdentifier); + try { + filterMetadata(metadata); + } catch (FilterException e) { + String errMsg = "Error filtering metadata from " + metadataIdentifier; + log.error(errMsg, e); + throw new MetadataProviderException(errMsg, e); + } + + log.debug("Releasing cached DOM for metadata from '{}'", metadataIdentifier); + releaseMetadataDOM(metadata); + + log.debug("Post-processing metadata from '{}'", metadataIdentifier); + postProcessMetadata(metadataBytes, metadataDom, metadata); + + log.debug("Computing expiration time for metadata from '{}'", metadataIdentifier); + DateTime metadataExpirationTime = + SAML2Helper.getEarliestExpiration(metadata, refreshStart.plus(getMaxRefreshDelay()), refreshStart); + log.debug("Expiration of metadata from '{}' will occur at {}", metadataIdentifier, + metadataExpirationTime.toString()); + + cachedMetadata = metadata; + lastUpdate = refreshStart; + + long nextRefreshDelay; + if (metadataExpirationTime.isBeforeNow()) { + expirationTime = new DateTime(ISOChronology.getInstanceUTC()).plus(getMinRefreshDelay()); + nextRefreshDelay = getMaxRefreshDelay(); + } else { + expirationTime = metadataExpirationTime; + nextRefreshDelay = computeNextRefreshDelay(expirationTime); + } + nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(nextRefreshDelay); + + emitChangeEvent(); + log.info("New metadata succesfully loaded for '{}'", getMetadataIdentifier()); + } + + /** + * Post-processing hook called after new metadata has been unmarshalled, filtered, and the DOM released (from the + * {@link XMLObject}) but before the metadata is saved off. Any exception thrown by this hook will cause the + * retrieved metadata to be discarded. + * + * The default implementation of this method is a no-op + * + * @param metadataBytes raw metadata bytes retrieved via {@link #fetchMetadata} + * @param metadataDom metadata after it has been parsed in to a DOM document + * @param metadata metadata after it has been run through all registered filters and its DOM released + * + * @throws MetadataProviderException thrown if there is a problem with the provided data + */ + protected void postProcessMetadata(byte[] metadataBytes, Document metadataDom, XMLObject metadata) + throws MetadataProviderException { + + } + + /** + * Computes the delay until the next refresh time based on the current metadata's expiration time and the refresh + * interval floor. + * + * @param expectedExpiration the time when the metadata is expected to expire and need refreshing + * + * @return delay, in milliseconds, until the next refresh time + */ + protected long computeNextRefreshDelay(DateTime expectedExpiration) { + long now = new DateTime(ISOChronology.getInstanceUTC()).getMillis(); + + long expireInstant = 0; + if (expectedExpiration != null) { + expireInstant = expectedExpiration.toDateTime(ISOChronology.getInstanceUTC()).getMillis(); + } + long refreshDelay = (long) ((expireInstant - now) * getRefreshDelayFactor()); + + // if the expiration time was null or the calculated refresh delay was less than the floor + // use the floor + if (refreshDelay < getMinRefreshDelay()) { + refreshDelay = getMinRefreshDelay(); + } + + return refreshDelay; + } + + /** + * Converts an InputStream into a byte array. + * + * @param ins input stream to convert + * + * @return resultant byte array + * + * @throws MetadataProviderException thrown if there is a problem reading the resultant byte array + */ + protected byte[] inputstreamToByteArray(InputStream ins) throws MetadataProviderException { + try { + // 1 MB read buffer + byte[] buffer = new byte[1024 * 1024]; + ByteArrayOutputStream output = new ByteArrayOutputStream(); + + int n = 0; + while (-1 != (n = ins.read(buffer))) { + output.write(buffer, 0, n); + } + + ins.close(); + return output.toByteArray(); + } catch (IOException e) { + throw new MetadataProviderException(e); + } + } + + /** Background task that refreshes metadata. */ + private class RefreshMetadataTask extends TimerTask { + + /** {@inheritDoc} */ + public void run() { + try { + if (!isInitialized()) { + // just in case the metadata provider was destroyed before this task runs + return; + } + + refresh(); + } catch (MetadataProviderException e) { + // nothing to do, error message already logged by refreshMetadata() + return; + } + } + } +} Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/BaseMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/BaseMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/BaseMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import org.opensaml.xml.Configuration; +import org.opensaml.xml.io.UnmarshallerFactory; + +/** + * Base class for metadata providers. + */ +public abstract class BaseMetadataProvider implements MetadataProvider { + + /** Unmarshaller factory used to get an unmarshaller for the metadata DOM. */ + protected UnmarshallerFactory unmarshallerFactory; + + /** Whether metadata is required to be valid. */ + private boolean requireValidMetadata; + + /** Filter applied to all metadata. */ + private MetadataFilter mdFilter; + + /** Constructor. */ + public BaseMetadataProvider() { + requireValidMetadata = false; + unmarshallerFactory = Configuration.getUnmarshallerFactory(); + } + + /** {@inheritDoc} */ + public boolean requireValidMetadata() { + return requireValidMetadata; + } + + /** {@inheritDoc} */ + public void setRequireValidMetadata(boolean require) { + requireValidMetadata = require; + } + + /** {@inheritDoc} */ + public MetadataFilter getMetadataFilter() { + return mdFilter; + } + + /** {@inheritDoc} */ + public void setMetadataFilter(MetadataFilter newFilter) throws MetadataProviderException { + mdFilter = newFilter; + } + + /** Destroys the metadata provider and frees any resources current held by it. Default method is a no-op. */ + public synchronized void destroy(){ + //no-op + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ChainingMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ChainingMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ChainingMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,665 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.xml.namespace.QName; + +import org.joda.time.DateTime; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.Namespace; +import org.opensaml.xml.NamespaceManager; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.util.IDIndex; +import org.opensaml.xml.util.LazySet; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * A metadata provider that uses registered providers, in turn, to answer queries. + * + * When searching for entity specific information (entity metadata, roles, etc.) the entity descriptor used is the first + * non-null descriptor found while iterating over the registered providers in insertion order. + * + * This chaining provider implements observation by registering an observer with each contained provider. When the + * contained provider emits a change this provider will also emit a change to observers registered with it. As such, + * developers should be careful not to register a the same observer with both container providers and this provider. + * Doing so will result in an observer being notified twice for each change. + */ +public class ChainingMetadataProvider extends BaseMetadataProvider implements ObservableMetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(ChainingMetadataProvider.class); + + /** List of registered observers. */ + private List observers; + + /** Registered providers. */ + private List providers; + + /** Lock used to block reads during write and vice versa. */ + private ReadWriteLock providerLock; + + /** Constructor. */ + public ChainingMetadataProvider() { + super(); + observers = new CopyOnWriteArrayList(); + providers = Collections.EMPTY_LIST; + providerLock = new ReentrantReadWriteLock(true); + } + + /** + * Gets an immutable the list of currently registered providers. + * + * @return list of currently registered providers + */ + public List getProviders() { + return providers; + } + + /** + * Replaces the current set of metadata providers with give collection. + * + * @param newProviders the metadata providers to replace the current providers with + * + * @throws MetadataProviderException thrown if there is a problem adding the metadata provider + */ + public void setProviders(List newProviders) throws MetadataProviderException { + Lock writeLock = providerLock.writeLock(); + writeLock.lock(); + + try { + if (newProviders == null || newProviders.isEmpty()) { + providers = Collections.emptyList(); + return; + } + + ArrayList checkedProviders = new ArrayList(); + for (MetadataProvider provider : newProviders) { + doAddMetadataProvider(provider, checkedProviders); + } + providers = Collections.unmodifiableList(checkedProviders); + } finally { + writeLock.unlock(); + } + } + + /** + * Adds a metadata provider to the list of registered providers. + * + * @param newProvider the provider to be added + * + * @throws MetadataProviderException thrown if there is a problem adding the metadata provider + */ + public void addMetadataProvider(MetadataProvider newProvider) throws MetadataProviderException { + Lock writeLock = providerLock.writeLock(); + writeLock.lock(); + + try { + ArrayList checkedProviders = new ArrayList(providers); + doAddMetadataProvider(newProvider, checkedProviders); + providers = Collections.unmodifiableList(checkedProviders); + } finally { + writeLock.unlock(); + } + } + + /** + * Adds a metadata provider to the given collection. The new provider is checked to see if it is null, if not the + * providers {@link MetadataProvider#requireValidMetadata()} property is set to the value of this metadata + * provider's property. If the given metadata provider is an instance of {@link ObservableMetadataProvider} then a + * ContainedProviderObserver is added to it as well. + * + * @param provider provider to be added to the collection + * @param providerList collection to which the provider is added + */ + protected void doAddMetadataProvider(MetadataProvider provider, List providerList) { + if (provider != null) { + provider.setRequireValidMetadata(requireValidMetadata()); + + if (provider instanceof ObservableMetadataProvider) { + ((ObservableMetadataProvider) provider).getObservers().add(new ContainedProviderObserver()); + } + + providerList.add(provider); + } + } + + /** + * Removes a metadata provider from the list of registered providers. + * + * @param provider provider to be removed + */ + public void removeMetadataProvider(MetadataProvider provider) { + Lock writeLock = providerLock.writeLock(); + writeLock.lock(); + + ObservableMetadataProvider observableProvider; + try { + if (providers.remove(provider) && provider instanceof ObservableMetadataProvider) { + observableProvider = (ObservableMetadataProvider) provider; + for (Observer observer : observableProvider.getObservers()) { + if (observer instanceof ContainedProviderObserver) { + observableProvider.getObservers().remove(observer); + } + } + } + } finally { + writeLock.unlock(); + } + } + + /** {@inheritDoc} */ + public void setRequireValidMetadata(boolean requireValidMetadata) { + super.setRequireValidMetadata(requireValidMetadata); + + Lock writeLock = providerLock.writeLock(); + writeLock.lock(); + try { + for (MetadataProvider provider : providers) { + provider.setRequireValidMetadata(requireValidMetadata); + } + } finally { + writeLock.unlock(); + } + } + + /** {@inheritDoc} */ + public MetadataFilter getMetadataFilter() { + log.warn("Attempt to access unsupported MetadataFilter property on ChainingMetadataProvider"); + return null; + } + + /** {@inheritDoc} */ + public void setMetadataFilter(MetadataFilter newFilter) throws MetadataProviderException { + throw new UnsupportedOperationException("Metadata filters are not supported on ChainingMetadataProviders"); + } + + /** + * Gets the metadata from every registered provider and places each within a newly created EntitiesDescriptor. + * + * {@inheritDoc} + */ + public XMLObject getMetadata() throws MetadataProviderException { + return new ChainingEntitiesDescriptor(); + } + + /** {@inheritDoc} */ + public EntitiesDescriptor getEntitiesDescriptor(String name) throws MetadataProviderException { + Lock readLock = providerLock.readLock(); + readLock.lock(); + + EntitiesDescriptor descriptor = null; + try { + for (MetadataProvider provider : providers) { + log.debug("Checking child metadata provider for entities descriptor with name: {}", name); + try { + descriptor = provider.getEntitiesDescriptor(name); + if (descriptor != null) { + break; + } + } catch (MetadataProviderException e) { + log.warn("Error retrieving metadata from provider of type {}, proceeding to next provider", + provider.getClass().getName(), e); + continue; + } + } + } finally { + readLock.unlock(); + } + + return descriptor; + } + + /** {@inheritDoc} */ + public EntityDescriptor getEntityDescriptor(String entityID) throws MetadataProviderException { + Lock readLock = providerLock.readLock(); + readLock.lock(); + + EntityDescriptor descriptor = null; + try { + for (MetadataProvider provider : providers) { + log.debug("Checking child metadata provider for entity descriptor with entity ID: {}", entityID); + try { + descriptor = provider.getEntityDescriptor(entityID); + if (descriptor != null) { + break; + } + } catch (MetadataProviderException e) { + log.warn("Error retrieving metadata from provider of type {}, proceeding to next provider", + provider.getClass().getName(), e); + continue; + } + } + } finally { + readLock.unlock(); + } + + return descriptor; + } + + /** {@inheritDoc} */ + public List getRole(String entityID, QName roleName) throws MetadataProviderException { + Lock readLock = providerLock.readLock(); + readLock.lock(); + + List roleDescriptors = null; + try { + for (MetadataProvider provider : providers) { + log.debug("Checking child metadata provider for entity descriptor with entity ID: {}", entityID); + try { + roleDescriptors = provider.getRole(entityID, roleName); + if (roleDescriptors != null && !roleDescriptors.isEmpty()) { + break; + } + } catch (MetadataProviderException e) { + log.warn("Error retrieving metadata from provider of type {}, proceeding to next provider", + provider.getClass().getName(), e); + continue; + } + } + } finally { + readLock.unlock(); + } + + return roleDescriptors; + } + + /** {@inheritDoc} */ + public RoleDescriptor getRole(String entityID, QName roleName, String supportedProtocol) + throws MetadataProviderException { + Lock readLock = providerLock.readLock(); + readLock.lock(); + + RoleDescriptor roleDescriptor = null; + try { + for (MetadataProvider provider : providers) { + log.debug("Checking child metadata provider for entity descriptor with entity ID: {}", entityID); + try { + roleDescriptor = provider.getRole(entityID, roleName, supportedProtocol); + if (roleDescriptor != null) { + break; + } + } catch (MetadataProviderException e) { + log.warn("Error retrieving metadata from provider of type {}, proceeding to next provider", + provider.getClass().getName(), e); + continue; + } + } + } finally { + readLock.unlock(); + } + + return roleDescriptor; + } + + /** {@inheritDoc} */ + public List getObservers() { + return observers; + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + super.destroy(); + + for(MetadataProvider provider : providers){ + if(provider instanceof BaseMetadataProvider){ + ((BaseMetadataProvider)provider).destroy(); + } + } + + providers = Collections.emptyList(); + observers = Collections.emptyList(); + } + + /** + * Convenience method for calling + * {@link org.opensaml.saml2.metadata.provider.ObservableMetadataProvider.Observer#onEvent(MetadataProvider)} on + * every registered Observer passing in this provider. + */ + protected void emitChangeEvent() { + if (observers == null || observers.size() == 0) { + return; + } + + List tempObserverList = new ArrayList(observers); + for (Observer observer : tempObserverList) { + if (observer != null) { + observer.onEvent(this); + } + } + } + + /** + * Observer that clears the descriptor index of this provider. + */ + private class ContainedProviderObserver implements Observer { + + /** {@inheritDoc} */ + public void onEvent(MetadataProvider provider) { + emitChangeEvent(); + } + } + + /** Class that wraps the currently list of providers and exposes it as an EntitiesDescriptors. */ + private class ChainingEntitiesDescriptor implements EntitiesDescriptor { + + /** Metadata from the child metadata providers. */ + private ArrayList childDescriptors; + + /** Constructor. */ + public ChainingEntitiesDescriptor() { + childDescriptors = new ArrayList(); + + Lock readLock = providerLock.readLock(); + readLock.lock(); + try { + for (MetadataProvider provider : providers) { + childDescriptors.add(provider.getMetadata()); + } + } catch (MetadataProviderException e) { + log.error("Unable to get metadata from child metadata provider", e); + } finally { + readLock.unlock(); + } + } + + /** {@inheritDoc} */ + public List getEntitiesDescriptors() { + ArrayList descriptors = new ArrayList(); + for (XMLObject descriptor : childDescriptors) { + if (descriptor instanceof EntitiesDescriptor) { + descriptors.add((EntitiesDescriptor) descriptor); + } + } + + return descriptors; + } + + /** {@inheritDoc} */ + public List getEntityDescriptors() { + ArrayList descriptors = new ArrayList(); + for (XMLObject descriptor : childDescriptors) { + if (descriptor instanceof EntityDescriptor) { + descriptors.add((EntityDescriptor) descriptor); + } + } + + return descriptors; + } + + /** {@inheritDoc} */ + public Extensions getExtensions() { + return null; + } + + /** {@inheritDoc} */ + public String getID() { + return null; + } + + /** {@inheritDoc} */ + public String getName() { + return null; + } + + /** {@inheritDoc} */ + public void setExtensions(Extensions extensions) { + + } + + /** {@inheritDoc} */ + public void setID(String newID) { + + } + + /** {@inheritDoc} */ + public void setName(String name) { + + } + + /** {@inheritDoc} */ + public String getSignatureReferenceID() { + return null; + } + + /** {@inheritDoc} */ + public Signature getSignature() { + return null; + } + + /** {@inheritDoc} */ + public boolean isSigned() { + return false; + } + + /** {@inheritDoc} */ + public void setSignature(Signature newSignature) { + + } + + /** {@inheritDoc} */ + public void addNamespace(Namespace namespace) { + + } + + /** {@inheritDoc} */ + public void detach() { + + } + + /** {@inheritDoc} */ + public Element getDOM() { + return null; + } + + /** {@inheritDoc} */ + public QName getElementQName() { + return EntitiesDescriptor.DEFAULT_ELEMENT_NAME; + } + + /** {@inheritDoc} */ + public IDIndex getIDIndex() { + return null; + } + + /** {@inheritDoc} */ + public NamespaceManager getNamespaceManager() { + return null; + } + + /** {@inheritDoc} */ + public Set getNamespaces() { + return new LazySet(); + } + + /** {@inheritDoc} */ + public String getNoNamespaceSchemaLocation() { + return null; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList descriptors = new ArrayList(); + try { + for (MetadataProvider provider : providers) { + descriptors.add(provider.getMetadata()); + } + } catch (MetadataProviderException e) { + log.error("Unable to generate list of child descriptors", e); + } + + return descriptors; + } + + /** {@inheritDoc} */ + public XMLObject getParent() { + return null; + } + + /** {@inheritDoc} */ + public String getSchemaLocation() { + return null; + } + + /** {@inheritDoc} */ + public QName getSchemaType() { + return EntitiesDescriptor.TYPE_NAME; + } + + /** {@inheritDoc} */ + public boolean hasChildren() { + return !getOrderedChildren().isEmpty(); + } + + /** {@inheritDoc} */ + public boolean hasParent() { + return false; + } + + /** {@inheritDoc} */ + public void releaseChildrenDOM(boolean propagateRelease) { + + } + + /** {@inheritDoc} */ + public void releaseDOM() { + + } + + /** {@inheritDoc} */ + public void releaseParentDOM(boolean propagateRelease) { + + } + + /** {@inheritDoc} */ + public void removeNamespace(Namespace namespace) { + + } + + /** {@inheritDoc} */ + public XMLObject resolveID(String id) { + return null; + } + + /** {@inheritDoc} */ + public XMLObject resolveIDFromRoot(String id) { + return null; + } + + /** {@inheritDoc} */ + public void setDOM(Element dom) { + + } + + /** {@inheritDoc} */ + public void setNoNamespaceSchemaLocation(String location) { + + } + + /** {@inheritDoc} */ + public void setParent(XMLObject parent) { + + } + + /** {@inheritDoc} */ + public void setSchemaLocation(String location) { + + } + + /** {@inheritDoc} */ + public void deregisterValidator(Validator validator) { + + } + + /** {@inheritDoc} */ + public List getValidators() { + return new ArrayList(); + } + + /** {@inheritDoc} */ + public void registerValidator(Validator validator) { + } + + /** {@inheritDoc} */ + public void validate(boolean validateDescendants) throws ValidationException { + } + + /** {@inheritDoc} */ + public DateTime getValidUntil() { + return null; + } + + /** {@inheritDoc} */ + public boolean isValid() { + return true; + } + + /** {@inheritDoc} */ + public void setValidUntil(DateTime validUntil) { + + } + + /** {@inheritDoc} */ + public Long getCacheDuration() { + return null; + } + + /** {@inheritDoc} */ + public void setCacheDuration(Long duration) { + + } + + /** {@inheritDoc} */ + public Boolean isNil() { + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue isNilXSBoolean() { + return new XSBooleanValue(Boolean.FALSE, false); + } + + /** {@inheritDoc} */ + public void setNil(Boolean arg0) { + // do nothing + } + + /** {@inheritDoc} */ + public void setNil(XSBooleanValue arg0) { + // do nothing + } + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/DOMMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/DOMMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/DOMMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Element; + +/** + * A MetadataProvider implementation that retrieves metadata from a DOM Element as + * supplied by the user. + * + * It is the responsibility of the caller to re-initialize, via {@link #initialize()}, if any properties of this + * provider are changed. + */ +public class DOMMetadataProvider extends AbstractObservableMetadataProvider implements MetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(DOMMetadataProvider.class); + + /** Root metadata element exposed by this provider. */ + private Element metadataElement; + + /** Unmarshalled metadata. */ + private XMLObject metadata; + + /** + * Constructor. + * + * @param mdElement the metadata element + */ + public DOMMetadataProvider(Element mdElement) { + super(); + metadataElement = mdElement; + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + metadata = null; + metadataElement = null; + + super.destroy(); + } + + /** {@inheritDoc} */ + protected XMLObject doGetMetadata() throws MetadataProviderException { + return metadata; + } + + /** {@inheritDoc} */ + protected void doInitialization() throws MetadataProviderException { + try { + Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataElement); + XMLObject metadataTemp = unmarshaller.unmarshall(metadataElement); + filterMetadata(metadataTemp); + releaseMetadataDOM(metadataTemp); + metadata = metadataTemp; + emitChangeEvent(); + } catch (UnmarshallingException e) { + String errorMsg = "Unable to unmarshall metadata element"; + log.error(errorMsg, e); + throw new MetadataProviderException(errorMsg, e); + } catch (FilterException e) { + String errorMsg = "Unable to filter metadata"; + log.error(errorMsg, e); + throw new MetadataProviderException(errorMsg, e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/EntityRoleFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/EntityRoleFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/EntityRoleFilter.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,245 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.XMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A filter the removes roles, from an entity descriptor. For those roles specified within the SAML metadata + * specification the role element QName is used to identify the role. For other roles, those that appear as + * <RoleDescriptor xsi:type="someRoleType"> the role schema type is used to identify the role. + * + * If the entity descriptor does not contain any roles after filter it may, optionally be removed as well. If the root + * element of the metadata document is an entity descriptor it will never be removed, regardless of of whether it still + * contains roles. + * + * If and entities descriptor does not contains any entity descriptors after filter it may, optionally, be removed as + * well. If the root element of the metadata document is an entities descriptor it will never be removed, regardless of + * of whether it still contains entity descriptors. + */ +public class EntityRoleFilter implements MetadataFilter { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(EntityRoleFilter.class); + + /** List of roles that are NOT removed by this filter. */ + private List roleWhiteList; + + /** Whether to keep entity descriptors that contain no roles; default value: true. */ + private boolean removeRolelessEntityDescriptors; + + /** Whether to keep entities descriptors that contain no entity descriptors; default value: true. */ + private boolean removeEmptyEntitiesDescriptors; + + /** QName of extension role element. */ + private final QName extRoleDescriptor = new QName(SAMLConstants.SAML20MD_NS, "RoleDescriptor"); + + /** + * Constructor. + * + * @param keptRoles list of roles NOT removed by this filter + */ + public EntityRoleFilter(List keptRoles) { + roleWhiteList = new ArrayList(); + + if (keptRoles != null) { + roleWhiteList.addAll(keptRoles); + } + roleWhiteList = Collections.unmodifiableList(roleWhiteList); + + removeRolelessEntityDescriptors = true; + removeEmptyEntitiesDescriptors = true; + } + + /** + * Gets the unmodifiable list of roles that are NOT removed by this filter. + * + * @return unmodifiable list of roles that are NOT removed by this filter + */ + public List getRoleWhiteList() { + return roleWhiteList; + } + + /** + * Gets whether to remove an entity descriptor if it does not contain any roles after filtering. + * + * @return whether to remove an entity descriptor if it does not contain any roles after filtering + */ + public boolean getRemoveRolelessEntityDescriptors() { + return removeRolelessEntityDescriptors; + } + + /** + * Sets whether to remove an entity descriptor if it does not contain any roles after filtering. + * + * @param remove whether to remove an entity descriptor if it does not contain any roles after filtering + */ + public void setRemoveRolelessEntityDescriptors(boolean remove) { + removeRolelessEntityDescriptors = remove; + } + + /** + * Gets whether to remove an entities descriptor if it does not contain any entity descriptor or entities + * descriptors. + * + * @return whether to remove an entities descriptor if it does not contain any entity descriptor or entities + * descriptors + */ + public boolean getRemoveEmptyEntitiesDescriptors() { + return removeEmptyEntitiesDescriptors; + } + + /** + * Sets whether to remove an entities descriptor if it does not contain any entity descriptor or entities + * descriptors. + * + * @param remove whether to remove an entities descriptor if it does not contain any entity descriptor or entities + * descriptors + */ + public void setRemoveEmptyEntitiesDescriptors(boolean remove) { + removeEmptyEntitiesDescriptors = remove; + } + + /** {@inheritDoc} */ + public void doFilter(XMLObject metadata) throws FilterException { + if (metadata == null) { + return; + } + + if (metadata instanceof EntitiesDescriptor) { + filterEntitiesDescriptor((EntitiesDescriptor) metadata); + } else { + filterEntityDescriptor((EntityDescriptor) metadata); + } + } + + /** + * Filters entities descriptor. + * + * @param descriptor entities descriptor to filter + * + * @throws FilterException thrown if an effective role name can not be determined + */ + protected void filterEntitiesDescriptor(EntitiesDescriptor descriptor) throws FilterException { + // First we filter out any contained EntityDescriptors + List entityDescriptors = descriptor.getEntityDescriptors(); + if (entityDescriptors != null && !entityDescriptors.isEmpty()) { + List emptyEntityDescriptors = new ArrayList(); + Iterator entityDescriptorsItr = entityDescriptors.iterator(); + EntityDescriptor entityDescriptor; + List entityRoles; + while (entityDescriptorsItr.hasNext()) { + entityDescriptor = entityDescriptorsItr.next(); + filterEntityDescriptor(entityDescriptor); + if (getRemoveRolelessEntityDescriptors()) { + entityRoles = entityDescriptor.getRoleDescriptors(); + if (entityRoles == null || entityRoles.isEmpty()) { + log.trace("Filtering out entity descriptor {} from entity group {}", entityDescriptor + .getEntityID(), descriptor.getName()); + emptyEntityDescriptors.add(entityDescriptor); + } + } + } + entityDescriptors.removeAll(emptyEntityDescriptors); + } + + // Next, contained EntityDescriptors + List entitiesDescriptors = descriptor.getEntitiesDescriptors(); + if (entitiesDescriptors != null && !entitiesDescriptors.isEmpty()) { + List emptyEntitiesDescriptors = new ArrayList(); + Iterator entitiesDescriptorsItr = entitiesDescriptors.iterator(); + EntitiesDescriptor entitiesDescriptor; + while (entitiesDescriptorsItr.hasNext()) { + entitiesDescriptor = entitiesDescriptorsItr.next(); + filterEntitiesDescriptor(entitiesDescriptor); + if (getRemoveEmptyEntitiesDescriptors()) { + // Remove the EntitiesDescriptor if does not contain any EntitiesDescriptors or EntityDescriptors + if ((entitiesDescriptor.getEntityDescriptors() == null || entitiesDescriptor.getEntityDescriptors() + .isEmpty()) + && (entitiesDescriptor.getEntitiesDescriptors() == null || entitiesDescriptor + .getEntitiesDescriptors().isEmpty())) { + log.trace("Filtering out entity descriptor {} from entity group {}", entitiesDescriptor + .getName(), descriptor.getName()); + emptyEntitiesDescriptors.add(entitiesDescriptor); + } + } + } + entitiesDescriptors.removeAll(emptyEntitiesDescriptors); + } + } + + /** + * Filters entity descriptor roles. + * + * @param descriptor entity descriptor to filter + * + * @throws FilterException thrown if an effective role name can not be determined + */ + protected void filterEntityDescriptor(EntityDescriptor descriptor) throws FilterException { + List roles = descriptor.getRoleDescriptors(); + + if (roles != null && !roles.isEmpty()) { + Iterator rolesItr = roles.iterator(); + QName roleName; + while (rolesItr.hasNext()) { + roleName = getRoleName(rolesItr.next()); + if (!roleWhiteList.contains(roleName)) { + log.trace("Filtering out role {} from entity {}", roleName, descriptor.getEntityID()); + rolesItr.remove(); + } + } + } + } + + /** + * Gets the effective name for the role. This is either the element QName for roles defined within the SAML metadata + * specification or the element schema type QName for those that are not. + * + * @param role role to get the effective name for + * + * @return effective name of the role + * + * @throws FilterException thrown if the effective role name can not be determined + */ + protected QName getRoleName(RoleDescriptor role) throws FilterException { + QName roleName = role.getElementQName(); + + if (extRoleDescriptor.equals(roleName)) { + roleName = role.getSchemaType(); + if (roleName == null) { + throw new FilterException("Role descriptor element was " + extRoleDescriptor + + " but did not contain a schema type. This is illegal."); + } + } + + return roleName; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FileBackedHTTPMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FileBackedHTTPMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FileBackedHTTPMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,163 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Timer; + +import org.apache.commons.httpclient.HttpClient; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * A URL metadata provider that caches a copy of the retrieved metadata to disk so that, in the event that the metadata + * may not be pulled from the URL it may be pulled from disk using the last fetched data. If the backing file does not + * already exist it will be created. + * + * It is the responsibility of the caller to re-initialize, via {@link #initialize()}, if any properties of this + * provider are changed. + */ +public class FileBackedHTTPMetadataProvider extends HTTPMetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(FileBackedHTTPMetadataProvider.class); + + /** File containing the backup of the metadata. */ + private File metadataBackupFile; + + /** + * Constructor. + * + * @param metadataURL the URL to fetch the metadata + * @param requestTimeout the time, in milliseconds, to wait for the metadata server to respond + * @param backupFilePath the file that will keep a backup copy of the metadata, + * + * @throws MetadataProviderException thrown if the URL is not a valid URL, the metadata can not be retrieved from + * the URL, the given file can not be created or written to + */ + @Deprecated + public FileBackedHTTPMetadataProvider(String metadataURL, int requestTimeout, String backupFilePath) + throws MetadataProviderException { + super(metadataURL, requestTimeout); + setBackupFile(backupFilePath); + } + + /** + * Constructor. + * + * @param client HTTP client used to fetch remove metadata + * @param backgroundTaskTimer timer used to schedule background metadata refresh tasks + * @param metadataURL the URL to fetch the metadata + * @param backupFilePath the file that will keep a backup copy of the metadata, + * + * @throws MetadataProviderException thrown if the URL is not a valid URL, the metadata can not be retrieved from + * the URL, the given file can not be created or written to + */ + public FileBackedHTTPMetadataProvider(Timer backgroundTaskTimer, HttpClient client, String metadataURL, + String backupFilePath) throws MetadataProviderException { + super(backgroundTaskTimer, client, metadataURL); + setBackupFile(backupFilePath); + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + metadataBackupFile = null; + + super.destroy(); + } + + /** + * Sets the file used to backup metadata. The given file path is checked to see if it is a read/writable file if it + * exists or if can be created if it does not exist. + * + * @param backupFilePath path to the backup file + * + * @throws MetadataProviderException thrown if the backup file is not read/writable or creatable + */ + protected void setBackupFile(String backupFilePath) throws MetadataProviderException { + File backingFile = new File(backupFilePath); + + if (!backingFile.exists()) { + try { + backingFile.createNewFile(); + } catch (IOException e) { + log.error("Unable to create backing file " + backupFilePath, e); + throw new MetadataProviderException("Unable to create backing file " + backupFilePath, e); + } + } + + if (backingFile.isDirectory()) { + throw new MetadataProviderException("Filepath " + backupFilePath + + " is a directory and may not be used as a backing metadata file"); + } + + if (!backingFile.canRead()) { + throw new MetadataProviderException("Filepath " + backupFilePath + + " exists but can not be read by this user"); + } + + if (!backingFile.canWrite()) { + throw new MetadataProviderException("Filepath " + backupFilePath + + " exists but can not be written to by this user"); + } + metadataBackupFile = backingFile; + } + + /** {@inheritDoc} */ + protected byte[] fetchMetadata() throws MetadataProviderException { + try { + return super.fetchMetadata(); + } catch (MetadataProviderException e) { + if (metadataBackupFile.exists()) { + try { + return DatatypeHelper.fileToByteArray(metadataBackupFile); + } catch (IOException ioe) { + String errMsg = "Unable to retrieve metadata from backup file " + + metadataBackupFile.getAbsolutePath(); + log.error(errMsg, ioe); + throw new MetadataProviderException(errMsg, ioe); + } + } else { + log.error("Unable to read metadata from remote server and backup does not exist"); + throw new MetadataProviderException( + "Unable to read metadata from remote server and backup does not exist"); + } + } + } + + /** {@inheritDoc} */ + protected void postProcessMetadata(byte[] metadataBytes, Document metadataDom, XMLObject metadata) + throws MetadataProviderException { + try { + FileOutputStream out = new FileOutputStream(metadataBackupFile); + out.write(metadataBytes); + out.flush(); + out.close(); + super.postProcessMetadata(metadataBytes, metadataDom, metadata); + } catch (IOException e) { + String errMsg = "Unable to write metadata to backup file " + metadataBackupFile.getAbsolutePath(); + log.error(errMsg); + throw new MetadataProviderException(errMsg, e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FilesystemMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FilesystemMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FilesystemMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,154 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Timer; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A metadata provider that pulls metadata from a file on the local filesystem. + * + * This metadata provider periodically checks to see if the read metadata file has changed. The delay between each + * refresh interval is calculated as follows. If no validUntil or cacheDuration is present then the + * {@link #getMaxRefreshDelay()} value is used. Otherwise, the earliest refresh interval of the metadata file is checked + * by looking for the earliest of all the validUntil attributes and cacheDuration attributes. If that refresh interval + * is larger than the max refresh delay then {@link #getMaxRefreshDelay()} is used. If that number is smaller than the + * min refresh delay then {@link #getMinRefreshDelay()} is used. Otherwise the calculated refresh delay multiplied by + * {@link #getRefreshDelayFactor()} is used. By using this factor, the provider will attempt to be refresh before the + * cache actually expires, allowing a some room for error and recovery. Assuming the factor is not exceedingly close to + * 1.0 and a min refresh delay that is not overly large, this refresh will likely occur a few times before the cache + * expires. + * + */ +public class FilesystemMetadataProvider extends AbstractReloadingMetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(FilesystemMetadataProvider.class); + + /** The metadata file. */ + private File metadataFile; + + /** + * Constructor. + * + * @param metadata the metadata file + * + * @throws MetadataProviderException thrown if the given file path is null, does not exist, does not represent a + * file, or if the metadata can not be parsed + */ + public FilesystemMetadataProvider(File metadata) throws MetadataProviderException { + super(); + setMetadataFile(metadata); + } + + /** + * Constructor. + * + * @param metadata the metadata file + * @param backgroundTaskTimer timer used to refresh metadata in the background + * + * @throws MetadataProviderException thrown if the given file path is null, does not exist, does not represent a + * file, or if the metadata can not be parsed + */ + public FilesystemMetadataProvider(Timer backgroundTaskTimer, File metadata) throws MetadataProviderException { + super(backgroundTaskTimer); + setMetadataFile(metadata); + } + + /** + * Sets the file from which metadata is read. The given file path is checked to see if it exists, is a file, and is + * readable. + * + * @param file path to the metadata file + * + * @throws MetadataProviderException thrown if the file does not exist or is not a readable file + */ + protected void setMetadataFile(File file) throws MetadataProviderException { + + if (!file.exists()) { + throw new MetadataProviderException("Give metadata file, " + file.getAbsolutePath() + " does not exist"); + } + + if (!file.isFile()) { + throw new MetadataProviderException("Give metadata file, " + file.getAbsolutePath() + " is not a file"); + } + + if (!file.canRead()) { + throw new MetadataProviderException("Give metadata file, " + file.getAbsolutePath() + " is not readable"); + } + + metadataFile = file; + } + + /** + * Gets whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @return whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @deprecated use {@link #requireValidMetadata()} instead + */ + public boolean maintainExpiredMetadata() { + return !requireValidMetadata(); + } + + /** + * Sets whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @param maintain whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @deprecated use {@link #setRequireValidMetadata(boolean)} instead + */ + public void setMaintainExpiredMetadata(boolean maintain) { + setRequireValidMetadata(!maintain); + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + metadataFile = null; + + super.destroy(); + } + + /** {@inheritDoc} */ + protected String getMetadataIdentifier() { + return metadataFile.getAbsolutePath(); + } + + /** {@inheritDoc} */ + protected byte[] fetchMetadata() throws MetadataProviderException { + try { + DateTime metadataUpdateTime = new DateTime(metadataFile.lastModified(), ISOChronology.getInstanceUTC()); + if (getLastRefresh() == null || metadataUpdateTime.isAfter(getLastRefresh())) { + return inputstreamToByteArray(new FileInputStream(metadataFile)); + } + + return null; + } catch (IOException e) { + String errMsg = "Unable to read metadata file " + metadataFile.getAbsolutePath(); + log.error(errMsg, e); + throw new MetadataProviderException(errMsg, e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FilterException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FilterException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/FilterException.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +/** + * An exception thrown during the evaluation of a {@link org.opensaml.saml2.metadata.provider.MetadataFilter}. + */ +public class FilterException extends Exception { + + /** + * Serial version UID + */ + private static final long serialVersionUID = 6214474330141026496L; + + /** + * Constructor. + */ + public FilterException() { + + } + + /** + * Constructor. + * + * @param message exception message + */ + public FilterException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public FilterException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public FilterException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/HTTPMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/HTTPMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/HTTPMetadataProvider.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,355 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Timer; +import java.util.zip.GZIPInputStream; +import java.util.zip.InflaterInputStream; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.auth.AuthScope; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.params.HttpClientParams; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A metadata provider that pulls metadata using an HTTP GET. Metadata is cached until one of these criteria is met: + *

    + *
  • The smallest cacheDuration within the metadata is exceeded
  • + *
  • The earliest validUntil time within the metadata is exceeded
  • + *
  • The maximum cache duration is exceeded
  • + *
+ * + * Metadata is filtered prior to determining the cache expiration data. This allows a filter to remove XMLObjects that + * may effect the cache duration but for which the user of this provider does not care about. + * + * It is the responsibility of the caller to re-initialize, via {@link #initialize()}, if any properties of this + * provider are changed. + */ +public class HTTPMetadataProvider extends AbstractReloadingMetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(HTTPMetadataProvider.class); + + /** HTTP Client used to pull the metadata. */ + private HttpClient httpClient; + + /** URL to the Metadata. */ + private URI metadataURI; + + /** The ETag provided when the currently cached metadata was fetched. */ + private String cachedMetadataETag; + + /** The Last-Modified information provided when the currently cached metadata was fetched. */ + private String cachedMetadataLastModified; + + /** URL scope that requires authentication. */ + private AuthScope authScope; + + /** + * Constructor. + * + * @param metadataURL the URL to fetch the metadata + * @param requestTimeout the time, in milliseconds, to wait for the metadata server to respond + * + * @throws MetadataProviderException thrown if the URL is not a valid URL or the metadata can not be retrieved from + * the URL + */ + @Deprecated + public HTTPMetadataProvider(String metadataURL, int requestTimeout) throws MetadataProviderException { + super(); + try { + metadataURI = new URI(metadataURL); + } catch (URISyntaxException e) { + throw new MetadataProviderException("Illegal URL syntax", e); + } + + HttpClientParams clientParams = new HttpClientParams(); + clientParams.setSoTimeout(requestTimeout); + httpClient = new HttpClient(clientParams); + httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(requestTimeout); + authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort()); + + } + + /** + * Constructor. + * + * @param client HTTP client used to pull in remote metadata + * @param backgroundTaskTimer timer used to schedule background metadata refresh tasks + * @param metadataURL URL to the remove remote metadata + * + * @throws MetadataProviderException thrown if the HTTP client is null or the metadata URL provided is invalid + */ + public HTTPMetadataProvider(Timer backgroundTaskTimer, HttpClient client, String metadataURL) + throws MetadataProviderException { + super(backgroundTaskTimer); + + if (client == null) { + throw new MetadataProviderException("HTTP client may not be null"); + } + httpClient = client; + + try { + metadataURI = new URI(metadataURL); + } catch (URISyntaxException e) { + throw new MetadataProviderException("Illegal URL syntax", e); + } + + authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort()); + } + + /** + * Gets the URL to fetch the metadata. + * + * @return the URL to fetch the metadata + */ + public String getMetadataURI() { + return metadataURI.toASCIIString(); + } + + /** + * Sets the username and password used to access the metadata URL. To disable BASIC authentication set the username + * and password to null; + * + * @param username the username + * @param password the password + */ + public void setBasicCredentials(String username, String password) { + if (username == null && password == null) { + httpClient.getState().setCredentials(null, null); + } else { + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); + httpClient.getState().setCredentials(authScope, credentials); + } + } + + /** + * Gets the length of time in milliseconds to wait for the server to respond. + * + * @return length of time in milliseconds to wait for the server to respond + */ + public int getRequestTimeout() { + return httpClient.getParams().getSoTimeout(); + } + + /** + * Sets the socket factory used to create sockets to the HTTP server. + * + * @see HTTPClient SSL guide + * + * @param newSocketFactory the socket factory used to produce sockets used to connect to the server + * + * @deprecated set this information on HTTP client used by provider + */ + public void setSocketFactory(ProtocolSocketFactory newSocketFactory) { + log.debug("Using the custom socket factory {} to connect to the HTTP server", newSocketFactory.getClass() + .getName()); + Protocol protocol = new Protocol(metadataURI.getScheme(), newSocketFactory, metadataURI.getPort()); + httpClient.getHostConfiguration().setHost(metadataURI.getHost(), metadataURI.getPort(), protocol); + } + + /** + * Gets the maximum amount of time, in seconds, metadata will be cached for. + * + * @return maximum amount of time, in seconds, metadata will be cached for + * + * @deprecated use {@link #getMaxRefreshDelay()} instead + */ + public int getMaxCacheDuration() { + return (int) getMaxRefreshDelay(); + } + + /** + * Sets the maximum amount of time, in seconds, metadata will be cached for. + * + * @param newDuration maximum amount of time, in seconds, metadata will be cached for + * + * @deprecated use {@link #setMaxRefreshDelay(long)} instead + */ + public void setMaxCacheDuration(int newDuration) { + setMaxRefreshDelay(newDuration * 1000); + } + + /** + * Gets whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @return whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @deprecated use {@link #requireValidMetadata()} instead + */ + public boolean maintainExpiredMetadata() { + return !requireValidMetadata(); + } + + /** + * Sets whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @param maintain whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @deprecated use {@link #setRequireValidMetadata(boolean)} instead + */ + public void setMaintainExpiredMetadata(boolean maintain) { + setRequireValidMetadata(!maintain); + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + httpClient = null; + metadataURI = null; + cachedMetadataETag = null; + cachedMetadataLastModified = null; + authScope = null; + + super.destroy(); + } + + /** {@inheritDoc} */ + protected String getMetadataIdentifier() { + return metadataURI.toString(); + } + + /** + * Gets the metadata document from the remote server. + * + * @return the metadata from remote server, or null if the metadata document has not changed since the last + * retrieval + * + * @throws MetadataProviderException thrown if there is a problem retrieving the metadata from the remote server + */ + protected byte[] fetchMetadata() throws MetadataProviderException { + GetMethod getMethod = buildGetMethod(); + + try { + log.debug("Attempting to fetch metadata document from '{}'", metadataURI); + httpClient.executeMethod(getMethod); + int httpStatus = getMethod.getStatusCode(); + + if (httpStatus == HttpStatus.SC_NOT_MODIFIED) { + log.debug("Metadata document from '{}' has not changed since last retrieval", getMetadataURI()); + return null; + } + + if (getMethod.getStatusCode() != HttpStatus.SC_OK) { + String errMsg = "Non-ok status code " + getMethod.getStatusCode() + + " returned from remote metadata source " + metadataURI; + log.error(errMsg); + throw new MetadataProviderException(errMsg); + } + + processConditionalRetrievalHeaders(getMethod); + + byte[] rawMetadata = getMetadataBytesFromResponse(getMethod); + log.debug("Successfully fetched {}bytes of metadata from {}", rawMetadata.length, getMetadataURI()); + + return rawMetadata; + } catch (IOException e) { + String errMsg = "Error retrieving metadata from " + metadataURI; + log.error(errMsg, e); + throw new MetadataProviderException(errMsg, e); + } + } + + /** + * Builds the HTTP GET method used to fetch the metadata. The returned method advertises support for GZIP and + * deflate compression, enables conditional GETs if the cached metadata came with either an ETag or Last-Modified + * information, and sets up basic authentication if such is configured. + * + * @return the constructed GET method + */ + protected GetMethod buildGetMethod() { + GetMethod getMethod = new GetMethod(getMetadataURI()); + + getMethod.setRequestHeader("Accept-Encoding", "gzip,deflate"); + if (cachedMetadataETag != null) { + getMethod.setRequestHeader("If-None-Match", cachedMetadataETag); + } + if (cachedMetadataLastModified != null) { + getMethod.setRequestHeader("If-Modified-Since", cachedMetadataLastModified); + } + + if (httpClient.getState().getCredentials(authScope) != null) { + log.debug("Using BASIC authentication when retrieving metadata from '{}", metadataURI); + getMethod.setDoAuthentication(true); + } + + return getMethod; + } + + /** + * Records the ETag and Last-Modified headers, from the response, if they are present. + * + * @param getMethod GetMethod containing a valid HTTP response + */ + protected void processConditionalRetrievalHeaders(GetMethod getMethod) { + Header httpHeader = getMethod.getResponseHeader("ETag"); + if (httpHeader != null) { + cachedMetadataETag = httpHeader.getValue(); + } + + httpHeader = getMethod.getResponseHeader("Last-Modified"); + if (httpHeader != null) { + cachedMetadataLastModified = httpHeader.getValue(); + } + } + + /** + * Extracts the raw metadata bytes from the response taking in to account possible deflate and GZip compression. + * + * @param getMethod GetMethod containing a valid HTTP response + * + * @return the raw metadata bytes + * + * @throws MetadataProviderException thrown if there is a problem getting the raw metadata bytes from the response + */ + protected byte[] getMetadataBytesFromResponse(GetMethod getMethod) throws MetadataProviderException { + log.debug("Attempting to extract metadata from response to request for metadata from '{}'", getMetadataURI()); + try { + InputStream ins = getMethod.getResponseBodyAsStream(); + + Header httpHeader = getMethod.getResponseHeader("Content-Encoding"); + if (httpHeader != null) { + String contentEncoding = httpHeader.getValue(); + if ("deflate".equalsIgnoreCase(contentEncoding)) { + log.debug("Metadata document from '{}' was deflate compressed, decompressing it", metadataURI); + ins = new InflaterInputStream(ins); + } + + if ("gzip".equalsIgnoreCase(contentEncoding)) { + log.debug("Metadata document from '{}' was GZip compressed, decompressing it", metadataURI); + ins = new GZIPInputStream(ins); + } + } + + return inputstreamToByteArray(ins); + } catch (IOException e) { + log.error("Unable to read response", e); + throw new MetadataProviderException("Unable to read response", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataFilter.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import org.opensaml.xml.XMLObject; + +/** + * A metadata filter is used to process a metadata document after it has been unmarshalled into object. + * + * Some example filters might remove everything but identity providers roles, decreasing the data a service provider + * needs to work with, or a filter could be used to perform integrity checking on the retrieved metadata by verifying a + * digital signature. + */ +public interface MetadataFilter { + + /** + * Filters the given metadata, perhaps to remove elements that are not wanted. + * + * @param metadata the metadata to be filtered. + * + * @throws FilterException thrown if an error occurs during the filtering process + */ + public void doFilter(XMLObject metadata) throws FilterException; +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataFilterChain.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataFilterChain.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataFilterChain.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xml.XMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A filter that allows the composition of {@link MetadataFilter}s. Filters will be executed on the given metadata + * document in the order they were added to the chain. + */ +public class MetadataFilterChain implements MetadataFilter { + + /** Class logger. */ + private Logger log = LoggerFactory.getLogger(MetadataFilterChain.class); + + /** Registered filters. */ + private List filters; + + /** + * Constructor. + */ + public MetadataFilterChain() { + filters = Collections.emptyList(); + } + + /** {@inheritDoc} */ + public final void doFilter(XMLObject xmlObject) throws FilterException { + synchronized (filters) { + if (filters == null || filters.isEmpty()) { + log.debug("No filters configured, nothing to do"); + } + for (MetadataFilter filter : filters) { + log.debug("Applying filter {}", filter.getClass().getName()); + filter.doFilter(xmlObject); + } + } + } + + /** + * Gets the list of {@link MetadataFilter}s that make up this chain. + * + * @return the filters that make up this chain + */ + public List getFilters() { + return filters; + } + + /** + * Sets the list of {@link MetadataFilter}s that make up this chain. + * + * @param newFilters list of {@link MetadataFilter}s that make up this chain + */ + public void setFilters(List newFilters) { + if (newFilters == null || newFilters.isEmpty()) { + filters.clear(); + } + + ArrayList checkedFilters = new ArrayList(); + for (MetadataFilter filter : newFilters) { + if (filter != null) { + checkedFilters.add(filter); + } + } + + filters = checkedFilters; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,133 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.XMLObject; + +/** + * A local store into which metadata can be loaded and queried. Specific implementations may perform additional logic + * such as caching (and refreshing) metadata and merging metadata, about a single entity, from multiple sources. + * + * NOTE, developers should not try to marshall the metadata that comes from a metadata provider. It is + * possible that the a provider, or {@link MetadataFilter}, implementation may make changes to the retrieved metadata + * that make it unusable for marshalling. For example, by removing elements required by the schema but not by the user + * of the provider as a way of saving on memory. + */ +public interface MetadataProvider { + + /** + * Gets whether the metadata returned by queries must be valid. At a minimum, metadata is valid only if the date + * expressed in the element, and all its ancestral element's, validUntil attribute has not passed. Specific + * implementations may add additional constraints. + * + * @return whether the metadata returned by queries must be valid + */ + public boolean requireValidMetadata(); + + /** + * Sets whether the metadata returned by queries must be valid. + * + * @param requireValidMetadata whether the metadata returned by queries must be valid + */ + public void setRequireValidMetadata(boolean requireValidMetadata); + + /** + * Gets the metadata filter applied to the metadata. + * + * @return the metadata filter applied to the metadata + */ + public MetadataFilter getMetadataFilter(); + + /** + * Sets the metadata filter applied to the metadata. + * + * @param newFilter the metadata filter applied to the metadata + * + * @throws MetadataProviderException thrown if the provider can not apply the filter to the metadata + */ + public void setMetadataFilter(MetadataFilter newFilter) throws MetadataProviderException; + + /** + * Gets the valid metadata tree, after the registered filter has been applied. + * + * @return the entire metadata tree + * + * @throws MetadataProviderException thrown if the provider can not fetch the metadata, must not be thrown simply if + * there is no metadata to fetch + */ + public XMLObject getMetadata() throws MetadataProviderException; + + /** + * Gets a valid named EntitiesDescriptor from the metadata. + * + * @param name the name of the EntitiesDescriptor + * + * @return the EntitiesDescriptor or null + * + * @throws MetadataProviderException thrown if the provider can not fetch the metadata, must not be thrown if there + * is simply no EntitiesDescriptor with the given name + */ + public EntitiesDescriptor getEntitiesDescriptor(String name) throws MetadataProviderException; + + /** + * Gets the valid metadata for a given entity. + * + * @param entityID the ID of the entity + * + * @return the entity's metadata or null if there is no metadata or no valid metadata + * + * @throws MetadataProviderException thrown if the provider can not fetch the metadata, must not be thrown if there + * is simply no EntityDescriptor with the given ID + */ + public EntityDescriptor getEntityDescriptor(String entityID) throws MetadataProviderException; + + /** + * Gets the valid role descriptors of a given type for a given entity. + * + * @param entityID the ID of the entity + * @param roleName the role type + * + * @return the modifiable list of role descriptors + * + * @throws MetadataProviderException thrown if the provider can not fetch the metadata, must not be thrown if there + * is simply no such entity with the given roles + */ + public List getRole(String entityID, QName roleName) throws MetadataProviderException; + + /** + * Gets the valid role descriptors of a given type for a given entity that support the given protocol. + * + * @param entityID the ID of the entity + * @param roleName the role type + * @param supportedProtocol the protocol supported by the role + * + * @return the role descriptor + * + * @throws MetadataProviderException thrown if the provider can not fetch the metadata, must not be thrown if there + * is simply no such entity with the given role supporting the given protocol + */ + public RoleDescriptor getRole(String entityID, QName roleName, String supportedProtocol) + throws MetadataProviderException; +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataProviderException.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataProviderException.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/MetadataProviderException.java 17 Aug 2012 15:03:14 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +/** + * Exception thrown by a {@link MetadataProvider}. + */ +public class MetadataProviderException extends Exception { + + /** Serial version UID. */ + private static final long serialVersionUID = -1361135333176800358L; + + /** + * Constructor. + */ + public MetadataProviderException() { + + } + + /** + * Constructor. + * + * @param message exception message + */ + public MetadataProviderException(String message) { + super(message); + } + + /** + * Constructor. + * + * @param wrappedException exception to be wrapped by this one + */ + public MetadataProviderException(Exception wrappedException) { + super(wrappedException); + } + + /** + * Constructor. + * + * @param message exception message + * @param wrappedException exception to be wrapped by this one + */ + public MetadataProviderException(String message, Exception wrappedException) { + super(message, wrappedException); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ObservableMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ObservableMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ObservableMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.List; + +/** + * A metadata provider that provides event notification to observers. This may be used, for example, to signal an update + * of an internal cache of metadata allowing other subsystems to perform some action based on that. + * + */ +public interface ObservableMetadataProvider extends MetadataProvider { + + /** + * Gets the list of observers for the provider. New observers may be added to the list or old ones removed. + * + * @return the list of observers + */ + public List getObservers(); + + /** + * An observer of metadata provider changes. + * + * NOTE: The metadata provider that has changed is passed in to the + * {@link #onEvent(MetadataProvider)} method. Observers should NOT keep a reference to this + * provider as this may prevent proper garbage collection. + */ + public interface Observer { + + /** + * Called when a provider signals an event has occured. + * + * @param provider the provider being observed + */ + public void onEvent(MetadataProvider provider); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/RequiredValidUntilFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/RequiredValidUntilFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/RequiredValidUntilFilter.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,107 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import org.joda.time.DateTime; +import org.joda.time.chrono.ISOChronology; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.XMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A metadata filter that requires the presence of a validUntil attribute on the root element of the + * metadata document. It can optionally also enforce that the validity period (now minus validUntil date) + * is not longer than a specified amount. + * + * A maximum validity interval of less than 1 means the no restriction is placed on the metadata's + * validUntil attribute. + */ +public class RequiredValidUntilFilter implements MetadataFilter { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(RequiredValidUntilFilter.class); + + /** The maximum interval, in milliseconds, between now and the validUntil date. */ + private long maxValidityInterval; + + /** Constructor. */ + public RequiredValidUntilFilter() { + maxValidityInterval = 0; + } + + /** + * Constructor. + * + * @param maxValidity maximum internal, in seconds, between now and the validUntil date + */ + public RequiredValidUntilFilter(long maxValidity) { + this.maxValidityInterval = maxValidity * 1000; + } + + /** + * Gets the maximum internal, in milliseconds, between now and the validUntil date. A value of less than 1 + * indicates that there is no restriction. + * + * @return maximum internal, in milliseconds, between now and the validUntil date + */ + public long getMaxValidityInterval() { + return maxValidityInterval; + } + + /** {@inheritDoc} */ + public void doFilter(XMLObject metadata) throws FilterException { + DateTime validUntil = getValidUntil(metadata); + + if (validUntil == null) { + throw new FilterException("Metadata did not include a validUntil attribute"); + } + + DateTime now = new DateTime(ISOChronology.getInstanceUTC()); + if (maxValidityInterval > 0 && validUntil.isAfter(now)) { + long validityInterval = validUntil.getMillis() - now.getMillis(); + if (validityInterval > maxValidityInterval) { + throw new FilterException("Metadata's validity interval, " + validityInterval + + "ms, is larger than is allowed, " + maxValidityInterval + "ms."); + } + } + } + + /** + * Gets the validUntil time of the metadata, if present. + * + * @param metadata metadata from which to get the validUntil instant + * + * @return the valid until instant or null if it is not present + * + * @throws FilterException thrown if the given XML object is not an {@link EntitiesDescriptor} or + * {@link EntityDescriptor} + */ + protected DateTime getValidUntil(XMLObject metadata) throws FilterException { + if (metadata instanceof EntitiesDescriptor) { + return ((EntitiesDescriptor) metadata).getValidUntil(); + } else if (metadata instanceof EntityDescriptor) { + return ((EntityDescriptor) metadata).getValidUntil(); + } else { + log.error("Metadata root element was not an EntitiesDescriptor or EntityDescriptor it was a {}", metadata + .getElementQName()); + throw new FilterException("Metadata root element was not an EntitiesDescriptor or EntityDescriptor"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ResourceBackedMetadataProvider.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ResourceBackedMetadataProvider.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/ResourceBackedMetadataProvider.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,142 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.Timer; + +import org.joda.time.DateTime; +import org.opensaml.util.resource.Resource; +import org.opensaml.util.resource.ResourceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A metadata provider that reads metadata from a {#link {@link Resource}. + * + * @since 2.2 + */ +public class ResourceBackedMetadataProvider extends AbstractReloadingMetadataProvider { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(ResourceBackedMetadataProvider.class); + + /** Resource from which metadata is read. */ + private Resource metadataResource; + + /** Time the metadata resource was last updated. */ + private DateTime lastResourceUpdate; + + /** + * Constructor. + * + * @param resource resource from which to read the metadata file. + * @param timer task timer used to schedule metadata refresh tasks + * @param maxMetadataCacheDuration maximum amount of time, in milliseconds, that metadata may be cached before being + * re-read + * + * @throws MetadataProviderException thrown if there is a problem retrieving information about the resource + * + * @deprecated + */ + public ResourceBackedMetadataProvider(Resource resource, Timer timer, long maxMetadataCacheDuration) + throws MetadataProviderException { + super(timer); + + try { + if (!resource.exists()) { + throw new MetadataProviderException("Resource " + resource.getLocation() + " does not exist."); + } + metadataResource = resource; + } catch (ResourceException e) { + throw new MetadataProviderException("Unable to read resource", e); + } + } + + /** + * Constructor. + * + * @param resource resource from which to read the metadata file. + * @param timer task timer used to schedule metadata refresh tasks + * + * @throws MetadataProviderException thrown if there is a problem retrieving information about the resource + */ + public ResourceBackedMetadataProvider(Timer timer, Resource resource) throws MetadataProviderException { + super(timer); + + try { + if (!resource.exists()) { + throw new MetadataProviderException("Resource " + resource.getLocation() + " does not exist."); + } + metadataResource = resource; + } catch (ResourceException e) { + throw new MetadataProviderException("Unable to read resource", e); + } + } + + /** + * Gets whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @return whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @deprecated use {@link #requireValidMetadata()} instead + */ + public boolean maintainExpiredMetadata(){ + return !requireValidMetadata(); + } + + /** + * Sets whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @param maintain whether cached metadata should be discarded if it expires and can not be refreshed. + * + * @deprecated use {@link #setRequireValidMetadata(boolean)} instead + */ + public void setMaintainExpiredMetadata(boolean maintain){ + setRequireValidMetadata(!maintain); + } + + /** {@inheritDoc} */ + public synchronized void destroy() { + metadataResource = null; + lastResourceUpdate = null; + + super.destroy(); + } + + /** {@inheritDoc} */ + protected String getMetadataIdentifier() { + return metadataResource.getLocation(); + } + + /** {@inheritDoc} */ + protected byte[] fetchMetadata() throws MetadataProviderException { + try { + DateTime metadataUpdateTime = metadataResource.getLastModifiedTime(); + log.debug("resource {} was last modified {}", metadataResource.getLocation(), metadataUpdateTime); + if (getLastRefresh() == null || metadataUpdateTime.isAfter(getLastRefresh())) { + return inputstreamToByteArray(metadataResource.getInputStream()); + } + + return null; + } catch (ResourceException e) { + String errorMsg = "Unable to read metadata file"; + log.error(errorMsg, e); + throw new MetadataProviderException(errorMsg, e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/SchemaValidationFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/SchemaValidationFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/SchemaValidationFilter.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Validator; + +import org.opensaml.common.xml.SAMLSchemaBuilder; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.SAXException; + +/** + * A metadata filter that schema validates an incoming metadata file. + */ +public class SchemaValidationFilter implements MetadataFilter { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SchemaValidationFilter.class); + + /** + * Constructor. + * + * @param extensionSchemas classpath location of metadata extension schemas, may be null + */ + public SchemaValidationFilter(String[] extensionSchemas) { + if (extensionSchemas != null) { + for (String extension : extensionSchemas) { + extension = DatatypeHelper.safeTrimOrNullString(extension); + if (extension != null) { + SAMLSchemaBuilder.addExtensionSchema(extension); + } + } + } + } + + /** {@inheritDoc} */ + public void doFilter(XMLObject metadata) throws FilterException { + Validator schemaValidator = null; + try { + schemaValidator = SAMLSchemaBuilder.getSAML11Schema().newValidator(); + } catch (SAXException e) { + log.error("Unable to build metadata validation schema", e); + throw new FilterException("Unable to build metadata validation schema", e); + } + + try { + schemaValidator.validate(new DOMSource(metadata.getDOM())); + } catch (Exception e) { + log.error("Incoming metadata was not schema valid.", e); + throw new FilterException("Incoming metadata was not schema valid.", e); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/SignatureValidationFilter.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/SignatureValidationFilter.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/SignatureValidationFilter.java 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,398 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.provider; + +import java.util.Iterator; + +import org.opensaml.saml2.metadata.AffiliationDescriptor; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.security.SAMLSignatureProfileValidator; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.signature.SignableXMLObject; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.SignatureTrustEngine; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A metadata filter that validates XML signatures. + */ +public class SignatureValidationFilter implements MetadataFilter { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SignatureValidationFilter.class); + + /** Trust engine used to validate a signature. */ + private SignatureTrustEngine signatureTrustEngine; + + /** Indicates whether signed metadata is required. */ + private boolean requireSignature; + + /** Set of externally specified default criteria for input to the trust engine. */ + private CriteriaSet defaultCriteria; + + /** Pre-validator for XML Signature instances. */ + private Validator sigValidator; + + /** + * Constructor. + * + * @param engine the trust engine used to validate signatures on incoming metadata. + */ + public SignatureValidationFilter(SignatureTrustEngine engine) { + if (engine == null) { + throw new IllegalArgumentException("Signature trust engine may not be null"); + } + + signatureTrustEngine = engine; + sigValidator = new SAMLSignatureProfileValidator(); + } + + /** + * Constructor. + * + * @param engine the trust engine used to validate signatures on incoming metadata. + * @param signatureValidator optional pre-validator used to validate Signature elements prior to the actual + * cryptographic validation operation + */ + public SignatureValidationFilter(SignatureTrustEngine engine, Validator signatureValidator) { + if (engine == null) { + throw new IllegalArgumentException("Signature trust engine may not be null"); + } + + signatureTrustEngine = engine; + sigValidator = signatureValidator; + } + + /** + * Gets the trust engine used to validate signatures on incoming metadata. + * + * @return trust engine used to validate signatures on incoming metadata + */ + public SignatureTrustEngine getSignatureTrustEngine() { + return signatureTrustEngine; + } + + /** + * Get the validator used to perform pre-validation on Signature tokens. + * + * @return the configured Signature validator, or null + */ + public Validator getSignaturePrevalidator() { + return sigValidator; + } + + /** + * Gets whether incoming metadata's root element is required to be signed. + * + * @return whether incoming metadata is required to be signed + */ + public boolean getRequireSignature() { + return requireSignature; + } + + /** + * Sets whether incoming metadata's root element is required to be signed. + * + * @param require whether incoming metadata is required to be signed + */ + public void setRequireSignature(boolean require) { + requireSignature = require; + } + + /** + * Get the set of default criteria used as input to the trust engine. + * + * @return the criteria set + */ + public CriteriaSet getDefaultCriteria() { + return defaultCriteria; + } + + /** + * Set the set of default criteria used as input to the trust engine. + * + * @param newCriteria the new criteria set to use + */ + public void setDefaultCriteria(CriteriaSet newCriteria) { + defaultCriteria = newCriteria; + } + + /** {@inheritDoc} */ + public void doFilter(XMLObject metadata) throws FilterException { + SignableXMLObject signableMetadata = (SignableXMLObject) metadata; + + if (!signableMetadata.isSigned()){ + if (getRequireSignature()) { + throw new FilterException("Metadata root element was unsigned and signatures are required."); + } + } + + if (signableMetadata instanceof EntityDescriptor) { + processEntityDescriptor((EntityDescriptor) signableMetadata); + } else if (signableMetadata instanceof EntitiesDescriptor) { + processEntityGroup((EntitiesDescriptor) signableMetadata); + } else { + log.error("Internal error, metadata object was of an unsupported type: {}", metadata.getClass().getName()); + } + } + + /** + * Process the signatures on the specified EntityDescriptor and any signed children. + * + * If signature verification fails on a child, it will be removed from the entity descriptor. + * + * @param entityDescriptor the EntityDescriptor to be processed + * @throws FilterException thrown if an error occurs during the signature verification process + * on the root EntityDescriptor specified + */ + protected void processEntityDescriptor(EntityDescriptor entityDescriptor) throws FilterException { + String entityID = entityDescriptor.getEntityID(); + log.trace("Processing EntityDescriptor: {}", entityID); + + if (entityDescriptor.isSigned()) { + verifySignature(entityDescriptor, entityID, false); + } + + Iterator roleIter = entityDescriptor.getRoleDescriptors().iterator(); + while (roleIter.hasNext()) { + RoleDescriptor roleChild = roleIter.next(); + if (!roleChild.isSigned()) { + log.trace("RoleDescriptor member '{}' was not signed, skipping signature processing...", + roleChild.getElementQName()); + continue; + } else { + log.trace("Processing signed RoleDescriptor member: {}", roleChild.getElementQName()); + } + + try { + String roleID = getRoleIDToken(entityID, roleChild); + verifySignature(roleChild, roleID, false); + } catch (FilterException e) { + log.error("RoleDescriptor '{}' subordinate to entity '{}' failed signature verification, " + + "removing from metadata provider", + roleChild.getElementQName(), entityID); + roleIter.remove(); + } + } + + if (entityDescriptor.getAffiliationDescriptor() != null) { + AffiliationDescriptor affiliationDescriptor = entityDescriptor.getAffiliationDescriptor(); + if (!affiliationDescriptor.isSigned()) { + log.trace("AffiliationDescriptor member was not signed, skipping signature processing..."); + } else { + log.trace("Processing signed AffiliationDescriptor member with owner ID: {}", + affiliationDescriptor.getOwnerID()); + + try { + verifySignature(affiliationDescriptor, affiliationDescriptor.getOwnerID(), false); + } catch (FilterException e) { + log.error("AffiliationDescriptor with owner ID '{}' subordinate to entity '{}' " + + "failed signature verification, removing from metadata provider", + affiliationDescriptor.getOwnerID(), entityID); + entityDescriptor.setAffiliationDescriptor(null); + } + + } + } + } + + + /** + * Process the signatures on the specified EntitiesDescriptor and any signed children. + * + * If signature verification fails on a child, it will be removed from the entities descriptor group. + * + * @param entitiesDescriptor the EntitiesDescriptor to be processed + * @throws FilterException thrown if an error occurs during the signature verification process + * on the root EntitiesDescriptor specified + */ + protected void processEntityGroup(EntitiesDescriptor entitiesDescriptor) throws FilterException { + log.trace("Processing EntitiesDescriptor group: {}", entitiesDescriptor.getName()); + + if (entitiesDescriptor.isSigned()) { + verifySignature(entitiesDescriptor, entitiesDescriptor.getName(), true); + } + + Iterator entityIter = entitiesDescriptor.getEntityDescriptors().iterator(); + while (entityIter.hasNext()) { + EntityDescriptor entityChild = entityIter.next(); + if (!entityChild.isSigned()) { + log.trace("EntityDescriptor member '{}' was not signed, skipping signature processing...", + entityChild.getEntityID()); + continue; + } else { + log.trace("Processing signed EntityDescriptor member: {}", entityChild.getEntityID()); + } + + try { + processEntityDescriptor(entityChild); + } catch (FilterException e) { + log.error("EntityDescriptor '{}' failed signature verification, removing from metadata provider", + entityChild.getEntityID()); + entityIter.remove(); + } + } + + Iterator entitiesIter = entitiesDescriptor.getEntitiesDescriptors().iterator(); + while(entitiesIter.hasNext()) { + EntitiesDescriptor entitiesChild = entitiesIter.next(); + log.trace("Processing EntitiesDescriptor member: {}", entitiesChild.getName()); + try { + processEntityGroup(entitiesChild); + } catch (FilterException e) { + log.error("EntitiesDescriptor '{}' failed signature verification, removing from metadata provider", + entitiesChild.getName()); + entitiesIter.remove(); + } + } + + } + + /** + * Evaluate the signature on the signed metadata instance. + * + * @param signedMetadata the metadata object whose signature is to be verified + * @param metadataEntryName the EntityDescriptor entityID, EntitiesDescriptor Name, + * AffiliationDescriptor affiliationOwnerID, + * or RoleDescriptor {@link #getRoleIDToken(String, RoleDescriptor)} + * corresponding to the element whose signature is being evaluated. + * This is used exclusively for logging/debugging purposes and + * should not be used operationally (e.g. for building a criteria set). + * @param isEntityGroup flag indicating whether the signed object is a metadata group (EntitiesDescriptor), + * primarily useful for constructing a criteria set for the trust engine + * @throws FilterException thrown if the metadata entry's signature can not be established as trusted, + * or if an error occurs during the signature verification process + */ + protected void verifySignature(SignableXMLObject signedMetadata, String metadataEntryName, + boolean isEntityGroup) throws FilterException { + + log.debug("Verifying signature on metadata entry: {}", metadataEntryName); + + Signature signature = signedMetadata.getSignature(); + if (signature == null) { + // We shouldn't ever be calling this on things that aren't actually signed, but just to be safe... + log.warn("Signature was null, skipping processing on metadata entry: {}", metadataEntryName); + return; + } + + performPreValidation(signature, metadataEntryName); + + CriteriaSet criteriaSet = buildCriteriaSet(signedMetadata, metadataEntryName, isEntityGroup); + + try { + if ( getSignatureTrustEngine().validate(signature, criteriaSet) ) { + log.trace("Signature trust establishment succeeded for metadata entry {}", metadataEntryName); + return; + } else { + log.error("Signature trust establishment failed for metadata entry {}", metadataEntryName); + throw new FilterException("Signature trust establishment failed for metadata entry"); + } + } catch (SecurityException e) { + // Treat evaluation errors as fatal + log.error("Error processing signature verification for metadata entry '{}': {} ", + metadataEntryName, e.getMessage()); + throw new FilterException("Error processing signature verification for metadata entry", e); + } + } + + /** + * Perform pre-validation on the Signature token. + * + * @param signature the signature to evaluate + * @param metadataEntryName the EntityDescriptor entityID, EntitiesDescriptor Name, + * AffiliationDescriptor affiliationOwnerID, + * or RoleDescriptor {@link #getRoleIDToken(String, RoleDescriptor)} + * corresponding to the element whose signature is being evaluated. + * This is used exclusively for logging/debugging purposes and + * should not be used operationally (e.g. for building a criteria set). + * @throws FilterException thrown if the signature element fails pre-validation + */ + protected void performPreValidation(Signature signature, String metadataEntryName) throws FilterException { + if (getSignaturePrevalidator() != null) { + try { + getSignaturePrevalidator().validate(signature); + } catch (ValidationException e) { + log.error("Signature on metadata entry '{}' failed signature pre-validation", metadataEntryName); + throw new FilterException("Metadata instance signature failed signature pre-validation", e); + } + } + } + + /** + * Build the criteria set which will be used as input to the configured trust engine. + * + * @param signedMetadata the metadata element whose signature is being verified + * @param metadataEntryName the EntityDescriptor entityID, EntitiesDescriptor Name, + * AffiliationDescriptor affiliationOwnerID, + * or RoleDescriptor {@link #getRoleIDToken(String, RoleDescriptor)} + * corresponding to the element whose signature is being evaluated. + * This is used exclusively for logging/debugging purposes and + * should not be used operationally (e.g. for building the criteria set). + * @param isEntityGroup flag indicating whether the signed object is a metadata group (EntitiesDescriptor) + * @return the newly constructed criteria set + */ + protected CriteriaSet buildCriteriaSet(SignableXMLObject signedMetadata, + String metadataEntryName, boolean isEntityGroup) { + + CriteriaSet newCriteriaSet = new CriteriaSet(); + + if (getDefaultCriteria() != null) { + newCriteriaSet.addAll( getDefaultCriteria() ); + } + + if (!newCriteriaSet.contains(UsageCriteria.class)) { + newCriteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); + } + + // TODO how to handle adding dynamic entity ID and/or other criteria for trust engine consumption? + // + // Have 4 signed metadata types: + // 1) EntitiesDescriptor + // 2) EntityDescriptor + // 3) RoleDescriptor + // 4) AffiliationDescriptor + // + // Logic will likely vary for how to specify criteria to trust engine for different types + specific use cases, + // e.g. for federation metadata publishers of EntitiesDescriptors vs. "self-signed" EntityDescriptors. + // May need to delegate to more specialized subclasses. + + return newCriteriaSet; + } + + /** + * Get a string token for logging/debugging purposes that contains role information and containing entityID. + * + * @param entityID the containing entityID + * @param role the role descriptor + * + * @return the constructed role ID token. + */ + protected String getRoleIDToken(String entityID, RoleDescriptor role) { + String roleName = role.getElementQName().getLocalPart(); + return "[Role: " + entityID + "::" + roleName + "]"; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/provider/package.html 17 Aug 2012 15:03:13 -0000 1.1 @@ -0,0 +1,12 @@ + + +Class for retrieving, filtering, and querying metadata. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/support/AttributeConsumingServiceSelector.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/support/AttributeConsumingServiceSelector.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/support/AttributeConsumingServiceSelector.java 17 Aug 2012 15:03:32 -0000 1.1 @@ -0,0 +1,249 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.support; + +import java.util.List; + +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.samlext.saml2mdquery.AttributeQueryDescriptorType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Metadata support class which selects an {@link AttributeConsumingService} based on input of a mandatory + * {@link RoleDescriptor} and an optional index. + * + *

+ * This implementation supports selecting an AttributeConsumingService from parent role descriptors of the following + * types: + * + *

    + *
  1. the standard SAML 2 metadata type {@link SPSSODescriptor}
  2. + *
  3. the extension type {@link AttributeQueryDescriptorType}
  4. + *
+ *

+ * + *

+ * Subclasses should override {@link #getCandidates()} if support for additional sources of attribute consuming services + * is needed. + *

+ * + *

+ * The selection algorithm is: + *

    + *
  1. If an index is supplied, the service with that index is returned. If no such service exists in metadata: if + * {@link #isOnBadIndexUseDefault()} is true, then the default service is returned as described below; otherwise null is + * returned.
  2. + *
  3. If an index is not supplied, then the default service is returned as follows: The service with an explicit + * isDefault of true is returned. If no such service exists, then the first service without an explicit isDefault is + * returned. If no service is yet selected, then the first service listed in metadata is returned.
  4. + *
+ *

+ */ +public class AttributeConsumingServiceSelector { + + /** Class logger. */ + private Logger log = LoggerFactory.getLogger(AttributeConsumingServiceSelector.class); + + /** The requested service index. */ + private Integer index; + + /** The AttributeConsumingService's parent role descriptor. */ + private RoleDescriptor roleDescriptor; + + /** + * Flag which determines whether, in the case of an invalid index, to return the default AttributeConsumingService. + */ + private boolean onBadIndexUseDefault; + + /** + * Get the index of the desired service. + * + * @return Returns the index. + */ + public Integer getIndex() { + return index; + } + + /** + * Set the index of the desired service. + * + * @param requestedIndex The index to set. + */ + public void setIndex(Integer requestedIndex) { + index = requestedIndex; + } + + /** + * Get the AttributeConsumingServie's parent RoleDescriptor. + * + * @return Returns the spSSODescriptor. + */ + public RoleDescriptor getRoleDescriptor() { + return roleDescriptor; + } + + /** + * Set the AttributeConsumingServie's parent RoleDescriptor. + * + * @param descriptor The roleDescriptor to set. + */ + public void setRoleDescriptor(RoleDescriptor descriptor) { + roleDescriptor = descriptor; + } + + /** + * Set the flag which determines whether, in the case of an invalid index, to return the default + * AttributeConsumingService. Defaults to false. + * + * @param flag The onBadIndexUseDefault to set. + */ + public void setOnBadIndexUseDefault(boolean flag) { + onBadIndexUseDefault = flag; + } + + /** + * Get the flag which determines whether, in the case of an invalid index, to return the default + * AttributeConsumingService. Defaults to false. + * + * @return Returns the onBadIndexUseDefault. + */ + public boolean isOnBadIndexUseDefault() { + return onBadIndexUseDefault; + } + + /** + * Select the AttributeConsumingService. + * + * @return the selected AttributeConsumingService, or null + */ + public AttributeConsumingService selectService() { + List candidates = getCandidates(); + + if (candidates == null || candidates.isEmpty()) { + log.debug("AttributeConsumingService candidate list was empty, can not select service"); + return null; + } + + log.debug("AttributeConsumingService index was specified: {}", index != null); + + AttributeConsumingService acs = null; + if (index != null) { + acs = selectByIndex(candidates); + if (acs == null && isOnBadIndexUseDefault()) { + acs = selectDefault(candidates); + } + } else { + return selectDefault(candidates); + } + + return acs; + } + + /** + * Get the list of candidate attribute consuming services. + * + *

+ * This implementation supports selecting an AttributeConsumingService from parent role descriptors of the following + * types: + * + *

    + *
  1. the standard SAML 2 metadata type {@link SPSSODescriptor}
  2. + *
  3. the extension type {@link AttributeQueryDescriptorType}
  4. + *
+ *

+ * + *

+ * Subclasses should override if support for additional sources of attribute consuming services is needed. + *

+ * + * @return the list of candidate AttributeConsumingServices, or null if none could be resolved + */ + protected List getCandidates() { + if (roleDescriptor == null) { + log.debug("RoleDescriptor was not supplied, unable to select AttributeConsumingService"); + return null; + } + + if (roleDescriptor instanceof SPSSODescriptor) { + log.debug("Resolving AttributeConsumingService candidates from SPSSODescriptor"); + return ((SPSSODescriptor) roleDescriptor).getAttributeConsumingServices(); + } else if (roleDescriptor instanceof AttributeQueryDescriptorType) { + log.debug("Resolving AttributeConsumingService candidates from AttributeQueryDescriptorType"); + return ((AttributeQueryDescriptorType) roleDescriptor).getAttributeConsumingServices(); + } else { + log.debug("Unable to resolve service candidates, role descriptor was of an unsupported type: {}", + roleDescriptor.getClass().getName()); + return null; + } + } + + /** + * Select the service based on the index value. + * + * @param candidates the list of candiate services + * @return the selected candidate or null + */ + private AttributeConsumingService selectByIndex(List candidates) { + log.debug("Selecting AttributeConsumingService by index"); + for (AttributeConsumingService attribCS : candidates) { + // Check for null b/c don't ever want to fail with an NPE due to autoboxing. + // Note: metadata index property is an int, not an Integer. + if (index != null) { + if (index == attribCS.getIndex()) { + log.debug("Selected AttributeConsumingService with index: {}", index); + return attribCS; + } + } + } + log.debug("A service index of '{}' was specified, but was not found in metadata", index); + return null; + } + + /** + * Select the default service. + * + * @param candidates the list of candiate services + * @return the selected candidate or null + */ + private AttributeConsumingService selectDefault(List candidates) { + log.debug("Selecting default AttributeConsumingService"); + AttributeConsumingService firstNoDefault = null; + for (AttributeConsumingService attribCS : candidates) { + if (attribCS.isDefault()) { + log.debug("Selected AttributeConsumingService with explicit isDefault of true"); + return attribCS; + } + + // This records the first element whose isDefault is not explicitly false + if (firstNoDefault == null && attribCS.isDefaultXSBoolean() == null) { + firstNoDefault = attribCS; + } + } + + if (firstNoDefault != null) { + log.debug("Selected first AttributeConsumingService with no explicit isDefault"); + return firstNoDefault; + } else { + log.debug("Selected first AttributeConsumingService with explicit isDefault of false"); + return candidates.get(0); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/support/SAML2MetadataHelper.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/support/SAML2MetadataHelper.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/support/SAML2MetadataHelper.java 17 Aug 2012 15:03:31 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.support; + +import java.util.List; + + +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility helper class for SAML 2 metadata objects. + */ +public final class SAML2MetadataHelper { + + /** Constructor. */ + private SAML2MetadataHelper() { } + + /** + * Select the default {@link IndexedEndpoint} from a list of candidates. + * + *

+ * The algorithm used is: + *

    + *
  1. Select the first endpoint with an explicit isDefault=true
  2. + *
  3. Select the first endpoint with no explicit isDefault
  4. + *
  5. Select the first endpoint
  6. + *
+ *

+ * + * + * @param candidates the list of candidate indexed endpoints + * @return the selected candidate (or null if the list is null or empty) + * + * @param the subtype of IndexedType + * + */ + public static T getDefaultIndexedEndpoint(List candidates) { + Logger log = getLogger(); + log.debug("Selecting default IndexedEndpoint"); + + if (candidates == null || candidates.isEmpty()) { + log.debug("IndexedEndpoint list was null or empty, returning null"); + return null; + } + + T firstNoDefault = null; + for (T endpoint : candidates) { + if (endpoint.isDefault()) { + log.debug("Selected IndexedEndpoint with explicit isDefault of true"); + return endpoint; + } + + // This records the first element whose isDefault is not explicitly false + if (firstNoDefault == null && endpoint.isDefaultXSBoolean() == null) { + firstNoDefault = endpoint; + } + } + + if (firstNoDefault != null) { + log.debug("Selected first IndexedEndpoint with no explicit isDefault"); + return firstNoDefault; + } else { + log.debug("Selected first IndexedEndpoint with explicit isDefault of false"); + return candidates.get(0); + } + + } + + /** + * Get an SLF4J Logger. + * + * @return a Logger instance + */ + private static Logger getLogger() { + return LoggerFactory.getLogger(SAML2MetadataHelper.class); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AdditionalMetadataLocationSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AdditionalMetadataLocationSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AdditionalMetadataLocationSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AdditionalMetadataLocation; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.AdditionalMetadataLocation} for Schema compliance. + */ +public class AdditionalMetadataLocationSchemaValidator implements Validator { + + /** Constructor */ + public AdditionalMetadataLocationSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AdditionalMetadataLocation aml) throws ValidationException { + validateLocation(aml); + validateNamespace(aml); + } + + /** + * Checks that Location is present. + * + * @param aml + * @throws ValidationException + */ + protected void validateLocation(AdditionalMetadataLocation aml) throws ValidationException { + if (DatatypeHelper.isEmpty(aml.getLocationURI())) { + throw new ValidationException("Location required"); + } + } + + /** + * Checks that Namespace is present. + * + * @param aml + * @throws ValidationException + */ + protected void validateNamespace(AdditionalMetadataLocation aml) throws ValidationException { + if (DatatypeHelper.isEmpty(aml.getNamespaceURI())) { + throw new ValidationException("Namespace required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AffiliateMemberSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AffiliateMemberSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AffiliateMemberSchemaValidator.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AffiliateMember; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.AffiliateMember} for Schema compliance. + */ +public class AffiliateMemberSchemaValidator implements Validator { + + /** Constructor */ + public AffiliateMemberSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AffiliateMember affiliateMember) throws ValidationException { + validateID(affiliateMember); + } + + /** + * Checks that ID is valid and present. + * + * @param affiliateMember + * @throws ValidationException + */ + protected void validateID(AffiliateMember affiliateMember) throws ValidationException { + if (DatatypeHelper.isEmpty(affiliateMember.getID())) { + throw new ValidationException("ID required"); + } else if (affiliateMember.getID().length() > 1024) { + throw new ValidationException("Max ID length is 1024"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AffiliationDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AffiliationDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AffiliationDescriptorSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,70 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AffiliationDescriptor; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.AffiliationDescriptor} for Schema compliance. + */ +public class AffiliationDescriptorSchemaValidator implements Validator { + + /** Constructor */ + public AffiliationDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AffiliationDescriptor affiliationDescriptor) throws ValidationException { + validateOwner(affiliationDescriptor); + validateMember(affiliationDescriptor); + } + + /** + * Checks that OwnerID is present and valid. + * + * @param affiliationDescriptor + * @throws ValidationException + */ + protected void validateOwner(AffiliationDescriptor affiliationDescriptor) throws ValidationException { + if (DatatypeHelper.isEmpty(affiliationDescriptor.getOwnerID())) { + throw new ValidationException("Owner ID required."); + } else if (affiliationDescriptor.getOwnerID().length() > 1024) { + throw new ValidationException("Max Owner ID length is 1024."); + } + } + + /** + * Checks that at least one Member is present. + * + * @param affiliationDescriptor + * @throws ValidationException + */ + protected void validateMember(AffiliationDescriptor affiliationDescriptor) throws ValidationException { + if (affiliationDescriptor.getMembers() == null || affiliationDescriptor.getMembers().size() < 1) { + throw new ValidationException("Must have one or more Affiliation Members."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ArtifactResolutionServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ArtifactResolutionServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ArtifactResolutionServiceSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.ArtifactResolutionService; + +/** + * Checks {@link org.opensaml.saml2.metadata.ArtifactResolutionService} for Schema compliance. + */ +public class ArtifactResolutionServiceSchemaValidator extends IndexedEndpointSchemaValidator { + + /** Constructor */ + public ArtifactResolutionServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ArtifactResolutionServiceSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ArtifactResolutionServiceSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ArtifactResolutionServiceSpecValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.ArtifactResolutionService; + +/** + * Checks {@link org.opensaml.saml2.metadata.ArtifactResolutionService} for Spec compliance. + */ +public class ArtifactResolutionServiceSpecValidator extends IndexedEndpointSchemaValidator { + + /** Constructor */ + public ArtifactResolutionServiceSpecValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AssertionConsumerServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AssertionConsumerServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AssertionConsumerServiceSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AssertionConsumerService; + +/** + * Checks {@link org.opensaml.saml2.metadata.AssertionConsumerService} for Schema compliance. + */ +public class AssertionConsumerServiceSchemaValidator extends IndexedEndpointSchemaValidator { + + /** Constructor */ + public AssertionConsumerServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AssertionIDRequestServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AssertionIDRequestServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AssertionIDRequestServiceSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AssertionIDRequestService; + +/** + * Checks {@link org.opensaml.saml2.metadata.AssertionIDRequestService} for Schema compliance. + */ +public class AssertionIDRequestServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public AssertionIDRequestServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeAuthorityDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeAuthorityDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeAuthorityDescriptorSchemaValidator.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.AttributeAuthorityDescriptor} for Schema compliance. + */ +public class AttributeAuthorityDescriptorSchemaValidator extends RoleDescriptorSchemaValidator { + + /** Constructor */ + public AttributeAuthorityDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AttributeAuthorityDescriptor attributeAuthorityDescriptor) throws ValidationException { + super.validate(attributeAuthorityDescriptor); + validateAttributeServices(attributeAuthorityDescriptor); + } + + /** + * Checks that at least one AttributeService is present. + * + * @param attributeAuthorityDescriptor + * @throws ValidationException + */ + protected void validateAttributeServices(AttributeAuthorityDescriptor attributeAuthorityDescriptor) + throws ValidationException { + if (attributeAuthorityDescriptor.getAttributeServices() == null + || attributeAuthorityDescriptor.getAttributeServices().size() == 0) { + throw new ValidationException("Must have one or more AttributeServices."); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeAuthorityDescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeAuthorityDescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeAuthorityDescriptorSpecValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor; + +/** + * Checks {@link org.opensaml.saml2.metadata.AttributeAuthorityDescriptor} for Spec compliance. + */ +public class AttributeAuthorityDescriptorSpecValidator extends RoleDescriptorSpecValidator { + + /** Constructor */ + public AttributeAuthorityDescriptorSpecValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeConsumingServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeConsumingServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeConsumingServiceSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,82 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.AttributeConsumingService} for Schema compliance. + */ +public class AttributeConsumingServiceSchemaValidator implements Validator { + + /** Constructor */ + public AttributeConsumingServiceSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AttributeConsumingService attributeConsumingService) throws ValidationException { + validateIndex(attributeConsumingService); + validateServiceNames(attributeConsumingService); + validateRequestedAttributes(attributeConsumingService); + } + + /** + * Checks that Index is positive. + * + * @param attributeConsumingService + * @throws ValidationException + */ + protected void validateIndex(AttributeConsumingService attributeConsumingService) throws ValidationException { + if (attributeConsumingService.getIndex() < 0) { + throw new ValidationException("Index must be positive integer"); + } + } + + /** + * Checks that one or more Service Names are present. + * + * @param attributeConsumingService + * @throws ValidationException + */ + protected void validateServiceNames(AttributeConsumingService attributeConsumingService) throws ValidationException { + if (attributeConsumingService.getNames() == null || attributeConsumingService.getNames().size() == 0) { + throw new ValidationException("Must have one or more Service Names."); + } + } + + /** + * Checks that one or more Requested Attributes are present. + * + * @param attributeConsumingService + * @throws ValidationException + */ + protected void validateRequestedAttributes(AttributeConsumingService attributeConsumingService) + throws ValidationException { + if (attributeConsumingService.getRequestAttributes() == null + || attributeConsumingService.getRequestAttributes().size() == 0) { + throw new ValidationException("Must have one or more Requested Attributes."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeProfileSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeProfileSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeProfileSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AttributeProfile; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.AttributeProfile} for Schema compliance. + */ +public class AttributeProfileSchemaValidator implements Validator { + + /** Constructor */ + public AttributeProfileSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AttributeProfile attributeProfile) throws ValidationException { + validateProfileURI(attributeProfile); + } + + /** + * Checks that ProfileURI is present. + * + * @param attributeProfile + * @throws ValidationException + */ + protected void validateProfileURI(AttributeProfile attributeProfile) throws ValidationException { + if (DatatypeHelper.isEmpty(attributeProfile.getProfileURI())) { + throw new ValidationException("ProfileURI required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AttributeServiceSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AttributeService; + +/** + * Checks {@link org.opensaml.saml2.metadata.AttributeService} for Schema compliance. + */ +public class AttributeServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public AttributeServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnAuthorityDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnAuthorityDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnAuthorityDescriptorSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.AuthnAuthorityDescriptor} for Schema compliance. + */ +public class AuthnAuthorityDescriptorSchemaValidator extends RoleDescriptorSchemaValidator { + + /** Constructor */ + public AuthnAuthorityDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(AuthnAuthorityDescriptor authnAuthorityDescriptor) throws ValidationException { + super.validate(authnAuthorityDescriptor); + validateAuthnQueryServices(authnAuthorityDescriptor); + } + + /** + * Checks that at least one AuthnService is present. + * + * @param authnAuthorityDescriptor + * @throws ValidationException + */ + protected void validateAuthnQueryServices(AuthnAuthorityDescriptor authnAuthorityDescriptor) + throws ValidationException { + if (authnAuthorityDescriptor.getAuthnQueryServices() == null + || authnAuthorityDescriptor.getAuthnQueryServices().size() == 0) { + throw new ValidationException("Must have one or more AuthnQueryServices."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnAuthorityDescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnAuthorityDescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnAuthorityDescriptorSpecValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor; + +/** + * Checks {@link org.opensaml.saml2.metadata.AuthnAuthorityDescriptor} for Spec compliance. + */ +public class AuthnAuthorityDescriptorSpecValidator extends RoleDescriptorSpecValidator { + + /** Constructor */ + public AuthnAuthorityDescriptorSpecValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnQueryServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnQueryServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthnQueryServiceSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AuthnQueryService; + +/** + * Checks {@link org.opensaml.saml2.metadata.AuthnQueryService} for Schema compliance. + */ +public class AuthnQueryServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public AuthnQueryServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthzServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthzServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/AuthzServiceSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.AuthzService; + +/** + * Checks {@link org.opensaml.saml2.metadata.AuthzService} for Schema compliance. + */ +public class AuthzServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public AuthzServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/CompanySchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/CompanySchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/CompanySchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.Company; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.Company} for Schema compliance. + */ +public class CompanySchemaValidator implements Validator { + + /** Constructor */ + public CompanySchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Company company) throws ValidationException { + validateName(company); + } + + /** + * Checks that Name is present. + * + * @param company + * @throws ValidationException + */ + protected void validateName(Company company) throws ValidationException { + if (DatatypeHelper.isEmpty(company.getName())) { + throw new ValidationException("Name required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ContactPersonSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ContactPersonSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ContactPersonSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.ContactPerson} for Schema compliance. + */ +public class ContactPersonSchemaValidator implements Validator { + + /** Constructor */ + public ContactPersonSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(ContactPerson contactPerson) throws ValidationException { + validateType(contactPerson); + } + + /** + * Checks that Type is present. + * + * @param contactPerson + * @throws ValidationException + */ + protected void validateType(ContactPerson contactPerson) throws ValidationException { + if (contactPerson.getType() == null) { + throw new ValidationException("Type required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EmailAddressSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EmailAddressSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EmailAddressSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.EmailAddress; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.EmailAddress} for Schema compliance. + */ +public class EmailAddressSchemaValidator implements Validator { + + /** Constructor */ + public EmailAddressSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EmailAddress emailAddress) throws ValidationException { + validateAddress(emailAddress); + } + + /** + * Checks that Address is present. + * + * @param emailAddress + * @throws ValidationException + */ + protected void validateAddress(EmailAddress emailAddress) throws ValidationException { + if (DatatypeHelper.isEmpty(emailAddress.getAddress())) { + throw new ValidationException("Address required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EncryptionMethodSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EncryptionMethodSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EncryptionMethodSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.EncryptionMethod; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.EncryptionMethod} for Schema compliance. + */ +public class EncryptionMethodSchemaValidator implements Validator { + + /** Constructor. */ + public EncryptionMethodSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EncryptionMethod encMethod) throws ValidationException { + validateAlgorithm(encMethod); + } + + /** + * Checks that Algorithm URI attribute is present and not empty. + * + * @param encMethod the encryption method to validate + * @throws ValidationException thrown if Algorithm attribute is missing or empty + */ + protected void validateAlgorithm(EncryptionMethod encMethod) throws ValidationException { + if (DatatypeHelper.isEmpty(encMethod.getAlgorithm())) { + throw new ValidationException("Algorithm URI attribute is required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EndpointSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EndpointSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EndpointSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.Endpoint} for Schema compliance. + */ +public class EndpointSchemaValidator implements Validator { + + /** Constructor */ + public EndpointSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EndpointType endpoint) throws ValidationException { + validateBinding(endpoint); + validateLocation(endpoint); + } + + /** + * Checks that Binding is present. + * + * @param endpoint + * @throws ValidationException + */ + protected void validateBinding(Endpoint endpoint) throws ValidationException { + if (DatatypeHelper.isEmpty(endpoint.getBinding())) { + throw new ValidationException("Binding required"); + } + } + + /** + * Checks that Location is present. + * + * @param endpoint + * @throws ValidationException + */ + protected void validateLocation(Endpoint endpoint) throws ValidationException { + if (DatatypeHelper.isEmpty(endpoint.getLocation())) { + throw new ValidationException("Location required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntitiesDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntitiesDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntitiesDescriptorSchemaValidator.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.EntitiesDescriptor} for Schema compliance. + */ +public class EntitiesDescriptorSchemaValidator implements Validator { + + /** Constructor */ + public EntitiesDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EntitiesDescriptor entitiesDescriptor) throws ValidationException { + validateEntityDescriptors(entitiesDescriptor); + } + + /** + * Checks that at least one EntitiesDescriptor or EntityDescriptor is present. + * + * @param entitiesDescriptor + * @throws ValidationException + */ + protected void validateEntityDescriptors(EntitiesDescriptor entitiesDescriptor) throws ValidationException { + if ((entitiesDescriptor.getEntitiesDescriptors() == null || entitiesDescriptor.getEntitiesDescriptors().size() < 1) + && (entitiesDescriptor.getEntityDescriptors() == null || entitiesDescriptor.getEntityDescriptors() + .size() < 1)) { + throw new ValidationException("Must have one or more EntitiesDescriptor or EntityDescriptor."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntitiesDescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntitiesDescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntitiesDescriptorSpecValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.EntitiesDescriptor} for Spec compliance. + */ +public class EntitiesDescriptorSpecValidator implements Validator { + + /** Constructor */ + public EntitiesDescriptorSpecValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EntitiesDescriptor entitiesDescriptor) throws ValidationException { + validateRoot(entitiesDescriptor); + } + + /** + * Checks that at least either Valid Until or Cache Duration is present when Entities Descriptor is root element. + * + * @param entitiesDescriptor + * @throws ValidationException + */ + protected void validateRoot(EntitiesDescriptor entitiesDescriptor) throws ValidationException { + if (entitiesDescriptor.getParent() == null && entitiesDescriptor.getValidUntil() == null + && entitiesDescriptor.getCacheDuration() == null) { + throw new ValidationException("Must have either ValidUntil or CacheDuration when is root element."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntityDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntityDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntityDescriptorSchemaValidator.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.EntityDescriptor} for Schema compliance. + */ +public class EntityDescriptorSchemaValidator implements Validator { + + /** Constructor */ + public EntityDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EntityDescriptor entityDescriptor) throws ValidationException { + validateEntityID(entityDescriptor); + validateDescriptors(entityDescriptor); + } + + /** + * Checks that EntityID is present and valid. + * + * @param entityDescriptor + * @throws ValidationException + */ + protected void validateEntityID(EntityDescriptor entityDescriptor) throws ValidationException { + if (DatatypeHelper.isEmpty(entityDescriptor.getEntityID())) { + throw new ValidationException("Entity ID required."); + } else if (entityDescriptor.getEntityID().length() > 1024) { + throw new ValidationException("Max Entity ID length is 1024."); + } + } + + /** + * Checks that an AffiliationDescriptor OR one or more RoleDescriptors are present. + * + * @param entityDescriptor + * @throws ValidationException + */ + protected void validateDescriptors(EntityDescriptor entityDescriptor) throws ValidationException { + if ((entityDescriptor.getRoleDescriptors() == null || entityDescriptor.getRoleDescriptors().size() < 1) + && entityDescriptor.getAffiliationDescriptor() == null) { + throw new ValidationException("Must have an AffiliationDescriptor or one or more RoleDescriptors."); + } + + if (entityDescriptor.getAffiliationDescriptor() != null && entityDescriptor.getRoleDescriptors() != null + && entityDescriptor.getRoleDescriptors().size() > 0) { + throw new ValidationException("Cannot have an AffiliationDescriptor AND RoleDescriptors"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntityDescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntityDescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/EntityDescriptorSpecValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.EntityDescriptor} for Spec compliance. + */ +public class EntityDescriptorSpecValidator implements Validator { + + /** Constructor */ + public EntityDescriptorSpecValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EntityDescriptor entityDescriptor) throws ValidationException { + validateRoot(entityDescriptor); + } + + /** + * Checks that at least either Valid Until or Cache Duration is present when Entity Descriptor is root element. + * + * @param entityDescriptor + * @throws ValidationException + */ + protected void validateRoot(EntityDescriptor entityDescriptor) throws ValidationException { + if (entityDescriptor.getParent() == null && entityDescriptor.getValidUntil() == null + && entityDescriptor.getCacheDuration() == null) { + throw new ValidationException("Must have either ValidUntil or CacheDuration when is root element."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/GivenNameSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/GivenNameSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/GivenNameSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.GivenName; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.GivenName} for Schema compliance. + */ +public class GivenNameSchemaValidator implements Validator { + + /** Constructor */ + public GivenNameSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(GivenName givenName) throws ValidationException { + validateName(givenName); + } + + /** + * Checks that Name is present. + * + * @param givenName + * @throws ValidationException + */ + protected void validateName(GivenName givenName) throws ValidationException { + if (DatatypeHelper.isEmpty(givenName.getName())) { + throw new ValidationException("Name required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IDPSSODescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IDPSSODescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IDPSSODescriptorSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.IDPSSODescriptor} for Schema compliance. + */ +public class IDPSSODescriptorSchemaValidator extends SSODescriptorSchemaValidator { + + /** Constructor */ + public IDPSSODescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(IDPSSODescriptor idpssoDescriptor) throws ValidationException { + super.validate(idpssoDescriptor); + validateSingleSignOnService(idpssoDescriptor); + } + + /** + * Checks that at least one SingleSignOnService is present. + * + * @param idpssoDescriptor + * @throws ValidationException + */ + protected void validateSingleSignOnService(IDPSSODescriptor idpssoDescriptor) throws ValidationException { + if (idpssoDescriptor.getSingleSignOnServices() == null || idpssoDescriptor.getSingleSignOnServices().size() < 1) { + throw new ValidationException("Must have one or more SingleSignOnServices."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IDPSSODescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IDPSSODescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IDPSSODescriptorSpecValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.IDPSSODescriptor} for Spec compliance. + */ +public class IDPSSODescriptorSpecValidator extends SSODescriptorSpecValidator { + + /** Constructor */ + public IDPSSODescriptorSpecValidator() { + + } + + public void validate(IDPSSODescriptor idpssoDescriptor) throws ValidationException { + super.validate(idpssoDescriptor); + validateSingleSign(idpssoDescriptor); + validateNameIDMapping(idpssoDescriptor); + } + + protected void validateSingleSign(IDPSSODescriptor idpssoDescriptor) throws ValidationException { + if (idpssoDescriptor.getSingleSignOnServices() != null && idpssoDescriptor.getSingleSignOnServices().size() > 0) { + for (int i = 0; i < idpssoDescriptor.getSingleSignOnServices().size(); i++) { + if (!DatatypeHelper.isEmpty(idpssoDescriptor.getSingleSignOnServices().get(i).getResponseLocation())) { + throw new ValidationException("ResponseLocation of all SingleSignOnServices must be null"); + } + } + } + } + + protected void validateNameIDMapping(IDPSSODescriptor idpssoDescriptor) throws ValidationException { + if (idpssoDescriptor.getNameIDMappingServices() != null + && idpssoDescriptor.getNameIDMappingServices().size() > 0) { + for (int i = 0; i < idpssoDescriptor.getNameIDMappingServices().size(); i++) { + if (!DatatypeHelper.isEmpty(idpssoDescriptor.getNameIDMappingServices().get(i).getResponseLocation())) { + throw new ValidationException("ResponseLocation of all NameIDMappingServices must be null"); + } + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IndexedEndpointSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IndexedEndpointSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/IndexedEndpointSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.IndexedEndpoint; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.IndexedEndpoint} for Schema compliance. + */ +public class IndexedEndpointSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public IndexedEndpointSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(EndpointType indexedEndpoint) throws ValidationException { + super.validate(indexedEndpoint); + validateIndex(indexedEndpoint); + } + + /** + * Checks that Index is non-negative. + * + * @param indexedEndpoint + * @throws ValidationException + */ + protected void validateIndex(IndexedEndpoint indexedEndpoint) throws ValidationException { + if (indexedEndpoint.getIndex() < 0) { + throw new ValidationException("Index must be non-negative"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/KeyDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/KeyDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/KeyDescriptorSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.KeyDescriptor} for Schema compliance. + */ +public class KeyDescriptorSchemaValidator implements Validator { + + /** Constructor. */ + public KeyDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(KeyDescriptor keyDescriptor) throws ValidationException { + validateKeyInfo(keyDescriptor); + validateUse(keyDescriptor); + } + + /** + * Checks that KeyInfo is present. + * + * @param keyDescriptor the key descriptor to validate + * @throws ValidationException thrown if KeyInfo is not present + */ + protected void validateKeyInfo(KeyDescriptor keyDescriptor) throws ValidationException { + if (keyDescriptor.getKeyInfo()==null) { + throw new ValidationException("KeyInfo required"); + } + } + + /** + * Checks that use attribute has only one of allowed values. + * + * @param keyDescriptor the key descriptor to validate + * @throws ValidationException throw in use attribute does not have a legal value + */ + protected void validateUse(KeyDescriptor keyDescriptor) throws ValidationException { + UsageType use = keyDescriptor.getUse(); + if (use == null) { + return; + } + if ( ! use.equals(UsageType.SIGNING) + && ! use.equals(UsageType.ENCRYPTION) + && ! use.equals(UsageType.UNSPECIFIED) ) { + throw new ValidationException("Invalid value for use attribute: " + use.toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ManageNameIDServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ManageNameIDServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ManageNameIDServiceSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.ManageNameIDService; + +/** + * Checks {@link org.opensaml.saml2.metadata.ManageNameIDService} for Schema compliance. + */ +public class ManageNameIDServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public ManageNameIDServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDFormatSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDFormatSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDFormatSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.NameIDFormat} for Schema compliance. + */ +public class NameIDFormatSchemaValidator implements Validator { + + /** Constructor */ + public NameIDFormatSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(NameIDFormat nameIDFormat) throws ValidationException { + validateFormat(nameIDFormat); + } + + /** + * Checks that Format is present. + * + * @param nameIDFormat + * @throws ValidationException + */ + protected void validateFormat(NameIDFormat nameIDFormat) throws ValidationException { + if (DatatypeHelper.isEmpty(nameIDFormat.getFormat())) { + throw new ValidationException("Format required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDMappingServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDMappingServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDMappingServiceSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.NameIDMappingService; + +/** + * Checks {@link org.opensaml.saml2.metadata.NameIDMappingService} for Schema compliance. + */ +public class NameIDMappingServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public NameIDMappingServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDMappingServiceSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDMappingServiceSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/NameIDMappingServiceSpecValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.NameIDMappingService; + +/** + * Checks {@link org.opensaml.saml2.metadata.NameIDMappingService} for Spec compliance. + */ +public class NameIDMappingServiceSpecValidator extends EndpointSchemaValidator { + + /** Constructor */ + public NameIDMappingServiceSpecValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationDisplayNameSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationDisplayNameSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationDisplayNameSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.OrganizationDisplayName; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.OrganizationDisplayName} for Schema compliance. + */ +public class OrganizationDisplayNameSchemaValidator implements Validator { + + /** Constructor */ + public OrganizationDisplayNameSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(OrganizationDisplayName name) throws ValidationException { + validateName(name); + } + + /** + * Checks that Name is present. + * + * @param organizationDisplayName + * @throws ValidationException + */ + protected void validateName(OrganizationDisplayName organizationDisplayName) throws ValidationException { + if (organizationDisplayName.getName() == null) { + throw new ValidationException("Name required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationNameSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationNameSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationNameSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.OrganizationName; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.OrganizationName} for Schema compliance. + */ +public class OrganizationNameSchemaValidator implements Validator { + + /** Constructor */ + public OrganizationNameSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(OrganizationName name) throws ValidationException { + validateName(name); + } + + /** + * Checks that Name is present. + * + * @param organizationName + * @throws ValidationException + */ + protected void validateName(OrganizationName organizationName) throws ValidationException { + if (organizationName.getName() == null) { + throw new ValidationException("Name required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationSchemaValidator.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.Organization} for Schema compliance. + */ +public class OrganizationSchemaValidator implements Validator { + + /** Constructor */ + public OrganizationSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(Organization organization) throws ValidationException { + validateName(organization); + validateDisplayName(organization); + validateURL(organization); + } + + /** + * Checks that at least one Organization Name is present. + * + * @param organization + * @throws ValidationException + */ + protected void validateName(Organization organization) throws ValidationException { + if (organization.getOrganizationNames() == null || organization.getOrganizationNames().size() < 1) { + throw new ValidationException("Must have one or more Organization Names."); + } + } + + /** + * Checks that at least one Display Name is present. + * + * @param organization + * @throws ValidationException + */ + protected void validateDisplayName(Organization organization) throws ValidationException { + if (organization.getDisplayNames() == null || organization.getDisplayNames().size() < 1) { + throw new ValidationException("Must have one or more Display Names."); + } + } + + /** + * Checks that at least one Organization URL is present. + * + * @param organization + * @throws ValidationException + */ + protected void validateURL(Organization organization) throws ValidationException { + if (organization.getURLs() == null || organization.getURLs().size() < 1) { + throw new ValidationException("Must have one or more Organization URLs."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationURLSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationURLSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/OrganizationURLSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.OrganizationURL; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.OrganizationURL} for Schema compliance. + */ +public class OrganizationURLSchemaValidator implements Validator { + + /** Constructor */ + public OrganizationURLSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(OrganizationURL organizationURL) throws ValidationException { + validateName(organizationURL); + } + + /** + * Checks that URL is present. + * + * @param organizationURL + * @throws ValidationException + */ + protected void validateName(OrganizationURL organizationURL) throws ValidationException { + if (organizationURL.getURL() == null) { + throw new ValidationException("URL required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/PDPDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/PDPDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/PDPDescriptorSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.PDPDescriptor; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.PDPDescriptor} for Schema compliance. + */ +public class PDPDescriptorSchemaValidator extends RoleDescriptorSchemaValidator { + + /** Constructor */ + public PDPDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(PDPDescriptor pdpDescriptor) throws ValidationException { + super.validate(pdpDescriptor); + validateAuthzServices(pdpDescriptor); + } + + /** + * Checks that one or more Authz Services are present. + * + * @param pdpDescriptor + * @throws ValidationException + */ + protected void validateAuthzServices(PDPDescriptor pdpDescriptor) throws ValidationException { + if (pdpDescriptor.getAuthzServices() == null || pdpDescriptor.getAuthzServices().size() == 0) { + throw new ValidationException("Must have one or more AuthzServices."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/PDPDescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/PDPDescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/PDPDescriptorSpecValidator.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.PDPDescriptor; + +/** + * Checks {@link org.opensaml.saml2.metadata.PDPDescriptor} for Spec compliance. + */ +public class PDPDescriptorSpecValidator extends RoleDescriptorSpecValidator { + + /** Constructor */ + public PDPDescriptorSpecValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RequestedAttributeSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RequestedAttributeSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RequestedAttributeSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.RequestedAttribute} for Schema compliance. + */ +public class RequestedAttributeSchemaValidator implements Validator { + + /** Constructor */ + public RequestedAttributeSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(RequestedAttribute attribute) throws ValidationException { + validateName(attribute); + } + + /** + * Checks that the Name attribute is present. + * + * @param attribute + * @throws ValidationException + */ + protected void validateName(RequestedAttribute attribute) throws ValidationException { + if (DatatypeHelper.isEmpty(attribute.getName())) { + throw new ValidationException("Name is required attribute"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RoleDescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RoleDescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RoleDescriptorSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.RoleDescriptor} for Schema compliance. + */ +public class RoleDescriptorSchemaValidator implements Validator { + + /** Constructor */ + public RoleDescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(RoleDescriptorType roleDescriptor) throws ValidationException { + validateProtocols(roleDescriptor); + } + + /** + * Checks that one or more Protocols are present. + * + * @param roleDescriptor + * @throws ValidationException + */ + protected void validateProtocols(RoleDescriptor roleDescriptor) throws ValidationException { + if (roleDescriptor.getSupportedProtocols() == null || roleDescriptor.getSupportedProtocols().size() == 0) { + throw new ValidationException("Must have at least one Supported Protocol."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RoleDescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RoleDescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/RoleDescriptorSpecValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.RoleDescriptor} for Spec compliance. + */ +public class RoleDescriptorSpecValidator implements Validator { + + /** Constructor */ + public RoleDescriptorSpecValidator() { + + } + + /** {@inheritDoc} */ + public void validate(RoleDescriptorType roleDescriptor) throws ValidationException { + validateProtocols(roleDescriptor); + } + + /** + * Checks that the SAML 2.0 protocol is present. + * + * @param roleDescriptor + * @throws ValidationException + */ + protected void validateProtocols(RoleDescriptor roleDescriptor) throws ValidationException { + boolean saml = false; + for (int i = 0; i < roleDescriptor.getSupportedProtocols().size(); i++) { + if (roleDescriptor.getSupportedProtocols().get(i).equals("urn:oasis:names:tc:SAML:2.0:protocol")) { + saml = true; + } + } + if (!saml) { + throw new ValidationException("SupportedProtocols must contain 'urn:oasis:names:tc:SAML:2.0:protocol'"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SPSSODescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SPSSODescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SPSSODescriptorSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.SPSSODescriptor} for Schema compliance. + */ +public class SPSSODescriptorSchemaValidator extends SSODescriptorSchemaValidator { + + /** Constructor */ + public SPSSODescriptorSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(SPSSODescriptor spssoDescriptor) throws ValidationException { + super.validate(spssoDescriptor); + validateAssertionConsumerServices(spssoDescriptor); + } + + /** + * Checks that at least one Assertion Consumer Service is present. + * + * @param spssoDescriptor descriptor to validate + * + * @throws ValidationException thrown if there is no AssertionConsumerServer within the descriptor + */ + protected void validateAssertionConsumerServices(SPSSODescriptor spssoDescriptor) throws ValidationException { + if (spssoDescriptor.getAssertionConsumerServices() == null || spssoDescriptor.getAssertionConsumerServices().size() < 1) { + throw new ValidationException("Must have one or more AssertionConsumerService."); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SPSSODescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SPSSODescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SPSSODescriptorSpecValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SPSSODescriptor; + +/** + * Checks {@link org.opensaml.saml2.metadata.SPSSODescriptor} for Spec compliance. + */ +public class SPSSODescriptorSpecValidator extends SSODescriptorSpecValidator { + + /** Constructor */ + public SPSSODescriptorSpecValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SSODescriptorSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SSODescriptorSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SSODescriptorSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SSODescriptor; + +/** + * Checks {@link org.opensaml.saml2.metadata.SSODescriptor} for Schema compliance. + */ +public class SSODescriptorSchemaValidator extends RoleDescriptorSchemaValidator { + + /** Constructor */ + public SSODescriptorSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SSODescriptorSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SSODescriptorSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SSODescriptorSpecValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SSODescriptor; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; + +/** + * Checks {@link org.opensaml.saml2.metadata.SSODescriptor} for Spec compliance. + */ +public class SSODescriptorSpecValidator extends RoleDescriptorSpecValidator { + + /** Constructor */ + public SSODescriptorSpecValidator() { + + } + + /** {@inheritDoc} */ + public void validate(SSODescriptorType ssoDescriptor) throws ValidationException { + validateResponseLocation(ssoDescriptor); + super.validate(ssoDescriptor); + } + + /** + * Checks that Response Location of Artifact Resolution Services is omitted. + * + * @param ssoDescriptor + * @throws ValidationException + */ + protected void validateResponseLocation(SSODescriptor ssoDescriptor) throws ValidationException { + if (ssoDescriptor.getArtifactResolutionServices() != null + && ssoDescriptor.getArtifactResolutionServices().size() > 0) { + for (int i = 0; i < ssoDescriptor.getArtifactResolutionServices().size(); i++) { + if (!DatatypeHelper.isEmpty(ssoDescriptor.getArtifactResolutionServices().get(i).getResponseLocation())) { + throw new ValidationException("ResponseLocation of all ArtificatResolutionServices must be null"); + } + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ServiceDescriptionSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ServiceDescriptionSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ServiceDescriptionSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.ServiceDescription; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.ServiceDescription} for Schema compliance. + */ +public class ServiceDescriptionSchemaValidator implements Validator { + + /** Constructor */ + public ServiceDescriptionSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(ServiceDescription serviceDescription) throws ValidationException { + validateDescription(serviceDescription); + } + + /** + * Checks that Description is present. + * + * @param serviceDescription + * @throws ValidationException + */ + protected void validateDescription(ServiceDescription serviceDescription) throws ValidationException { + if (serviceDescription.getDescription() == null) { + throw new ValidationException("Description required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ServiceNameSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ServiceNameSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/ServiceNameSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.ServiceName} for Schema compliance. + */ +public class ServiceNameSchemaValidator implements Validator { + + /** Constructor */ + public ServiceNameSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(ServiceName serviceName) throws ValidationException { + validateName(serviceName); + } + + /** + * Checks that Name is present. + * + * @param serviceName + * @throws ValidationException + */ + protected void validateName(ServiceName serviceName) throws ValidationException { + if (serviceName.getName() == null) { + throw new ValidationException("Name required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleLogoutServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleLogoutServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleLogoutServiceSchemaValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SingleLogoutService; + +/** + * Checks {@link org.opensaml.saml2.metadata.SingleLogoutService} for Schema compliance. + */ +public class SingleLogoutServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public SingleLogoutServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleSignOnServiceSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleSignOnServiceSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleSignOnServiceSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SingleSignOnService; + +/** + * Checks {@link org.opensaml.saml2.metadata.SingleSignOnService} for Schema compliance. + */ +public class SingleSignOnServiceSchemaValidator extends EndpointSchemaValidator { + + /** Constructor */ + public SingleSignOnServiceSchemaValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleSignOnServiceSpecValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleSignOnServiceSpecValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SingleSignOnServiceSpecValidator.java 17 Aug 2012 15:03:41 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SingleSignOnService; + +/** + * Checks {@link org.opensaml.saml2.metadata.SingleSignOnService} for Spec compliance. + */ +public class SingleSignOnServiceSpecValidator extends EndpointSchemaValidator { + + /** Constructor */ + public SingleSignOnServiceSpecValidator() { + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SurNameSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SurNameSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/SurNameSchemaValidator.java 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.SurName; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.SurName} for Schema compliance. + */ +public class SurNameSchemaValidator implements Validator { + + /** Constructor */ + public SurNameSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(SurName surName) throws ValidationException { + validateName(surName); + } + + /** + * Checks that Name is present. + * + * @param surName + * @throws ValidationException + */ + protected void validateName(SurName surName) throws ValidationException { + if (DatatypeHelper.isEmpty(surName.getName())) { + throw new ValidationException("Name required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/TelephoneNumberSchemaValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/TelephoneNumberSchemaValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/TelephoneNumberSchemaValidator.java 17 Aug 2012 15:03:39 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.saml2.metadata.validator; + +import org.opensaml.saml2.metadata.TelephoneNumber; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; + +/** + * Checks {@link org.opensaml.saml2.metadata.TelephoneNumber} for Schema compliance. + */ +public class TelephoneNumberSchemaValidator implements Validator { + + /** Constructor */ + public TelephoneNumberSchemaValidator() { + + } + + /** {@inheritDoc} */ + public void validate(TelephoneNumber telephoneNumber) throws ValidationException { + validateNumber(telephoneNumber); + } + + /** + * Checks that Number is present. + * + * @param telephoneNumber + * @throws ValidationException + */ + protected void validateNumber(TelephoneNumber telephoneNumber) throws ValidationException { + if (DatatypeHelper.isEmpty(telephoneNumber.getNumber())) { + throw new ValidationException("Number required"); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/saml2/metadata/validator/package.html 17 Aug 2012 15:03:40 -0000 1.1 @@ -0,0 +1,15 @@ + + +Validation rules for SAML 2.0 metadata types and elements. +

+Schema validators check to ensure that SAMLObjects adhere to the SAML 2.0 metadata XML schemas while spec validators ensure +the objects adhere to the additional constraints placed upon the object by the SAML 2.0 metadata specification. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponse.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponse.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponse.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.idpdisco; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.IndexedEndpoint; + +/** SAML Identity Provider Discovery Protocol DiscoveryResponse */ +public interface DiscoveryResponse extends IndexedEndpoint { + + /** Namespace for Discovery Service metadata extensions. */ + public static final String IDP_DISCO_NS = "urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol"; + + /** Default namespace prefix used by this library. */ + public static final String IDP_DISCO_PREFIX = "idpdisco"; + + /** Name of the element inside the Extensions. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "DiscoveryResponse"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(IDP_DISCO_NS, DEFAULT_ELEMENT_LOCAL_NAME, + IDP_DISCO_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseBuilder.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.idpdisco; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; + +/** Builder of {@link org.opensaml.samlext.idpdisco.DiscoveryResponse}. */ +public class DiscoveryResponseBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor. */ + public DiscoveryResponseBuilder() { + + } + + /** {@inheritDoc} */ + public DiscoveryResponse buildObject() { + return buildObject(SAMLConstants.SAML20MD_NS, DiscoveryResponse.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MD_PREFIX); + } + + /** {@inheritDoc} */ + public DiscoveryResponse buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DiscoveryResponseImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseImpl.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + */ + +package org.opensaml.samlext.idpdisco; + +import org.opensaml.saml2.metadata.impl.IndexedEndpointImpl; + +/** + * This plugs into the standard opensaml2 parser framework to allow us to get use DiscoverResponse + * elements in our extensions. + */ +public class DiscoveryResponseImpl extends IndexedEndpointImpl implements DiscoveryResponse { + + /** + * Constructor. + * + * @param namespaceURI the Uri + * @param elementLocalName the local name + * @param namespacePrefix the prefix + */ + protected DiscoveryResponseImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseMarshaller.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.idpdisco; + +import org.opensaml.saml2.metadata.impl.IndexedEndpointMarshaller; + +/** A thread-safe Marshaller for {@link org.opensaml.samlext.idpdisco.DiscoveryResponse} objects. */ +public class DiscoveryResponseMarshaller extends IndexedEndpointMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/idpdisco/DiscoveryResponseUnmarshaller.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.idpdisco; + +import org.opensaml.saml2.metadata.impl.IndexedEndpointUnmarshaller; + +/** A thread-safe Unmarshaller for {@link org.opensaml.samlext.idpdisco.DiscoveryResponse} objects. */ +public class DiscoveryResponseUnmarshaller extends IndexedEndpointUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/EntityAttributes.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/EntityAttributes.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdattr/EntityAttributes.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdattr; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Attribute; + +/** SAML V2.0 Metadata Extension for Entity Attributes EntityAttributes SAML object. */ +public interface EntityAttributes extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "EntityAttributes"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = + new QName(SAMLConstants.SAML20MDATTR_NS, DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20MDATTR_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "EntityAttributesType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = + new QName(SAMLConstants.SAML20MDATTR_NS, TYPE_LOCAL_NAME, SAMLConstants.SAML20MDATTR_PREFIX); + + /** + * Gets the attributes about the entity. + * + * @return attributes about the entity + */ + public List getAttributes(); + + /** + * Gets the assertions about the entity. + * + * @return assertions about the entity + */ + public List getAssertions(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceBuilder.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdquery.ActionNamespace; + +/** + * Builder of {@link ActionNamespaceImpl} objects. + */ +public class ActionNamespaceBuilder extends AbstractSAMLObjectBuilder { + + /** Constructor */ + public ActionNamespaceBuilder() { + + } + + /** {@inheritDoc} */ + public ActionNamespace buildObject() { + return buildObject(SAMLConstants.SAML20MDQUERY_NS, ActionNamespace.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX); + } + + /** {@inheritDoc} */ + public ActionNamespace buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionNamespaceImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceImpl.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdquery.ActionNamespace; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link ActionNamespace}. + */ +public class ActionNamespaceImpl extends AbstractSAMLObject implements ActionNamespace { + + /** Action namespace value */ + private String value; + + /** + * Constructor + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ActionNamespaceImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + value = prepareForAssignment(value, newValue); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + // no children + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceMarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.samlext.saml2mdquery.ActionNamespace; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * Marshaller of {@link ActionNamespace} objects. + */ +public class ActionNamespaceMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + ActionNamespace actionNamespace = (ActionNamespace) xmlObject; + + if (!DatatypeHelper.isEmpty(actionNamespace.getValue())) { + XMLHelper.appendTextContent(domElement, actionNamespace.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/ActionNamespaceUnmarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml2mdquery.ActionNamespace; +import org.opensaml.xml.XMLObject; + +/** + * Unmarshaller for {@link ActionNamespace} objects. + */ +public class ActionNamespaceUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + ActionNamespace actionNamespace = (ActionNamespace) samlObject; + + actionNamespace.setValue(elementContent); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeBuilder.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdquery.AttributeQueryDescriptorType; + +/** + * Builder of {@link AttributeQueryDescriptorTypeImpl} objects. + */ +public class AttributeQueryDescriptorTypeBuilder extends AbstractSAMLObjectBuilder { + + /** {@inheritDoc} */ + public AttributeQueryDescriptorType buildObject() { + return buildObject(SAMLConstants.SAML20MDQUERY_NS, AttributeQueryDescriptorType.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX, AttributeQueryDescriptorType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public AttributeQueryDescriptorType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeQueryDescriptorTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeImpl.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.samlext.saml2mdquery.AttributeQueryDescriptorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link AttributeQueryDescriptorType}. + */ +public class AttributeQueryDescriptorTypeImpl extends QueryDescriptorTypeImpl implements AttributeQueryDescriptorType { + + /** Attribute consuming endpoints. */ + private XMLObjectChildrenList attributeConsumingServices; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeQueryDescriptorTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + + attributeConsumingServices = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributeConsumingServices() { + return attributeConsumingServices; + } + + /** {@inheritDoc} */ + public List getEndpoints() { + return new ArrayList(); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + return null; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(attributeConsumingServices); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeMarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +/** + * Marshaller for {@link org.opensaml.samlext.saml2mdquery.AttributeQueryDescriptorType} objects. + */ +public class AttributeQueryDescriptorTypeMarshaller extends QueryDescriptorTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AttributeQueryDescriptorTypeUnmarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.samlext.saml2mdquery.AttributeQueryDescriptorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller of {@link AttributeQueryDescriptorType} objects. + */ +public class AttributeQueryDescriptorTypeUnmarshaller extends QueryDescriptorTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AttributeQueryDescriptorType descriptor = (AttributeQueryDescriptorType) parentSAMLObject; + + if (childSAMLObject instanceof AttributeConsumingService) { + descriptor.getAttributeConsumingServices().add((AttributeConsumingService) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeBuilder.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdquery.AuthnQueryDescriptorType; + +/** + * Builder of {@link AuthnQueryDescriptorTypeImpl} objects. + */ +public class AuthnQueryDescriptorTypeBuilder extends AbstractSAMLObjectBuilder { + + /** {@inheritDoc} */ + public AuthnQueryDescriptorType buildObject() { + return buildObject(SAMLConstants.SAML20MDQUERY_NS, AuthnQueryDescriptorType.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX, AuthnQueryDescriptorType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public AuthnQueryDescriptorType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthnQueryDescriptorTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeImpl.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.samlext.saml2mdquery.AuthnQueryDescriptorType; + +/** + * Concrete implementation of {@link AuthnQueryDescriptorType}. + */ +public class AuthnQueryDescriptorTypeImpl extends QueryDescriptorTypeImpl implements AuthnQueryDescriptorType{ + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthnQueryDescriptorTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getEndpoints() { + return new ArrayList(); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeMarshaller.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +/** + * Marshaller for {@link org.opensaml.samlext.saml2mdquery.AuthnQueryDescriptorType} objects. + */ +public class AuthnQueryDescriptorTypeMarshaller extends QueryDescriptorTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthnQueryDescriptorTypeUnmarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +/** + * Unmarshaller of {@link org.opensaml.samlext.saml2mdquery.AuthnQueryDescriptorType} objects. + */ +public class AuthnQueryDescriptorTypeUnmarshaller extends QueryDescriptorTypeUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeBuilder.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdquery.AuthzDecisionQueryDescriptorType; + +/** + * Builder of {@link AuthzDecisionQueryDescriptorType} objects. + */ +public class AuthzDecisionQueryDescriptorTypeBuilder extends AbstractSAMLObjectBuilder { + + /** {@inheritDoc} */ + public AuthzDecisionQueryDescriptorType buildObject() { + return buildObject(SAMLConstants.SAML20MDQUERY_NS, AuthzDecisionQueryDescriptorType.DEFAULT_ELEMENT_LOCAL_NAME, + SAMLConstants.SAML20MDQUERY_PREFIX, AuthzDecisionQueryDescriptorType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public AuthzDecisionQueryDescriptorType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AuthzDecisionQueryDescriptorTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeImpl.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.Endpoint; +import org.opensaml.samlext.saml2mdquery.ActionNamespace; +import org.opensaml.samlext.saml2mdquery.AuthzDecisionQueryDescriptorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link AuthzDecisionQueryDescriptorType}. + */ +public class AuthzDecisionQueryDescriptorTypeImpl extends QueryDescriptorTypeImpl implements AuthzDecisionQueryDescriptorType{ + + /** Supported action namespaces. */ + private XMLObjectChildrenList actionNamespaces; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AuthzDecisionQueryDescriptorTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + + actionNamespaces = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getActionNamespaces() { + return actionNamespaces; + } + + /** {@inheritDoc} */ + public List getEndpoints() { + return new ArrayList(); + } + + /** {@inheritDoc} */ + public List getEndpoints(QName type) { + return null; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(actionNamespaces); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeMarshaller.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +/** + * Marshaller of {@link org.opensaml.samlext.saml2mdquery.AuthzDecisionQueryDescriptorType} objects. + */ +public class AuthzDecisionQueryDescriptorTypeMarshaller extends QueryDescriptorTypeMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/AuthzDecisionQueryDescriptorTypeUnmarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.samlext.saml2mdquery.ActionNamespace; +import org.opensaml.samlext.saml2mdquery.AuthzDecisionQueryDescriptorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link AuthzDecisionQueryDescriptorType} objects. */ +public class AuthzDecisionQueryDescriptorTypeUnmarshaller extends QueryDescriptorTypeUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + AuthzDecisionQueryDescriptorType descriptor = (AuthzDecisionQueryDescriptorType) parentSAMLObject; + + if (childSAMLObject instanceof ActionNamespace) { + descriptor.getActionNamespaces().add((ActionNamespace) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeImpl.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.impl.RoleDescriptorImpl; +import org.opensaml.samlext.saml2mdquery.QueryDescriptorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link QueryDescriptorType}. + */ +public abstract class QueryDescriptorTypeImpl extends RoleDescriptorImpl implements QueryDescriptorType { + + /** WantAssertionSigned attribute value. */ + private XSBooleanValue wantAssertionsSigned; + + /** Supported NameID formats. */ + private XMLObjectChildrenList nameIDFormats; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected QueryDescriptorTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + + nameIDFormats = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public Boolean getWantAssertionsSigned() { + if (wantAssertionsSigned != null) { + return wantAssertionsSigned.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public void setWantAssertionsSigned(Boolean newWantAssertionsSigned) { + if (newWantAssertionsSigned != null) { + wantAssertionsSigned = prepareForAssignment(wantAssertionsSigned, + new XSBooleanValue(newWantAssertionsSigned, false)); + } else { + wantAssertionsSigned = prepareForAssignment(wantAssertionsSigned, null); + } + } + + /** {@inheritDoc} */ + public XSBooleanValue getWantAssertionsSignedXSBoolean(){ + return wantAssertionsSigned; + } + + /** {@inheritDoc} */ + public void setWantAssertionsSigned(XSBooleanValue wantAssertionSigned){ + this.wantAssertionsSigned = prepareForAssignment(this.wantAssertionsSigned, wantAssertionSigned); + } + + /** {@inheritDoc} */ + public List getNameIDFormat(){ + return nameIDFormats; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(super.getOrderedChildren()); + children.addAll(nameIDFormats); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeMarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.saml2.metadata.impl.RoleDescriptorMarshaller; +import org.opensaml.samlext.saml2mdquery.QueryDescriptorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link QueryDescriptorType} objects. + */ +public abstract class QueryDescriptorTypeMarshaller extends RoleDescriptorMarshaller { + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + QueryDescriptorType descriptor = (QueryDescriptorType) xmlObject; + + if (descriptor.getWantAssertionsSignedXSBoolean() != null) { + domElement.setAttributeNS(null, QueryDescriptorType.WANT_ASSERTIONS_SIGNED_ATTRIB_NAME, descriptor + .getWantAssertionsSignedXSBoolean().toString()); + } + + super.marshallAttributes(xmlObject, domElement); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/QueryDescriptorTypeUnmarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdquery.impl; + +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.impl.RoleDescriptorUnmarshaller; +import org.opensaml.samlext.saml2mdquery.QueryDescriptorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link QueryDescriptorType} objects. */ +public class QueryDescriptorTypeUnmarshaller extends RoleDescriptorUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + QueryDescriptorType descriptor = (QueryDescriptorType) parentSAMLObject; + + if (childSAMLObject instanceof NameIDFormat) { + descriptor.getNameIDFormat().add((NameIDFormat) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + QueryDescriptorType descriptor = (QueryDescriptorType) samlObject; + + if (attribute.getLocalName().equals(QueryDescriptorType.WANT_ASSERTIONS_SIGNED_ATTRIB_NAME)) { + descriptor.setWantAssertionsSigned(XSBooleanValue.valueOf(attribute.getValue())); + } else { + super.processAttribute(samlObject, attribute); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdquery/impl/package.html 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,12 @@ + + +Implemention for SAML 2 metadata standalone query endpoints profile objects. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Description.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Description.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Description.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.LocalizedString; + +/** + * DisplayName. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * Reflects the Description in the IdP Discovery and Login UI Metadata Extension Profile. + * + */ +public interface Description extends LocalizedName { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Description"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(UIInfo.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, UIInfo.MDUI_PREFIX); + + /** + * Gets the description of the EndPoint. + * + * @return the description of the EndPoint + */ + public LocalizedString getDescription(); + + /** + * Sets the description of the EndPoint. + * + * @param newDescription description of the EndPoint + */ + public void setDescription(LocalizedString newDescription); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DiscoHints.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DiscoHints.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DiscoHints.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,69 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; + +/** + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author RDW 27/Aug/2010 + * + * Reflects the DiscoHints + */ +public interface DiscoHints extends SAMLObject { + /** Namespace for Discovery Service metadata extensions. */ + public static final String MDUI_NS = "urn:oasis:names:tc:SAML:metadata:ui"; + + /** Default namespace prefix used by this library. */ + public static final String MDUI_PREFIX = "mdui"; + + /** Name of the element inside the Extensions. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "DiscoHints"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(MDUI_NS, DEFAULT_ELEMENT_LOCAL_NAME, + MDUI_PREFIX); + + /** + * The element specifies a set of [CIDR] blocks associated with, + * or serviced by, the entity. Both IPv4 and IPv6 CIDR blocks MUST be supported. + * + * @return hints + */ + public List getIPHints(); + + /** The element specifies a set of DNS domains associated with, + * or serviced by, the entity. + * @return hints. + */ + public List getDomainHints(); + + /** The element specifies the geographic coordinates associated + * with, or serviced by, the entity. Coordinates are given in decimal form using + * the World Geodetic System (2d) coordinate system. + * + * @return hints + */ + public List getGeolocationHints(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DisplayName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DisplayName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DisplayName.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.LocalizedString; + +/** + * DisplayName. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * Reflects the UINFO in the IdP Discovery and Login UI Metadata Extension Profile/ + * */ +public interface DisplayName extends LocalizedName { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "DisplayName"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(UIInfo.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, UIInfo.MDUI_PREFIX); + + /** + * Gets the name of the EndPoint. + * + * @return the name of the EndPoint + * + public LocalizedString getName(); + + /** + * Sets the EndPoint name. + * + * @param newName EndPoint name + * + public void setName(LocalizedString newName);*/ +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DomainHint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DomainHint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/DomainHint.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; + +/** + * IPHint. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * The element specifies a set of DNS domains associated with, + * or serviced by, the entity. + */ +public interface DomainHint extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "DomainHint"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DiscoHints.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, DiscoHints.MDUI_PREFIX); + + /** + * Gets the Hint. + * + * @return the Hint + */ + public String getHint(); + + /** + * Sets the hint. + * + * @param newHint hint + */ + public void setHint(String newHint); +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/GeolocationHint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/GeolocationHint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/GeolocationHint.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; + +/** + * IPHint. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * The element specifies the geographic coordinates associated + * with, or serviced by, the entity. Coordinates are given in decimal form using + * the World Geodetic System (2d) coordinate system. + */ +public interface GeolocationHint extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "GeolocationHint"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DiscoHints.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, DiscoHints.MDUI_PREFIX); + + /** + * Gets the Hint. + * + * @return the Hint + */ + public String getHint(); + + /** + * Sets the hint. + * + * @param newHint hint + */ + public void setHint(String newHint); +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/IPHint.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/IPHint.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/IPHint.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; + +/** + * IPHint. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * The element specifies a set of [CIDR] blocks associated with, + * or serviced by, the entity. Both IPv4 and IPv6 CIDR blocks MUST be supported. + */ +public interface IPHint extends SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "IPHint"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DiscoHints.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, DiscoHints.MDUI_PREFIX); + + /** + * Gets the Hint. + * + * @return the Hint + */ + public String getHint(); + + /** + * Sets the hint. + * + * @param newHint hint + */ + public void setHint(String newHint); +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/InformationURL.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/InformationURL.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/InformationURL.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.LocalizedString; + +/** + * InformationURL. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * Reflects the InformationURL in the IdP Discovery and Login UI Metadata Extension Profile. + * + */ +public interface InformationURL extends LocalizedURI { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "InformationURL"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(DiscoHints.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, DiscoHints.MDUI_PREFIX); + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Keywords.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Keywords.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Keywords.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.xml.LangBearing; + +/** + * DisplayName. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * Reflects the Description in the IdP Discovery and Login UI Metadata Extension Profile. + * + */ +public interface Keywords extends SAMLObject, LangBearing { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Keywords"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(UIInfo.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, UIInfo.MDUI_PREFIX); + + /** + * Gets the keywords. + * + * @return the keywords + */ + public List getKeywords(); + + /** + * Sets the keywords. + * + * @param val The keywords + */ + public void setKeywords(List val); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/LocalizedName.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/LocalizedName.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/LocalizedName.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.xml.LangBearing; + +/** + * LocalizedName. + */ +public interface LocalizedName extends SAMLObject, LangBearing { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "localizedNameType"; + + /** + * Gets the name. + * + * @return the name + */ + public LocalizedString getName(); + + /** + * Sets the name. + * + * @param newName new name + */ + public void setName(LocalizedString newName); +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/LocalizedURI.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/LocalizedURI.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/LocalizedURI.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.xml.LangBearing; + +/** + * LocalizedURI. + */ +public interface LocalizedURI extends SAMLObject, LangBearing { + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "localizedURIType"; + + /** + * Gets the URI. + * + * @return the URI + */ + public LocalizedString getURI(); + + /** + * Sets the URI. + * + * @param newURI the new value + */ + public void setURI(LocalizedString newURI); +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Logo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Logo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/Logo.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,88 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.xml.LangBearing; + +/** + * Localized logo type. + * + * + * @author RDW 27/Aug/2010 + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + */ +public interface Logo extends LangBearing, SAMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Logo"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(UIInfo.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, UIInfo.MDUI_PREFIX); + + /** Attribute label. */ + public static final String HEIGHT_ATTR_NAME = "height"; + + /** Attribute label. */ + public static final String WIDTH_ATTR_NAME = "width"; + + + /** + * Gets the URL. + * + * @return the URL + */ + public String getURL(); + + /** + * Sets the URL. + * + * @param newURL the URL + */ + public void setURL(String newURL); + + /** + * Get the height of the logo. + * @return the height of the logo + */ + public Integer getHeight(); + + /** + * Sets the height of the logo. + * @param newHeight the height of the logo + */ + public void setHeight(Integer newHeight); + + /** + * Get the width of the logo. + * @return the width of the logo + */ + public Integer getWidth(); + + /** + * Sets the width of the logo. + * @param newWidth the height of the logo + */ + public void setWidth(Integer newWidth); +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/PrivacyStatementURL.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/PrivacyStatementURL.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/PrivacyStatementURL.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,43 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.LocalizedString; + +/** + * PrivacyStatementURL. + * + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * Reflects the PrivacyStatementURL in the IdP Discovery and Login UI Metadata Extension Profile. + * + */ +public interface PrivacyStatementURL extends LocalizedURI { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "PrivacyStatementURL"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(UIInfo.MDUI_NS, + DEFAULT_ELEMENT_LOCAL_NAME, UIInfo.MDUI_PREFIX); + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/UIInfo.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/UIInfo.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/UIInfo.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,109 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; + +/** + * See IdP Discovery and Login UI Metadata Extension Profile. + * + * @author Rod Widdowson August 2010 + * + * Reflects the UINFO in the IdP Discovery and Login UI Metadata Extension Profile, + * + */ +public interface UIInfo extends SAMLObject { + /** Namespace for Discovery Service metadata extensions. */ + public static final String MDUI_NS = "urn:oasis:names:tc:SAML:metadata:ui"; + + /** Default namespace prefix used by this library. */ + public static final String MDUI_PREFIX = "mdui"; + + /** Name of the element inside the Extensions. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "UIInfo"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(MDUI_NS, DEFAULT_ELEMENT_LOCAL_NAME, + MDUI_PREFIX); + + /** Language attribute name. */ + public static final String LANG_ATTRIB_NAME = "lang"; + + /** + * Get the Display Names + * + * The element specifies a set of localized names fit for + * display to users. Such names are meant to allow a user to distinguish + * and identify the entity acting in a particular role. + * @return the names + */ + public List getDisplayNames(); + + /** Get the Keywords. */ + public List getKeywords(); + + /** + * Return the descriptions. + * + * The element specifies a set of brief, localized descriptions + * fit for display to users. In the case of service providers this SHOULD be a + * description of the service being offered. In the case of an identity provider + * this SHOULD be a description of the community serviced. In all cases this text + * SHOULD be standalone, meaning it is not meant to be filled in to some template + * text (e.g. 'This service offers $description'). + * @return descriptions + */ + public List getDescriptions(); + + /** + * Get the logos. + * + * The element specifies a set of localized logos fit for display to users. + * + * @return a list of logos + */ + public List getLogos(); + + /** + * Get the URLs. + * + * The specifies URLs to localized information, about the entity + * acting in a given role, meant to be viewed by users. The contents found at + * these URLs SHOULD give a more complete set of information about than what is + * provided by the element + * + * @return the URLs + */ + public List getInformationURLs(); + + /** + * Get the Privacy Statement URLs. + * + * The specifies URLs to localized privacy statements. + * Such statements are meant to provide a user with information about how + * information will be used and managed by the entity + * + * @return the URLs + */ + public List getPrivacyStatementURLs(); + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionBuilder.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.Description; +import org.opensaml.samlext.saml2mdui.UIInfo; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.Description} objects. + * @author Rod Widdowson + */ +public class DescriptionBuilder extends AbstractSAMLObjectBuilder { + /** + * Constructor. + */ + public DescriptionBuilder() { + + } + + /** {@inheritDoc} */ + public Description buildObject() { + return buildObject(UIInfo.MDUI_NS, + Description.DEFAULT_ELEMENT_LOCAL_NAME, + UIInfo.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public Description buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DescriptionImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.samlext.saml2mdui.Description; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.Description}. + */ +public class DescriptionImpl extends LocalizedNameImpl implements Description { + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected DescriptionImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getDescription() { + return getName(); + } + + /** {@inheritDoc} */ + public void setDescription(LocalizedString newDescription) { + setName(newDescription); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,26 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.Description} objects. + */ +public class DescriptionMarshaller extends LocalizedNameMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DescriptionUnmarshaller.java 17 Aug 2012 15:04:51 -0000 1.1 @@ -0,0 +1,26 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.Description} objects. + */ +public class DescriptionUnmarshaller extends LocalizedNameUnmarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsBuilder.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.DiscoHints; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.UIInfo}. + */ +public class DiscoHintsBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public DiscoHintsBuilder() { + + } + + /** {@inheritDoc} */ + public DiscoHints buildObject() { + return buildObject(DiscoHints.MDUI_NS, + DiscoHints.DEFAULT_ELEMENT_LOCAL_NAME, + DiscoHints.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public DiscoHints buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DiscoHintsImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdui.DiscoHints; +import org.opensaml.samlext.saml2mdui.DomainHint; +import org.opensaml.samlext.saml2mdui.GeolocationHint; +import org.opensaml.samlext.saml2mdui.IPHint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link org.opensaml.samlext.saml2mdui.DiscoHints}. */ +public class DiscoHintsImpl extends AbstractSAMLObject implements DiscoHints { + + /** DNS Domain hints. */ + private final XMLObjectChildrenList domainHints; + + /** IP Address hints. */ + private final XMLObjectChildrenList iPHints; + + /** GeoLocation hints. */ + private final XMLObjectChildrenList geoHints; + + /** + * Constructor. + * + * @param namespaceURI namespaceURI + * @param elementLocalName elementLocalName + * @param namespacePrefix namespacePrefix + */ + protected DiscoHintsImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + domainHints = new XMLObjectChildrenList(this); + iPHints = new XMLObjectChildrenList(this); + geoHints = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getDomainHints() { + return domainHints; + } + + /** {@inheritDoc} */ + public List getGeolocationHints() { + return geoHints; + } + + /** {@inheritDoc} */ + public List getIPHints() { + return iPHints; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(domainHints); + children.addAll(iPHints); + children.addAll(geoHints); + return children; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.DiscoHints} objects. + */ +public class DiscoHintsMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DiscoHintsUnmarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml2mdui.DiscoHints; +import org.opensaml.samlext.saml2mdui.DomainHint; +import org.opensaml.samlext.saml2mdui.GeolocationHint; +import org.opensaml.samlext.saml2mdui.IPHint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.samlext.saml2mdui.DiscoHints} objects. + */ +public class DiscoHintsUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + DiscoHints info = (DiscoHints) parentSAMLObject; + + if (childSAMLObject instanceof IPHint) { + info.getIPHints().add((IPHint) childSAMLObject); + } else if (childSAMLObject instanceof DomainHint) { + info.getDomainHints().add((DomainHint) childSAMLObject); + } else if (childSAMLObject instanceof GeolocationHint) { + info.getGeolocationHints().add((GeolocationHint) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameBuilder.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.DisplayName; +import org.opensaml.samlext.saml2mdui.UIInfo; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.DisplayName} objects. + */ +public class DisplayNameBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public DisplayNameBuilder() { + + } + + /** {@inheritDoc} */ + public DisplayName buildObject() { + return buildObject(UIInfo.MDUI_NS, + DisplayName.DEFAULT_ELEMENT_LOCAL_NAME, + UIInfo.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public DisplayName buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DisplayNameImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameImpl.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.samlext.saml2mdui.DisplayName; + + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.DisplayName}. + */ +public class DisplayNameImpl extends LocalizedNameImpl implements DisplayName { + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected DisplayNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameMarshaller.java 17 Aug 2012 15:04:51 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.DisplayName} objects. + */ +public class DisplayNameMarshaller extends LocalizedNameMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DisplayNameUnmarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.DisplayName} objects. + */ +public class DisplayNameUnmarshaller extends LocalizedNameUnmarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintBuilder.java 17 Aug 2012 15:04:51 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.DiscoHints; +import org.opensaml.samlext.saml2mdui.DomainHint; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.DomainHint} objects. + */ +public class DomainHintBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public DomainHintBuilder() { + + } + + /** {@inheritDoc} */ + public DomainHint buildObject() { + return buildObject(DiscoHints.MDUI_NS, + DomainHint.DEFAULT_ELEMENT_LOCAL_NAME, + DiscoHints.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public DomainHint buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DomainHintImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintImpl.java 17 Aug 2012 15:04:51 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdui.DomainHint; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.DomainHint}. + */ +public class DomainHintImpl extends AbstractSAMLObject implements DomainHint{ + + /** + * local storage. + */ + private String hint; + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected DomainHintImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getHint() { + return hint; + } + + /** {@inheritDoc} */ + public void setHint(String newHint) { + hint = prepareForAssignment(hint, newHint); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.samlext.saml2mdui.DomainHint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.DomainHint} objects. + */ +public class DomainHintMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + DomainHint name = (DomainHint) samlObject; + + if (name.getHint() != null) { + XMLHelper.appendTextContent(domElement, name.getHint()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/DomainHintUnmarshaller.java 17 Aug 2012 15:04:48 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml2mdui.DomainHint; +import org.opensaml.xml.XMLObject; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.DomainHint} objects. + */ +public class DomainHintUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + DomainHint hint = (DomainHint) samlObject; + + hint.setHint(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintBuilder.java 17 Aug 2012 15:04:51 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.DiscoHints; +import org.opensaml.samlext.saml2mdui.GeolocationHint; + +/** + * Builder of {@link GeolocationHint} objects. + */ +public class GeolocationHintBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public GeolocationHintBuilder() { + + } + + /** {@inheritDoc} */ + public GeolocationHint buildObject() { + return buildObject(DiscoHints.MDUI_NS, + GeolocationHint.DEFAULT_ELEMENT_LOCAL_NAME, + DiscoHints.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public GeolocationHint buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new GeolocationHintImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/GeolocationHintMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.samlext.saml2mdui.GeolocationHint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.GeolocationHint} objects. + */ +public class GeolocationHintMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + GeolocationHint name = (GeolocationHint) samlObject; + + if (name.getHint() != null) { + XMLHelper.appendTextContent(domElement, name.getHint()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintBuilder.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.DiscoHints; +import org.opensaml.samlext.saml2mdui.IPHint; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.IPHint} objects. + */ +public class IPHintBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public IPHintBuilder() { + + } + + /** {@inheritDoc} */ + public IPHint buildObject() { + return buildObject(DiscoHints.MDUI_NS, + IPHint.DEFAULT_ELEMENT_LOCAL_NAME, + DiscoHints.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public IPHint buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IPHintImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdui.IPHint; +import org.opensaml.xml.XMLObject; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.IPHint}. + */ +public class IPHintImpl extends AbstractSAMLObject implements IPHint { + + /** + * local storage. + */ + private String hint; + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected IPHintImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getHint() { + return hint; + } + + /** {@inheritDoc} */ + public void setHint(String newHint) { + hint = prepareForAssignment(hint, newHint); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/IPHintMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.samlext.saml2mdui.IPHint; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.IPHint} objects. + */ +public class IPHintMarshaller extends AbstractSAMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + IPHint name = (IPHint) samlObject; + + if (name.getHint() != null) { + XMLHelper.appendTextContent(domElement, name.getHint()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLBuilder.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.InformationURL; +import org.opensaml.samlext.saml2mdui.UIInfo; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.InformationURL} objects. + * @author Rod Widdowson + */ +public class InformationURLBuilder extends AbstractSAMLObjectBuilder { + /** + * Constructor. + */ + public InformationURLBuilder() { + + } + + /** {@inheritDoc} */ + public InformationURL buildObject() { + return buildObject(UIInfo.MDUI_NS, + InformationURL.DEFAULT_ELEMENT_LOCAL_NAME, + UIInfo.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public InformationURL buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new InformationURLImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/InformationURLImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.samlext.saml2mdui.InformationURL; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.InformationURL}. + * @author Rod Widdowson + */ + +public class InformationURLImpl extends LocalizedURIImpl implements InformationURL { + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected InformationURLImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,87 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdui.Keywords; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete Implementation of {@link org.opensaml.samlext.saml2mdui.Keywords}. + */ +public class KeywordsImpl extends AbstractSAMLObject implements Keywords { + + /** The language. */ + private String lang; + /** The data. */ + private List data; + /** + * Constructor. + * + * @param namespaceURI the URI + * @param elementLocalName the local name + * @param namespacePrefix the prefix + */ + protected KeywordsImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + + /** {@inheritDoc} */ + public String getXMLLang() { + return lang; + } + + /** {@inheritDoc} */ + public void setXMLLang(String newLang) { + boolean hasValue = newLang != null && !DatatypeHelper.isEmpty(newLang); + lang = prepareForAssignment(lang, newLang); + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasValue); + } + + /** {@inheritDoc} */ + public List getKeywords() { + return data; + } + + /** {@inheritDoc} */ + public void setKeywords(List val) { + data = prepareForAssignment(data, val); + } + + /** + * {@inheritDoc} + */ + public int hashCode() { + int hash = lang.hashCode(); + for (String s: data) { + hash = hash * 31 + s.hashCode(); + } + return hash; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdui.Keywords; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.Keywords} objects. + */ +public class KeywordsMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + Keywords words = (Keywords) samlObject; + + if (words.getXMLLang() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + LangBearing.XML_LANG_ATTR_LOCAL_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(words.getXMLLang()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Keywords words = (Keywords) samlObject; + + if (words.getKeywords() != null) { + StringBuilder sb = new StringBuilder(); + for (String s : words.getKeywords()) { + sb.append(s); + sb.append(' '); + } + XMLHelper.appendTextContent(domElement, sb.toString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/KeywordsUnmarshaller.java 17 Aug 2012 15:04:51 -0000 1.1 @@ -0,0 +1,59 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.ArrayList; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdui.Keywords; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.Keywords} objects. + */ +public class KeywordsUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(LangBearing.XML_LANG_ATTR_LOCAL_NAME) + && SAMLConstants.XML_NS.equals(attribute.getNamespaceURI())) { + Keywords keywords = (Keywords) samlObject; + + keywords.setXMLLang(attribute.getValue()); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Keywords keywords = (Keywords) samlObject; + String[] words = elementContent.split("\\s+"); + ArrayList wordlist = new ArrayList(words.length); + + for (String s : words) { + wordlist.add(s); + } + + keywords.setKeywords(wordlist); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.samlext.saml2mdui.LocalizedName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.LocalizedName}. + */ +public class LocalizedNameImpl extends AbstractSAMLObject implements LocalizedName { + + /** Display name. */ + private LocalizedString name; + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected LocalizedNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getName() { + return name; + } + + /** {@inheritDoc} */ + public void setName(LocalizedString newName) { + name = prepareForAssignment(name, newName); + boolean hasXMLLang = false; + if (name != null && !DatatypeHelper.isEmpty(name.getLanguage())) { + hasXMLLang = true; + } + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasXMLLang); + } + + /** {@inheritDoc} */ + public String getXMLLang() { + return name.getLanguage(); + } + + /** {@inheritDoc} */ + public void setXMLLang(String newLang) { + name.setLanguage(newLang); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedNameUnmarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.samlext.saml2mdui.LocalizedName; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.LocalizedName} objects. + */ +public class LocalizedNameUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(LangBearing.XML_LANG_ATTR_LOCAL_NAME) + && SAMLConstants.XML_NS.equals(attribute.getNamespaceURI())) { + LocalizedName name = (LocalizedName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLanguage(attribute.getValue()); + name.setName(nameStr); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + LocalizedName name = (LocalizedName) samlObject; + + LocalizedString nameStr = name.getName(); + if (nameStr == null) { + nameStr = new LocalizedString(); + } + + nameStr.setLocalizedString(elementContent); + name.setName(nameStr); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,78 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.samlext.saml2mdui.LocalizedURI; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.LocalizedURI}. + */ +public class LocalizedURIImpl extends AbstractSAMLObject implements LocalizedURI{ + + /** Display name. */ + private LocalizedString uri; + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected LocalizedURIImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public LocalizedString getURI() { + return uri; + } + + /** {@inheritDoc} */ + public void setURI(LocalizedString newURI) { + uri = prepareForAssignment(uri, newURI); + boolean hasXMLLang = false; + if (uri != null && !DatatypeHelper.isEmpty(uri.getLanguage())) { + hasXMLLang = true; + } + manageQualifiedAttributeNamespace(LangBearing.XML_LANG_ATTR_NAME, hasXMLLang); + } + + /** {@inheritDoc} */ + public String getXMLLang() { + return uri.getLanguage(); + } + + /** {@inheritDoc} */ + public void setXMLLang(String newLang) { + uri.setLanguage(newLang); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdui.LocalizedURI; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.LocalizedURI} objects. + */ +public class LocalizedURIMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + LocalizedURI name = (LocalizedURI) samlObject; + + if (name.getURI() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + LangBearing.XML_LANG_ATTR_LOCAL_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(name.getURI().getLanguage()); + domElement.setAttributeNodeNS(attribute); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + LocalizedURI name = (LocalizedURI) samlObject; + + if (name.getURI() != null) { + XMLHelper.appendTextContent(domElement, name.getURI().getLocalString()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LocalizedURIUnmarshaller.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.samlext.saml2mdui.LocalizedURI; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe unmarshaller for {@link org.opensaml.samlext.saml2mdui.LocalizedURI} objects. + */ +public class LocalizedURIUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** + * {@inheritDoc} + */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(LangBearing.XML_LANG_ATTR_LOCAL_NAME) + && SAMLConstants.XML_NS.equals(attribute.getNamespaceURI())) { + LocalizedURI uri = (LocalizedURI) samlObject; + + LocalizedString uriStr = uri.getURI(); + if (uriStr == null) { + uriStr = new LocalizedString(); + } + + uriStr.setLanguage(attribute.getValue()); + uri.setURI(uriStr); + } + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + LocalizedURI uri = (LocalizedURI) samlObject; + + LocalizedString uriStr = uri.getURI(); + if (uriStr == null) { + uriStr = new LocalizedString(); + } + + uriStr.setLocalizedString(elementContent); + uri.setURI(uriStr); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoBuilder.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.Logo; +import org.opensaml.samlext.saml2mdui.UIInfo; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.Logo} objects. + */ +public class LogoBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public LogoBuilder() { + + } + + /** {@inheritDoc} */ + public Logo buildObject() { + return buildObject(UIInfo.MDUI_NS, + Logo.DEFAULT_ELEMENT_LOCAL_NAME, + UIInfo.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public Logo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new LogoImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdui.Logo; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.Logo} objects. + */ +public class LogoMarshaller extends AbstractSAMLObjectMarshaller { + + /** + * {@inheritDoc} + */ + protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException { + Logo logo = (Logo) samlObject; + + if (logo.getXMLLang() != null) { + Attr attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), SAMLConstants.XML_NS, + LangBearing.XML_LANG_ATTR_LOCAL_NAME, SAMLConstants.XML_PREFIX); + attribute.setValue(logo.getXMLLang()); + domElement.setAttributeNodeNS(attribute); + } + if (logo.getHeight() != null) { + domElement.setAttributeNS(null, Logo.HEIGHT_ATTR_NAME, logo.getHeight().toString()); + } + if (logo.getWidth() != null) { + domElement.setAttributeNS(null, Logo.WIDTH_ATTR_NAME, logo.getWidth().toString()); + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + Logo logo = (Logo) samlObject; + + if (logo.getURL() != null) { + XMLHelper.appendTextContent(domElement, logo.getURL()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/LogoUnmarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.samlext.saml2mdui.Logo; +import org.opensaml.xml.LangBearing; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.samlext.saml2mdui.Logo} objects. + */ +public class LogoUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + Logo logo = (Logo) samlObject; + + logo.setURL(elementContent); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + Logo logo = (Logo) samlObject; + + if (attribute.getLocalName().equals(LangBearing.XML_LANG_ATTR_LOCAL_NAME) + && SAMLConstants.XML_NS.equals(attribute.getNamespaceURI())) { + logo.setXMLLang(attribute.getValue()); + } else if (attribute.getLocalName().equals(Logo.HEIGHT_ATTR_NAME)) { + logo.setHeight(Integer.valueOf(attribute.getValue())); + } else if (attribute.getLocalName().equals(Logo.WIDTH_ATTR_NAME)) { + logo.setWidth(Integer.valueOf(attribute.getValue())); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLBuilder.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.PrivacyStatementURL; +import org.opensaml.samlext.saml2mdui.UIInfo; + + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.PrivacyStatementURL} objects. + * @author Rod Widdowson + */ +public class PrivacyStatementURLBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public PrivacyStatementURLBuilder() { + + } + + /** {@inheritDoc} */ + public PrivacyStatementURL buildObject() { + return buildObject(UIInfo.MDUI_NS, + PrivacyStatementURL.DEFAULT_ELEMENT_LOCAL_NAME, + UIInfo.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public PrivacyStatementURL buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PrivacyStatementURLImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLImpl.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.samlext.saml2mdui.PrivacyStatementURL; + + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.PrivacyStatementURL}. + * @author Rod Widdowson + */ + +public class PrivacyStatementURLImpl extends LocalizedURIImpl implements PrivacyStatementURL { + + /** + * Constructor. + * + * @param namespaceURI the namespaceURI + * @param elementLocalName the elementLocalName + * @param namespacePrefix the namespacePrefix + */ + protected PrivacyStatementURLImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/PrivacyStatementURLMarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,25 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.PrivacyStatementURL} objects. + */ +public class PrivacyStatementURLMarshaller extends LocalizedURIMarshaller { +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoBuilder.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.samlext.saml2mdui.UIInfo; + +/** + * Builder of {@link org.opensaml.samlext.saml2mdui.UIInfo}. + */ +public class UIInfoBuilder extends AbstractSAMLObjectBuilder { + + /** + * Constructor. + */ + public UIInfoBuilder() { + + } + + /** {@inheritDoc} */ + public UIInfo buildObject() { + return buildObject(UIInfo.MDUI_NS, UIInfo.DEFAULT_ELEMENT_LOCAL_NAME, UIInfo.MDUI_PREFIX); + } + + /** {@inheritDoc} */ + public UIInfo buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new UIInfoImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoImpl.java 17 Aug 2012 15:04:45 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.samlext.saml2mdui.Description; +import org.opensaml.samlext.saml2mdui.DisplayName; +import org.opensaml.samlext.saml2mdui.InformationURL; +import org.opensaml.samlext.saml2mdui.Keywords; +import org.opensaml.samlext.saml2mdui.Logo; +import org.opensaml.samlext.saml2mdui.PrivacyStatementURL; +import org.opensaml.samlext.saml2mdui.UIInfo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Concrete implementation of {@link org.opensaml.samlext.saml2mdui.UIInfo}. + * @author Rod Widdowson + */ +public class UIInfoImpl extends AbstractSAMLObject implements UIInfo { + + /** localized descriptions. */ + private final XMLObjectChildrenList descriptions; + + /** localized displayNames. */ + private final XMLObjectChildrenList displayNames; + + /** localized displayNames. */ + private final XMLObjectChildrenList keywords; + + /** (posibly) localized Logos. */ + private final XMLObjectChildrenList logos; + + /** localized Informational URLs. */ + private final XMLObjectChildrenList urls; + + /** localized PrivacyStatementURLs. */ + private final XMLObjectChildrenList privacyStatementURLs; + + /** + * Constructor. + * @param namespaceURI namespaceURI + * @param elementLocalName elementLocalName + * @param namespacePrefix namespacePrefix + */ + protected UIInfoImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + + descriptions = new XMLObjectChildrenList(this); + displayNames = new XMLObjectChildrenList(this); + logos = new XMLObjectChildrenList(this); + urls = new XMLObjectChildrenList(this); + keywords = new XMLObjectChildrenList(this); + privacyStatementURLs = new XMLObjectChildrenList(this); + } + + + /** {@inheritDoc} */ + public List getDescriptions() { + return descriptions; + } + + /** {@inheritDoc} */ + public List getDisplayNames() { + return displayNames; + } + + /** {@inheritDoc} */ + public List getKeywords() { + return keywords; + } + + /** {@inheritDoc} */ + public List getInformationURLs() { + return urls; + } + + /** {@inheritDoc} */ + public List getLogos() { + return logos; + } + + /** {@inheritDoc} */ + public List getPrivacyStatementURLs() { + return privacyStatementURLs; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(displayNames); + children.addAll(descriptions); + children.addAll(keywords); + children.addAll(urls); + children.addAll(logos); + children.addAll(privacyStatementURLs); + return children; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoMarshaller.java 17 Aug 2012 15:04:50 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +/** + * A thread safe Marshaller for {@link org.opensaml.samlext.saml2mdui.UIInfo} objects. + */ +public class UIInfoMarshaller extends AbstractSAMLObjectMarshaller { + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/samlext/saml2mdui/impl/UIInfoUnmarshaller.java 17 Aug 2012 15:04:46 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.samlext.saml2mdui.impl; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.samlext.saml2mdui.Description; +import org.opensaml.samlext.saml2mdui.DisplayName; +import org.opensaml.samlext.saml2mdui.InformationURL; +import org.opensaml.samlext.saml2mdui.Keywords; +import org.opensaml.samlext.saml2mdui.Logo; +import org.opensaml.samlext.saml2mdui.PrivacyStatementURL; +import org.opensaml.samlext.saml2mdui.UIInfo; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A thread-safe Unmarshaller for {@link org.opensaml.samlext.saml2mdui.UIInfo} objects. + */ +public class UIInfoUnmarshaller extends AbstractSAMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + UIInfo info = (UIInfo) parentSAMLObject; + + if (childSAMLObject instanceof Description) { + info.getDescriptions().add((Description) childSAMLObject); + } else if (childSAMLObject instanceof DisplayName) { + info.getDisplayNames().add((DisplayName) childSAMLObject); + } else if (childSAMLObject instanceof Keywords) { + info.getKeywords().add((Keywords) childSAMLObject); + } else if (childSAMLObject instanceof InformationURL) { + info.getInformationURLs().add((InformationURL) childSAMLObject); + } else if (childSAMLObject instanceof Logo) { + info.getLogos().add((Logo) childSAMLObject); + } else if (childSAMLObject instanceof PrivacyStatementURL) { + info.getPrivacyStatementURLs().add((PrivacyStatementURL) childSAMLObject); + } else { + super.processChildElement(parentSAMLObject, childSAMLObject); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/security/MetadataCredentialResolver.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/security/MetadataCredentialResolver.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/security/MetadataCredentialResolver.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,458 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.security; + +import java.lang.ref.SoftReference; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.saml2.metadata.provider.ObservableMetadataProvider; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.AbstractCriteriaFilteringCredentialResolver; +import org.opensaml.xml.security.credential.BasicCredential; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.EntityIDCriteria; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.security.keyinfo.KeyInfoCredentialResolver; +import org.opensaml.xml.security.keyinfo.KeyInfoCriteria; +import org.opensaml.xml.util.DatatypeHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A credential resolver capable of resolving credentials from SAML 2 metadata; + * + * The instance of {@link CriteriaSet} passed to {@link #resolve(CriteriaSet)} and {@link #resolveSingle(CriteriaSet)} + * must minimally contain 2 criteria: {@link EntityIDCriteria} and {@link MetadataCriteria}. The values for + * {@link EntityIDCriteria#getEntityID()} and {@link MetadataCriteria#getRole()} are mandatory. If the protocol value + * obtained via {@link MetadataCriteria#getProtocol()} is not supplied, credentials will be resolved from all matching + * roles, regardless of protocol support. Specification of a {@link UsageCriteria} is optional. If usage criteria is + * absent from the criteria set, the effective value {@link UsageType#UNSPECIFIED} will be used for credential + * resolution. + * + * This credential resolver will cache the resolved the credentials in a memory-sensitive cache. If the metadata + * provider is an {@link ObservableMetadataProvider} this resolver will also clear its cache when the underlying + * metadata changes. + */ +public class MetadataCredentialResolver extends AbstractCriteriaFilteringCredentialResolver { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(MetadataCredentialResolver.class); + + /** Metadata provider from which to fetch the credentials. */ + private MetadataProvider metadata; + + /** Cache of resolved credentials. [MetadataCacheKey, Credentials] */ + private Map>> cache; + + /** Credential resolver used to resolve credentials from role descriptor KeyInfo elements. */ + private KeyInfoCredentialResolver keyInfoCredentialResolver; + + /** Lock used to synchronize access to the credential cache. */ + private ReadWriteLock rwlock; + + /** + * Constructor. + * + * @param metadataProvider provider of the metadata + * + * @throws IllegalArgumentException thrown if the supplied provider is null + */ + public MetadataCredentialResolver(MetadataProvider metadataProvider) { + super(); + if (metadataProvider == null) { + throw new IllegalArgumentException("Metadata provider may not be null"); + } + metadata = metadataProvider; + + cache = new HashMap>>(); + + keyInfoCredentialResolver = Configuration.getGlobalSecurityConfiguration() + .getDefaultKeyInfoCredentialResolver(); + + rwlock = new ReentrantReadWriteLock(); + + if (metadata instanceof ObservableMetadataProvider) { + ObservableMetadataProvider observable = (ObservableMetadataProvider) metadataProvider; + observable.getObservers().add(new MetadataProviderObserver()); + } + + } + + /** + * Get the KeyInfo credential resolver used by this metadata resolver to handle KeyInfo elements. + * + * @return KeyInfo credential resolver + */ + public KeyInfoCredentialResolver getKeyInfoCredentialResolver() { + return keyInfoCredentialResolver; + } + + /** + * Set the KeyInfo credential resolver used by this metadata resolver to handle KeyInfo elements. + * + * @param keyInfoResolver the new KeyInfoCredentialResolver to use + */ + public void setKeyInfoCredentialResolver(KeyInfoCredentialResolver keyInfoResolver) { + keyInfoCredentialResolver = keyInfoResolver; + } + + /** + * Get the lock instance used to synchronize access to the credential cache. + * + * @return a read-write lock instance + */ + protected ReadWriteLock getReadWriteLock() { + return rwlock; + } + + /** {@inheritDoc} */ + protected Iterable resolveFromSource(CriteriaSet criteriaSet) throws SecurityException { + + checkCriteriaRequirements(criteriaSet); + + String entityID = criteriaSet.get(EntityIDCriteria.class).getEntityID(); + MetadataCriteria mdCriteria = criteriaSet.get(MetadataCriteria.class); + QName role = mdCriteria.getRole(); + String protocol = mdCriteria.getProtocol(); + UsageCriteria usageCriteria = criteriaSet.get(UsageCriteria.class); + UsageType usage = null; + if (usageCriteria != null) { + usage = usageCriteria.getUsage(); + } else { + usage = UsageType.UNSPECIFIED; + } + + // See Jira issue SIDP-229. + log.debug("Forcing on-demand metadata provider refresh if necessary"); + try { + metadata.getMetadata(); + } catch (MetadataProviderException e) { + // don't care about errors at this level + } + + MetadataCacheKey cacheKey = new MetadataCacheKey(entityID, role, protocol, usage); + Collection credentials = retrieveFromCache(cacheKey); + + if (credentials == null) { + credentials = retrieveFromMetadata(entityID, role, protocol, usage); + cacheCredentials(cacheKey, credentials); + } + + return credentials; + } + + /** + * Check that all necessary credential criteria are available. + * + * @param criteriaSet the credential set to evaluate + */ + protected void checkCriteriaRequirements(CriteriaSet criteriaSet) { + EntityIDCriteria entityCriteria = criteriaSet.get(EntityIDCriteria.class); + MetadataCriteria mdCriteria = criteriaSet.get(MetadataCriteria.class); + if (entityCriteria == null) { + throw new IllegalArgumentException("Entity criteria must be supplied"); + } + if (mdCriteria == null) { + throw new IllegalArgumentException("SAML metadata criteria must be supplied"); + } + if (DatatypeHelper.isEmpty(entityCriteria.getEntityID())) { + throw new IllegalArgumentException("Credential owner entity ID criteria value must be supplied"); + } + if (mdCriteria.getRole() == null) { + throw new IllegalArgumentException("Credential metadata role criteria value must be supplied"); + } + } + + /** + * Retrieves pre-resolved credentials from the cache. + * + * @param cacheKey the key to the metadata cache + * + * @return the collection of cached credentials or null + */ + protected Collection retrieveFromCache(MetadataCacheKey cacheKey) { + log.debug("Attempting to retrieve credentials from cache using index: {}", cacheKey); + Lock readLock = getReadWriteLock().readLock(); + readLock.lock(); + log.trace("Read lock over cache acquired"); + try { + if (cache.containsKey(cacheKey)) { + SoftReference> reference = cache.get(cacheKey); + if (reference.get() != null) { + log.debug("Retrieved credentials from cache using index: {}", cacheKey); + return reference.get(); + } + } + } finally { + readLock.unlock(); + log.trace("Read lock over cache released"); + } + + log.debug("Unable to retrieve credentials from cache using index: {}", cacheKey); + return null; + } + + /** + * Retrieves credentials from the provided metadata. + * + * @param entityID entityID of the credential owner + * @param role role in which the entity is operating + * @param protocol protocol over which the entity is operating (may be null) + * @param usage intended usage of resolved credentials + * + * @return the resolved credentials or null + * + * @throws SecurityException thrown if the key, certificate, or CRL information is represented in an unsupported + * format + */ + protected Collection retrieveFromMetadata(String entityID, QName role, String protocol, UsageType usage) + throws SecurityException { + + log.debug("Attempting to retrieve credentials from metadata for entity: {}", entityID); + Collection credentials = new HashSet(3); + + List roleDescriptors = getRoleDescriptors(entityID, role, protocol); + if(roleDescriptors == null || roleDescriptors.isEmpty()){ + return credentials; + } + + for (RoleDescriptor roleDescriptor : roleDescriptors) { + List keyDescriptors = roleDescriptor.getKeyDescriptors(); + if(keyDescriptors == null || keyDescriptors.isEmpty()){ + return credentials; + } + for (KeyDescriptor keyDescriptor : keyDescriptors) { + UsageType mdUsage = keyDescriptor.getUse(); + if (mdUsage == null) { + mdUsage = UsageType.UNSPECIFIED; + } + if (matchUsage(mdUsage, usage)) { + if (keyDescriptor.getKeyInfo() != null) { + CriteriaSet critSet = new CriteriaSet(); + critSet.add(new KeyInfoCriteria(keyDescriptor.getKeyInfo())); + + Iterable creds = getKeyInfoCredentialResolver().resolve(critSet); + if(credentials == null){ + continue; + } + for (Credential cred : creds) { + if (cred instanceof BasicCredential) { + BasicCredential basicCred = (BasicCredential) cred; + basicCred.setEntityId(entityID); + basicCred.setUsageType(mdUsage); + basicCred.getCredentalContextSet().add(new SAMLMDCredentialContext(keyDescriptor)); + } + credentials.add(cred); + } + } + } + } + + } + + return credentials; + } + + /** + * Match usage enum type values from metadata KeyDescriptor and from credential criteria. + * + * @param metadataUsage the value from the 'use' attribute of a metadata KeyDescriptor element + * @param criteriaUsage the value from credential criteria + * @return true if the two usage specifiers match for purposes of resolving credentials, false otherwise + */ + protected boolean matchUsage(UsageType metadataUsage, UsageType criteriaUsage) { + if (metadataUsage == UsageType.UNSPECIFIED || criteriaUsage == UsageType.UNSPECIFIED) { + return true; + } + return metadataUsage == criteriaUsage; + } + + /** + * Get the list of metadata role descriptors which match the given entityID, role and protocol. + * + * @param entityID entity ID of the credential owner + * @param role role in which the entity is operating + * @param protocol protocol over which the entity is operating (may be null) + * @return a list of role descriptors matching the given parameters, or null + * @throws SecurityException thrown if there is an error retrieving role descriptors from the metadata provider + */ + protected List getRoleDescriptors(String entityID, QName role, String protocol) + throws SecurityException { + try { + if (log.isDebugEnabled()) { + log.debug("Retrieving metadata for entity '{}' in role '{}' for protocol '{}'", + new Object[] {entityID, role, protocol}); + } + + if (DatatypeHelper.isEmpty(protocol)) { + return metadata.getRole(entityID, role); + } else { + RoleDescriptor roleDescriptor = metadata.getRole(entityID, role, protocol); + if (roleDescriptor == null) { + return null; + } + List roles = new ArrayList(); + roles.add(roleDescriptor); + return roles; + } + } catch (MetadataProviderException e) { + log.error("Unable to read metadata from provider", e); + throw new SecurityException("Unable to read metadata provider", e); + } + } + + /** + * Adds resolved credentials to the cache. + * + * @param cacheKey the key for caching the credentials + * @param credentials collection of credentials to cache + */ + protected void cacheCredentials(MetadataCacheKey cacheKey, Collection credentials) { + Lock writeLock = getReadWriteLock().writeLock(); + writeLock.lock(); + log.trace("Write lock over cache acquired"); + try { + cache.put(cacheKey, new SoftReference>(credentials)); + log.debug("Added new credential collection to cache with key: {}", cacheKey); + } finally { + writeLock.unlock(); + log.trace("Write lock over cache released"); + } + } + + /** + * A class which serves as the key into the cache of credentials previously resolved. + */ + protected class MetadataCacheKey { + + /** Entity ID of credential owner. */ + private String id; + + /** Role in which the entity is operating. */ + private QName role; + + /** Protocol over which the entity is operating (may be null). */ + private String protocol; + + /** Intended usage of the resolved credentials. */ + private UsageType usage; + + /** + * Constructor. + * + * @param entityID entity ID of the credential owner + * @param entityRole role in which the entity is operating + * @param entityProtocol protocol over which the entity is operating (may be null) + * @param entityUsage usage of the resolved credentials + */ + protected MetadataCacheKey(String entityID, QName entityRole, String entityProtocol, UsageType entityUsage) { + if (entityID == null) { + throw new IllegalArgumentException("Entity ID may not be null"); + } + if (entityRole == null) { + throw new IllegalArgumentException("Entity role may not be null"); + } + if (entityUsage == null) { + throw new IllegalArgumentException("Credential usage may not be null"); + } + id = entityID; + role = entityRole; + protocol = entityProtocol; + usage = entityUsage; + } + + /** {@inheritDoc} */ + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof MetadataCacheKey)) { + return false; + } + MetadataCacheKey other = (MetadataCacheKey) obj; + if (!this.id.equals(other.id) || !this.role.equals(other.role) || this.usage != other.usage) { + return false; + } + if (this.protocol == null) { + if (other.protocol != null) { + return false; + } + } else { + if (!this.protocol.equals(other.protocol)) { + return false; + } + } + return true; + } + + /** {@inheritDoc} */ + public int hashCode() { + int result = 17; + result = 37 * result + id.hashCode(); + result = 37 * result + role.hashCode(); + if (protocol != null) { + result = 37 * result + protocol.hashCode(); + } + result = 37 * result + usage.hashCode(); + return result; + } + + /** {@inheritDoc} */ + public String toString() { + return String.format("[%s,%s,%s,%s]", id, role, protocol, usage); + } + + } + + /** + * An observer that clears the credential cache if the underlying metadata changes. + */ + protected class MetadataProviderObserver implements ObservableMetadataProvider.Observer { + + /** {@inheritDoc} */ + public void onEvent(MetadataProvider provider) { + Lock writeLock = getReadWriteLock().writeLock(); + writeLock.lock(); + log.trace("Write lock over cache acquired"); + try { + cache.clear(); + log.debug("Credential cache cleared"); + } finally { + writeLock.unlock(); + log.trace("Write lock over cache released"); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/security/MetadataCredentialResolverFactory.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/security/MetadataCredentialResolverFactory.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/security/MetadataCredentialResolverFactory.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.security; + +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.xml.util.AbstractWrappedSingletonFactory; + +/** + * Singleton factory for producing instances of {@link MetadataCredentialResolver} + * based on a given instance of {@link MetadataProvider}. + * + *

+ * Only once instance of a metadata credential resolver will exist for + * each metadata provider instance. + *

+ */ +public class MetadataCredentialResolverFactory + extends AbstractWrappedSingletonFactory { + + /** The global instance of the factory itself. */ + private static MetadataCredentialResolverFactory factory; + + /** + * Constructor. + * + * This constructor hides the superclass public constructor, forcing + * the single, global factory instance to be obtained from {@link #getFactory()}. + * + */ + protected MetadataCredentialResolverFactory() { + super(); + } + + /** + * Return the global factory instance. + * + * @return the global factory instance + */ + public static synchronized MetadataCredentialResolverFactory getFactory() { + if (factory == null) { + factory = new MetadataCredentialResolverFactory(); + } + return factory; + } + + /** {@inheritDoc} */ + protected MetadataCredentialResolver createNewInstance(MetadataProvider metadataProvider) { + return new MetadataCredentialResolver(metadataProvider); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/security/MetadataCriteria.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/security/MetadataCriteria.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/security/MetadataCriteria.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.security; + +import javax.xml.namespace.QName; + +import org.opensaml.xml.security.Criteria; +import org.opensaml.xml.util.DatatypeHelper; + +/** + * An implementation of {@link Criteria} which specifies criteria pertaining + * to SAML 2 metadata. + */ +public final class MetadataCriteria implements Criteria { + + /** Metadata role indicated by the criteria. */ + private QName entityRole; + + /** Metadata protocol of the role indicated by the criteria. */ + private String entityProtocol; + + /** + * Constructor. + * + * @param role the entity role + * @param protocol the entity protocol + */ + public MetadataCriteria(QName role, String protocol) { + setRole(role); + setProtocol(protocol); + } + + /** + * Get the entity protocol. + * + * @return the protocol. + */ + public String getProtocol() { + return entityProtocol; + } + + /** + * Set the entity protocol. + * + * @param protocol The protocol to set. + */ + public void setProtocol(String protocol) { + entityProtocol = DatatypeHelper.safeTrimOrNullString(protocol); + } + + /** + * Get the entity role. + * + * @return Returns the role. + */ + public QName getRole() { + return entityRole; + } + + /** + * Set the entity role. + * + * @param role the QName of entity role + */ + public void setRole(QName role) { + if (role == null) { + throw new IllegalArgumentException("Role criteria may not be null"); + } + entityRole = role; + } + + + + + +} Index: 3rdParty_sources/opensaml/org/opensaml/security/SAMLMDCredentialContext.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/security/SAMLMDCredentialContext.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/security/SAMLMDCredentialContext.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.security; + +import java.util.List; + +import org.opensaml.saml2.metadata.EncryptionMethod; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.xml.security.credential.CredentialContext; + +/** + * A credential context for credentials resolved from a {@link org.opensaml.xml.signature.KeyInfo} that was found in + * SAML 2 metadata. + */ +public class SAMLMDCredentialContext implements CredentialContext { + + /** Key descriptor which contained the KeyInfo used. */ + private KeyDescriptor keyDescriptor; + + /** Role in which credential was resolved. */ + private RoleDescriptor role; + + /** Encryption methods associated with the credential. */ + private List encMethods; + + /** + * Constructor. + * + * @param descriptor the KeyDescriptor context from which a credential was resolved + */ + public SAMLMDCredentialContext(KeyDescriptor descriptor) { + keyDescriptor = descriptor; + if (descriptor != null) { + // KeyDescriptor / EncryptionMethod + encMethods = descriptor.getEncryptionMethods(); + // KeyDescriptor -> RoleDescriptor + role = (RoleDescriptor) descriptor.getParent(); + } + } + + /** + * Get the key descriptor context. + * + * @return key descriptor + */ + public KeyDescriptor getKeyDescriptor() { + return keyDescriptor; + } + + /** + * Return the list of {@link EncryptionMethod}'s associated with credential context. + * + * @return a list of SAML metadata encryption method associated with this context + */ + public List getEncryptionMethod() { + return encMethods; + } + + /** + * Get the role descriptor context. + * + * @return role descriptor + */ + public RoleDescriptor getRoleDescriptor() { + return role; + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/security/SAMLSignatureProfileValidator.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/security/SAMLSignatureProfileValidator.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/security/SAMLSignatureProfileValidator.java 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,259 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.security; + +import org.apache.xml.security.exceptions.XMLSecurityException; +import org.apache.xml.security.signature.Reference; +import org.apache.xml.security.signature.XMLSignature; +import org.apache.xml.security.transforms.Transform; +import org.apache.xml.security.transforms.TransformationException; +import org.apache.xml.security.transforms.Transforms; +import org.apache.xml.security.utils.IdResolver; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.impl.SignatureImpl; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.validation.ValidationException; +import org.opensaml.xml.validation.Validator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * A validator for instances of {@link Signature}, which validates that the signature meets security-related + * requirements indicated by the SAML profile of XML Signature. + */ +public class SAMLSignatureProfileValidator implements Validator { + + /** Class logger. */ + private final Logger log = LoggerFactory.getLogger(SAMLSignatureProfileValidator.class); + + /** {@inheritDoc} */ + public void validate(Signature signature) throws ValidationException { + + if (!(signature instanceof SignatureImpl)) { + log.info("Signature was not an instance of SignatureImpl, was {} validation not supported", signature + .getClass().getName()); + return; + } + + validateSignatureImpl((SignatureImpl) signature); + } + + /** + * Validate an instance of {@link SignatureImpl}, which is in turn based on underlying Apache XML Security + * XMLSignature instance. + * + * @param sigImpl the signature implementation object to validate + * @throws ValidationException thrown if the signature is not valid with respect to the profile + */ + protected void validateSignatureImpl(SignatureImpl sigImpl) throws ValidationException { + + if (sigImpl.getXMLSignature() == null) { + log.error("SignatureImpl did not contain the an Apache XMLSignature child"); + throw new ValidationException("Apache XMLSignature does not exist on SignatureImpl"); + } + XMLSignature apacheSig = sigImpl.getXMLSignature(); + + if (!(sigImpl.getParent() instanceof SignableSAMLObject)) { + log.error("Signature is not an immedidate child of a SignableSAMLObject"); + throw new ValidationException("Signature is not an immediate child of a SignableSAMLObject."); + } + SignableSAMLObject signableObject = (SignableSAMLObject) sigImpl.getParent(); + + Reference ref = validateReference(apacheSig); + + String uri = ref.getURI(); + + validateReferenceURI(uri, signableObject); + + validateTransforms(ref); + + validateObjectChildren(apacheSig); + } + + /** + * Validate the Signature's SignedInfo Reference. + * + * The SignedInfo must contain exactly 1 Reference. + * + * @param apacheSig the Apache XML Signature instance + * @return the valid Reference contained within the SignedInfo + * @throws ValidationException thrown if the Signature does not contain exactly 1 Reference, or if there is an error + * obtaining the Reference instance + */ + protected Reference validateReference(XMLSignature apacheSig) throws ValidationException { + int numReferences = apacheSig.getSignedInfo().getLength(); + if (numReferences != 1) { + log.error("Signature SignedInfo had invalid number of References: " + numReferences); + throw new ValidationException("Signature SignedInfo must have exactly 1 Reference element"); + } + + Reference ref = null; + try { + ref = apacheSig.getSignedInfo().item(0); + } catch (XMLSecurityException e) { + log.error("Apache XML Security exception obtaining Reference", e); + throw new ValidationException("Could not obtain Reference from Signature/SignedInfo", e); + } + if (ref == null) { + log.error("Signature Reference was null"); + throw new ValidationException("Signature Reference was null"); + } + return ref; + } + + /** + * Validate the Signature's Reference URI. + * + * First validate the Reference URI against the parent's ID itself. Then validate that the + * URI (if non-empty) resolves to the same Element node as is cached by the SignableSAMLObject. + * + * + * @param uri the Signature Reference URI attribute value + * @param signableObject the SignableSAMLObject whose signature is being validated + * @throws ValidationException if the URI is invalid or doesn't resolve to the expected DOM node + */ + protected void validateReferenceURI(String uri, SignableSAMLObject signableObject) throws ValidationException { + String id = signableObject.getSignatureReferenceID(); + validateReferenceURI(uri, id); + + if (DatatypeHelper.isEmpty(uri)) { + return; + } + + String uriID = uri.substring(1); + + Element expected = signableObject.getDOM(); + if (expected == null) { + log.error("SignableSAMLObject does not have a cached DOM Element."); + throw new ValidationException("SignableSAMLObject does not have a cached DOM Element."); + } + Document doc = expected.getOwnerDocument(); + + Element resolved = IdResolver.getElementById(doc, uriID); + if (resolved == null) { + log.error("Apache xmlsec IdResolver could not resolve the Element for id reference: {}", uriID); + throw new ValidationException("Apache xmlsec IdResolver could not resolve the Element for id reference: " + + uriID); + } + + if (!expected.isSameNode(resolved)) { + log.error("Signature Reference URI '{}' did not resolve to the expected parent Element", uri); + throw new ValidationException("Signature Reference URI did not resolve to the expected parent Element"); + } + } + + /** + * Validate the Reference URI and parent ID attribute values. + * + * The URI must either be null or empty (indicating that the entire enclosing document was signed), or else it must + * be a local document fragment reference and point to the SAMLObject parent via the latter's ID attribute value. + * + * @param uri the Signature Reference URI attribute value + * @param id the Signature parents ID attribute value + * @throws ValidationException thrown if the URI or ID attribute values are invalid + */ + protected void validateReferenceURI(String uri, String id) throws ValidationException { + if (!DatatypeHelper.isEmpty(uri)) { + if (!uri.startsWith("#")) { + log.error("Signature Reference URI was not a document fragment reference: " + uri); + throw new ValidationException("Signature Reference URI was not a document fragment reference"); + } else if (DatatypeHelper.isEmpty(id)) { + log.error("SignableSAMLObject did not contain an ID attribute"); + throw new ValidationException("SignableSAMLObject did not contain an ID attribute"); + } else if (uri.length() < 2 || !id.equals(uri.substring(1))) { + log.error("Reference URI '{}' did not point to SignableSAMLObject with ID '{}'", uri, id); + throw new ValidationException("Reference URI did not point to parent ID"); + } + } + } + + /** + * Validate the transforms included in the Signature Reference. + * + * The Reference may contain at most 2 transforms. One of them must be the Enveloped signature transform. An + * Exclusive Canonicalization transform (with or without comments) may also be present. No other transforms are + * allowed. + * + * @param reference the Signature reference containing the transforms to evaluate + * @throws ValidationException thrown if the set of transforms is invalid + */ + protected void validateTransforms(Reference reference) throws ValidationException { + Transforms transforms = null; + try { + transforms = reference.getTransforms(); + } catch (XMLSecurityException e) { + log.error("Apache XML Security error obtaining Transforms instance", e); + throw new ValidationException("Apache XML Security error obtaining Transforms instance", e); + } + + if (transforms == null) { + log.error("Error obtaining Transforms instance, null was returned"); + throw new ValidationException("Transforms instance was null"); + } + + int numTransforms = transforms.getLength(); + if (numTransforms > 2) { + log.error("Invalid number of Transforms was present: " + numTransforms); + throw new ValidationException("Invalid number of transforms"); + } + + boolean sawEnveloped = false; + for (int i = 0; i < numTransforms; i++) { + Transform transform = null; + try { + transform = transforms.item(i); + } catch (TransformationException e) { + log.error("Error obtaining transform instance", e); + throw new ValidationException("Error obtaining transform instance", e); + } + String uri = transform.getURI(); + if (Transforms.TRANSFORM_ENVELOPED_SIGNATURE.equals(uri)) { + log.debug("Saw Enveloped signature transform"); + sawEnveloped = true; + } else if (Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS.equals(uri) + || Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS.equals(uri)) { + log.debug("Saw Exclusive C14N signature transform"); + } else { + log.error("Saw invalid signature transform: " + uri); + throw new ValidationException("Signature contained an invalid transform"); + } + } + + if (!sawEnveloped) { + log.error("Signature was missing the required Enveloped signature transform"); + throw new ValidationException("Transforms did not contain the required enveloped transform"); + } + } + + /** + * Validate that the Signature instance does not contain any ds:Object children. + * + * @param apacheSig the Apache XML Signature instance + * @throws ValidationException if the signature contains ds:Object children + */ + protected void validateObjectChildren(XMLSignature apacheSig) throws ValidationException { + if (apacheSig.getObjectLength() > 0) { + log.error("Signature contained {} ds:Object child element(s)", apacheSig.getObjectLength()); + throw new ValidationException("Signature contained illegal ds:Object children"); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/security/package.html =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/security/package.html,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/security/package.html 17 Aug 2012 15:04:41 -0000 1.1 @@ -0,0 +1,12 @@ + + +Classes related to verifying various credentials within a SAML system. +

+Information on using this library can be found in the +User's Manual and information +on extending its functionality can be found in the +Developer's Manual. + +@see OpenSAML Wiki + + \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeImpl.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.ActionType; +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link ActionType}. */ +public class ActionTypeImpl extends AbstractXACMLObject implements ActionType { + + /** Lists of the attributes in the subject. */ + private XMLObjectChildrenList attributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ActionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(attributes); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeImplBuilder.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ActionType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link ActionType} objects.*/ +public class ActionTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public ActionTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public ActionType buildObject() { + return buildObject(ActionType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ActionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionTypeImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeMarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.ctx.ActionType} objects. */ +public class ActionTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ActionTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected ActionTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ActionTypeUnmarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ActionType; +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link ActionType} objects. */ +public class ActionTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ActionTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected ActionTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + ActionType action = (ActionType) parentObject; + + if (childObject instanceof AttributeType) { + action.getAttributes().add((AttributeType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeImpl.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link AttributeType}. */ +public class AttributeTypeImpl extends AbstractXACMLObject implements AttributeType { + + /** Issuer of the attribute. */ + private String issuer; + + /** AttributeID of the attribute. */ + private String attributeID; + + /** Datatype of the attribute. */ + private String datatype; + + /** List of values for this attribute. */ + private final XMLObjectChildrenList attributeValues; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeValues = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getAttributeID() { + return attributeID; + } + + /** {@inheritDoc} */ + public String getDataType() { + return datatype; + } + + /** {@inheritDoc} */ + public String getIssuer() { + return issuer; + } + + /** {@inheritDoc} */ + public void setAttributeID(String attributeId) { + this.attributeID = prepareForAssignment(this.attributeID, attributeId); + } + + /** {@inheritDoc} */ + public void setDataType(String datatype) { + this.datatype = prepareForAssignment(this.datatype, datatype); + } + + /** {@inheritDoc} */ + public void setIssuer(String issuer) { + this.issuer = prepareForAssignment(this.issuer, issuer); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(attributeValues); + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public List getAttributeValues() { + return attributeValues; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeImplBuilder.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link AttributeType} objects. */ +public class AttributeTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public AttributeTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeType buildObject() { + return buildObject(AttributeType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public AttributeType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeMarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** Marshaller for {@link AttributeType} objects. */ +public class AttributeTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public AttributeTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected AttributeTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AttributeType attribute = (AttributeType) samlElement; + + if (attribute.getIssuer() != null) { + domElement.setAttributeNS(null, AttributeType.ISSUER_ATTRIB_NAME, attribute.getIssuer()); + } + + if (attribute.getDataType() != null) { + domElement.setAttributeNS(null, AttributeType.DATATYPE_ATTRIB_NAME, attribute.getDataType()); + } + + if (attribute.getAttributeID() != null) { + domElement.setAttributeNS(null, AttributeType.ATTRIBUTEID_ATTTRIB_NAME, attribute.getAttributeID()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeTypeUnmarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link AttributeType} objects. */ +public class AttributeTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public AttributeTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected AttributeTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + AttributeType attribute = (AttributeType) parentObject; + + if (childObject instanceof AttributeValueType) { + attribute.getAttributeValues().add((AttributeValueType)childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + AttributeType attrib = (AttributeType) xmlObject; + + if (attribute.getLocalName().equals(AttributeType.ATTRIBUTEID_ATTTRIB_NAME)) { + attrib.setAttributeID(attribute.getValue()); + } else if (attribute.getLocalName().equals(AttributeType.DATATYPE_ATTRIB_NAME)) { + attrib.setDataType(attribute.getValue()); + } else if (attribute.getLocalName().equals(AttributeType.ISSUER_ATTRIB_NAME)) { + attrib.setIssuer(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeImpl.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,93 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link AttributeValueType}. */ +public class AttributeValueTypeImpl extends AbstractXACMLObject implements AttributeValueType { + + /** "any" elements. */ + private IndexedXMLObjectChildrenList unknownElements; + + /** "any" attributes. */ + private AttributeMap unknownAttributes; + + /** Text content of value element. */ + private String textContent; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeValueTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownElements = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (textContent == null) { + children.addAll(unknownElements); + } + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownElements; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownElements.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public String getValue() { + return textContent; + } + + /** {@inheritDoc} */ + public void setValue(String value) { + textContent = prepareForAssignment(textContent, value); + } +} + Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeImplBuilder.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link AttributeValueType} objects. */ +public class AttributeValueTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public AttributeValueTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public AttributeValueType buildObject() { + return buildObject(AttributeValueType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public AttributeValueType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeValueTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeMarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** Marshaller for {@link AttributeValueType} objects. */ +public class AttributeValueTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public AttributeValueTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + + Attr attribute; + for (Entry entry : attributeValue.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || attributeValue.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + + if(attributeValue.getValue() != null){ + XMLHelper.appendTextContent(domElement, attributeValue.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/AttributeValueTypeUnmarshaller.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link AttributeValueType} objects. */ +public class AttributeValueTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public AttributeValueTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected AttributeValueTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + attributeValue.getUnknownAttributes().registerID(attribQName); + } + attributeValue.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + + AttributeValueType attributeValue = (AttributeValueType) parentXMLObject; + attributeValue.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + attributeValue.setValue(DatatypeHelper.safeTrimOrNullString(elementContent)); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeImpl.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.ctx.DecisionType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; + +/** Concrete implementation of {@link DecisionType}. */ +public class DecisionTypeImpl extends AbstractXACMLObject implements DecisionType { + + /** Value for the decision. */ + private DECISION decision; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected DecisionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return new ArrayList(); + } + + /** {@inheritDoc} */ + public DECISION getDecision() { + return decision; + } + + /** {@inheritDoc} */ + public void setDecision(DECISION decision) { + this.decision = prepareForAssignment(this.decision, decision); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeImplBuilder.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.DecisionType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link DecisionType} objects. */ +public class DecisionTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public DecisionTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public DecisionType buildObject() { + return buildObject(DecisionType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public DecisionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DecisionTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeMarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.DecisionType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** Marshaller for {@link DecisionType} objects. */ +public class DecisionTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public DecisionTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected DecisionTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject samlObject, Element domElement) throws MarshallingException { + DecisionType decision = (DecisionType) samlObject; + XMLHelper.appendTextContent(domElement, decision.getDecision().toString()); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/DecisionTypeUnmarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.DecisionType; +import org.opensaml.xacml.ctx.DecisionType.DECISION; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; + +/** Unmarshaller for {@link DecisionType} objects. */ +public class DecisionTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public DecisionTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected DecisionTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject samlObject, String elementContent) { + DecisionType decision = (DecisionType) samlObject; + decision.setDecision(DECISION.valueOf(elementContent)); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeImpl.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.EnvironmentType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link EnvironmentType}. */ +public class EnvironmentTypeImpl extends AbstractXACMLObject implements EnvironmentType { + + /** List of the values in the environment. */ + private XMLObjectChildrenList attributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EnvironmentTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(attributes); + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeImplBuilder.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.EnvironmentType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link EnvironmentType} objects. */ +public class EnvironmentTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public EnvironmentTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public EnvironmentType buildObject() { + return buildObject(EnvironmentType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EnvironmentType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EnvironmentTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeMarshaller.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.ctx.EnvironmentType} objects. */ +public class EnvironmentTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public EnvironmentTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected EnvironmentTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/EnvironmentTypeUnmarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.EnvironmentType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link EnvironmentType} objects. */ +public class EnvironmentTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public EnvironmentTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected EnvironmentTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + EnvironmentType environment = (EnvironmentType) parentObject; + + if (childObject instanceof AttributeType) { + environment.getAttributes().add((AttributeType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeImpl.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.ctx.MissingAttributeDetailType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link MissingAttributeDetailType}. */ +public class MissingAttributeDetailTypeImpl extends AbstractXACMLObject implements MissingAttributeDetailType { + + /** Lists of the attribute values in details. */ + private XMLObjectChildrenList attributeValues; + + /** ID of the attribute. */ + private String attributeId; + + /** Data type of the attribute. */ + private String dataType; + + /** Issuer of the attribute. */ + private String issuer; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected MissingAttributeDetailTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeValues = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getAttributeId() { + return attributeId; + } + + /** {@inheritDoc} */ + public List getAttributeValues() { + return attributeValues; + } + + /** {@inheritDoc} */ + public String getDataType() { + return dataType; + } + + /** {@inheritDoc} */ + public String getIssuer() { + return issuer; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(attributeValues); + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public void setAttributeId(String id) { + attributeId = prepareForAssignment(attributeId, id); + } + + /** {@inheritDoc} */ + public void setDataType(String type) { + dataType = prepareForAssignment(dataType, type); + } + + /** {@inheritDoc} */ + public void setIssuer(String issuer) { + this.issuer = prepareForAssignment(this.issuer, issuer); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeImplBuilder.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.MissingAttributeDetailType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link MissingAttributeDetailType} objects. */ +public class MissingAttributeDetailTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public MissingAttributeDetailTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public MissingAttributeDetailType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new MissingAttributeDetailTypeImpl(namespaceURI, localName, namespacePrefix); + } + + /** {@inheritDoc} */ + public MissingAttributeDetailType buildObject() { + return buildObject(MissingAttributeDetailType.DEFAULT_ELEMENT_NAME); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeMarshaller.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.MissingAttributeDetailType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** Marshaller for {@link MissingAttributeDetailType} objects. */ +public class MissingAttributeDetailTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public MissingAttributeDetailTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected MissingAttributeDetailTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + MissingAttributeDetailType madt = (MissingAttributeDetailType) xmlObject; + + if (madt.getAttributeId() != null) { + domElement.setAttributeNS(null, MissingAttributeDetailType.ATTRIBUTE_ID_ATTRIB_NAME, madt.getAttributeId()); + } + + if (madt.getDataType() != null) { + domElement.setAttributeNS(null, MissingAttributeDetailType.DATA_TYPE_ATTRIB_NAME, madt.getDataType()); + } + + if (madt.getIssuer() != null) { + domElement.setAttributeNS(null, MissingAttributeDetailType.ISSUER_ATTRIB_NAME, madt.getIssuer()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/MissingAttributeDetailTypeUnmarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeValueType; +import org.opensaml.xacml.ctx.MissingAttributeDetailType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link MissingAttributeDetailType} objects. */ +public class MissingAttributeDetailTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public MissingAttributeDetailTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected MissingAttributeDetailTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + MissingAttributeDetailType madt = (MissingAttributeDetailType) xmlObject; + + if (attribute.getLocalName().equals(MissingAttributeDetailType.ATTRIBUTE_ID_ATTRIB_NAME)) { + madt.setAttributeId(attribute.getValue()); + } else if (attribute.getLocalName().equals(MissingAttributeDetailType.DATA_TYPE_ATTRIB_NAME)) { + madt.setDataType(attribute.getValue()); + } else if (attribute.getLocalName().equals(MissingAttributeDetailType.ISSUER_ATTRIB_NAME)) { + madt.setIssuer(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + MissingAttributeDetailType madt = (MissingAttributeDetailType) parentXMLObject; + if (childXMLObject instanceof AttributeValueType) { + madt.getAttributeValues().add((AttributeValueType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeImpl.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,108 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.ActionType; +import org.opensaml.xacml.ctx.EnvironmentType; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.ctx.ResourceType; +import org.opensaml.xacml.ctx.SubjectType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link RequestType}. */ +public class RequestTypeImpl extends AbstractXACMLObject implements RequestType { + + /** The subjects of the request. */ + private XMLObjectChildrenList subjects; + + /** The resources of the request. */ + private XMLObjectChildrenList resources; + + /** The environment of the request. */ + private EnvironmentType environment; + + /** The action of the request. */ + private ActionType action; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RequestTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + subjects = new XMLObjectChildrenList(this); + resources = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getSubjects() { + return subjects; + } + + /** {@inheritDoc} */ + public List getResources() { + return resources; + } + + /** {@inheritDoc} */ + public EnvironmentType getEnvironment() { + return environment; + } + + /** {@inheritDoc} */ + public void setEnvironment(EnvironmentType environment) { + this.environment = prepareForAssignment(this.environment, environment); + } + + /** {@inheritDoc} */ + public ActionType getAction() { + return action; + } + + /** {@inheritDoc} */ + public void setAction(ActionType action) { + this.action = prepareForAssignment(this.action, action); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(subjects); + children.addAll(resources); + + if (action != null) { + children.add(action); + } + + if (environment != null) { + children.add(environment); + } + + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeImplBuilder.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link RequestType} objects. */ +public class RequestTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public RequestTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public RequestType buildObject() { + return buildObject(RequestType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RequestType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RequestTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeMarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.ctx.RequestType} objects. */ +public class RequestTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public RequestTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected RequestTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/RequestTypeUnmarshaller.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ActionType; +import org.opensaml.xacml.ctx.EnvironmentType; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.ctx.ResourceType; +import org.opensaml.xacml.ctx.SubjectType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link EnvironmentType} objects. */ +public class RequestTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public RequestTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected RequestTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RequestType request = (RequestType) parentXMLObject; + + if (childXMLObject instanceof ActionType) { + request.setAction((ActionType) childXMLObject); + } else if (childXMLObject instanceof EnvironmentType) { + request.setEnvironment((EnvironmentType) childXMLObject); + } else if (childXMLObject instanceof SubjectType) { + request.getSubjects().add((SubjectType) childXMLObject); + } else if (childXMLObject instanceof ResourceType) { + request.getResources().add((ResourceType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeImpl.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,90 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.ctx.ResourceContentType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link ResourceContentType}. */ +public class ResourceContentTypeImpl extends AbstractXACMLObject implements ResourceContentType { + + /** "any" elements. */ + private IndexedXMLObjectChildrenList unknownElements; + + /** "any" attributes. */ + private AttributeMap unknownAttributes; + + /** String value of the mixed content element. */ + private String value; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResourceContentTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownElements = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(unknownElements); + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownElements; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownElements.subList(typeOrName); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + value = prepareForAssignment(value, newValue); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeImplBuilder.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ResourceContentType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link ResourceContentType} objects. */ +public class ResourceContentTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public ResourceContentTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public ResourceContentType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResourceContentTypeImpl(namespaceURI, localName, namespacePrefix); + } + + /** {@inheritDoc} */ + public ResourceContentType buildObject() { + return buildObject(ResourceContentType.DEFAULT_ELEMENT_NAME); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeMarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.xacml.ctx.ResourceContentType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** Marshaller for {@link ResourceContentType} objects. */ +public class ResourceContentTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ResourceContentTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected ResourceContentTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + ResourceContentType resourceContent = (ResourceContentType)xmlObject; + + Attr attribute; + for (Entry entry : resourceContent.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || resourceContent.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + ResourceContentType resourceContent = (ResourceContentType) xmlObject; + + if(resourceContent.getValue() != null){ + XMLHelper.appendTextContent(domElement, resourceContent.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceContentTypeUnmarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.ctx.ResourceContentType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link ResourceContentType} objects. */ +public class ResourceContentTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ResourceContentTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected ResourceContentTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + ResourceContentType resourceContent = (ResourceContentType) xmlObject; + + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + resourceContent.getUnknownAttributes().registerID(attribQName); + } + resourceContent.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ResourceContentType resourceContent = (ResourceContentType) parentXMLObject; + resourceContent.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + ResourceContentType resourceContent = (ResourceContentType) xmlObject; + resourceContent.setValue(DatatypeHelper.safeTrimOrNullString(elementContent)); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeImpl.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.ResourceContentType; +import org.opensaml.xacml.ctx.ResourceType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link ResourceType}. */ +public class ResourceTypeImpl extends AbstractXACMLObject implements ResourceType { + + /** Lists of the attributes in the subject. */ + private XMLObjectChildrenList attributes; + + /** Resources content. */ + private ResourceContentType resourceContent; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResourceTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (resourceContent != null) { + children.add(resourceContent); + } + children.addAll(attributes); + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public ResourceContentType getResourceContent() { + return resourceContent; + } + + /** {@inheritDoc} */ + public void setResourceContent(ResourceContentType content) { + resourceContent = prepareForAssignment(resourceContent, content); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeImplBuilder.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ResourceType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link ResourceType} objects. */ +public class ResourceTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public ResourceTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public ResourceType buildObject() { + return buildObject(ResourceType.DEFAULT_ELEMENT_NAME); + + } + + /** {@inheritDoc} */ + public ResourceType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResourceTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeMarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.ctx.RequestType} objects. */ +public class ResourceTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ResourceTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected ResourceTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResourceTypeUnmarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.ResourceContentType; +import org.opensaml.xacml.ctx.ResourceType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link ResourceType} objects. */ +public class ResourceTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ResourceTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected ResourceTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + ResourceType resource = (ResourceType) parentObject; + + if (childObject instanceof ResourceContentType) { + resource.setResourceContent((ResourceContentType) childObject); + } else if (childObject instanceof AttributeType) { + resource.getAttributes().add((AttributeType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeImpl.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.ResourceType; +import org.opensaml.xacml.ctx.ResponseType; +import org.opensaml.xacml.ctx.ResultType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; + +/** Concrete implementation of {@link ResourceType}. */ +public class ResponseTypeImpl extends AbstractXACMLObject implements ResponseType { + + /** The result of the response. */ + private ResultType result; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResponseTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (result != null) { + children.add(result); + } + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public ResultType getResult() { + return result; + } + + /** {@inheritDoc} */ + public void setResult(ResultType result) { + this.result = prepareForAssignment(this.result, result); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeImplBuilder.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.ctx.ResponseType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link ResponseType} objects. */ +public class ResponseTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public ResponseTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public ResponseType buildObject() { + return buildObject(ResponseType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ResponseType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResponseTypeImpl(namespaceURI, localName, XACMLConstants.XACMLCONTEXT_PREFIX); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeMarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.ctx.ResponseType} objects. */ +public class ResponseTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ResponseTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected ResponseTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResponseTypeUnmarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ResponseType; +import org.opensaml.xacml.ctx.ResultType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link ResponseType} objects. */ +public class ResponseTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ResponseTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected ResponseTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ResponseType response = (ResponseType) parentXMLObject; + if (childXMLObject instanceof ResultType) { + response.setResult((ResultType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeImpl.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,114 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.DecisionType; +import org.opensaml.xacml.ctx.ResultType; +import org.opensaml.xacml.ctx.StatusType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xml.XMLObject; + +/** Concrete implementation of {@link ResultType}. */ +public class ResultTypeImpl extends AbstractXACMLObject implements ResultType { + + /** Attribute resource id. */ + private String resourceId; + + /** The decision of the result. */ + private DecisionType decision; + + /** List of the status of this result. */ + private StatusType status; + + /** The obligations in this Result. */ + private ObligationsType obligations; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResultTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public DecisionType getDecision() { + return decision; + } + + /** {@inheritDoc} */ + public ObligationsType getObligations() { + return obligations; + } + + /** {@inheritDoc} */ + public void setObligations(ObligationsType obligationsIn) { + this.obligations = prepareForAssignment(this.obligations, obligationsIn); + } + + /** {@inheritDoc} */ + public String getResourceId() { + return resourceId; + } + + /** {@inheritDoc} */ + public StatusType getStatus() { + return status; + } + + /** {@inheritDoc} */ + public void setStatus(StatusType statusIn) { + this.status = prepareForAssignment(this.status, statusIn); + } + + /** {@inheritDoc} */ + public void setDecision(DecisionType decisionIn) { + this.decision = prepareForAssignment(this.decision, decisionIn); + } + + /** {@inheritDoc} */ + public void setResourceId(String newResourceId) { + resourceId = prepareForAssignment(this.resourceId, newResourceId); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (decision != null) { + children.add(decision); + } + + if (status != null) { + children.add(status); + } + + if (obligations != null) { + children.add(obligations); + } + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeImplBuilder.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ResultType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link ResultType} objects. */ +public class ResultTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public ResultTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public ResultType buildObject() { + return buildObject(ResultType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ResultType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResultTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeMarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,55 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.ResultType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** Marshaller for {@link ResultType} objects. */ +public class ResultTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ResultTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected ResultTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + ResultType result = (ResultType) samlElement; + + if (result.getResourceId() != null) { + domElement.setAttributeNS(null, ResultType.RESOURCE_ID_ATTTRIB_NAME, result.getResourceId()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/ResultTypeUnmarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,74 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.DecisionType; +import org.opensaml.xacml.ctx.ResultType; +import org.opensaml.xacml.ctx.StatusType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link ResultType} objects. */ +public class ResultTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ResultTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected ResultTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + ResultType result = (ResultType) xmlObject; + if (attribute.getLocalName().equals(ResultType.RESOURCE_ID_ATTTRIB_NAME)) { + result.setResourceId(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + ResultType result = (ResultType) parentObject; + + if (childObject instanceof ObligationsType) { + result.setObligations((ObligationsType) childObject); + } else if (childObject instanceof StatusType) { + result.setStatus((StatusType) childObject); + } else if (childObject instanceof DecisionType) { + result.setDecision((DecisionType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeImpl.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.StatusCodeType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; + +/** Concrete implementation of {@link StatusCodeType}. */ +public class StatusCodeTypeImpl extends AbstractXACMLObject implements StatusCodeType { + + /** Sub status code. */ + private StatusCodeType statusCode; + + /** The attribute Value. */ + private String value; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusCodeTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (statusCode != null) { + children.add(statusCode); + } + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public StatusCodeType getStatusCode() { + return statusCode; + } + + /** {@inheritDoc} */ + public String getValue() { + return value; + } + + /** {@inheritDoc} */ + public void setStatusCode(StatusCodeType code) { + statusCode = prepareForAssignment(statusCode, code); + } + + /** {@inheritDoc} */ + public void setValue(String newValue) { + this.value = prepareForAssignment(this.value, newValue); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeImplBuilder.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusCodeType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link StatusCodeType} objects. */ +public class StatusCodeTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public StatusCodeTypeImplBuilder() { + } + + /** {@inheritDoc} */ + public StatusCodeType buildObject() { + return buildObject(StatusCodeType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public StatusCodeType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusCodeTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeMarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusCodeType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** Marshaller for {@link StatusCodeType} objects. */ +public class StatusCodeTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public StatusCodeTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected StatusCodeTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + StatusCodeType attribute = (StatusCodeType) samlElement; + if (attribute.getValue() != null) { + domElement.setAttributeNS(null, StatusCodeType.VALUE_ATTTRIB_NAME, attribute.getValue()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusCodeTypeUnmarshaller.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusCodeType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link StatusCodeType} objects. */ +public class StatusCodeTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public StatusCodeTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected StatusCodeTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + StatusCodeType statusCode = (StatusCodeType) xmlObject; + if (attribute.getLocalName().equals(StatusCodeType.VALUE_ATTTRIB_NAME)) { + statusCode.setValue(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + StatusCodeType statuscode = (StatusCodeType) parentObject; + if (childObject instanceof StatusCodeType) { + statuscode.setStatusCode((StatusCodeType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeImpl.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,68 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.ctx.StatusCodeType; +import org.opensaml.xacml.ctx.StatusDetailType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link StatusCodeType}. */ +public class StatusDetailTypeImpl extends AbstractXACMLObject implements StatusDetailType { + + /** "any" children. */ + private IndexedXMLObjectChildrenList unknownChildren; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusDetailTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownChildren = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(unknownChildren); + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownChildren; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownChildren.subList(typeOrName); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeImplBuilder.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusDetailType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link StatusDetailType} objects. */ +public class StatusDetailTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public StatusDetailTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public StatusDetailType buildObject() { + return null; + } + + /** {@inheritDoc} */ + public StatusDetailType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusDetailTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeMarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.ctx.StatusDetailType} objects. */ +public class StatusDetailTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public StatusDetailTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected StatusDetailTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusDetailTypeUnmarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusDetailType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link StatusDetailType} objects. */ +public class StatusDetailTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public StatusDetailTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected StatusDetailTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** + * {@inheritDoc} + */ + protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject) + throws UnmarshallingException { + StatusDetailType statusDetail = (StatusDetailType) parentSAMLObject; + statusDetail.getUnknownXMLObjects().add(childSAMLObject); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeImpl.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.List; + +import org.opensaml.xacml.ctx.StatusMessageType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; + +/** + * Implementation of {@link org.opensaml.xacml.ctx.StatusMessageType}. + */ +public class StatusMessageTypeImpl extends AbstractXACMLObject implements StatusMessageType { + + /**Message.*/ + private String message; + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusMessageTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValue() { + return message; + } + + /** {@inheritDoc} */ + public void setValue(String newMessage) { + message = prepareForAssignment(message,newMessage); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeImplBuilder.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.ctx.StatusMessageType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** + * Builder for {@link org.opensaml.xacml.ctx.StatusMessageType}. + */ +public class StatusMessageTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** + * Constructor. + */ + public StatusMessageTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public StatusMessageType buildObject() { + return buildObject(XACMLConstants.XACML20CTX_NS, StatusMessageType.DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACMLCONTEXT_PREFIX); + } + + /** {@inheritDoc} */ + public StatusMessageType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusMessageTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeMarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,41 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusMessageType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + *Masrhaller for {@link org.opensaml.xacml.ctx.StatusMessageType}. + */ +public class StatusMessageTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + StatusMessageType message = (StatusMessageType)xmlObject; + + if(message.getValue() != null){ + XMLHelper.appendTextContent(domElement, message.getValue()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusMessageTypeUnmarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusMessageType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; + +/** + *Unmarshaller for {@link org.opensaml.xacml.ctx.StatusMessageType}. + */ +public class StatusMessageTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String content) { + StatusMessageType message = (StatusMessageType)xmlObject; + message.setValue(content); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeImpl.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,102 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.StatusCodeType; +import org.opensaml.xacml.ctx.StatusDetailType; +import org.opensaml.xacml.ctx.StatusMessageType; +import org.opensaml.xacml.ctx.StatusType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; + +/** Concrete implementation of {@link StatusType}. */ +public class StatusTypeImpl extends AbstractXACMLObject implements StatusType { + + /** Status code. */ + private StatusCodeType statusCode; + + /** The status message. */ + private StatusMessageType statusMessage; + + /** Status detail element. */ + private StatusDetailType statusDetail; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected StatusTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public StatusCodeType getStatusCode() { + return statusCode; + } + + /** {@inheritDoc} */ + public void setStatusCode(StatusCodeType newStatusCode) { + statusCode = prepareForAssignment(this.statusCode, newStatusCode); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (statusCode != null) { + children.add(statusCode); + } + + if (statusMessage != null) { + children.add(statusMessage); + } + + if (statusDetail != null) { + children.add(statusDetail); + } + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public StatusMessageType getStatusMessage() { + return statusMessage; + } + + /** {@inheritDoc} */ + public void setStatusMessage(StatusMessageType newStatusMessage) { + this.statusMessage = prepareForAssignment(this.statusMessage, newStatusMessage); + } + + /** {@inheritDoc} */ + public StatusDetailType getStatusDetail() { + return statusDetail; + } + + /** {@inheritDoc} */ + public void setStatusDetail(StatusDetailType newStatusDetail) { + this.statusDetail = prepareForAssignment(this.statusDetail, newStatusDetail); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeImplBuilder.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link StatusType} objects. */ +public class StatusTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public StatusTypeImplBuilder() { + } + + /** {@inheritDoc} */ + public StatusType buildObject() { + return buildObject(StatusType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public StatusType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new StatusTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeMarshaller.java 17 Aug 2012 15:04:37 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** Marshaller for {@link org.opensaml.xacml.ctx.StatusType} objects. */ +public class StatusTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public StatusTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected StatusTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/StatusTypeUnmarshaller.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.StatusCodeType; +import org.opensaml.xacml.ctx.StatusDetailType; +import org.opensaml.xacml.ctx.StatusMessageType; +import org.opensaml.xacml.ctx.StatusType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** Unmarshaller for {@link StatusType} objects. */ +public class StatusTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public StatusTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected StatusTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + StatusType status = (StatusType) parentObject; + + if (childObject instanceof StatusCodeType) { + status.setStatusCode((StatusCodeType) childObject); + } else if (childObject instanceof StatusMessageType) { + status.setStatusMessage((StatusMessageType) childObject); + } else if (childObject instanceof StatusDetailType) { + status.setStatusDetail((StatusDetailType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeImpl.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.SubjectType; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Concrete implementation of {@link SubjectType}. */ +public class SubjectTypeImpl extends AbstractXACMLObject implements SubjectType { + + /** Subject category of the Subject. */ + private String subjectCategory; + + /** Lists of the attributes in the subject. */ + private XMLObjectChildrenList attributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributes = new XMLObjectChildrenList(this); + subjectCategory = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + } + + /** {@inheritDoc} */ + public String getSubjectCategory() { + return subjectCategory; + } + + /** {@inheritDoc} */ + public void setSubjectCategory(String newSubjectCategory) { + subjectCategory = prepareForAssignment(this.subjectCategory, newSubjectCategory); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(attributes); + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public List getAttributes() { + return attributes; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeImplBuilder.java 17 Aug 2012 15:04:39 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.SubjectType; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; + +/** Builder for {@link SubjectType} objects. */ +public class SubjectTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** Constructor. */ + public SubjectTypeImplBuilder() { + + } + + /** {@inheritDoc} */ + public SubjectType buildObject() { + return buildObject(SubjectType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SubjectType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeMarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.SubjectType; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.w3c.dom.Element; + +/** Marshaller for {@link SubjectType} objects. */ +public class SubjectTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public SubjectTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + protected SubjectTypeMarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + SubjectType attribute = (SubjectType) samlElement; + if (attribute.getSubjectCategory() != null) { + domElement.setAttributeNS(null, SubjectType.SUBJECT_CATEGORY_ATTTRIB_NAME, attribute.getSubjectCategory()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/ctx/impl/SubjectTypeUnmarshaller.java 17 Aug 2012 15:04:38 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.ctx.impl; + +import org.opensaml.xacml.ctx.AttributeType; +import org.opensaml.xacml.ctx.SubjectType; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link SubjectType} objects. */ +public class SubjectTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public SubjectTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * unmarshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * unmarshaller operates on + */ + protected SubjectTypeUnmarshaller(String targetNamespaceURI, String targetLocalName) { + super(targetNamespaceURI, targetLocalName); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + SubjectType attrib = (SubjectType) xmlObject; + if (attribute.getLocalName().equals(SubjectType.SUBJECT_CATEGORY_ATTTRIB_NAME)) { + attrib.setSubjectCategory(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + SubjectType subject = (SubjectType) parentObject; + if (childObject instanceof AttributeType) { + subject.getAttributes().add((AttributeType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionMatchType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionMatchType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionMatchType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML ActionMatch schema type. */ +public interface ActionMatchType extends XACMLObject { + + /** Local name of the element ActionMatch. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ActionMatch"; + + /** QName of the element ActionMatch. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ActionMatchType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** MatchID attribute name. */ + public static final String MATCH_ID_ATTRIB_NAME = "MatchId"; + + /** + * Gets the attribute value for this match. + * + * @return attribute value for this match + */ + public AttributeValueType getAttributeValue(); + + /** + * Sets the attribute value for this match. + * + * @param value attribute value for this match + */ + public void setAttributeValue(AttributeValueType value); + + /** + * Gets the action attribute designator for this match. + * + * @return action attribute designator for this match + */ + public AttributeDesignatorType getActionAttributeDesignator(); + + /** + * Sets the action attribute designator for this match. + * + * @param attribute action attribute designator for this match + */ + public void setActionAttributeDesignator(AttributeDesignatorType attribute); + + /** + * Gets the attribute selector for this match. + * + * @return attribute selector for this match + */ + public AttributeSelectorType getAttributeSelector(); + + /** + * Sets the attribute selector for this match. + * + * @param selector attribute selector for this match + */ + public void setAttributeSelector(AttributeSelectorType selector); + + /** + * Gets the ID of this match. + * + * @return ID of this match + */ + public String getMatchId(); + + /** + * Sets the ID of this match. + * + * @param id ID of this match + */ + public void setMatchId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Action schema type. */ +public interface ActionType extends XACMLObject { + + /** Local name of the element Action. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Action"; + + /** QName of the element Action. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ActionType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the action matches for this action. + * + * @return action matches for this action + */ + public List getActionMatches(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionsType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionsType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ActionsType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Actions schema type. */ +public interface ActionsType extends XACMLObject { + + /** Local name of the element Actions. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Actions"; + + /** QName of the element Actions. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ActionsType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the actions. + * + * @return actions + */ + public List getActions(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ApplyType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ApplyType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ApplyType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML Apply schema type. */ +public interface ApplyType extends ExpressionType { + + /** Local name of the element Apply. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Apply"; + + /** QName of the element Apply. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ApplyType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** FunctionId attribute name. */ + public static final String FUNCTION_ID_ATTRIB_NAME = "FunctionId"; + + /** + * Gets the ID of the function. + * + * @return ID of the function + */ + public String getFunctionId(); + + /** + * Sets the ID of the function. + * + * @param id ID of the function + */ + public void setFunctionId(String id); + + /** + * Gets the expressions for this condition. + * + * @return expressions for this condition + */ + public List getExpressions(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeAssignmentType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeAssignmentType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeAssignmentType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML AttributeAssignment schema type. */ +public interface AttributeAssignmentType extends AttributeValueType { + + /** Local name of the element AttributeAssignment. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeAssignment"; + + /** QName of the element AttributeAssignment. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "AttributeAssignmentType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Id of the attribute to be assign . */ + public static final String ATTR_ID_ATTRIB_NAME = "AttributeId"; + + /** + * Gets the ID of the attribute to be assigned. + * + * @return ID of the attribute to be assigned + */ + public String getAttributeId(); + + /** + * Sets the ID of the attribute to be assigned. + * + * @param id ID of the attribute to be assigned + */ + public void setAttributeId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeDesignatorType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeDesignatorType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeDesignatorType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,144 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** XACML AttribtueDesignator schema type. */ +public interface AttributeDesignatorType extends ExpressionType { + + /** Local name of the element SubjectAttributeDesignator. */ + public static final String SUBJECT_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME = "SubjectAttributeDesignator"; + + /** QName of the element SubjectAttributeDesignator. */ + public static final QName SUBJECT_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + SUBJECT_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the element ResourceAttributeDesignator. */ + public static final String RESOURCE_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME = "ResourceAttributeDesignator"; + + /** QName of the element ResourceAttributeDesignator. */ + public static final QName RESOURCE_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + RESOURCE_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the element ActionAttributeDesignator. */ + public static final String ACTION_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME = "ActionAttributeDesignator"; + + /** QName of the element ActionAttributeDesignator. */ + public static final QName ACTION_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + ACTION_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the element EnvironmentAttribtueDesignator. */ + public static final String ENVIRONMENT_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME = "EnvironmentAttributeDesignator"; + + /** QName of the element EnvironmentAttribtueDesignator. */ + public static final QName ENVIRONMENT_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + ENVIRONMENT_ATTRIBUTE_DESIGNATOR_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "AttributeDesignatorType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** AttribtueId attribute name. */ + public static final String ATTRIBUTE_ID_ATTRIB_NAME = "AttributeId"; + + /** DataType attribute name. */ + public static final String DATA_TYPE_ATTRIB_NAME = "DataType"; + + /** Issuer attribute name. */ + public static final String ISSUER_ATTRIB_NAME = "Issuer"; + + /** MustBePresent attribute name. */ + public static final String MUST_BE_PRESENT_ATTRIB_NAME = "MustBePresent"; + + /** + * Gets the ID of the designated attribute. + * + * @return ID of the designated attribute + */ + public String getAttributeId(); + + /** + * Sets the ID of the designated attribute. + * + * @param id ID of the designated attribute + */ + public void setAttribtueId(String id); + + /** + * Gets the data type of the designated attribute. + * + * @return data type of the designated attribute + */ + public String getDataType(); + + /** + * Sets the data type of the designated attribute. + * + * @param type data type of the designated attribute + */ + public void setDataType(String type); + + /** + * Gets the issuer of the designated attribute. + * + * @return issuer of the designated attribute + */ + public String getIssuer(); + + /** + * Sets the issuer of the designated attribute. + * + * @param issuer issuer of the designated attribute + */ + public void setIssuer(String issuer); + + /** + * Gets whether the designated attribute must be present. + * + * @return whether the designated attribute must be present + */ + public XSBooleanValue getMustBePresentXSBoolean(); + + /** + * Sets whether the designated attribute must be present. + * + * @param present whether the designated attribute must be present + */ + public void setMustBePresentXSBoolean(XSBooleanValue present); + + /** + * Sets whether the designated attribute must be present. + * + * @param present whether the designated attribute must be present + */ + public void setMustBePresent(Boolean present); + + /** + * Gets whether the designated attribute must be present. + * + * @return whether the designated attribute must be present + */ + public Boolean getMustBePresent(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeSelectorType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeSelectorType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeSelectorType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,112 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xml.schema.XSBooleanValue; + +/** XACML AttributeSelector schema type. */ +public interface AttributeSelectorType extends ExpressionType { + + /** Local name of the element AttributeSelector. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeSelector"; + + /** QName of the element AttributeSelector. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName( + XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "AttributeSelectorType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName( + XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** RequestContextPath attribute name. */ + public static final String REQUEST_CONTEXT_PATH_ATTRIB_NAME = "RequestContextPath"; + + /** DataType attribute name. */ + public static final String DATA_TYPE_ATTRIB_NAME = "DataType"; + + /** MustBePresent attribute name. */ + public static final String MUST_BE_PRESENT_ATTRIB_NAME = "MustBePresent"; + + /** + * Gets the request context path of the attribute to be selected. + * + * @return request context path of the attribute to be selected + */ + public String getRequestContextPath(); + + /** + * Sets the request context path of the attribute to be selected. + * + * @param path + * request context path of the attribute to be selected + */ + public void setRequestContextPath(String path); + + /** + * Gets the data type of the attribute to be selected. + * + * @return data type of the attribute to be selected + */ + public String getDataType(); + + /** + * Sets the data type of the attribute to be selected. + * + * @param type + * data type of the attribute to be selected + */ + public void setDataType(String type); + + /** + * Gets whether the attribute to be selected must be present. + * + * @return whether the attribute to be selected must be present + */ + public Boolean getMustBePresent(); + + /** + * Gets whether the attribute to be selected must be present. + * + * @return whether the attribute to be selected must be present + */ + public XSBooleanValue getMustBePresentXSBoolean(); + + /** + * Sets whether the attribute to be selected must be present. + * + * @param present + * whether the attribute to be selected must be present + */ + public void setMustBePresent(Boolean present); + + /** + * Sets whether the attribute to be selected must be present. + * + * @param present + * whether the attribute to be selected must be present + */ + public void setMustBePresentXSBoolean(XSBooleanValue present); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeValueType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeValueType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/AttributeValueType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.ElementExtensibleXMLObject; + +/** XACML AttributeValue schema type. */ +public interface AttributeValueType extends ExpressionType, AttributeExtensibleXMLObject, ElementExtensibleXMLObject { + + /** Local name of the element AttributeValue. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "AttributeValue"; + + /** QName of the element AttributeValue. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "AttributeValueType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** DataType attribute name. */ + public static final String DATA_TYPE_ATTRIB_NAME = "DataType"; + + /** + * Gets the data type of the designated attribute. + * + * @return data type of the designated attribute + */ + public String getDataType(); + + /** + * Sets the data type of the designated attribute. + * + * @param type data type of the designated attribute + */ + public void setDataType(String type); + + /** + * Gets the text content of the element. + * + * @return text content of the element + */ + public String getValue(); + + /** + * Sets the text content of the element. + * + * NOTE because the library does not support mixed content setting textual content will prohibit + * element content. + * + * @param value text content of the element + */ + public void setValue(String value); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/CombinerParameterType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/CombinerParameterType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/CombinerParameterType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,72 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML CombinerParameter schema type. */ +public interface CombinerParameterType extends XACMLObject { + + /** Local name of the element CombinerParameters. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "CombinerParameter"; + + /** QName of the element CombinerParameters. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "CombinerParameterType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** ParameterName attribute name. */ + public static final String PARAMETER_NAMEATTRIB_NAME = "ParameterName"; + + /** + * Gets the attribute value type for this parameter. + * + * @return attribute value type for this parameter + */ + public AttributeValueType getAttributeValue(); + + /** + * Sets the attribute value type for this parameter. + * + * @param value attribute value type for this parameter + */ + public void setAttributeValue(AttributeValueType value); + + /** + * Gets the parameter name. + * + * @return the parameter name + */ + public String getParameterName(); + + /** + * Sets the the parameter name. + * + * @param name the parameter name + */ + public void setParameterName(String name); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/CombinerParametersType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/CombinerParametersType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/CombinerParametersType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML CombinerParameters schema type. */ +public interface CombinerParametersType extends XACMLObject { + + /** Local name of the element CombinerParameters. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "CombinerParameters"; + + /** QName of the element CombinerParameters. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "CombinerParametersType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the combiner parameters. + * + * @return combiner parameters + */ + public List getCombinerParameters(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ConditionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ConditionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ConditionType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,54 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML Condition schema type. */ +public interface ConditionType extends ExpressionType { + + /** Local name of the element Condition. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Condition"; + + /** QName of the element Condition. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ConditionType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the expression for this condition. + * + * @return expression for this condition + */ + public ExpressionType getExpression(); + + /** + * Sets the expression for this condition. + * + * @param expression for this condition + */ + public void setExpression(ExpressionType expression); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/DefaultsType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/DefaultsType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/DefaultsType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.schema.XSString; + +/** XACML Defaults schema type. */ +public interface DefaultsType extends XACMLObject { + + /** Local name of the element PolicySetDefaults. */ + public static final String POLICY_SET_DEFAULTS_ELEMENT_LOCAL_NAME = "PolicySetDefaults"; + + /** QName of the element PolicySetDefaults. */ + public static final QName POLICY_SET_DEFAULTS_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + POLICY_SET_DEFAULTS_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the element PolicyDefaults. */ + public static final String POLICY_DEFAULTS_ELEMENT_LOCAL_NAME = "PolicyDefaults"; + + /** QName of the element PolicyDefaults. */ + public static final QName POLICY_DEFAULTS_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + POLICY_DEFAULTS_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "DefaultsType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the XPath version for this type. + * + * @return XPath version for this type + */ + public XSString getXPathVersion(); + + /** + * Sets the XPath version for this type. + * + * @param version XPath version for this type + */ + public void setXPathVersion(XSString version); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/DescriptionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/DescriptionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/DescriptionType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.schema.XSString; + +/** XACML Description schema type. */ +public interface DescriptionType extends XSString, XACMLObject { + + /** Local name of the element Description. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Description"; + + /** QName of the element Description. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EffectType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/EffectType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EffectType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +/** XACML policy effect type. */ +public enum EffectType { + /** "Permit" effect type. */ + Permit, + + /** "Deny" effect type. */ + Deny +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentMatchType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentMatchType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentMatchType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML EnvironmentMatch schema type. */ +public interface EnvironmentMatchType extends XACMLObject { + + /** Local name of the element EnvironmentMatch. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "EnvironmentMatch"; + + /** QName of the element EnvironmentMatch. */ + public static final QName DEFAULT_ELEMENT_QNAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "EnvironmentMatchType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** MatchID attribute name. */ + public static final String MATCH_ID_ATTRIB_NAME = "MatchId"; + + /** + * Gets the attribute value for this match. + * + * @return attribute value for this match + */ + public AttributeValueType getAttributeValue(); + + /** + * Sets the attribute value for this match. + * + * @param value attribute value for this match + */ + public void setAttributeValue(AttributeValueType value); + + /** + * Gets the environment attribute designator for this match. + * + * @return environment attribute designator for this match + */ + public AttributeDesignatorType getEnvironmentAttributeDesignator(); + + /** + * Sets the environment attribute designator for this match. + * + * @param attribute environment attribute designator for this match + */ + public void setEnvironmentAttributeDesignator(AttributeDesignatorType attribute); + + /** + * Gets the attribute selector for this match. + * + * @return attribute selector for this match + */ + public AttributeSelectorType getAttributeSelector(); + + /** + * Sets the attribute selector for this match. + * + * @param selector attribute selector for this match + */ + public void setAttributeSelector(AttributeSelectorType selector); + + /** + * Gets the ID of this match. + * + * @return ID of this match + */ + public String getMatchId(); + + /** + * Sets the ID of this match. + * + * @param id ID of this match + */ + public void setMatchId(String id); +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Environment schema type. */ +public interface EnvironmentType extends XACMLObject { + + /** Local name of the element Environment. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Environment"; + + /** QName of the element Environment. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "EnvironmentType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the environment matches for this environment. + * + * @return environment matches for this environment + */ + public List getEnvrionmentMatches(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentsType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentsType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/EnvironmentsType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Environments schema type. */ +public interface EnvironmentsType extends XACMLObject { + + /** Local name of the element Environments. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Environments"; + + /** QName of the element Environments. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "EnvironmentsType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the environments. + * + * @return environments + */ + public List getEnvrionments(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ExpressionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ExpressionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ExpressionType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,42 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Expression schema type. */ +public interface ExpressionType extends XACMLObject { + + /** Local name of the element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Expression"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML20 = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ExpressionType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/FunctionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/FunctionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/FunctionType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML Function schema type. */ +public interface FunctionType extends ExpressionType { + + /** Local name of the element Function. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Function"; + + /** QName of the element Function. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "FunctionType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** FunctionId attribute name. */ + public static final String FUNCTION_ID_ATTRIB_NAME = "FunctionId"; + + /** + * Gets the ID of this function. + * + * @return ID of this function + */ + public String getFunctionId(); + + /** + * Sets the ID of this function. + * + * @param id ID of this function + */ + public void setFunctionId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/IdReferenceType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/IdReferenceType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/IdReferenceType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,101 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.schema.XSString; + +/** XACML IdReference schema type. */ +public interface IdReferenceType extends XACMLObject, XSString { + + /** Local name of the element PolicySetIdReference. */ + public static final String POLICY_SET_ID_REFERENCE_ELEMENT_LOCAL_NAME = "PolicySetIdReference"; + + /** QName of the element PolicySetIdReference. */ + public static final QName POLICY_SET_ID_REFERENCE_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + POLICY_SET_ID_REFERENCE_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the element PolicyIdReference. */ + public static final String POLICY_ID_REFERENCE_ELEMENT_LOCAL_NAME = "PolicyIdReference"; + + /** QName of the element PolicyIdReference. */ + public static final QName POLICY_ID_REFERENCE_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + POLICY_ID_REFERENCE_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "IdReferenceType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Version attribute name. */ + public static final String VERSION_ATTRIB_NAME = "Version"; + + /** EarliestVersion attribute name. */ + public static final String EARLIEST_VERSION_ATTRIB_NAME = "EarliestVersion"; + + /** LatestVersion attribute name. */ + public static final String LATEST_VERSION_ATTRIB_NAME = "LatestVersion"; + + /** + * Gets the version of the reference. + * + * @return version of the reference + */ + public String getVersion(); + + /** + * Sets the version of the reference. + * + * @param version version of the reference + */ + public void setVersion(String version); + + /** + * Gets the earliest version of the reference. + * + * @return earliest version of the reference + */ + public String getEarliestVersion(); + + /** + * Sets the earliest version of the reference. + * + * @param version earliest version of the reference + */ + public void setEarliestVersion(String version); + + /** + * Gets the latest version of the reference. + * + * @return latest version of the reference + */ + public String getLatestVersion(); + + /** + * Sets the latest version of the reference. + * + * @param version latest version of the reference + */ + public void setLatestVersion(String version); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ObligationType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ObligationType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ObligationType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,84 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Obligation schema type. */ +public interface ObligationType extends XACMLObject { + + /** Local name of the element Obligation. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Obligation"; + + /** QName of the element Obligation. */ + public static final QName DEFAULT_ELEMENT_QNAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ObligationType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** ObligationId attribute name. */ + public static final String OBLIGATION_ID_ATTRIB_NAME = "ObligationId"; + + /** FulfillOn attribute name. */ + public static final String FULFILL_ON_ATTRIB_NAME = "FulfillOn"; + + /** + * Gets the attribute assignments for this obligation. + * + * @return attribute assignments for this obligation + */ + public List getAttributeAssignments(); + + /** + * Gets the ID of this obligation. + * + * @return ID of this obligation + */ + public String getObligationId(); + + /** + * Sets the ID of this obligation. + * + * @param id ID of this obligation + */ + public void setObligationId(String id); + + /** + * Gets the fulfill on effect. + * + * @return fulfill on effect + */ + public EffectType getFulfillOn(); + + /** + * Sets fulfill on effect. + * + * @param type fulfill on effect + */ + public void setFulfillOn(EffectType type); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ObligationsType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ObligationsType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ObligationsType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Obligations schema type. */ +public interface ObligationsType extends XACMLObject { + + /** Local name of the element Obligations. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Obligations"; + + /** QName of the element Obligations. */ + public static final QName DEFAULT_ELEMENT_QNAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ObligationsType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Get the list of obligations. + * + * @return list of obligations + */ + public List getObligations(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicyCombinerParametersType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicyCombinerParametersType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicyCombinerParametersType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML PolicyCombinerParameters schema type. */ +public interface PolicyCombinerParametersType extends CombinerParametersType { + + /** Local name of the element PolicyCombinerParameters. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "PolicyCombinerParameters"; + + /** QName of the element PolicyCombinerParameters. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "PolicyCombinerParametersType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** PolicyIdRef attribute name. */ + public static final String POLICY_ID_REF_ATTRIB_NAME = "PolicyIdRef"; + + /** + * Gets the referenced policy's ID. + * + * @return referenced policy's ID + */ + public String getPolicyIdRef(); + + /** + * Sets the referenced policy's ID. + * + * @param ref referenced policy's ID + */ + public void setPolicyIdRef(String ref); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicySetCombinerParametersType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicySetCombinerParametersType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicySetCombinerParametersType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML PolicySetCombineParameters schema type. */ +public interface PolicySetCombinerParametersType extends CombinerParametersType { + + /** Local name of the element PolicySetCombineParameters. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "PolicySetCombineParameters"; + + /** QName of the element PolicySetCombineParameters. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "PolicySetCombineParametersType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** PolicySetIdRef attribute name. */ + public static final String POLICY_SET_ID_REF_ATTRIB_NAME = "PolicySetIdRef"; + + /** + * Gets the referenced policy set's ID. + * + * @return referenced policy set's ID + */ + public String getPolicySetIdRef(); + + /** + * Sets the referenced policy set's ID. + * + * @param ref referenced policy set's ID + */ + public void setPolicySetIdRef(String ref); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicySetType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicySetType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicySetType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,214 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** XACML PolicySet schema types. */ +public interface PolicySetType extends XACMLObject { + + /** Local name of the element PolicySet. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "PolicySet"; + + /** QName of the element PolicySet. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "PolicySetType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** PolicySetId attribute name. */ + public static final String POLICY_SET_ID_ATTRIB_NAME = "PolicySetId"; + + /** Version attribute name. */ + public static final String VERSION_ATTRIB_NAME = "Version"; + + /** PolicyCombiningAlgId attribute name. */ + public static final String POLICY_COMBINING_ALG_ID_ATTRIB_NAME = "PolicyCombiningAlgId"; + + /** + * Gets the description for this policy set. + * + * @return description for this policy set + */ + public DescriptionType getDescription(); + + /** + * Sets the description for this policy set. + * + * @param description description for this policy set + */ + public void setDescription(DescriptionType description); + + /** + * Gets the backing object for the choice group containing the {@link PolicySetType}, {@link PolicyType}, + * {@link IdReferenceType}, {@link CombinerParametersType}, {@link PolicyCombinerParametersType}, + * {@link PolicySetCombinerParametersType}. The individual getter/setter methods should be preferred over this + * method, however this method may be used to fine tune the ordering of all of these objects if that should be + * necessary. + * + * @return backing object for the choice group containing the {@link PolicySetType}, {@link PolicyType}, + * {@link IdReferenceType}, {@link CombinerParametersType}, {@link PolicyCombinerParametersType}, + * {@link PolicySetCombinerParametersType} + */ + public IndexedXMLObjectChildrenList getPolicyChoiceGroup(); + + /** + * Gets the defaults for this policy set. + * + * @return defaults for this policy set + */ + public DefaultsType getPolicySetDefaults(); + + /** + * Sets the defaults for this policy set. + * + * @param defaults defaults for this policy set + */ + public void setPolicySetDefaults(DefaultsType defaults); + + /** + * Gets the target of this policy set. + * + * @return target of this policy set + */ + public TargetType getTarget(); + + /** + * Sets the target of this policy set. + * + * @param target target of this policy set + */ + public void setTarget(TargetType target); + + /** + * Gets the child policy sets. + * + * @return child policy sets + */ + public List getPolicySets(); + + /** + * Gets the child policies. + * + * @return child policies + */ + public List getPolicies(); + + /** + * Gets the policy set Id references. + * + * @return policy set Id references + */ + public List getPolicySetIdReferences(); + + /** + * Gets the policy Id references. + * + * @return policy Id references + */ + public List getPolicyIdReferences(); + + /** + * Gets the combiner parameters for this policy set. + * + * @return combiner parameters for this policy set + */ + public List getCombinerParameters(); + + /** + * Gets the policy combiner parameters for this policy set. + * + * @return policy combiner parameters for this policy set + */ + public List getPolicyCombinerParameters(); + + /** + * Gets the policy set combiner parameters for this policy set. + * + * @return policy set combiner parameters for this policy set + */ + public List getPolicySetCombinerParameters(); + + /** + * Gets the obligations of this policy set. + * + * @return obligations of this policy set + */ + public ObligationsType getObligations(); + + /** + * Sets the obligations of this policy set. + * + * @param obligations obligations of this policy set + */ + public void setObligations(ObligationsType obligations); + + /** + * Gets the ID of this policy set. + * + * @return ID of this policy set + */ + public String getPolicySetId(); + + /** + * Sets the ID of this policy set. + * + * @param id ID of this policy set + */ + public void setPolicySetId(String id); + + /** + * Gets the XACML version of this policy set. + * + * @return XACML version of this policy set + */ + public String getVersion(); + + /** + * Sets the XACML version of this policy set. + * + * @param version XACML version of this policy set + */ + public void setVersion(String version); + + /** + * Gets the policy combining algorithm used with this policy set. + * + * @return policy combining algorithm used with this policy set + */ + public String getPolicyCombiningAlgoId(); + + /** + * Sets the policy combining algorithm used with this policy set. + * + * @param id policy combining algorithm used with this policy set + */ + public void setPolicyCombiningAlgoId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicyType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicyType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/PolicyType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,178 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Policy schema type. */ +public interface PolicyType extends XACMLObject { + + /** Local name of the element Policy. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Policy"; + + /** QName of the element Policy. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "PolicyType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** PolicyId attribute name. */ + public static final String POLICY_ID_ATTRIB_NAME = "PolicyId"; + + /** Version attribute name. */ + public static final String VERSION_ATTRIB_NAME = "Version"; + + /** RuleCombiningAlgId attribute name. */ + public static final String RULE_COMBINING_ALG_ID_ATTRIB_NAME = "RuleCombiningAlgId"; + + /** + * Gets the description for this policy. + * + * @return description for this policy + */ + public DescriptionType getDescription(); + + /** + * Sets the description for this policy. + * + * @param description description for this policy + */ + public void setDescription(DescriptionType description); + + /** + * Gets the defaults for this policy. + * + * @return defaults for this policy + */ + public DefaultsType getPolicyDefaults(); + + /** + * Sets the defaults for this policy. + * + * @param defaults defaults for this policy + */ + public void setPolicyDefaults(DefaultsType defaults); + + /** + * Gets the target of this policy. + * + * @return target of this policy + */ + public TargetType getTarget(); + + /** + * Sets the target of this policy. + * + * @param target target of this policy + */ + public void setTarget(TargetType target); + + /** + * Gets the combiner parameters for this policy. + * + * @return combiner parameters for this policy + */ + public List getCombinerParameters(); + + /** + * Gets the rule combiner parameters for this policy. + * + * @return rule combiner parameters for this policy + */ + public List getRuleCombinerParameters(); + + /** + * Gets the variable definition for this policy. + * + * @return variable definition for this policy + */ + public List getVariableDefinitions(); + + /** + * Gets the rules for this policy. + * + * @return rules for this policy + */ + public List getRules(); + + /** + * Gets the obligations of this policy. + * + * @return obligations of this policy + */ + public ObligationsType getObligations(); + + /** + * Sets the obligations of this policy. + * + * @param obligations obligations of this policy + */ + public void setObligations(ObligationsType obligations); + + /** + * Gets the ID of this policy. + * + * @return ID of this policy + */ + public String getPolicyId(); + + /** + * Sets the ID of this policy. + * + * @param id ID of this policy + */ + public void setPolicyId(String id); + + /** + * Gets the XACML version of this policy. + * + * @return XACML version of this policy + */ + public String getVersion(); + + /** + * Sets the XACML version of this policy. + * + * @param version XACML version of this policy + */ + public void setVersion(String version); + + /** + * Gets the rule combining algorithm used with this policy. + * + * @return rule combining algorithm used with this policy + */ + public String getRuleCombiningAlgoId(); + + /** + * Sets the rule combining algorithm used with this policy. + * + * @param id rule combining algorithm used with this policy + */ + public void setRuleCombiningAlgoId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourceMatchType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourceMatchType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourceMatchType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML ResourceMatch schema type. */ +public interface ResourceMatchType extends XACMLObject { + + /** Local name of the element ResourceMatch. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ResourceMatch"; + + /** QName of the element ResourceMatch. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ResourceMatchType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** MatchID attribute name. */ + public static final String MATCH_ID_ATTRIB_NAME = "MatchId"; + + /** + * Gets the attribute value for this match. + * + * @return attribute value for this match + */ + public AttributeValueType getAttributeValue(); + + /** + * Sets the attribute value for this match. + * + * @param value attribute value for this match + */ + public void setAttributeValue(AttributeValueType value); + + /** + * Gets the resource attribute designator for this match. + * + * @return resource attribute designator for this match + */ + public AttributeDesignatorType getResourceAttributeDesignator(); + + /** + * Sets the resource attribute designator for this match. + * + * @param attribute resource attribute designator for this match + */ + public void setResourceAttributeDesignator(AttributeDesignatorType attribute); + + /** + * Gets the attribute selector for this match. + * + * @return attribute selector for this match + */ + public AttributeSelectorType getAttributeSelector(); + + /** + * Sets the attribute selector for this match. + * + * @param selector attribute selector for this match + */ + public void setAttributeSelector(AttributeSelectorType selector); + + /** + * Gets the ID of this match. + * + * @return ID of this match + */ + public String getMatchId(); + + /** + * Sets the ID of this match. + * + * @param id ID of this match + */ + public void setMatchId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourceType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourceType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourceType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Resource schema type. */ +public interface ResourceType extends XACMLObject { + + /** Local name of the element Resource. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Resource"; + + /** QName of the element Resource. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ResourceType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the resource matches for this action. + * + * @return resource matches for this action + */ + public List getResourceMatches(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourcesType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourcesType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/ResourcesType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Resources schema type. */ +public interface ResourcesType extends XACMLObject { + + /** Local name of the element Resources. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Resources"; + + /** QName of the element Resources. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "ResourcesType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the resources. + * + * @return resources + */ + public List getResources(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/RuleCombinerParametersType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/RuleCombinerParametersType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/RuleCombinerParametersType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML RuleCombinerParameters schema type. */ +public interface RuleCombinerParametersType extends CombinerParametersType { + + /** Local name of the element RuleCombinerParameters. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "RuleCombinerParameters"; + + /** QName of the element RuleCombinerParameters. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "RuleCombinerParametersType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** RuleIdRef attribute name. */ + public static final String RULE_ID_REF_ATTRIB_NAME = "RuleIdRef"; + + /** + * Gets the referenced rule's ID. + * + * @return referenced rule's ID + */ + public String getRuleIdRef(); + + /** + * Sets the referenced rule's ID. + * + * @param ref referenced rule's ID + */ + public void setRuleIdRef(String ref); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/RuleType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/RuleType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/RuleType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,117 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Rule schema type. */ +public interface RuleType extends XACMLObject { + + /** Local name of the element Rule. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Rule"; + + /** QName of the element Rule. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "RuleType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** RuleId attribute name. */ + public static final String RULE_ID_ATTRIB_NAME = "RuleId"; + + /** Effect attribute name. */ + public static final String EFFECT_ATTRIB_NAME = "Effect"; + + /** + * Gets the description of this rule. + * + * @return description of this rule + */ + public DescriptionType getDescription(); + + /** + * Sets the description of this rule. + * + * @param description the description of this rule + */ + public void setDescription(DescriptionType description); + + /** + * Gets the target of this rule. + * + * @return the target of this rule + */ + public TargetType getTarget(); + + /** + * Sets the target of this rule. + * + * @param target the target of this rule + */ + public void setTarget(TargetType target); + + /** + * Gets the condition for this rule. + * + * @return the condition for this rule + */ + public ConditionType getCondition(); + + /** + * Sets the the condition for this rule. + * + * @param condition the condition for this rule + */ + public void setCondition(ConditionType condition); + + /** + * Gets the ID for this rule. + * + * @return the ID for this rule + */ + public String getRuleId(); + + /** + * Sets the ID for this rule. + * + * @param id the ID for this rule + */ + public void setRuleId(String id); + + /** + * Gets the effect of the rule. + * + * @return the effect of the rule + */ + public EffectType getEffect(); + + /** + * Sets the effect of the rule. + * + * @param type the effect of the rule + */ + public void setEffect(EffectType type); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectAttributeDesignatorType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectAttributeDesignatorType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectAttributeDesignatorType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,57 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML SubjectAttributeDesignator schema type. */ +public interface SubjectAttributeDesignatorType extends AttributeDesignatorType { + + /** Local name of the element Obligation. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectAttributeDesignator"; + + /** QName of the element Obligation. */ + public static final QName DEFAULT_ELEMENT_QNAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "SubjectAttributeDesignatorType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** SubjectCategory attribute name. */ + public static final String SUBJECT_CATEGORY_ATTRIB_NAME = "SubjectCategory"; + + /** + * Gets the category of the Subject. + * + * @return category of the Subject + */ + public String getSubjectCategory(); + + /** + * Sets the category of the Subject. + * + * @param category category of the Subject + */ + public void setSubjectCategory(String category); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectMatchType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectMatchType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectMatchType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,100 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML SubjectMatch schema type. */ +public interface SubjectMatchType extends XACMLObject { + + /** Local name of the element SubjectMatch. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "SubjectMatch"; + + /** QName of the element SubjectMatch. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "SubjectMatchType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** MatchID attribute name. */ + public static final String MATCH_ID_ATTRIB_NAME = "MatchId"; + + /** + * Gets the attribute value for this match. + * + * @return attribute value for this match + */ + public AttributeValueType getAttributeValue(); + + /** + * Sets the attribute value for this match. + * + * @param value attribute value for this match + */ + public void setAttributeValue(AttributeValueType value); + + /** + * Gets the subject attribute designator for this match. + * + * @return subject attribute designator for this match + */ + public AttributeDesignatorType getSubjectAttributeDesignator(); + + /** + * Sets the subject attribute designator for this match. + * + * @param attribute subject attribute designator for this match + */ + public void setSubjectAttributeDesignator(AttributeDesignatorType attribute); + + /** + * Gets the attribute selector for this match. + * + * @return attribute selector for this match + */ + public AttributeSelectorType getAttributeSelector(); + + /** + * Sets the attribute selector for this match. + * + * @param selector attribute selector for this match + */ + public void setAttributeSelector(AttributeSelectorType selector); + + /** + * Gets the ID of this match. + * + * @return ID of this match + */ + public String getMatchId(); + + /** + * Sets the ID of this match. + * + * @param id ID of this match + */ + public void setMatchId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectType.java 17 Aug 2012 15:04:44 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Subject schema type. */ +public interface SubjectType extends XACMLObject { + + /** Local name of the element Subject. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Subject"; + + /** QName of the element Subject. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "SubjectType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the subject matches for this action. + * + * @return subject matches for this action + */ + public List getSubjectMatches(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectsType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectsType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/SubjectsType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Subjects schema type. */ +public interface SubjectsType extends XACMLObject { + + /** Local name of the element Subjects. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Subjects"; + + /** QName of the element Subjects. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "SubjectsType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the subjects. + * + * @return subjects + */ + public List getSubjects(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/TargetType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/TargetType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/TargetType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,94 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML Target schema type. */ +public interface TargetType extends XACMLObject { + + /** Local name of the element Target. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "Target"; + + /** QName of the element Target. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String SCHEMA_TYPE_LOCAL_NAME = "TargetType"; + + /** QName of the XSI type. */ + public static final QName SCHEMA_TYPE_NAME = new QName(XACMLConstants.XACML20_NS, SCHEMA_TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** + * Gets the subjects of this target. + * + * @return subjects of this target + */ + public SubjectsType getSubjects(); + + /** + * Gets the resources of this target. + * + * @return resources of this target + */ + public ResourcesType getResources(); + + /** + * Gets the actions of this target. + * + * @return actions of this target + */ + public ActionsType getActions(); + + /** + * Gets the environments of this target. + * + * @return environments of this target + */ + public EnvironmentsType getEnvironments(); + + /** + * Sets the subjects in the target. + * @param subjects the subject in the target + */ + public void setSubjects(SubjectsType subjects); + + /** + * Sets the actions in the target. + * @param actions the subject in the target + */ + public void setActions(ActionsType actions); + + /** + * Sets the resources in the target. + * @param resources the subject in the target + */ + public void setResources(ResourcesType resources); + + /** + * Sets the environments in the target. + * @param environments the subject in the target + */ + public void setEnvironments(EnvironmentsType environments); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/VariableDefinitionType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/VariableDefinitionType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/VariableDefinitionType.java 17 Aug 2012 15:04:42 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML VariableDefinition schema type. */ +public interface VariableDefinitionType extends XACMLObject { + + /** Local name of the element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "VariableDefinition"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "VariableDefinitionType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME = new QName(XACMLConstants.XACML20_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Name of VariableId attribute. */ + public static final String VARIABLE_ID_ATTRIB_NAME = "VariableId"; + + /** + * Gets the expression for this definition. + * + * @return expression for this definition + */ + public ExpressionType getExpression(); + + /** + * Gets the ID of this defined variable. + * + * @return ID of this defined variable + */ + public String getVariableId(); + + /** + * Sets the ID of this defined variable. + * + * @param id ID of this defined variable + */ + public void setVariableId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/VariableReferenceType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/VariableReferenceType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/VariableReferenceType.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** XACML VariableReference. */ +public interface VariableReferenceType extends ExpressionType { + + /** Local name of the element. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "VariableReference"; + + /** Default element name. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML20 = new QName(XACMLConstants.XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "VariableReferenceType"; + + /** QName of the XSI type. */ + public static final QName TYPE_NAME_XACML20 = new QName(XACMLConstants.XACML20_NS, TYPE_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + + /** Name of VariableId attribute. */ + public static final String VARIABLE_ID_ATTRIB_NAME = "VariableId"; + + /** + * Gets the expressions for this definition. + * + * @return expressions for this definition + */ + public List getExpressions(); + + /** + * Gets the ID of the referenced variable. + * + * @return ID of the referenced variable + */ + public String getVariableId(); + + /** + * Sets the ID of the referenced variable. + * + * @param id ID of the referenced variable + */ + public void setVariableId(String id); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/XPathVersion.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/XPathVersion.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/XPathVersion.java 17 Aug 2012 15:04:43 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.XACMLObject; + +/** XACML XPathVersion schema. */ +public interface XPathVersion extends XACMLObject { + + + /** Local name of the element. */ + public static final String ELEMENT_LOCAL_NAME = "XPathVersion"; + + /** QName of the element element. */ + public static final QName DEFAULTS_ELEMENT_NAME = new QName(XACMLConstants.XACML20_NS, + ELEMENT_LOCAL_NAME, XACMLConstants.XACML_PREFIX); + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeImpl.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,128 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ActionMatchType; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link ActionMatchType}. */ +public class ActionMatchTypeImpl extends AbstractXACMLObject implements ActionMatchType { + + /** Match's attribute value. */ + private AttributeValueType attributeValue; + + /** Match's choice of attribute elements. */ + private IndexedXMLObjectChildrenList attributeChoice; + + /** Gets the ID of this match. */ + private String matchId; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + public ActionMatchTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeChoice = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AttributeSelectorType getAttributeSelector() { + List selectors = (List) attributeChoice + .subList(AttributeSelectorType.DEFAULT_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeSelectorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public AttributeValueType getAttributeValue() { + return attributeValue; + } + + /** {@inheritDoc} */ + public AttributeDesignatorType getActionAttributeDesignator() { + List selectors = (List) attributeChoice + .subList(AttributeDesignatorType.ACTION_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeDesignatorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public String getMatchId() { + return matchId; + } + + /** {@inheritDoc} */ + public void setAttributeSelector(AttributeSelectorType selector) { + AttributeSelectorType currentSelector = getAttributeSelector(); + if (currentSelector != null) { + attributeChoice.remove(currentSelector); + } + + attributeChoice.add(selector); + } + + /** {@inheritDoc} */ + public void setAttributeValue(AttributeValueType value) { + attributeValue = prepareForAssignment(attributeValue, value); + } + + /** {@inheritDoc} */ + public void setActionAttributeDesignator(AttributeDesignatorType attribute) { + AttributeDesignatorType currentDesignator = getActionAttributeDesignator(); + if (currentDesignator != null) { + attributeChoice.remove(currentDesignator); + } + + attributeChoice.add(attribute); + } + + /** {@inheritDoc} */ + public void setMatchId(String id) { + matchId = prepareForAssignment(matchId, id); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.add(attributeValue); + if (!attributeChoice.isEmpty()) { + children.addAll(attributeChoice); + } + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeImplBuilder.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ActionMatchType; + +/** Builder of {@link ActionMatchType} objects. */ +public class ActionMatchTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ActionMatchType buildObject() { + return buildObject(ActionMatchType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ActionMatchType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionMatchTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ActionMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller of {@link ActionMatchType} objects. */ +public class ActionMatchTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ActionMatchTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + ActionMatchType matchType = (ActionMatchType) xmlObject; + + if (!DatatypeHelper.isEmpty(matchType.getMatchId())) { + domElement.setAttribute(ActionMatchType.MATCH_ID_ATTRIB_NAME, matchType.getMatchId()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionMatchTypeUnmarshaller.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ActionMatchType; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** Unmarshaller of {@link ActionMatchType} objects. */ +public class ActionMatchTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ActionMatchTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(ActionMatchType.MATCH_ID_ATTRIB_NAME)) { + ActionMatchType matchType = (ActionMatchType) xmlObject; + matchType.setMatchId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ActionMatchType matchType = (ActionMatchType) parentXMLObject; + + if (childXMLObject instanceof AttributeValueType) { + matchType.setAttributeValue((AttributeValueType) childXMLObject); + } else if (childXMLObject instanceof AttributeDesignatorType) { + matchType.setActionAttributeDesignator((AttributeDesignatorType) childXMLObject); + } else if (childXMLObject instanceof AttributeSelectorType) { + matchType.setAttributeSelector((AttributeSelectorType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeImpl.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ActionMatchType; +import org.opensaml.xacml.policy.ActionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation for {@link ActionType}. + */ +public class ActionTypeImpl extends AbstractXACMLObject implements ActionType { + + /**List of action matches.*/ + private XMLObjectChildrenList actionMatch; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ActionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + actionMatch = new XMLObjectChildrenList(this); + } + /** {@inheritDoc} */ + public List getActionMatches() { + return actionMatch; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + children.addAll(actionMatch); + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeImplBuilder.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ActionType; + +/** + *Builder for {@link ActionType}. + */ +public class ActionTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ActionType buildObject() { + return buildObject(ActionType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ActionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionTypeImpl(namespaceURI,localName,namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,32 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** + * Marshaller for {@link org.opensaml.xacml.policy.ActionType}. + */ +public class ActionTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /**Constructor.*/ + public ActionTypeMarshaller(){ + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionTypeUnmarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ActionMatchType; +import org.opensaml.xacml.policy.ActionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + *Unmarshaller for {@link ActionType}. + */ +public class ActionTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ActionTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ActionType actionType = (ActionType) parentXMLObject; + + if(childXMLObject instanceof ActionMatchType){ + actionType.getActionMatches().add((ActionMatchType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeImpl.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ActionType; +import org.opensaml.xacml.policy.ActionsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link ActionsType}. + */ +public class ActionsTypeImpl extends AbstractXACMLObject implements ActionsType { + + /**List of action types.*/ + private XMLObjectChildrenList action; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ActionsTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + action = new XMLObjectChildrenList(this); + } + /** {@inheritDoc} */ + public List getActions() { + return action; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + children.addAll(action); + + return children; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeImplBuilder.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ActionsType; + +/** + * Builder for {@link ActionsType}. + */ +public class ActionsTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ActionsType buildObject() { + return buildObject(ActionsType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ActionsType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ActionsTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeMarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ActionsType; + +/** + * Marshaller for {@link ActionsType}. + */ +public class ActionsTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ActionsTypeMarshaller() { + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ActionsTypeUnmarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ActionType; +import org.opensaml.xacml.policy.ActionsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + *Unmarshaller for {@link ActionsType}. + */ +public class ActionsTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + + /** Constructor. */ + public ActionsTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ActionsType actionType = (ActionsType) parentXMLObject; + + if(childXMLObject instanceof ActionType){ + actionType.getActions().add((ActionType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeImpl.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,80 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ApplyType; +import org.opensaml.xacml.policy.ExpressionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + *Implementation of {@link ApplyType}. + */ +public class ApplyTypeImpl extends AbstractXACMLObject implements ApplyType { + + /**List of expressions.*/ + private XMLObjectChildrenList expressions; + + /**Function Id.*/ + private String functionId; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ApplyTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + expressions = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getExpressions() { + return expressions; + } + + /** {@inheritDoc} */ + public String getFunctionId() { + return functionId; + } + + /** {@inheritDoc} */ + public void setFunctionId(String id) { + this.functionId = prepareForAssignment(this.functionId,id); + } + + /** {@inheritDoc} */ + public List getOrderedChildren(){ + ArrayList children = new ArrayList(); + + if(!expressions.isEmpty()){ + children.addAll(expressions); + } + + return Collections.unmodifiableList(children); + } +} + + Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeImplBuilder.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ApplyType; + +/** + * Builder for {@link ApplyType}. + */ +public class ApplyTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ApplyType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ApplyTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public ApplyType buildObject() { + return buildObject(ApplyType.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeMarshaller.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ApplyType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link ApplyType}. + */ +public class ApplyTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ApplyTypeMarshaller() { + super(); + } + + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + ApplyType applyType = (ApplyType)xmlObject; + + if(!DatatypeHelper.isEmpty(applyType.getFunctionId())){ + domElement.setAttribute(ApplyType.FUNCTION_ID_ATTRIB_NAME, applyType.getFunctionId()); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ApplyTypeUnmarshaller.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ApplyType; +import org.opensaml.xacml.policy.ExpressionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link ApplyType}. + */ +public class ApplyTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ApplyTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + if (attribute.getLocalName().equals(ApplyType.FUNCTION_ID_ATTRIB_NAME)) { + ApplyType applyType = (ApplyType) xmlObject; + applyType.setFunctionId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ApplyType applayType = (ApplyType) parentXMLObject; + if (childXMLObject instanceof ExpressionType) { + ExpressionType expression = (ExpressionType) childXMLObject; + applayType.getExpressions().add(expression); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeImpl.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.policy.AttributeAssignmentType; +import org.opensaml.xml.XMLObject; + +/** Implementation for {@link AttributeAssignmentType}. */ +public class AttributeAssignmentTypeImpl extends AttributeValueTypeImpl implements AttributeAssignmentType { + + /** Value for the attribute AttributeId. */ + private String attributeId; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeAssignmentTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getAttributeId() { + return attributeId; + } + + /** {@inheritDoc} */ + public void setAttributeId(String newAttributeID) { + attributeId = prepareForAssignment(this.attributeId, newAttributeID); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (!super.getOrderedChildren().isEmpty()) { + children.addAll(super.getOrderedChildren()); + } + return Collections.unmodifiableList(children); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeImplBuilder.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.AttributeAssignmentType; + +/** Builder for {@link AttributeAssignmentType}. */ +public class AttributeAssignmentTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public AttributeAssignmentType buildObject() { + return buildObject(AttributeAssignmentType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public AttributeAssignmentType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeAssignmentTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeMarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.AttributeAssignmentType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller for {@link AttributeAssignmentType}. */ +public class AttributeAssignmentTypeMarshaller extends AttributeValueTypeMarshaller { + + /** Constructor. */ + public AttributeAssignmentTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + AttributeAssignmentType attributeAssignment = (AttributeAssignmentType) samlElement; + + if (!DatatypeHelper.isEmpty(attributeAssignment.getAttributeId())) { + domElement.setAttributeNS(null, AttributeAssignmentType.ATTR_ID_ATTRIB_NAME, attributeAssignment + .getAttributeId()); + } + if(!DatatypeHelper.isEmpty(attributeAssignment.getDataType())){ + super.marshallAttributes(samlElement, domElement); + } + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeAssignmentTypeUnmarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.AttributeAssignmentType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** UnMarshaller for {@link AttributeAssignmentType}. */ +public class AttributeAssignmentTypeUnmarshaller extends AttributeValueTypeUnmarshaller { + + /** Constructor. */ + public AttributeAssignmentTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { + + AttributeAssignmentType attrib = (AttributeAssignmentType) samlObject; + + if (attribute.getLocalName().equals(AttributeAssignmentType.ATTR_ID_ATTRIB_NAME)) { + attrib.setAttributeId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else{ + super.processAttribute(samlObject, attribute); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeImpl.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,127 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.LazyList; + +/** + * Implementation of {@link AttributeDesignatorType}. + */ +public class AttributeDesignatorTypeImpl extends AbstractXACMLObject implements AttributeDesignatorType { + + /** Attribute Id. */ + private String attributeId; + + /** Datatype. */ + private String dataType; + + /** Issuer. */ + private String issuer; + + /** Must be present. */ + private XSBooleanValue mustBePresentXS = null; + + /** + * Constructor. + * + * @param namespaceURI + * the namespace the element is in + * @param elementLocalName + * the local name of the XML element this Object represents + * @param namespacePrefix + * the prefix for the given namespace + */ + protected AttributeDesignatorTypeImpl(String namespaceURI, + String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + mustBePresentXS = XSBooleanValue.valueOf("false"); + } + + /** {@inheritDoc} */ + public String getAttributeId() { + return attributeId; + } + + /** {@inheritDoc} */ + public String getDataType() { + return dataType; + } + + /** {@inheritDoc} */ + public String getIssuer() { + return issuer; + } + + /** {@inheritDoc} */ + public XSBooleanValue getMustBePresentXSBoolean() { + return mustBePresentXS; + } + + /** {@inheritDoc} */ + public Boolean getMustBePresent() { + if (mustBePresentXS != null) { + return mustBePresentXS.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public void setAttribtueId(String id) { + this.attributeId = prepareForAssignment(this.attributeId, id); + } + + /** {@inheritDoc} */ + public void setDataType(String type) { + this.dataType = prepareForAssignment(this.dataType, type); + } + + /** {@inheritDoc} */ + public void setIssuer(String newIssuer) { + this.issuer = prepareForAssignment(this.issuer, newIssuer); + } + + /** {@inheritDoc} */ + public void setMustBePresentXSBoolean(XSBooleanValue present) { + this.mustBePresentXS = prepareForAssignment(this.mustBePresentXS, + present); + } + + /** {@inheritDoc} */ + public void setMustBePresent(Boolean present) { + if (present != null) { + this.mustBePresentXS = prepareForAssignment(this.mustBePresentXS, + new XSBooleanValue(present, false)); + } else { + this.mustBePresentXS = prepareForAssignment(this.mustBePresentXS, + null); + } + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return new LazyList(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeImplBuilder.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.saml1.core.AttributeDesignator; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.AttributeDesignatorType; + +/** + * Builder for {@link AttributeDesignatorType}. + */ +public class AttributeDesignatorTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public AttributeDesignatorType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeDesignatorTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public AttributeDesignatorType buildObject() { + return buildObject(AttributeDesignator.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeMarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link AttributeDesignatorType}. + */ +public class AttributeDesignatorTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public AttributeDesignatorTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) + throws MarshallingException { + AttributeDesignatorType attributeDesignatorType = (AttributeDesignatorType) xmlObject; + + if (!DatatypeHelper.isEmpty(attributeDesignatorType.getAttributeId())) { + domElement.setAttribute( + AttributeDesignatorType.ATTRIBUTE_ID_ATTRIB_NAME, + attributeDesignatorType.getAttributeId()); + } + if (!DatatypeHelper.isEmpty(attributeDesignatorType.getDataType())) { + domElement.setAttribute( + AttributeDesignatorType.DATA_TYPE_ATTRIB_NAME, + attributeDesignatorType.getDataType()); + } + if (!DatatypeHelper.isEmpty(attributeDesignatorType.getIssuer())) { + domElement.setAttribute(AttributeDesignatorType.ISSUER_ATTRIB_NAME, + attributeDesignatorType.getIssuer()); + } + if (attributeDesignatorType.getMustBePresentXSBoolean() != null) { + domElement.setAttribute( + AttributeDesignatorType.MUST_BE_PRESENT_ATTRIB_NAME, + Boolean.toString(attributeDesignatorType + .getMustBePresentXSBoolean().getValue())); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeDesignatorTypeUnmarshaller.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link AttributeDesignatorType}. + */ +public class AttributeDesignatorTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public AttributeDesignatorTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + AttributeDesignatorType attributeDesignatorType = (AttributeDesignatorType) xmlObject; + + if (attribute.getLocalName().equals(AttributeDesignatorType.ATTRIBUTE_ID_ATTRIB_NAME)){ + attributeDesignatorType.setAttribtueId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else if (attribute.getLocalName().equals(AttributeDesignatorType.DATA_TYPE_ATTRIB_NAME)){ + attributeDesignatorType.setDataType(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else if (attribute.getLocalName().equals(AttributeDesignatorType.ISSUER_ATTRIB_NAME)){ + attributeDesignatorType.setIssuer(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else if (attribute.getLocalName().equals(AttributeDesignatorType.MUST_BE_PRESENT_ATTRIB_NAME)){ + if (attribute.getValue().equals("True") || attribute.getValue().equals("true")) { + attributeDesignatorType.setMustBePresentXSBoolean(XSBooleanValue.valueOf("1")); + } else { + attributeDesignatorType.setMustBePresentXSBoolean(XSBooleanValue.valueOf("0")); + } + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeImpl.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,111 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.LazyList; + +/** + * Implementation {@link AttributeSelectorType}. + */ +public class AttributeSelectorTypeImpl extends AbstractXACMLObject implements AttributeSelectorType { + + /** Datatype. */ + private String dataType; + + /** Issuer. */ + private String requestContextPath; + + /** Must be present.Default = false */ + private XSBooleanValue mustBePresentXS = null; + + /** + * Constructor. + * + * @param namespaceURI + * the namespace the element is in + * @param elementLocalName + * the local name of the XML element this Object represents + * @param namespacePrefix + * the prefix for the given namespace + */ + protected AttributeSelectorTypeImpl(String namespaceURI, + String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + mustBePresentXS = XSBooleanValue.valueOf("false"); + } + + /** {@inheritDoc} */ + public String getDataType() { + return dataType; + } + + /** {@inheritDoc} */ + public Boolean getMustBePresent() { + if (mustBePresentXS != null) { + return mustBePresentXS.getValue(); + } + return Boolean.FALSE; + } + + /** {@inheritDoc} */ + public XSBooleanValue getMustBePresentXSBoolean() { + return mustBePresentXS; + } + + /** {@inheritDoc} */ + public String getRequestContextPath() { + return requestContextPath; + } + + /** {@inheritDoc} */ + public void setDataType(String type) { + this.dataType = prepareForAssignment(this.dataType, type); + } + + /** {@inheritDoc} */ + public void setMustBePresentXSBoolean(XSBooleanValue present) { + mustBePresentXS = prepareForAssignment(this.mustBePresentXS, present); + } + + /** {@inheritDoc} */ + public void setMustBePresent(Boolean present) { + if (present != null) { + mustBePresentXS = prepareForAssignment(mustBePresentXS, + new XSBooleanValue(present, false)); + } else { + mustBePresentXS = prepareForAssignment(mustBePresentXS, null); + } + } + + /** {@inheritDoc} */ + public void setRequestContextPath(String path) { + requestContextPath = prepareForAssignment(this.requestContextPath, path); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return new LazyList(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeImplBuilder.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.AttributeSelectorType; + +/** + *Builder for {@link AttributeSelectorType}. + */ +public class AttributeSelectorTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public AttributeSelectorType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeSelectorTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public AttributeSelectorType buildObject() { + return buildObject(AttributeSelectorType.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link AttributeSelectorType}. + */ +public class AttributeSelectorTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public AttributeSelectorTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributeSelectorType attributeSelectorType = (AttributeSelectorType) xmlObject; + + if(!DatatypeHelper.isEmpty(attributeSelectorType.getDataType())){ + domElement.setAttribute(AttributeSelectorType.DATA_TYPE_ATTRIB_NAME, + attributeSelectorType.getDataType()); + } + if(!DatatypeHelper.isEmpty(attributeSelectorType.getRequestContextPath())){ + domElement.setAttribute(AttributeSelectorType.REQUEST_CONTEXT_PATH_ATTRIB_NAME, + attributeSelectorType.getRequestContextPath()); + } + if(attributeSelectorType.getMustBePresentXSBoolean() != null){ + domElement.setAttribute(AttributeDesignatorType.MUST_BE_PRESENT_ATTRIB_NAME, + Boolean.toString(attributeSelectorType.getMustBePresentXSBoolean().getValue())); + } + if(!attributeSelectorType.getMustBePresent()){ + domElement.setAttribute(AttributeDesignatorType.MUST_BE_PRESENT_ATTRIB_NAME, + Boolean.toString(attributeSelectorType.getMustBePresent())); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeSelectorTypeUnmarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + *Unmarshaller for {@link AttributeSelectorType}. + */ +public class AttributeSelectorTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public AttributeSelectorTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributeSelectorType attributeSelectorType = (AttributeSelectorType) xmlObject; + + if (attribute.getLocalName().equals(AttributeSelectorType.REQUEST_CONTEXT_PATH_ATTRIB_NAME)){ + attributeSelectorType.setRequestContextPath(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else if (attribute.getLocalName().equals(AttributeSelectorType.DATA_TYPE_ATTRIB_NAME)){ + attributeSelectorType.setDataType(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else if (attribute.getLocalName().equals(AttributeSelectorType.MUST_BE_PRESENT_ATTRIB_NAME)){ + if (attribute.getValue().equals("True") || attribute.getValue().equals("true")) { + attributeSelectorType.setMustBePresentXSBoolean(XSBooleanValue.valueOf("1")); + } else { + attributeSelectorType.setMustBePresentXSBoolean(XSBooleanValue.valueOf("0")); + } + } else { + super.processAttribute(xmlObject, attribute); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeImpl.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,105 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Implementation of {@link AttributeValueType}. */ +public class AttributeValueTypeImpl extends AbstractXACMLObject implements AttributeValueType { + + /** Data type. */ + private String dataType; + + /** Text content of value element. */ + private String textContent; + + /** "any" elements. */ + private IndexedXMLObjectChildrenList unknownElements; + + /** "any" attributes. */ + private AttributeMap unknownAttributes; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected AttributeValueTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + unknownElements = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getDataType() { + return dataType; + } + + /** {@inheritDoc} */ + public void setDataType(String type) { + dataType = prepareForAssignment(this.dataType, type); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (textContent == null) { + children.addAll(unknownElements); + } + + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc} */ + public AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects() { + return unknownElements; + } + + /** {@inheritDoc} */ + public List getUnknownXMLObjects(QName typeOrName) { + return (List) unknownElements.subList(typeOrName); + } + + /** {@inheritDoc} */ + public String getValue() { + return textContent; + } + + /** {@inheritDoc} */ + public void setValue(String value) { + textContent = prepareForAssignment(textContent, value); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeImplBuilder.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.AttributeValueType; + +/** Builder for {@link org.opensaml.xacml.policy.AttributeValueType}. */ +public class AttributeValueTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public AttributeValueType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new AttributeValueTypeImpl(namespaceURI, localName, namespacePrefix); + } + + /** {@inheritDoc} */ + public AttributeValueType buildObject() { + return buildObject(AttributeValueType.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeMarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,71 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.Map.Entry; + +import javax.xml.namespace.QName; + +import org.opensaml.Configuration; +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.AttributeAssignmentType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +/** Marshaller for {@link org.opensaml.xacml.policy.AttributeValueType}. */ +public class AttributeValueTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public AttributeValueTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + + if(!DatatypeHelper.isEmpty(attributeValue.getDataType())){ + domElement.setAttributeNS(null,AttributeAssignmentType.DATA_TYPE_ATTRIB_NAME, attributeValue.getDataType()); + } + + Attr attribute; + for (Entry entry : attributeValue.getUnknownAttributes().entrySet()) { + attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attribute.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attribute); + if (Configuration.isIDAttribute(entry.getKey()) + || attributeValue.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attribute.getOwnerElement().setIdAttributeNode(attribute, true); + } + } + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + + if (attributeValue.getValue() != null) { + XMLHelper.appendTextContent(domElement, attributeValue.getValue()); + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/AttributeValueTypeUnmarshaller.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link org.opensaml.xacml.policy.AttributeValueType}. */ +public class AttributeValueTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public AttributeValueTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + + QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + attributeValue.getUnknownAttributes().registerID(attribQName); + } + attributeValue.getUnknownAttributes().put(attribQName, attribute.getValue()); + + if(attribute.getLocalName().equals(AttributeValueType.DATA_TYPE_ATTRIB_NAME)){ + attributeValue.setDataType(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + AttributeValueType attributeValue = (AttributeValueType) parentXMLObject; + attributeValue.getUnknownXMLObjects().add(childXMLObject); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + AttributeValueType attributeValue = (AttributeValueType) xmlObject; + attributeValue.setValue(elementContent); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeImpl.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,81 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xml.XMLObject; + +/** + *Implementation of {@link CombinerParameterType}. + */ +public class CombinerParameterTypeImpl extends AbstractXACMLObject implements CombinerParameterType { + + /**Parameter name. */ + private String name; + + /**Values.*/ + private AttributeValueType value; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected CombinerParameterTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + } + + /** {@inheritDoc} */ + public AttributeValueType getAttributeValue() { + return value; + } + + /** {@inheritDoc} */ + public String getParameterName() { + return name; + } + + /** {@inheritDoc} */ + public void setAttributeValue(AttributeValueType newValue) { + this.value = prepareForAssignment(this.value,newValue); + } + + /** {@inheritDoc} */ + public void setParameterName(String newName){ + this.name = prepareForAssignment(this.name,newName); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(value != null){ + children.add(value); + } + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeImplBuilder.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.CombinerParameterType; + +/** + * Builder for {@link CombinerParameterType}. + */ +public class CombinerParameterTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public CombinerParameterType buildObject() { + return buildObject(CombinerParameterType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public CombinerParameterType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new CombinerParameterTypeImpl(namespaceURI,localName,namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeMarshaller.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link CombinerParameterType}. + */ +public class CombinerParameterTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public CombinerParameterTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + CombinerParameterType combinerParameterType = (CombinerParameterType) xmlObject; + + if (!DatatypeHelper.isEmpty(combinerParameterType.getParameterName())) { + domElement.setAttribute(CombinerParameterType.PARAMETER_NAMEATTRIB_NAME, + combinerParameterType.getParameterName()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParameterTypeUnmarshaller.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link CombinerParameterType}. + */ +public class CombinerParameterTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public CombinerParameterTypeUnmarshaller() { + super(); + } + + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + CombinerParameterType combinerParameterType = (CombinerParameterType) xmlObject; + + if(attribute.getLocalName().equals(CombinerParameterType.PARAMETER_NAMEATTRIB_NAME)){ + combinerParameterType.setParameterName(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + CombinerParameterType combinerParameterType = (CombinerParameterType) parentXMLObject; + + if(childXMLObject instanceof AttributeValueType){ + combinerParameterType.setAttributeValue((AttributeValueType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeImpl.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xacml.policy.CombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link CombinerParametersType}. + */ +public class CombinerParametersTypeImpl extends AbstractXACMLObject implements CombinerParametersType { + + /**List or the combiner parameters.*/ + private XMLObjectChildrenList combinerParameters; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected CombinerParametersTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + combinerParameters = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getCombinerParameters() { + return combinerParameters; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(combinerParameters); + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeImplBuilder.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.CombinerParametersType; + +/** + * Builder for {@link CombinerParametersType}. + */ +public class CombinerParametersTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public CombinerParametersType buildObject() { + return buildObject(CombinerParametersType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public CombinerParametersType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new CombinerParametersTypeImpl(namespaceURI,localName,namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.CombinerParametersType; + +/** + * Marshaller for {@link CombinerParametersType}. + */ +public class CombinerParametersTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public CombinerParametersTypeMarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + public CombinerParametersTypeMarshaller(String targetNamespaceURI,String targetLocalName ) { + super(targetNamespaceURI,targetLocalName); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/CombinerParametersTypeUnmarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xacml.policy.CombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link CombinerParametersType}. + */ +public class CombinerParametersTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public CombinerParametersTypeUnmarshaller() { + super(); + } + + /** + * Constructor. + * + * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this + * marshaller operates on + * @param targetLocalName the local name of either the schema type QName or element QName of the elements this + * marshaller operates on + */ + public CombinerParametersTypeUnmarshaller(String targetNamespaceURI,String targetLocalName ) { + super(targetNamespaceURI,targetLocalName); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + CombinerParametersType combinerParametersType = (CombinerParametersType) parentXMLObject; + + if(childXMLObject instanceof CombinerParameterType){ + combinerParametersType.getCombinerParameters().add((CombinerParameterType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeImpl.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,66 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ConditionType; +import org.opensaml.xacml.policy.ExpressionType; +import org.opensaml.xml.XMLObject; + +/** + *Implementation of {@link ConditionType}. + */ +public class ConditionTypeImpl extends AbstractXACMLObject implements ConditionType { + + /**List of expressions.*/ + private ExpressionType expression; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ConditionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + } + + /** {@inheritDoc} */ + public ExpressionType getExpression() { + return expression; + } + + /** {@inheritDoc} */ + public void setExpression(ExpressionType expression){ + this.expression = prepareForAssignment(this.expression, expression); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(expression != null){ + children.add(expression); + } + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeImplBuilder.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ConditionType; + +/** + * Builder for {@link ConditionType}. + */ +public class ConditionTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ConditionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ConditionTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public ConditionType buildObject() { + return buildObject(ConditionType.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeMarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ConditionType; + +/** + * Marshaller for {@link ConditionType}. + */ +public class ConditionTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ConditionTypeMarshaller() { + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ConditionTypeUnmarshaller.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ConditionType; +import org.opensaml.xacml.policy.ExpressionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link ConditionType}. + */ +public class ConditionTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ConditionTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + if(childXMLObject instanceof ExpressionType){ + ConditionType conditionType = (ConditionType)parentXMLObject; + conditionType.setExpression((ExpressionType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeImpl.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,67 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.DefaultsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSString; + +/** Implementation for {@link DefaultsType}. */ +public class DefaultsTypeImpl extends AbstractXACMLObject implements DefaultsType { + + /** XPath version. */ + private XSString xPathVersion; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected DefaultsTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public XSString getXPathVersion() { + return xPathVersion; + } + + /** {@inheritDoc} */ + public void setXPathVersion(XSString version) { + this.xPathVersion = prepareForAssignment(this.xPathVersion, version); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (xPathVersion != null) { + children.add(xPathVersion); + } + return Collections.unmodifiableList(children); + + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeImplBuilder.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.DefaultsType; + +/** Builder for {@link DefaultsType}. */ +public class DefaultsTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public DefaultsType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DefaultsTypeImpl(namespaceURI, localName, namespacePrefix); + + } + + /** {@inheritDoc} */ + public DefaultsType buildObject() { + return null; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeMarshaller.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,30 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.DefaultsType; +/** Marshaller for {@link DefaultsType}. */ +public class DefaultsTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public DefaultsTypeMarshaller() { + super(); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DefaultsTypeUnmarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.DefaultsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.XSString; + +/** Unmarshaller for {@link DefaultsType}. */ +public class DefaultsTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + if (childXMLObject instanceof XSString) { + DefaultsType defaultType = (DefaultsType) parentXMLObject; + defaultType.setXPathVersion((XSString) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeImpl.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xml.XMLObject; + +/** + * + * Concrete implementation of {@link org.opensaml.xacml.policy.DescriptionType}. + * + */ +public class DescriptionTypeImpl extends AbstractXACMLObject implements DescriptionType { + + /**Value of the description.*/ + private String description; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected DescriptionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getValue() { + return description; + } + + /** {@inheritDoc} */ + public void setValue(String arg0) { + description = prepareForAssignment(this.description, arg0); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeImplBuilder.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.DescriptionType; + +/** + * Builder for {@link org.opensaml.xacml.policy.DescriptionType}. + */ +public class DescriptionTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** + * Constructor. + * + */ + public DescriptionTypeImplBuilder() { + } + + /** {@inheritDoc} */ + public DescriptionType buildObject() { + return buildObject(XACMLConstants.XACML20_NS, DescriptionType.DEFAULT_ELEMENT_LOCAL_NAME, + XACMLConstants.XACML_PREFIX); + } + + /** {@inheritDoc} */ + public DescriptionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new DescriptionTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeMarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +/** + *Marshaller for {@link org.opensaml.xacml.policy.DescriptionType}. + */ +public class DescriptionTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public DescriptionTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallElementContent(XMLObject xmlobject, Element domElement) throws MarshallingException { + DescriptionType message = (DescriptionType) xmlobject; + + if (message.getValue() != null) { + XMLHelper.appendTextContent(domElement, message.getValue()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/DescriptionTypeUnmarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,40 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xml.XMLObject; + +/** + * Unmarshaller for {@link org.opensaml.xacml.policy.DescriptionType}. + */ +public class DescriptionTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public DescriptionTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processElementContent(XMLObject xmlObject, String elementContent) { + DescriptionType description = (DescriptionType) xmlObject; + description.setValue(elementContent); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeImpl.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,128 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.EnvironmentMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link EnvironmentMatchType}. */ +public class EnvironmentMatchTypeImpl extends AbstractXACMLObject implements EnvironmentMatchType { + + /** Match's attribute value. */ + private AttributeValueType attributeValue; + + /** Match's choice of attribute elements. */ + private IndexedXMLObjectChildrenList attributeChoice; + + /** Gets the ID of this match. */ + private String matchId; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + public EnvironmentMatchTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeChoice = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AttributeSelectorType getAttributeSelector() { + List selectors = (List) attributeChoice + .subList(AttributeSelectorType.DEFAULT_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeSelectorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public AttributeValueType getAttributeValue() { + return attributeValue; + } + + /** {@inheritDoc} */ + public AttributeDesignatorType getEnvironmentAttributeDesignator() { + List selectors = (List) attributeChoice + .subList(AttributeDesignatorType.ENVIRONMENT_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeDesignatorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public String getMatchId() { + return matchId; + } + + /** {@inheritDoc} */ + public void setAttributeSelector(AttributeSelectorType selector) { + AttributeSelectorType currentSelector = getAttributeSelector(); + if (currentSelector != null) { + attributeChoice.remove(currentSelector); + } + + attributeChoice.add(selector); + } + + /** {@inheritDoc} */ + public void setAttributeValue(AttributeValueType value) { + attributeValue = prepareForAssignment(attributeValue, value); + } + + /** {@inheritDoc} */ + public void setEnvironmentAttributeDesignator(AttributeDesignatorType attribute) { + AttributeDesignatorType currentDesignator = getEnvironmentAttributeDesignator(); + if (currentDesignator != null) { + attributeChoice.remove(currentDesignator); + } + + attributeChoice.add(attribute); + } + + /** {@inheritDoc} */ + public void setMatchId(String id) { + matchId = prepareForAssignment(matchId, id); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.add(attributeValue); + if (!attributeChoice.isEmpty()) { + children.addAll(attributeChoice); + } + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeImplBuilder.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.EnvironmentMatchType; + +/** Builder of {@link EnvironmentMatchType} objects. */ +public class EnvironmentMatchTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public EnvironmentMatchType buildObject() { + return buildObject(EnvironmentMatchType.DEFAULT_ELEMENT_QNAME); + } + + /** {@inheritDoc} */ + public EnvironmentMatchType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EnvironmentMatchTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.EnvironmentMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller of {@link EnvironmentMatchType} objects. */ +public class EnvironmentMatchTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public EnvironmentMatchTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + EnvironmentMatchType matchType = (EnvironmentMatchType) xmlObject; + + if (!DatatypeHelper.isEmpty(matchType.getMatchId())) { + domElement.setAttribute(EnvironmentMatchType.MATCH_ID_ATTRIB_NAME, matchType.getMatchId()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentMatchTypeUnmarshaller.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.EnvironmentMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** Unmarshaller of {@link EnvironmentMatchType} objects. */ +public class EnvironmentMatchTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public EnvironmentMatchTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(EnvironmentMatchType.MATCH_ID_ATTRIB_NAME)) { + EnvironmentMatchType matchType = (EnvironmentMatchType) xmlObject; + matchType.setMatchId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + EnvironmentMatchType matchType = (EnvironmentMatchType) parentXMLObject; + if (childXMLObject instanceof AttributeValueType) { + matchType.setAttributeValue((AttributeValueType) childXMLObject); + } else if (childXMLObject instanceof AttributeDesignatorType) { + matchType.setEnvironmentAttributeDesignator((AttributeDesignatorType) childXMLObject); + } else if (childXMLObject instanceof AttributeSelectorType) { + matchType.setAttributeSelector((AttributeSelectorType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeImpl.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.EnvironmentMatchType; +import org.opensaml.xacml.policy.EnvironmentType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation for {@link EnvironmentType}. + */ +public class EnvironmentTypeImpl extends AbstractXACMLObject implements EnvironmentType { + + /**List of environment matches.*/ + private XMLObjectChildrenList environmentMatches; + + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EnvironmentTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + environmentMatches = new XMLObjectChildrenList(this); + } + /** {@inheritDoc} */ + public List getEnvrionmentMatches() { + return environmentMatches; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + children.addAll(environmentMatches); + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeImplBuilder.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.EnvironmentType; + +/** + *Builder for {@link EnvironmentType}. + */ +public class EnvironmentTypeImplBuilder extends AbstractXACMLObjectBuilder { + + + /** {@inheritDoc} */ + public EnvironmentType buildObject() { + return buildObject(EnvironmentType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EnvironmentType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EnvironmentTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeMarshaller.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.EnvironmentType; + +/** + * Marshaller for {@link EnvironmentType}. + */ +public class EnvironmentTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /**Constructor.*/ + public EnvironmentTypeMarshaller(){ + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentTypeUnmarshaller.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.EnvironmentMatchType; +import org.opensaml.xacml.policy.EnvironmentType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link EnvironmentType}. + */ +public class EnvironmentTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public EnvironmentTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + EnvironmentType environmentType = (EnvironmentType) parentXMLObject; + + if(childXMLObject instanceof EnvironmentMatchType){ + environmentType.getEnvrionmentMatches().add((EnvironmentMatchType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeImpl.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.EnvironmentType; +import org.opensaml.xacml.policy.EnvironmentsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link EnvironmentsType}. + */ +public class EnvironmentsTypeImpl extends AbstractXACMLObject implements EnvironmentsType { + + /**List of action matches.*/ + private XMLObjectChildrenList environments; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected EnvironmentsTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + environments = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getEnvrionments() { + return environments; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(environments); + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeImplBuilder.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,36 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.EnvironmentsType; + +/** + *Builder for {@link EnvironmentsType}. + */ +public class EnvironmentsTypeImplBuilder extends AbstractXACMLObjectBuilder { + /** {@inheritDoc} */ + public EnvironmentsType buildObject() { + return buildObject(EnvironmentsType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public EnvironmentsType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new EnvironmentsTypeImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.EnvironmentsType; + +/** + * Marshaller for {@link EnvironmentsType}. + */ +public class EnvironmentsTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public EnvironmentsTypeMarshaller() { + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/EnvironmentsTypeUnmarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.EnvironmentType; +import org.opensaml.xacml.policy.EnvironmentsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link EnvironmentsType}. + */ +public class EnvironmentsTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public EnvironmentsTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + EnvironmentsType environmentsType = (EnvironmentsType) parentXMLObject; + + if(childXMLObject instanceof EnvironmentType){ + environmentsType.getEnvrionments().add((EnvironmentType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeImpl.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.FunctionType; +import org.opensaml.xml.XMLObject; + +/** + * Implementation of {@link FunctionType}. + */ +public class FunctionTypeImpl extends AbstractXACMLObject implements FunctionType { + + /**Function Id.*/ + private String functionId; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected FunctionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + } + + /** {@inheritDoc} */ + public String getFunctionId() { + return functionId; + } + + /** {@inheritDoc} */ + public void setFunctionId(String id) { + functionId = prepareForAssignment(this.functionId,id); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return null; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeImplBuilder.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.FunctionType; + +/** + * Builder for {@link FunctionType}. + */ +public class FunctionTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public FunctionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new FunctionTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public FunctionType buildObject() { + return buildObject(FunctionType.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeMarshaller.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,45 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.FunctionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link FunctionType}. + */ +public class FunctionTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public FunctionTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + FunctionType functionType = (FunctionType) xmlObject; + if(!DatatypeHelper.isEmpty(functionType.getFunctionId())){ + domElement.setAttribute(FunctionType.FUNCTION_ID_ATTRIB_NAME,functionType.getFunctionId()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/FunctionTypeUnmarshaller.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,49 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.FunctionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + *Unmarshaller for {@link FunctionType}. + */ +public class FunctionTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public FunctionTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + if(attribute.getLocalName().equals(FunctionType.FUNCTION_ID_ATTRIB_NAME)){ + FunctionType functionType = (FunctionType) xmlObject; + functionType.setFunctionId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeImpl.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,79 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.IdReferenceType; +import org.opensaml.xml.schema.impl.XSStringImpl; + +/** + * Implementation of {@link IdReferenceType}. + */ +public class IdReferenceTypeImpl extends XSStringImpl implements IdReferenceType { + + /**Value of the earliest version.*/ + private String earliestVersion; + + /**Value of the latest version.*/ + private String latestVersion; + + /**Value of this version.*/ + private String version; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected IdReferenceTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + + /** {@inheritDoc} */ + public String getEarliestVersion() { + return earliestVersion; + } + + /** {@inheritDoc} */ + public String getLatestVersion() { + return latestVersion; + } + + /** {@inheritDoc} */ + public String getVersion() { + return version; + } + + /** {@inheritDoc} */ + public void setEarliestVersion(String newEarliestVersion) { + this.earliestVersion = prepareForAssignment(this.earliestVersion,newEarliestVersion); + } + + /** {@inheritDoc} */ + public void setLatestVersion(String newLastestVersion) { + this.latestVersion = prepareForAssignment(this.latestVersion,newLastestVersion); + } + + /** {@inheritDoc} */ + public void setVersion(String newVersion) { + this.version = prepareForAssignment(this.version,newVersion); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeImplBuilder.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.IdReferenceType; + +/** + * Builder for {@link IdReferenceType}. + */ +public class IdReferenceTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public IdReferenceType buildObject() { + return buildObject(IdReferenceType.TYPE_NAME); + } + + /** {@inheritDoc} */ + public IdReferenceType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new IdReferenceTypeImpl(namespaceURI, localName,namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeMarshaller.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.IdReferenceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.impl.XSStringMarshaller; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link IdReferenceType}. + */ +public class IdReferenceTypeMarshaller extends XSStringMarshaller { + + /** Constructor. */ + public IdReferenceTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + IdReferenceType idReferenceType = (IdReferenceType)xmlObject; + + if(!DatatypeHelper.isEmpty(idReferenceType.getEarliestVersion())){ + domElement.setAttribute(IdReferenceType.EARLIEST_VERSION_ATTRIB_NAME, + idReferenceType.getEarliestVersion()); + }else if(!DatatypeHelper.isEmpty(idReferenceType.getLatestVersion())){ + domElement.setAttribute(IdReferenceType.LATEST_VERSION_ATTRIB_NAME, + idReferenceType.getLatestVersion()); + }else if(!DatatypeHelper.isEmpty(idReferenceType.getVersion())){ + domElement.setAttribute(IdReferenceType.VERSION_ATTRIB_NAME, + idReferenceType.getVersion()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/IdReferenceTypeUnmarshaller.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,53 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.IdReferenceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.schema.impl.XSStringUnmarshaller; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link IdReferenceType}. + */ +public class IdReferenceTypeUnmarshaller extends XSStringUnmarshaller { + + /** Constructor. */ + public IdReferenceTypeUnmarshaller() { + super(); + } + + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + IdReferenceType idReferenceType = (IdReferenceType)xmlObject; + + if(attribute.getLocalName().equals(IdReferenceType.EARLIEST_VERSION_ATTRIB_NAME)){ + idReferenceType.setEarliestVersion(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + }else if(attribute.getLocalName().equals(IdReferenceType.LATEST_VERSION_ATTRIB_NAME)){ + idReferenceType.setLatestVersion(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + }else if(attribute.getLocalName().equals(IdReferenceType.VERSION_ATTRIB_NAME)){ + idReferenceType.setVersion(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeImpl.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,89 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeAssignmentType; +import org.opensaml.xacml.policy.EffectType; +import org.opensaml.xacml.policy.ObligationType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Implementation for {@link ObligationType}. */ +public class ObligationTypeImpl extends AbstractXACMLObject implements ObligationType { + + /** List of the atrributeAssignments in the obligation. */ + private XMLObjectChildrenList attributeAssignments; + + /** The attribute fulfillOn. */ + private EffectType fulFillOn; + + /** Obligation Id. */ + private String obligationId; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ObligationTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeAssignments = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getAttributeAssignments() { + return attributeAssignments; + } + + /** {@inheritDoc} */ + public EffectType getFulfillOn() { + return fulFillOn; + } + + /** {@inheritDoc} */ + public String getObligationId() { + return obligationId; + } + + /** {@inheritDoc} */ + public void setFulfillOn(EffectType newFulfillOn) { + fulFillOn = prepareForAssignment(this.fulFillOn, newFulfillOn); + } + + /** {@inheritDoc} */ + public void setObligationId(String newObligationId) { + obligationId = prepareForAssignment(this.obligationId, newObligationId); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if (!attributeAssignments.isEmpty()) { + children.addAll(attributeAssignments); + } + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeImplBuilder.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ObligationType; + +/** Builder for {@link ObligationType}. */ +public class ObligationTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ObligationType buildObject() { + return buildObject(ObligationType.DEFAULT_ELEMENT_QNAME); + } + + /** {@inheritDoc} */ + public ObligationType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ObligationTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeMarshaller.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.EffectType; +import org.opensaml.xacml.policy.ObligationType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller for {@link ObligationType}. */ +public class ObligationTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ObligationTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException { + ObligationType obligation = (ObligationType) samlElement; + + if (!DatatypeHelper.isEmpty(obligation.getObligationId())) { + domElement.setAttributeNS(null, ObligationType.OBLIGATION_ID_ATTRIB_NAME, obligation.getObligationId()); + } + if (obligation.getFulfillOn() != null) { + if (obligation.getFulfillOn().equals(EffectType.Deny)) { + domElement.setAttributeNS(null, ObligationType.FULFILL_ON_ATTRIB_NAME, EffectType.Deny.toString()); + } else { + domElement.setAttributeNS(null, ObligationType.FULFILL_ON_ATTRIB_NAME, EffectType.Permit.toString()); + } + } + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationTypeUnmarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeAssignmentType; +import org.opensaml.xacml.policy.EffectType; +import org.opensaml.xacml.policy.ObligationType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** UnMarshaller for {@link org.opensaml.xacml.policy.ObligationType}. */ +public class ObligationTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + ObligationType obligation = (ObligationType) parentObject; + + if (childObject instanceof AttributeAssignmentType) { + obligation.getAttributeAssignments().add((AttributeAssignmentType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + ObligationType obligation = (ObligationType) xmlObject; + + if (attribute.getLocalName().equals(ObligationType.OBLIGATION_ID_ATTRIB_NAME)) { + obligation.setObligationId(attribute.getValue()); + } else if (attribute.getLocalName().equals(ObligationType.FULFILL_ON_ATTRIB_NAME)) { + if (attribute.getValue().equals(EffectType.Permit.toString())) { + obligation.setFulfillOn(EffectType.Permit); + } else { + obligation.setFulfillOn(EffectType.Deny); + } + } else { + super.processAttribute(xmlObject, attribute); + } + + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeImpl.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ObligationType; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** Implementation for {@link ObligationsType}. */ +public class ObligationsTypeImpl extends AbstractXACMLObject implements ObligationsType { + + /** A list of the obligations. */ + private XMLObjectChildrenList obligations; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ObligationsTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + obligations = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getObligations() { + return obligations; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(obligations); + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeImplBuilder.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ObligationsType; + +/** Builder for {@link ObligationsType}. */ +public class ObligationsTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ObligationsType buildObject() { + return buildObject(ObligationsType.DEFAULT_ELEMENT_QNAME); + } + + /** {@inheritDoc} */ + public ObligationsType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ObligationsTypeImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeMarshaller.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,31 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ObligationsType; + +/** Marshaller for {@link ObligationsType}. */ +public class ObligationsTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ObligationsTypeMarshaller() { + super(); + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ObligationsTypeUnmarshaller.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ObligationType; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** UnMarshaller for {@link ObligationsType}. */ +public class ObligationsTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ObligationsTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { + + ObligationsType obligations = (ObligationsType) parentObject; + + if (childObject instanceof ObligationType) { + obligations.getObligations().add((ObligationType) childObject); + } else { + super.processChildElement(parentObject, childObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeImpl.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link PolicyCombinerParametersTypeUnmarshaller}. + */ +public class PolicyCombinerParametersTypeImpl extends AbstractXACMLObject implements + org.opensaml.xacml.policy.PolicyCombinerParametersType { + + /**Policy indentity reference.*/ + private String policyIdRef; + + /**List or the combiner parameters.*/ + private XMLObjectChildrenList combinerParameters; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected PolicyCombinerParametersTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + combinerParameters = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getPolicyIdRef() { + return policyIdRef; + } + + /** {@inheritDoc} */ + public void setPolicyIdRef(String ref) { + this.policyIdRef = prepareForAssignment(this.policyIdRef,ref); + } + + /** {@inheritDoc} */ + public List getCombinerParameters() { + return combinerParameters; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(combinerParameters); + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeImplBuilder.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.PolicyCombinerParametersType; + +/** + * Builder for {@link PolicyCombinerParametersType}. + */ +public class PolicyCombinerParametersTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public PolicyCombinerParametersType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PolicyCombinerParametersTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public PolicyCombinerParametersType buildObject() { + return buildObject(PolicyCombinerParametersType.DEFAULT_ELEMENT_NAME); + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeMarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.PolicyCombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshalelr for {@link PolicyCombinerParametersType}. + */ +public class PolicyCombinerParametersTypeMarshaller extends CombinerParametersTypeMarshaller { + + /** Constructor. */ + public PolicyCombinerParametersTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + PolicyCombinerParametersType policyCombinerParametersType = (PolicyCombinerParametersType)xmlObject; + + if(!DatatypeHelper.isEmpty(policyCombinerParametersType.getPolicyIdRef())){ + domElement.setAttribute(PolicyCombinerParametersType.POLICY_ID_REF_ATTRIB_NAME, + policyCombinerParametersType.getPolicyIdRef()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyCombinerParametersTypeUnmarshaller.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.PolicyCombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link PolicyCombinerParametersType}. + */ +public class PolicyCombinerParametersTypeUnmarshaller extends CombinerParametersTypeUnmarshaller { + + /** Constructor. */ + public PolicyCombinerParametersTypeUnmarshaller() { + super(); + } + + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + if(attribute.getLocalName().equals(PolicyCombinerParametersType.POLICY_ID_REF_ATTRIB_NAME)){ + PolicyCombinerParametersType policyCombinerParametersType = (PolicyCombinerParametersType)xmlObject; + policyCombinerParametersType.setPolicyIdRef(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeImpl.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,60 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.List; + +import org.opensaml.xacml.policy.PolicySetCombinerParametersType; +import org.opensaml.xml.XMLObject; + +/** + *Implementation of {@link PolicySetCombinerParametersType}. + */ +public class PolicySetCombinerParametersTypeImpl extends CombinerParametersTypeImpl implements + PolicySetCombinerParametersType { + + /**Policy indentity reference.*/ + private String policySetIdRef; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected PolicySetCombinerParametersTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + } + + /** {@inheritDoc} */ + public String getPolicySetIdRef() { + return policySetIdRef; + } + + /** {@inheritDoc} */ + public void setPolicySetIdRef(String ref) { + this.policySetIdRef = prepareForAssignment(this.policySetIdRef,ref); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return super.getOrderedChildren(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeImplBuilder.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.PolicySetCombinerParametersType; + +/** + * Builder for {@link PolicySetCombinerParametersType}. + */ +public class PolicySetCombinerParametersTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public PolicySetCombinerParametersType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PolicySetCombinerParametersTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public PolicySetCombinerParametersType buildObject() { + return buildObject(PolicySetCombinerParametersType.DEFAULT_ELEMENT_NAME); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeMarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.PolicySetCombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link PolicySetCombinerParametersType}. + */ +public class PolicySetCombinerParametersTypeMarshaller extends CombinerParametersTypeMarshaller { + + /** Constructor. */ + public PolicySetCombinerParametersTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + PolicySetCombinerParametersType policySetCombinerParametersType = (PolicySetCombinerParametersType)xmlObject; + + if(!DatatypeHelper.isEmpty(policySetCombinerParametersType.getPolicySetIdRef())){ + domElement.setAttribute(PolicySetCombinerParametersType.POLICY_SET_ID_REF_ATTRIB_NAME, + policySetCombinerParametersType.getPolicySetIdRef()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetCombinerParametersTypeUnmarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.PolicySetCombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link PolicySetCombinerParametersType}. + */ +public class PolicySetCombinerParametersTypeUnmarshaller extends CombinerParametersTypeUnmarshaller { + /** + * Constructor. + */ + public PolicySetCombinerParametersTypeUnmarshaller(){ + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + if(attribute.getLocalName().equals(PolicySetCombinerParametersType.POLICY_SET_ID_REF_ATTRIB_NAME)){ + PolicySetCombinerParametersType policySetCombinerParametersType = + (PolicySetCombinerParametersType)xmlObject; + policySetCombinerParametersType.setPolicySetIdRef( + DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeImpl.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,212 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.CombinerParametersType; +import org.opensaml.xacml.policy.DefaultsType; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xacml.policy.IdReferenceType; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xacml.policy.PolicyCombinerParametersType; +import org.opensaml.xacml.policy.PolicySetCombinerParametersType; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link PolicySetType}. */ +public class PolicySetTypeImpl extends AbstractXACMLObject implements PolicySetType { + + /** Policy set description. */ + private DescriptionType description; + + /** Policy set defaults. */ + private DefaultsType policySetDefaults; + + /** Policy set target. */ + private TargetType target; + + /** Elements within the choice group. */ + private IndexedXMLObjectChildrenList choiceGroup; + + /** Policy obligations. */ + private ObligationsType obligations; + + /** ID of this policy set. */ + private String policySetId; + + /** Version of this policy set. */ + private String version; + + /** Policy combinging algorithm ID. */ + private String combiningAlgo; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected PolicySetTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + choiceGroup = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getCombinerParameters() { + return (List) choiceGroup.subList(CombinerParametersType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public DescriptionType getDescription() { + return description; + } + + /** {@inheritDoc} */ + public ObligationsType getObligations() { + return obligations; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (description != null) { + children.add(description); + } + + if (policySetDefaults != null) { + children.add(policySetDefaults); + } + + children.add(target); + + if (!choiceGroup.isEmpty()) { + children.addAll(choiceGroup); + } + + if (obligations != null) { + children.add(obligations); + } + + return children; + } + + /** {@inheritDoc} */ + public List getPolicies() { + return (List) choiceGroup.subList(PolicyType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicyCombinerParameters() { + return (List) choiceGroup + .subList(PolicyCombinerParametersType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public String getPolicyCombiningAlgoId() { + return combiningAlgo; + } + + /** {@inheritDoc} */ + public List getPolicyIdReferences() { + return (List) choiceGroup.subList(IdReferenceType.POLICY_ID_REFERENCE_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicySetCombinerParameters() { + return (List) choiceGroup + .subList(PolicySetCombinerParametersType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public DefaultsType getPolicySetDefaults() { + return policySetDefaults; + } + + /** {@inheritDoc} */ + public String getPolicySetId() { + return policySetId; + } + + /** {@inheritDoc} */ + public List getPolicySetIdReferences() { + return (List) choiceGroup.subList(IdReferenceType.POLICY_SET_ID_REFERENCE_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public List getPolicySets() { + return (List) choiceGroup.subList(PolicySetType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public TargetType getTarget() { + return target; + } + + /** {@inheritDoc} */ + public String getVersion() { + return version; + } + + /** {@inheritDoc} */ + public void setDescription(DescriptionType newDescription) { + this.description = prepareForAssignment(this.description, newDescription); + } + + /** {@inheritDoc} */ + public void setObligations(ObligationsType newObligations) { + this.obligations = prepareForAssignment(this.obligations, newObligations); + } + + /** {@inheritDoc} */ + public void setPolicyCombiningAlgoId(String id) { + combiningAlgo = prepareForAssignment(combiningAlgo, id); + } + + /** {@inheritDoc} */ + public void setPolicySetDefaults(DefaultsType defaults) { + policySetDefaults = prepareForAssignment(policySetDefaults, defaults); + } + + /** {@inheritDoc} */ + public void setPolicySetId(String id) { + policySetId = prepareForAssignment(policySetId, id); + } + + /** {@inheritDoc} */ + public void setTarget(TargetType newTarget) { + this.target = prepareForAssignment(this.target, newTarget); + } + + /** {@inheritDoc} */ + public void setVersion(String newVersion) { + this.version = prepareForAssignment(this.version, newVersion); + } + + /** {@inheritDoc} */ + public IndexedXMLObjectChildrenList getPolicyChoiceGroup() { + return (IndexedXMLObjectChildrenList) choiceGroup; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeImplBuilder.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.PolicySetType; + +/** Builder of {@link PolicySetType} objects. */ +public class PolicySetTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public PolicySetType buildObject() { + return buildObject(PolicySetType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public PolicySetType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PolicySetTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeMarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,51 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller for {@link PolicySetType} objects. */ +public class PolicySetTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public PolicySetTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + PolicySetType policySet = (PolicySetType) xmlObject; + + if (!DatatypeHelper.isEmpty(policySet.getPolicySetId())) { + domElement.setAttribute(PolicySetType.POLICY_SET_ID_ATTRIB_NAME, policySet.getPolicySetId()); + } + if (!DatatypeHelper.isEmpty(policySet.getVersion())) { + domElement.setAttribute(PolicySetType.VERSION_ATTRIB_NAME, policySet.getVersion()); + } + if (!DatatypeHelper.isEmpty(policySet.getPolicyCombiningAlgoId())) { + domElement.setAttribute(PolicySetType.POLICY_COMBINING_ALG_ID_ATTRIB_NAME, policySet + .getPolicyCombiningAlgoId()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicySetTypeUnmarshaller.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,91 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.XACMLConstants; +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.CombinerParametersType; +import org.opensaml.xacml.policy.DefaultsType; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xacml.policy.IdReferenceType; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xacml.policy.PolicyCombinerParametersType; +import org.opensaml.xacml.policy.PolicySetCombinerParametersType; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link PolicySetType} objects. */ +public class PolicySetTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public PolicySetTypeUnmarshaller() { + super(XACMLConstants.XACML20_NS, PolicySetType.DEFAULT_ELEMENT_LOCAL_NAME); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + PolicySetType policySet = (PolicySetType) xmlObject; + + if (attribute.getLocalName().equals(PolicySetType.POLICY_SET_ID_ATTRIB_NAME)) { + policySet.setPolicySetId(attribute.getValue()); + } else if (attribute.getLocalName().equals(PolicySetType.VERSION_ATTRIB_NAME)) { + policySet.setVersion(attribute.getValue()); + } else if (attribute.getLocalName().equals(PolicySetType.POLICY_COMBINING_ALG_ID_ATTRIB_NAME)) { + policySet.setPolicyCombiningAlgoId(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + PolicySetType policySet = (PolicySetType) parentXMLObject; + + if (childXMLObject instanceof DescriptionType) { + policySet.setDescription((DescriptionType) childXMLObject); + } else if (childXMLObject instanceof DefaultsType) { + policySet.setPolicySetDefaults((DefaultsType) childXMLObject); + } else if (childXMLObject instanceof TargetType){ + policySet.setTarget((TargetType) childXMLObject); + } else if (childXMLObject instanceof PolicySetType) { + policySet.getPolicySets().add((PolicySetType) childXMLObject); + } else if (childXMLObject instanceof PolicyType) { + policySet.getPolicies().add((PolicyType) childXMLObject); + } else if (childXMLObject.getElementQName().equals(IdReferenceType.POLICY_SET_ID_REFERENCE_ELEMENT_NAME)) { + policySet.getPolicySetIdReferences().add((IdReferenceType) childXMLObject); + } else if (childXMLObject.getElementQName().equals(IdReferenceType.POLICY_ID_REFERENCE_ELEMENT_NAME)) { + policySet.getPolicyIdReferences().add((IdReferenceType) childXMLObject); + } else if (childXMLObject.getElementQName().equals(CombinerParametersType.DEFAULT_ELEMENT_NAME)) { + policySet.getCombinerParameters().add((CombinerParametersType) childXMLObject); + } else if (childXMLObject.getElementQName().equals(PolicyCombinerParametersType.DEFAULT_ELEMENT_NAME)) { + policySet.getPolicyCombinerParameters().add((PolicyCombinerParametersType) childXMLObject); + } else if (childXMLObject.getElementQName().equals(PolicySetCombinerParametersType.DEFAULT_ELEMENT_NAME)) { + policySet.getPolicySetCombinerParameters().add((PolicySetCombinerParametersType) childXMLObject); + } else if (childXMLObject instanceof ObligationsType) { + policySet.setObligations((ObligationsType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeImpl.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,189 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.CombinerParametersType; +import org.opensaml.xacml.policy.DefaultsType; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.policy.RuleCombinerParametersType; +import org.opensaml.xacml.policy.RuleType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xacml.policy.VariableDefinitionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implemenation of {@link PolicyType}. */ +public class PolicyTypeImpl extends AbstractXACMLObject implements PolicyType { + + /** Policy description. */ + private DescriptionType description; + + /** Policy defaults. */ + private DefaultsType policyDefaults; + + /** Policy target. */ + private TargetType target; + + /** Elements within the choice group. */ + private IndexedXMLObjectChildrenList choiceGroup; + + /** Policy obligations. */ + private ObligationsType obligations; + + /** ID of this policy. */ + private String policyId; + + /** Version of this policy. */ + private String version; + + /** Rule combinging algorithm ID. */ + private String ruleCombiningAlgo; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected PolicyTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + choiceGroup = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getCombinerParameters() { + return (List) choiceGroup.subList(CombinerParametersType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public DescriptionType getDescription() { + return description; + } + + /** {@inheritDoc} */ + public ObligationsType getObligations() { + return obligations; + } + + /** {@inheritDoc} */ + public DefaultsType getPolicyDefaults() { + return policyDefaults; + } + + /** {@inheritDoc} */ + public String getPolicyId() { + return policyId; + } + + /** {@inheritDoc} */ + public List getRuleCombinerParameters() { + return (List) choiceGroup.subList(RuleCombinerParametersType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public String getRuleCombiningAlgoId() { + return ruleCombiningAlgo; + } + + /** {@inheritDoc} */ + public List getRules() { + return (List) choiceGroup.subList(RuleType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public TargetType getTarget() { + return target; + } + + /** {@inheritDoc} */ + public List getVariableDefinitions() { + return (List) choiceGroup.subList(VariableDefinitionType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public String getVersion() { + return version; + } + + /** {@inheritDoc} */ + public void setDescription(DescriptionType newDescription) { + this.description = prepareForAssignment(this.description, newDescription); + } + + /** {@inheritDoc} */ + public void setObligations(ObligationsType newObligations) { + this.obligations = prepareForAssignment(this.obligations, newObligations); + } + + /** {@inheritDoc} */ + public void setPolicyDefaults(DefaultsType defaults) { + policyDefaults = prepareForAssignment(policyDefaults, defaults); + } + + /** {@inheritDoc} */ + public void setPolicyId(String id) { + policyId = prepareForAssignment(policyId, id); + } + + /** {@inheritDoc} */ + public void setRuleCombiningAlgoId(String id) { + ruleCombiningAlgo = prepareForAssignment(ruleCombiningAlgo, id); + } + + /** {@inheritDoc} */ + public void setTarget(TargetType newTarget) { + this.target = prepareForAssignment(this.target, newTarget); + } + + /** {@inheritDoc} */ + public void setVersion(String newVersion) { + this.version = prepareForAssignment(this.version, newVersion); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + if (description != null) { + children.add(description); + } + + if (policyDefaults != null) { + children.add(policyDefaults); + } + + children.add(target); + + if (!choiceGroup.isEmpty()) { + children.addAll(choiceGroup); + } + + if (obligations != null) { + children.add(obligations); + } + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeImplBuilder.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.PolicyType; + +/** Builder of {@link PolicyType} objects. */ +public class PolicyTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public PolicyType buildObject() { + return buildObject(PolicyType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public PolicyType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new PolicyTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeMarshaller.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,52 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller for {@link PolicyType} objects. */ +public class PolicyTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public PolicyTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + PolicyType policy = (PolicyType) xmlObject; + + if (!DatatypeHelper.isEmpty(policy.getPolicyId())) { + domElement.setAttribute(PolicyType.POLICY_ID_ATTRIB_NAME, policy.getPolicyId()); + } + + if (!DatatypeHelper.isEmpty(policy.getVersion())) { + domElement.setAttribute(PolicyType.VERSION_ATTRIB_NAME, policy.getVersion()); + } + + if (!DatatypeHelper.isEmpty(policy.getRuleCombiningAlgoId())) { + domElement.setAttribute(PolicyType.RULE_COMBINING_ALG_ID_ATTRIB_NAME, policy.getRuleCombiningAlgoId()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/PolicyTypeUnmarshaller.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,83 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.CombinerParametersType; +import org.opensaml.xacml.policy.DefaultsType; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xacml.policy.ObligationsType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xacml.policy.RuleCombinerParametersType; +import org.opensaml.xacml.policy.RuleType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xacml.policy.VariableDefinitionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Attr; + +/** Unmarshaller for {@link PolicyType} objects. */ +public class PolicyTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public PolicyTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + PolicyType policy = (PolicyType) xmlObject; + + if (attribute.getLocalName().equals(PolicyType.POLICY_ID_ATTRIB_NAME)) { + policy.setPolicyId(attribute.getValue()); + } else if (attribute.getLocalName().equals(PolicyType.VERSION_ATTRIB_NAME)) { + policy.setVersion(attribute.getValue()); + } else if (attribute.getLocalName().equals(PolicyType.RULE_COMBINING_ALG_ID_ATTRIB_NAME)) { + policy.setRuleCombiningAlgoId(attribute.getValue()); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + PolicyType policy = (PolicyType) parentXMLObject; + + if (childXMLObject instanceof DescriptionType) { + policy.setDescription((DescriptionType) childXMLObject); + } else if (childXMLObject.getElementQName().equals(DefaultsType.POLICY_DEFAULTS_ELEMENT_NAME)) { + policy.setPolicyDefaults((DefaultsType) childXMLObject); + } else if (childXMLObject instanceof TargetType) { + policy.setTarget((TargetType) childXMLObject); + } else if (childXMLObject instanceof CombinerParametersType) { + policy.getCombinerParameters().add((CombinerParametersType) childXMLObject); + } else if (childXMLObject instanceof RuleCombinerParametersType) { + policy.getRuleCombinerParameters().add((RuleCombinerParametersType) childXMLObject); + } else if (childXMLObject instanceof VariableDefinitionType) { + policy.getVariableDefinitions().add((VariableDefinitionType) childXMLObject); + } else if (childXMLObject instanceof RuleType) { + policy.getRules().add((RuleType)childXMLObject); + } else if (childXMLObject instanceof ObligationsType) { + policy.setObligations((ObligationsType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeImpl.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,127 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.ResourceMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link ResourceMatchType}. */ +public class ResourceMatchTypeImpl extends AbstractXACMLObject implements ResourceMatchType { + + /** Match's attribute value. */ + private AttributeValueType attributeValue; + + /** Match's choice of attribute elements. */ + private IndexedXMLObjectChildrenList attributeChoice; + + /** Gets the ID of this match. */ + private String matchId; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + public ResourceMatchTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeChoice = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AttributeSelectorType getAttributeSelector() { + List selectors = (List) attributeChoice.subList(AttributeSelectorType.DEFAULT_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeSelectorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public AttributeValueType getAttributeValue() { + return attributeValue; + } + + /** {@inheritDoc} */ + public AttributeDesignatorType getResourceAttributeDesignator() { + List selectors = (List) attributeChoice + .subList(AttributeDesignatorType.RESOURCE_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeDesignatorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public String getMatchId() { + return matchId; + } + + /** {@inheritDoc} */ + public void setAttributeSelector(AttributeSelectorType selector) { + AttributeSelectorType currentSelector = getAttributeSelector(); + if (currentSelector != null) { + attributeChoice.remove(currentSelector); + } + + attributeChoice.add(selector); + } + + /** {@inheritDoc} */ + public void setAttributeValue(AttributeValueType value) { + attributeValue = prepareForAssignment(attributeValue, value); + } + + /** {@inheritDoc} */ + public void setResourceAttributeDesignator(AttributeDesignatorType attribute) { + AttributeDesignatorType currentDesignator = getResourceAttributeDesignator(); + if (currentDesignator != null) { + attributeChoice.remove(currentDesignator); + } + + attributeChoice.add(attribute); + } + + /** {@inheritDoc} */ + public void setMatchId(String id) { + matchId = prepareForAssignment(matchId, id); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.add(attributeValue); + if (!attributeChoice.isEmpty()) { + children.addAll(attributeChoice); + } + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeImplBuilder.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ResourceMatchType; + +/** Builder of {@link ResourceMatchType} objects. */ +public class ResourceMatchTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ResourceMatchType buildObject() { + return buildObject(ResourceMatchType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ResourceMatchType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResourceMatchTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ResourceMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller of {@link ResourceMatchType} objects. */ +public class ResourceMatchTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ResourceMatchTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + ResourceMatchType matchType = (ResourceMatchType) xmlObject; + + if (!DatatypeHelper.isEmpty(matchType.getMatchId())) { + domElement.setAttribute(ResourceMatchType.MATCH_ID_ATTRIB_NAME, matchType.getMatchId()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceMatchTypeUnmarshaller.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.ResourceMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** Unmarshaller of {@link ResourceMatchType} objects. */ +public class ResourceMatchTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ResourceMatchTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(ResourceMatchType.MATCH_ID_ATTRIB_NAME)) { + ResourceMatchType matchType = (ResourceMatchType) xmlObject; + matchType.setMatchId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ResourceMatchType matchType = (ResourceMatchType) parentXMLObject; + + if (childXMLObject instanceof AttributeValueType) { + matchType.setAttributeValue((AttributeValueType) childXMLObject); + } else if (childXMLObject instanceof AttributeSelectorType) { + matchType.setAttributeSelector((AttributeSelectorType) childXMLObject); + } else if (childXMLObject.getElementQName().equals( + AttributeDesignatorType.RESOURCE_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME)) { + matchType.setResourceAttributeDesignator((AttributeDesignatorType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeImpl.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ResourceMatchType; +import org.opensaml.xacml.policy.ResourceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + *Implementation of {@link ResourceType}. + */ +public class ResourceTypeImpl extends AbstractXACMLObject implements ResourceType { + + + /**List of resource matches.*/ + private XMLObjectChildrenList resourceMatch; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected ResourceTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + resourceMatch = new XMLObjectChildrenList(this); + } + /** {@inheritDoc} */ + public List getResourceMatches() { + return resourceMatch; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + children.addAll(resourceMatch); + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeImplBuilder.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ResourceType; + +/** + * Builder for {@link ResourceType}. + */ +public class ResourceTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ResourceType buildObject() { + return buildObject(ResourceType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ResourceType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResourceTypeImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeMarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ResourceType; + +/** + * Marshaller for {@link ResourceType}. + */ +public class ResourceTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ResourceTypeMarshaller() { + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourceTypeUnmarshaller.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ResourceMatchType; +import org.opensaml.xacml.policy.ResourceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link ResourceType}. + */ +public class ResourceTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ResourceTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ResourceType resourceType = (ResourceType) parentXMLObject; + + if(childXMLObject instanceof ResourceMatchType){ + resourceType.getResourceMatches().add((ResourceMatchType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeImpl.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ResourceType; +import org.opensaml.xacml.policy.ResourcesType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link ResourcesType}. + */ +public class ResourcesTypeImpl extends AbstractXACMLObject implements ResourcesType { + + /**List of resource matches.*/ + private XMLObjectChildrenList resource; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + public ResourcesTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + + resource = new XMLObjectChildrenList(this); + } + /** {@inheritDoc} */ + public List getResources() { + return resource; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + children.addAll(resource); + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeImplBuilder.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.ResourcesType; + +/** + * Builder for {@link ResourcesType}. + */ +public class ResourcesTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public ResourcesType buildObject() { + return buildObject(ResourcesType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public ResourcesType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new ResourcesTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeMarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.ResourcesType; + +/** + * Marshaller for {@link ResourcesType}. + */ +public class ResourcesTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public ResourcesTypeMarshaller() { + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/ResourcesTypeUnmarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ResourceType; +import org.opensaml.xacml.policy.ResourcesType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link ResourcesType}. + */ +public class ResourcesTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public ResourcesTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + ResourcesType resourcesType = (ResourcesType) parentXMLObject; + + if (childXMLObject instanceof ResourceType){ + resourcesType.getResources().add((ResourceType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeImpl.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,75 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation for {@link RuleCombinerParametersTypeImplBuilder}. + */ +public class RuleCombinerParametersTypeImpl extends AbstractXACMLObject implements + org.opensaml.xacml.policy.RuleCombinerParametersType { + + /**Rule indentity reference.*/ + private String ruleIdRef; + /**List or the combiner parameters.*/ + private XMLObjectChildrenList combinerParameters; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RuleCombinerParametersTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + combinerParameters = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public String getRuleIdRef() { + return ruleIdRef; + } + + /** {@inheritDoc} */ + public void setRuleIdRef(String ref) { + this.ruleIdRef = prepareForAssignment(this.ruleIdRef, ref); + } + + /** {@inheritDoc} */ + public List getCombinerParameters() { + return combinerParameters; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + children.addAll(combinerParameters); + + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeImplBuilder.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.RuleCombinerParametersType; + +/** + * Builder for {@link RuleCombinerParametersType}. + */ +public class RuleCombinerParametersTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public RuleCombinerParametersType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RuleCombinerParametersTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public RuleCombinerParametersType buildObject() { + return buildObject(RuleCombinerParametersType.DEFAULT_ELEMENT_NAME); + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeMarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.RuleCombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link RuleCombinerParametersType}. + */ +public class RuleCombinerParametersTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public RuleCombinerParametersTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + RuleCombinerParametersType ruleCombinerParametersType = (RuleCombinerParametersType)xmlObject; + + if(!DatatypeHelper.isEmpty(ruleCombinerParametersType.getRuleIdRef())){ + domElement.setAttribute(RuleCombinerParametersType.RULE_ID_REF_ATTRIB_NAME, + ruleCombinerParametersType.getRuleIdRef()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleCombinerParametersTypeUnmarshaller.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,62 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.CombinerParameterType; +import org.opensaml.xacml.policy.RuleCombinerParametersType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link RuleCombinerParametersType}. + */ +public class RuleCombinerParametersTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public RuleCombinerParametersTypeUnmarshaller() { + super(); + } + + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + if(attribute.getLocalName().equals(RuleCombinerParametersType.RULE_ID_REF_ATTRIB_NAME)){ + RuleCombinerParametersType ruleCombinerParametersType = (RuleCombinerParametersType)xmlObject; + ruleCombinerParametersType.setRuleIdRef(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RuleCombinerParametersType ruleCombinerParametersType = (RuleCombinerParametersType) parentXMLObject; + + if(childXMLObject instanceof CombinerParameterType){ + ruleCombinerParametersType.getCombinerParameters().add((CombinerParameterType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeImpl.java 17 Aug 2012 15:04:34 -0000 1.1 @@ -0,0 +1,129 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ConditionType; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xacml.policy.EffectType; +import org.opensaml.xacml.policy.RuleType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xml.XMLObject; + +/** + *Implementation for {@link RuleType}. + */ +public class RuleTypeImpl extends AbstractXACMLObject implements RuleType { + + /** Condition of the policy.*/ + private ConditionType condition; + + /** The rule target.*/ + private TargetType target; + + /**Dscription of the rule.*/ + private DescriptionType description; + + /**Effect type of the rule.*/ + private EffectType effectType; + + /**The id of the rule.*/ + private String ruleId; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected RuleTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + } + + /** {@inheritDoc} */ + public ConditionType getCondition() { + return condition; + } + + /** {@inheritDoc} */ + public DescriptionType getDescription() { + return description; + } + + /** {@inheritDoc} */ + public EffectType getEffect() { + return effectType; + } + + /** {@inheritDoc} */ + public String getRuleId() { + return ruleId; + } + + /** {@inheritDoc} */ + public TargetType getTarget() { + return target; + } + + /** {@inheritDoc} */ + public void setCondition(ConditionType newCondition) { + this.condition = prepareForAssignment(this.condition,newCondition); + } + + /** {@inheritDoc} */ + public void setDescription(DescriptionType newDescription) { + this.description = prepareForAssignment(this.description,newDescription); + } + + /** {@inheritDoc} */ + public void setEffect(EffectType type) { + this.effectType = prepareForAssignment(this.effectType,type); + } + + /** {@inheritDoc} */ + public void setRuleId(String id) { + this.ruleId = prepareForAssignment(this.ruleId,id); + } + + /** {@inheritDoc} */ + public void setTarget(TargetType newTarget) { + this.target = prepareForAssignment(this.target,newTarget); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + if(description != null){ + children.add(description); + } + if(target != null){ + children.add(target); + } + if(condition != null){ + children.add(condition); + } + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeImplBuilder.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.RuleType; + +/** + * Builder for {@link RuleType}. + */ +public class RuleTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public RuleType buildObject() { + return buildObject(RuleType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public RuleType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new RuleTypeImpl(namespaceURI,localName,namespacePrefix); + } + + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeMarshaller.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,56 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.EffectType; +import org.opensaml.xacml.policy.RuleType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link RuleType}. + */ +public class RuleTypeMarshaller extends AbstractXACMLObjectMarshaller { + + + /** Constructor. */ + public RuleTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + RuleType ruleType = (RuleType) xmlObject; + + if (!DatatypeHelper.isEmpty(ruleType.getRuleId())) { + domElement.setAttribute(RuleType.RULE_ID_ATTRIB_NAME, ruleType.getRuleId()); + } + + if(!DatatypeHelper.isEmpty(ruleType.getEffect().toString())){ + if(ruleType.getEffect().equals(EffectType.Deny)){ + domElement.setAttribute(RuleType.EFFECT_ATTRIB_NAME,EffectType.Deny.toString()); + }else{ + domElement.setAttribute(RuleType.EFFECT_ATTRIB_NAME,EffectType.Permit.toString()); + } + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/RuleTypeUnmarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,73 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ConditionType; +import org.opensaml.xacml.policy.DescriptionType; +import org.opensaml.xacml.policy.EffectType; +import org.opensaml.xacml.policy.RuleType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link RuleType}. + */ +public class RuleTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public RuleTypeUnmarshaller() { + super(); + } + + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + RuleType ruleType = (RuleType) xmlObject; + + if(attribute.getLocalName().equals(RuleType.EFFECT_ATTRIB_NAME)){ + ruleType.setEffect(EffectType.valueOf( + DatatypeHelper.safeTrimOrNullString(attribute.getValue()))); + } else if(attribute.getLocalName().equals(RuleType.RULE_ID_ATTRIB_NAME)){ + ruleType.setRuleId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + RuleType ruleType = (RuleType) parentXMLObject; + + if(childXMLObject instanceof TargetType){ + ruleType.setTarget((TargetType)childXMLObject); + } else if(childXMLObject instanceof DescriptionType){ + ruleType.setDescription((DescriptionType)childXMLObject); + }else if(childXMLObject instanceof ConditionType){ + ruleType.setCondition((ConditionType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeImpl.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,64 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.List; + +import org.opensaml.xacml.policy.SubjectAttributeDesignatorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.LazyList; + +/** + * Implementation of {@link SubjectAttributeDesignatorType}. + */ +public class SubjectAttributeDesignatorTypeImpl extends AttributeDesignatorTypeImpl + implements SubjectAttributeDesignatorType { + + /** Subject category. */ + private String subjectCategory; + + /** + * Constructor. + * + * @param namespaceURI + * the namespace the element is in + * @param elementLocalName + * the local name of the XML element this Object represents + * @param namespacePrefix + * the prefix for the given namespace + */ + protected SubjectAttributeDesignatorTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + /** {@inheritDoc} */ + public String getSubjectCategory() { + return subjectCategory; + } + + /** {@inheritDoc} */ + public void setSubjectCategory(String category) { + this.subjectCategory = prepareForAssignment(this.subjectCategory, category); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + return new LazyList(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeImplBuilder.java 17 Aug 2012 15:04:33 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.SubjectAttributeDesignatorType; + +/** + * Bilder for {@link SubjectAttributeDesignatorType}. + */ +public class SubjectAttributeDesignatorTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public SubjectAttributeDesignatorType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectAttributeDesignatorTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public SubjectAttributeDesignatorType buildObject() { + return buildObject(SubjectAttributeDesignatorType.DEFAULT_ELEMENT_QNAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeMarshaller.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.SubjectAttributeDesignatorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link SubjectAttributeDesignatorType}. + */ +public class SubjectAttributeDesignatorTypeMarshaller extends AttributeDesignatorTypeMarshaller { + + /** Constructor. */ + public SubjectAttributeDesignatorTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + SubjectAttributeDesignatorType subjectAttributeDesignatorType = (SubjectAttributeDesignatorType) xmlObject; + + if(!DatatypeHelper.isEmpty(subjectAttributeDesignatorType.getSubjectCategory())){ + domElement.setAttribute(SubjectAttributeDesignatorType.SUBJECT_CATEGORY_ATTRIB_NAME, + subjectAttributeDesignatorType.getSubjectCategory()); + } + super.marshallAttributes(xmlObject, domElement); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectAttributeDesignatorTypeUnmarshaller.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,46 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.policy.SubjectAttributeDesignatorType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; +/** + * Unmarshaller for {@link SubjectAttributeDesignatorType}. + */ +public class SubjectAttributeDesignatorTypeUnmarshaller extends AttributeValueTypeUnmarshaller { + + /** Constructor. */ + public SubjectAttributeDesignatorTypeUnmarshaller() { + super(); + } + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + if(attribute.getLocalName().equals(SubjectAttributeDesignatorType.SUBJECT_CATEGORY_ATTRIB_NAME)){ + SubjectAttributeDesignatorType subjectAttributeDesignatorType = (SubjectAttributeDesignatorType) xmlObject; + subjectAttributeDesignatorType.setSubjectCategory(DatatypeHelper. + safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeImpl.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,128 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.SubjectMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +/** Concrete implementation of {@link SubjectMatchType}. */ +public class SubjectMatchTypeImpl extends AbstractXACMLObject implements SubjectMatchType { + + /** Match's attribute value. */ + private AttributeValueType attributeValue; + + /** Match's choice of attribute elements. */ + private IndexedXMLObjectChildrenList attributeChoice; + + /** Gets the ID of this match. */ + private String matchId; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + public SubjectMatchTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + attributeChoice = new IndexedXMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public AttributeSelectorType getAttributeSelector() { + List selectors = (List) attributeChoice + .subList(AttributeSelectorType.DEFAULT_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeSelectorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public AttributeValueType getAttributeValue() { + return attributeValue; + } + + /** {@inheritDoc} */ + public AttributeDesignatorType getSubjectAttributeDesignator() { + List selectors = (List) attributeChoice + .subList(AttributeDesignatorType.SUBJECT_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME); + if (selectors != null && !selectors.isEmpty()) { + return (AttributeDesignatorType) selectors.get(0); + } + + return null; + } + + /** {@inheritDoc} */ + public String getMatchId() { + return matchId; + } + + /** {@inheritDoc} */ + public void setAttributeSelector(AttributeSelectorType selector) { + AttributeSelectorType currentSelector = getAttributeSelector(); + if (currentSelector != null) { + attributeChoice.remove(currentSelector); + } + + attributeChoice.add(selector); + } + + /** {@inheritDoc} */ + public void setAttributeValue(AttributeValueType value) { + attributeValue = prepareForAssignment(attributeValue, value); + } + + /** {@inheritDoc} */ + public void setSubjectAttributeDesignator(AttributeDesignatorType attribute) { + AttributeDesignatorType currentDesignator = getSubjectAttributeDesignator(); + if (currentDesignator != null) { + attributeChoice.remove(currentDesignator); + } + + attributeChoice.add(attribute); + } + + /** {@inheritDoc} */ + public void setMatchId(String id) { + matchId = prepareForAssignment(matchId, id); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + children.add(attributeValue); + if (!attributeChoice.isEmpty()) { + children.addAll(attributeChoice); + } + + return children; + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeImplBuilder.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,35 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.SubjectMatchType; + +/** Builder of {@link SubjectMatchType} objects. */ +public class SubjectMatchTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public SubjectMatchType buildObject() { + return buildObject(SubjectMatchType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SubjectMatchType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectMatchTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeMarshaller.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,44 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.SubjectMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** Marshaller of {@link SubjectMatchType} objects. */ +public class SubjectMatchTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public SubjectMatchTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + SubjectMatchType matchType = (SubjectMatchType) xmlObject; + + if (!DatatypeHelper.isEmpty(matchType.getMatchId())) { + domElement.setAttribute(SubjectMatchType.MATCH_ID_ATTRIB_NAME, matchType.getMatchId()); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectMatchTypeUnmarshaller.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,65 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.AttributeDesignatorType; +import org.opensaml.xacml.policy.AttributeSelectorType; +import org.opensaml.xacml.policy.AttributeValueType; +import org.opensaml.xacml.policy.SubjectMatchType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** Unmarshaller of {@link SubjectMatchType} objects. */ +public class SubjectMatchTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public SubjectMatchTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + if (attribute.getLocalName().equals(SubjectMatchType.MATCH_ID_ATTRIB_NAME)) { + SubjectMatchType matchType = (SubjectMatchType) xmlObject; + matchType.setMatchId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + SubjectMatchType matchType = (SubjectMatchType) parentXMLObject; + + if (childXMLObject instanceof AttributeValueType) { + matchType.setAttributeValue((AttributeValueType) childXMLObject); + } else if (childXMLObject.getElementQName().equals( + AttributeDesignatorType.SUBJECT_ATTRIBUTE_DESIGNATOR_ELEMENT_NAME)) { + matchType.setSubjectAttributeDesignator((AttributeDesignatorType) childXMLObject); + } else if (childXMLObject instanceof AttributeSelectorType) { + matchType.setAttributeSelector((AttributeSelectorType) childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeImpl.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.SubjectMatchType; +import org.opensaml.xacml.policy.SubjectType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + *Implementation of {@link SubjectType}. + */ +public class SubjectTypeImpl extends AbstractXACMLObject implements SubjectType { + + /**List of subject matches.*/ + private XMLObjectChildrenList subjectMatch; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + subjectMatch = new XMLObjectChildrenList(this); + } + /** {@inheritDoc} */ + public List getSubjectMatches() { + return subjectMatch; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + children.addAll(subjectMatch); + + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeImplBuilder.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.SubjectType; + +/** + * Builder for {@link SubjectType}. + */ +public class SubjectTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public SubjectType buildObject() { + return buildObject(SubjectType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SubjectType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectTypeImpl(namespaceURI, localName, namespacePrefix); + } +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeMarshaller.java 17 Aug 2012 15:04:31 -0000 1.1 @@ -0,0 +1,34 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.SubjectType; + +/** + *Marshaller for {@link SubjectType}. + */ +public class SubjectTypeMarshaller extends AbstractXACMLObjectMarshaller { + + + /**Constructor.*/ + public SubjectTypeMarshaller(){ + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectTypeUnmarshaller.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,48 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.SubjectMatchType; +import org.opensaml.xacml.policy.SubjectType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshaller for {@link SubjectType}. + */ +public class SubjectTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public SubjectTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + SubjectType subjectType = (SubjectType) parentXMLObject; + + if(childXMLObject instanceof SubjectMatchType){ + subjectType.getSubjectMatches().add((SubjectMatchType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeImpl.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.SubjectType; +import org.opensaml.xacml.policy.SubjectsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link SubjectsType}. + */ +public class SubjectsTypeImpl extends AbstractXACMLObject implements SubjectsType { + + /**List of action types.*/ + private XMLObjectChildrenList subject; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected SubjectsTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + subject = new XMLObjectChildrenList(this); + } + /** {@inheritDoc} */ + public List getSubjects() { + return subject; + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + + ArrayList children = new ArrayList(); + + children.addAll(subject); + + return children; + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeImplBuilder.java 17 Aug 2012 15:04:28 -0000 1.1 @@ -0,0 +1,39 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.SubjectsType; + +/** + *Builder for {@link SubjectsType}. + */ +public class SubjectsTypeImplBuilder extends AbstractXACMLObjectBuilder { + + + /** {@inheritDoc} */ + public SubjectsType buildObject() { + return buildObject(SubjectsType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc} */ + public SubjectsType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new SubjectsTypeImpl(namespaceURI, localName, namespacePrefix); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeMarshaller.java 17 Aug 2012 15:04:36 -0000 1.1 @@ -0,0 +1,33 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.SubjectsType; + +/** + * Marshaller for {@link SubjectsType}. + */ +public class SubjectsTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public SubjectsTypeMarshaller() { + super(); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/SubjectsTypeUnmarshaller.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.SubjectType; +import org.opensaml.xacml.policy.SubjectsType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * Unmarshalle for {@link SubjectsType}. + */ +public class SubjectsTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + + /** Constructor. */ + public SubjectsTypeUnmarshaller() { + super(); + } + + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + SubjectsType subjectsType = (SubjectsType) parentXMLObject; + + if(childXMLObject instanceof SubjectType){ + subjectsType.getSubjects().add((SubjectType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeImpl.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,119 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ActionsType; +import org.opensaml.xacml.policy.EnvironmentsType; +import org.opensaml.xacml.policy.ResourcesType; +import org.opensaml.xacml.policy.SubjectsType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xml.XMLObject; + +/** + * Implementing {@link org.opensaml.xacml.policy.TargetType}. + */ +public class TargetTypeImpl extends AbstractXACMLObject implements TargetType { + + /** The actions in the policy. */ + private ActionsType actions; + + /** The environments in the policy. */ + private EnvironmentsType environments; + + /** The subjects in the policy. */ + private SubjectsType subjects; + + /** The resourcese in the policy. */ + private ResourcesType resources; + + /** + * Constructor. + * + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected TargetTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { + super(namespaceURI, elementLocalName, namespacePrefix); + } + + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(subjects != null){ + children.add(subjects); + } + if(actions != null){ + children.add(actions); + } + if(resources != null){ + children.add(resources); + } + if(environments != null){ + children.add(environments); + } + return Collections.unmodifiableList(children); + } + + /** {@inheritDoc}*/ + public SubjectsType getSubjects() { + return subjects; + } + + /** {@inheritDoc}*/ + public ResourcesType getResources() { + return resources; + } + + /** {@inheritDoc}*/ + public ActionsType getActions() { + return actions; + } + + /**{@inheritDoc}*/ + public EnvironmentsType getEnvironments() { + return environments; + } + + /**{@inheritDoc}*/ + public void setActions(ActionsType newActions) { + this.actions = prepareForAssignment(this.actions,newActions); + } + + /**{@inheritDoc}*/ + public void setEnvironments(EnvironmentsType newEnvironments) { + this.environments = prepareForAssignment(this.environments,newEnvironments); + } + + /**{@inheritDoc}*/ + public void setResources(ResourcesType newResources) { + this.resources = prepareForAssignment(this.resources,newResources); + } + + /**{@inheritDoc}*/ + public void setSubjects(SubjectsType newSubjects) { + this.subjects = prepareForAssignment(this.subjects,newSubjects); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeImplBuilder.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,37 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.TargetType; +/** + * Implementation for {@link TargetType}. + * + */ +public class TargetTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc}**/ + public TargetType buildObject() { + return buildObject(TargetType.DEFAULT_ELEMENT_NAME); + } + + /** {@inheritDoc}**/ + public TargetType buildObject(String namespaceURI, String localName,String namespacePrefix) { + return new TargetTypeImpl(namespaceURI, localName, namespacePrefix); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeMarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,27 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; + +/** + * A marshaller for the {@link org.opensaml.xacml.policy.TargetType}. + */ +public class TargetTypeMarshaller extends AbstractXACMLObjectMarshaller { + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/TargetTypeUnmarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,58 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ActionsType; +import org.opensaml.xacml.policy.EnvironmentsType; +import org.opensaml.xacml.policy.ResourcesType; +import org.opensaml.xacml.policy.SubjectsType; +import org.opensaml.xacml.policy.TargetType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +/** + * A unmarshaller for {@link TargetType}. + */ +public class TargetTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public TargetTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + TargetType targetType = (TargetType) parentXMLObject; + + if(childXMLObject.getElementQName().equals(ActionsType.DEFAULT_ELEMENT_NAME)){ + targetType.setActions((ActionsType)childXMLObject); + } else if(childXMLObject.getElementQName().equals(EnvironmentsType.DEFAULT_ELEMENT_NAME)){ + targetType.setEnvironments((EnvironmentsType)childXMLObject); + } else if(childXMLObject.getElementQName().equals(ResourcesType.DEFAULT_ELEMENT_NAME)){ + targetType.setResources((ResourcesType)childXMLObject); + } else if(childXMLObject.getElementQName().equals(SubjectsType.DEFAULT_ELEMENT_NAME)){ + targetType.setSubjects((SubjectsType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeImpl.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,76 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ExpressionType; +import org.opensaml.xacml.policy.VariableDefinitionType; +import org.opensaml.xml.XMLObject; + +/** + * Implementation {@link VariableDefinitionType}. + */ +public class VariableDefinitionTypeImpl extends AbstractXACMLObject implements VariableDefinitionType { + + /**Expression.*/ + private ExpressionType expression; + + /**Variable id.*/ + private String variableId; + + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected VariableDefinitionTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + } + + /** {@inheritDoc} */ + public ExpressionType getExpression() { + return expression; + } + + /** {@inheritDoc} */ + public String getVariableId() { + return variableId; + } + + /** {@inheritDoc} */ + public void setVariableId(String id) { + this.variableId = prepareForAssignment(this.variableId,id); + + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(expression != null){ + children.add(expression); + } + return Collections.unmodifiableList(children); + } +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeImplBuilder.java 17 Aug 2012 15:04:27 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.VariableDefinitionType; + +/** + * Builder for {@link VariableDefinitionType}. + */ +public class VariableDefinitionTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public VariableDefinitionType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new VariableDefinitionTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public VariableDefinitionType buildObject() { + return buildObject(VariableDefinitionType.DEFAULT_ELEMENT_NAME); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeMarshaller.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.VariableDefinitionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link VariableDefinitionType}. + */ +public class VariableDefinitionTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public VariableDefinitionTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + VariableDefinitionType variableDefinitionType = (VariableDefinitionType) xmlObject; + + if(!DatatypeHelper.isEmpty(variableDefinitionType.getVariableId())){ + domElement.setAttribute(VariableDefinitionType.VARIABLE_ID_ATTRIB_NAME, + variableDefinitionType.getVariableId()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableDefinitionTypeUnmarshaller.java 17 Aug 2012 15:04:30 -0000 1.1 @@ -0,0 +1,50 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.VariableDefinitionType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link VariableDefinitionType}. + */ +public class VariableDefinitionTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + + /** Constructor. */ + public VariableDefinitionTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + if(attribute.getLocalName().equals(VariableDefinitionType.VARIABLE_ID_ATTRIB_NAME)){ + VariableDefinitionType variableDefinitionType = (VariableDefinitionType) xmlObject; + variableDefinitionType.setVariableId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeImpl.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeImpl.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeImpl.java 17 Aug 2012 15:04:32 -0000 1.1 @@ -0,0 +1,77 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.opensaml.xacml.impl.AbstractXACMLObject; +import org.opensaml.xacml.policy.ExpressionType; +import org.opensaml.xacml.policy.VariableReferenceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.XMLObjectChildrenList; + +/** + * Implementation of {@link VariableReferenceType}. + */ +public class VariableReferenceTypeImpl extends AbstractXACMLObject implements VariableReferenceType { + + /**List or expressions.*/ + private XMLObjectChildrenList expressions; + + /**Variable id.*/ + private String valiableId; + + /** + * Constructor. + * @param namespaceURI the namespace the element is in + * @param elementLocalName the local name of the XML element this Object represents + * @param namespacePrefix the prefix for the given namespace + */ + protected VariableReferenceTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix){ + super(namespaceURI,elementLocalName,namespacePrefix); + expressions = new XMLObjectChildrenList(this); + } + + /** {@inheritDoc} */ + public List getExpressions() { + return expressions; + } + + /** {@inheritDoc} */ + public String getVariableId() { + return valiableId; + } + + /** {@inheritDoc} */ + public void setVariableId(String id) { + this.valiableId = prepareForAssignment(this.valiableId,id); + } + + /** {@inheritDoc} */ + public List getOrderedChildren() { + ArrayList children = new ArrayList(); + + if(!expressions.isEmpty()){ + children.addAll(expressions); + } + return Collections.unmodifiableList(children); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeImplBuilder.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeImplBuilder.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeImplBuilder.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,38 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectBuilder; +import org.opensaml.xacml.policy.VariableReferenceType; + +/** + * Builder for {@link VariableReferenceType}. + */ +public class VariableReferenceTypeImplBuilder extends AbstractXACMLObjectBuilder { + + /** {@inheritDoc} */ + public VariableReferenceType buildObject(String namespaceURI, String localName, String namespacePrefix) { + return new VariableReferenceTypeImpl(namespaceURI,localName,namespacePrefix); + } + + /** {@inheritDoc} */ + public VariableReferenceType buildObject() { + return buildObject(VariableReferenceType.DEFAULT_ELEMENT_NAME_XACML20); + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeMarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeMarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeMarshaller.java 17 Aug 2012 15:04:35 -0000 1.1 @@ -0,0 +1,47 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectMarshaller; +import org.opensaml.xacml.policy.VariableReferenceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Element; + +/** + * Marshaller for {@link VariableReferenceType}. + */ +public class VariableReferenceTypeMarshaller extends AbstractXACMLObjectMarshaller { + + /** Constructor. */ + public VariableReferenceTypeMarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException { + VariableReferenceType variableReferenceType = (VariableReferenceType) xmlObject; + + if(!DatatypeHelper.isEmpty(variableReferenceType.getVariableId())){ + domElement.setAttribute(VariableReferenceType.VARIABLE_ID_ATTRIB_NAME, + variableReferenceType.getVariableId()); + } + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeUnmarshaller.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeUnmarshaller.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/policy/impl/VariableReferenceTypeUnmarshaller.java 17 Aug 2012 15:04:29 -0000 1.1 @@ -0,0 +1,63 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.policy.impl; + +import org.opensaml.xacml.impl.AbstractXACMLObjectUnmarshaller; +import org.opensaml.xacml.policy.ExpressionType; +import org.opensaml.xacml.policy.VariableReferenceType; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.DatatypeHelper; +import org.w3c.dom.Attr; + +/** + * Unmarshaller for {@link VariableReferenceType}. + */ +public class VariableReferenceTypeUnmarshaller extends AbstractXACMLObjectUnmarshaller { + + /** Constructor. */ + public VariableReferenceTypeUnmarshaller() { + super(); + } + + /** {@inheritDoc} */ + protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { + + if(attribute.getLocalName().equals(VariableReferenceType.VARIABLE_ID_ATTRIB_NAME)){ + VariableReferenceType variableReferenceType = (VariableReferenceType) xmlObject; + variableReferenceType.setVariableId(DatatypeHelper.safeTrimOrNullString(attribute.getValue())); + } else { + super.processAttribute(xmlObject, attribute); + } + + } + + /** {@inheritDoc} */ + protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) + throws UnmarshallingException { + + if(childXMLObject instanceof ExpressionType){ + VariableReferenceType variableReferenceType = (VariableReferenceType) parentXMLObject; + variableReferenceType.getExpressions().add((ExpressionType)childXMLObject); + } else { + super.processChildElement(parentXMLObject, childXMLObject); + } + + } + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/ReferencedPoliciesType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/ReferencedPoliciesType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/ReferencedPoliciesType.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,85 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; + +/** + * /** A SAML XACML profile ReferencedPoliciesType schema type. + */ +public interface ReferencedPoliciesType extends SAMLObject, XACMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "ReferencedPolicies"; + + /** Default element name for XACML 1.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 1.1. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 2.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 3.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "ReferencedPoliciesType"; + + /** QName of the XSI type.XACML1.0. */ + public static final QName TYPE_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML1.1. */ + public static final QName TYPE_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML2.0. */ + public static final QName TYPE_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML3.0 . */ + public static final QName TYPE_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** + * Gets the policieSets in this element. + * + * @return the policieSets in this element + */ + public List getPolicySets(); + + /** + * Gets the policies in this element. + * + * @return the policies in this element + */ + public List getPolicies(); +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/SAMLProfileConstants.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/SAMLProfileConstants.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/SAMLProfileConstants.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,61 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml; + +import javax.xml.namespace.QName; + +import org.opensaml.xacml.XACMLConstants; + +/** Defines the constants for this XACML SAML2.0 profile. */ +public class SAMLProfileConstants extends XACMLConstants { + + /** The prefix for the use of saml-xacml assertion. */ + public static final String SAML20XACMLASSERTION_PREFIX = "xacml-saml"; + + /** The prefix for the use of saml20-xacml protocol. */ + public static final String SAML20XACMLPROTOCOL_PREFIX = "xacml-samlp"; + + /** The namespaces for use of XACML 1.0 SAML 2.0 protocol. */ + public static final String SAML20XACML10P_NS = "urn:oasis:names:tc:xacml:1.0:profile:saml2.0:v2:schema:protocol"; + + /** The namespaces for use of XACML 1.0 SAML 2.0 assertion. */ + public static final String SAML20XACML10_NS = "urn:oasis:names:tc:xacml:1.0:profile:saml2.0:v2:schema:assertion"; + + /** The namespace for use of XACML 1.1 SAML 2.0 protocol. */ + public static final String SAML20XACML1_1P_NS = "urn:oasis:names:tc:xacml:1.1:profile:saml2.0:v2:schema:protocol"; + + /** The namespace for use of XACML 1.1 SAML 2.0 assertion. */ + public static final String SAML20XACML1_1_NS = "urn:oasis:names:tc:xacml:1.1:profile:saml2.0:v2:schema:assertion"; + + /** The namespaces for use of XACML 2.0 SAML 2.0 protocol. */ + public static final String SAML20XACML20P_NS = "urn:oasis:names:tc:xacml:2.0:profile:saml2.0:v2:schema:protocol"; + + /** The namespaces for use of XACML 2.0 SAML 2.0 assertion. */ + public static final String SAML20XACML20_NS = "urn:oasis:names:tc:xacml:2.0:profile:saml2.0:v2:schema:assertion"; + + /** The namespaces for use of XACML 3.0 SAML 2.0 protocol. */ + public static final String SAML20XACML30P_NS = "urn:oasis:names:tc:xacml:3.0:profile:saml2.0:v2:schema:protocol"; + + /** The namespaces for use of XACML 3.0 SAML 2.0 assertion. */ + public static final String SAML20XACML30_NS = "urn:oasis:names:tc:xacml:3.0:profile:saml2.0:v2:schema:assertion"; + + /** QName of the DataType attribute that must be on SAML attributes that meet the XACML attribute profile spec. */ + public static final QName SAML_DATATYPE_ATTRIB = new QName( + "urn:oasis:names:tc:SAML:2.0:profiles:attribute:XACML", "DataType", "xacmlprof"); + +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLAuthzDecisionQueryType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLAuthzDecisionQueryType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLAuthzDecisionQueryType.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,207 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; +import org.opensaml.xml.schema.XSBooleanValue; + +/** A SAML XACML profile XACMLAuthzDecisionQuery schema type. */ +public interface XACMLAuthzDecisionQueryType extends RequestAbstractType, XACMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "XACMLAuthzDecisionQuery"; + + /** Default element name for XACML 1.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Default element name for XACML 1.1. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Default element name for XACML 2.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Default element name for XACML 3.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "XACMLAuthzDecisionQueryType"; + + /** QName of the XSI type.XACML1.0. */ + public static final QName TYPE_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** QName of the XSI type.XACML1.1. */ + public static final QName TYPE_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** QName of the XSI type.XACML2.0. */ + public static final QName TYPE_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** QName of the XSI type.XACML3.0. */ + public static final QName TYPE_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** InputContextOnly attribute name. */ + public static final String INPUTCONTEXTONLY_ATTRIB_NAME = "InputContextOnly"; + + /** ReturnContext attribute name. */ + public static final String RETURNCONTEXT_ATTRIB_NAME = "ReturnContext"; + + /** CombinePolicies attribute name. */ + public static final String COMBINEPOLICIES_ATTRIB_NAME = "CombinePolicies"; + + /** + * Returns if the PDP can combine policies from the query and local policies. + * + * @return XSBooleanValue true if the PDP can combine policies from the query and locally + */ + public XSBooleanValue getCombinePoliciesXSBooleanValue(); + + /** + * True then use only information in the XACMLAuthzDecisionQuery, if false could use external XACML attributes. + * + * @return if the use of just attributes in the XACMLAuthzDecisionQuery is allowed + */ + public XSBooleanValue getInputContextOnlyXSBooleanValue(); + + /** + * Gets the policies to be used while rendering a decision. + * + * @return policies to be used while rendering a decision + */ + public List getPolicies(); + + /** + * Gets the policy sets to be used while rendering a decision. + * + * @return policy sets to be used while rendering a decision + */ + public List getPolicySets(); + + /** + * Gets the reference to the policies to be used while rendering a decision. + * + * @return references to the policies to be used while rendering a decision + */ + public ReferencedPoliciesType getReferencedPolicies(); + + /** + * Sets the reference to the policies to be used while rendering a decision. + * + * @param policies reference to the policies to be used while rendering a decision + */ + public void setReferencedPolicies(ReferencedPoliciesType policies); + + /** + * Gets the request of the query. + * + * @return XACMLRequest The request inside the query + */ + public RequestType getRequest(); + + /** + * If true then include the {@link org.opensaml.xacml.ctx.RequestType} in the response. + * + * @return boolean true if the {@link org.opensaml.xacml.ctx.RequestType} should be included in the response + */ + public XSBooleanValue getReturnContextXSBooleanValue(); + + /** + * Returns if the PDP can combine policies from the query and local policies. + * + * @return true if the PDP can combine policies from the query and locally + */ + public Boolean isCombinePolicies(); + + /** + * True then use only information in the XACMLAuthzDecisionQuery, if false could use external XACML attributes. + * + * @return boolean true then use of just attributes in the XACMLAuthzDecisionQuery is allowed + */ + public Boolean isInputContextOnly(); + + /** + * If true then include the {@link RequestType} in the response. + * + * @return boolean if the {@link RequestType} should be included in the response + */ + public Boolean isReturnContext(); + + /** + * Sets if the PDP can combine policies from this query and the one locally. + * + * @param combinePolicies If true then the PDP can combine policies from this query and the one locally + */ + public void setCombinePolicies(Boolean combinePolicies); + + /** + * Sets if the PDP can combine policies from this query and the one locally. + * + * @param combinePolicies If true then the PDP can combine policies from this query and the one locally + */ + public void setCombinePolicies(XSBooleanValue combinePolicies); + + /** + * Sets if external attributes is allowed in the decision, true if it's allowed. + * + * @param inputContextOnly if external attributes is allowed in the decision, true if it's allowed. + */ + public void setInputContextOnly(Boolean inputContextOnly); + + /** + * Sets if external attributes is allowed in the decision, true if it's allowed. + * + * @param inputContextOnly if external attributes is allowed in the decision, true if it's allowed. + */ + public void setInputContextOnly(XSBooleanValue inputContextOnly); + + /** + * Set's the XACML Request. + * + * @param request The request of the decision query + */ + public void setRequest(RequestType request); + + /** + * Set's if the {@link RequestType} should be included inside the request message. + * + * @param returnContext is true if the {@link RequestType} should be included inside the request message + */ + public void setReturnContext(Boolean returnContext); + + /** + * Set's if the {@link RequestType} should be included inside the request message. + * + * @param returnContext is true if the {@link RequestType} should be included inside the request message + */ + public void setReturnContext(XSBooleanValue returnContext); + +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLAuthzDecisionStatementType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLAuthzDecisionStatementType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLAuthzDecisionStatementType.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,95 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.core.Statement; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.ctx.ResponseType; + +/** A SAML XACML profile XACMLAuthzDecisionStatement schema type. */ +public interface XACMLAuthzDecisionStatementType extends Statement, XACMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "XACMLAuthzDecisionStatement"; + + /** Default element name for XACML 1.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 1.1. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 2.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 3.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "XACMLAuthzDecisionStatementType"; + + /** QName of the XSI type.XACML1.0. */ + public static final QName TYPE_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML1.1. */ + public static final QName TYPE_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML2.0. */ + public static final QName TYPE_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML3.0 . */ + public static final QName TYPE_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** + * Get's the {@link RequestType} from the XACMLAuthzDecisionStatement. + * + * @return the {@link RequestType} inside the XACMLAuthzDecisionStatement + */ + public RequestType getRequest(); + + /** + * Get's the {@link ResponseType} from the XACMLAuthzDecisionStatement. + * + * @return the {@link ResponseType} inside the XACMLAuthzDecisionStatement + */ + public ResponseType getResponse(); + + /** + * Sets a {@link ResponseType} to the XACMLAuthzDecisionStatement. + * + * @param request {@link RequestType} + */ + public void setRequest(RequestType request); + + /** + * Sets a {@link ResponseType} to the XACMLAuthzDecisionStatement. + * + * @param response {@link ResponseType} + */ + public void setResponse(ResponseType response); +} Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLPolicyQueryType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLPolicyQueryType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLPolicyQueryType.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,90 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.ctx.RequestType; +import org.opensaml.xacml.policy.IdReferenceType; + +/** A SAML XACML profile XACMLPolicyQuery schema type. */ +public interface XACMLPolicyQueryType extends RequestAbstractType, XACMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "XACMLPolicyQuery"; + + /** Default element name for XACML 1.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Default element name for XACML 1.1. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Default element name for XACML 2.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Default element nam for XACML 3.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30P_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "XACMLPolicyQueryType"; + + /** QName of the XSI type.XACML1.0. */ + public static final QName TYPE_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** QName of the XSI type.XACML1.1. */ + public static final QName TYPE_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** QName of the XSI type.XACML2.0. */ + public static final QName TYPE_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** QName of the XSI type.XACML3.0. */ + public static final QName TYPE_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30P_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLPROTOCOL_PREFIX); + + /** + * Gets the Requests inside the policy query. + * + * @return the XACML Request + */ + public List getRequests(); + + /** + * Gets the IDs for referenced policy sets. + * + * @return IDs for referenced policy sets + */ + public List getPolicySetIdReferences(); + + /** + * Gets the IDs for referenced policies. + * + * @return IDs for referenced policies + */ + public List getPolicyIdReferences(); +} \ No newline at end of file Index: 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLPolicyStatementType.java =================================================================== RCS file: /usr/local/cvsroot/3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLPolicyStatementType.java,v diff -u --- /dev/null 1 Jan 1970 00:00:00 -0000 +++ 3rdParty_sources/opensaml/org/opensaml/xacml/profile/saml/XACMLPolicyStatementType.java 17 Aug 2012 15:04:40 -0000 1.1 @@ -0,0 +1,97 @@ +/* + * Licensed to the University Corporation for Advanced Internet Development, + * Inc. (UCAID) under one or more contributor license agreements. See the + * NOTICE file distributed with this work for additional information regarding + * copyright ownership. The UCAID licenses this file to You under the Apache + * License, Version 2.0 (the "License"); you may not use this file except in + * compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.opensaml.xacml.profile.saml; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.core.Statement; +import org.opensaml.xacml.XACMLObject; +import org.opensaml.xacml.policy.PolicySetType; +import org.opensaml.xacml.policy.PolicyType; + +/** A SAML XACML profile XACMLPolicyStatement schema type. */ +public interface XACMLPolicyStatementType extends Statement, XACMLObject { + + /** Element local name. */ + public static final String DEFAULT_ELEMENT_LOCAL_NAME = "XACMLPolicyStatement"; + + /** Default element name for XACML 1.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 1.1. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 2.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Default element name for XACML 3.0. */ + public static final QName DEFAULT_ELEMENT_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30_NS, + DEFAULT_ELEMENT_LOCAL_NAME, SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** Local name of the XSI type. */ + public static final String TYPE_LOCAL_NAME = "XACMLPolicyStatementType"; + + /** QName of the XSI type.XACML1.0. */ + public static final QName TYPE_NAME_XACML10 = new QName(SAMLProfileConstants.SAML20XACML10_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML1.1. */ + public static final QName TYPE_NAME_XACML11 = new QName(SAMLProfileConstants.SAML20XACML1_1_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML2.0. */ + public static final QName TYPE_NAME_XACML20 = new QName(SAMLProfileConstants.SAML20XACML20_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** QName of the XSI type.XACML3.0. */ + public static final QName TYPE_NAME_XACML30 = new QName(SAMLProfileConstants.SAML20XACML30_NS, TYPE_LOCAL_NAME, + SAMLProfileConstants.SAML20XACMLASSERTION_PREFIX); + + /** + * Return the XACMLPolicy inside the policy statement. + * + * @return the Policy + */ + public List getPolicies(); + + /** + * Return the XACMLPolicySet inside the policy statement. + * + * @return the PolicySet + */ + public List getPolicySets(); + + /** + * Gets the referenced policies. + * + * @return referenced policies + */ + public ReferencedPoliciesType getReferencedPolicies(); + + /** + * Sets the referenced policies. + * + * @param policies the referenced policies + */ + public void setReferencedPolicies(ReferencedPoliciesType policies); +}